File size: 1,399 Bytes
bc7e9cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
export interface ParsedDocument {
  world: string;
  scripts: string[];
}

/**
 * Simple HTML Document Parser for JSFiddle-style content processing
 * Parses complete HTML documents and extracts world/script content
 */
export class HTMLDocumentParser {
  static parseDocument(html: string): ParsedDocument {
    try {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, "text/html");

      const world = this.extractWorld(doc);
      const scripts = this.extractScripts(doc);

      return {
        world: world || '<world canvas="#game-canvas"></world>',
        scripts,
      };
    } catch {
      return {
        world: '<world canvas="#game-canvas"></world>',
        scripts: [],
      };
    }
  }

  private static extractWorld(doc: Document): string {
    const worldElements = doc.getElementsByTagName("world");

    if (worldElements.length === 0) {
      return "";
    }

    return worldElements[0].outerHTML;
  }

  private static extractScripts(doc: Document): string[] {
    const scripts: string[] = [];
    const scriptElements = doc.getElementsByTagName("script");

    for (let i = 0; i < scriptElements.length; i++) {
      const script = scriptElements[i];
      const content = script.textContent || script.innerHTML;

      if (content && content.trim()) {
        scripts.push(content.trim());
      }
    }

    return scripts;
  }
}