|
| 1 | +/** |
| 2 | + * Game Processor |
| 3 | + * |
| 4 | + * Fetches and processes archive.org game HTML for embedding in MCP Apps. |
| 5 | + * Uses <base href="https://archive.org/"> for relative URL resolution, |
| 6 | + * and rewrites ES module import() calls to classic <script src> loading |
| 7 | + * (dynamic import() doesn't work in srcdoc iframes due to null origin). |
| 8 | + */ |
| 9 | + |
| 10 | +// Cache for the modified emulation script content |
| 11 | +let cachedEmulationScript: string | null = null; |
| 12 | + |
| 13 | +/** |
| 14 | + * Returns the cached modified emulation script. |
| 15 | + * Called by the server's /scripts/emulation.js endpoint. |
| 16 | + */ |
| 17 | +export function getCachedEmulationScript(): string | null { |
| 18 | + return cachedEmulationScript; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Fetches and processes archive.org game HTML for inline embedding. |
| 23 | + */ |
| 24 | +export async function processGameEmbed( |
| 25 | + gameId: string, |
| 26 | + serverPort: number, |
| 27 | +): Promise<string> { |
| 28 | + const encodedGameId = encodeURIComponent(gameId); |
| 29 | + const embedUrl = `https://archive.org/embed/${encodedGameId}`; |
| 30 | + |
| 31 | + const response = await fetch(embedUrl, { |
| 32 | + headers: { |
| 33 | + "User-Agent": "MCP-Arcade-Server/1.0", |
| 34 | + Accept: "text/html", |
| 35 | + }, |
| 36 | + }); |
| 37 | + |
| 38 | + if (!response.ok) { |
| 39 | + throw new Error( |
| 40 | + `Failed to fetch game: ${response.status} ${response.statusText}`, |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + let html = await response.text(); |
| 45 | + |
| 46 | + // Remove archive.org's <base> tag (would violate CSP base-uri) |
| 47 | + html = html.replace(/<base\s+[^>]*>/gi, ""); |
| 48 | + |
| 49 | + // Inject our <base> tag, hash-link interceptor, script loader, and layout CSS |
| 50 | + const headMatch = html.match(/<head[^>]*>/i); |
| 51 | + if (headMatch) { |
| 52 | + html = html.replace( |
| 53 | + headMatch[0], |
| 54 | + `${headMatch[0]} |
| 55 | + <base href="https://archive.org/"> |
| 56 | + <script> |
| 57 | + // Intercept hash-link clicks that would navigate away due to <base> |
| 58 | + document.addEventListener("click", function(e) { |
| 59 | + var el = e.target; |
| 60 | + while (el && el.tagName !== "A") el = el.parentElement; |
| 61 | + if (el && el.getAttribute("href") && el.getAttribute("href").charAt(0) === "#") { |
| 62 | + e.preventDefault(); |
| 63 | + } |
| 64 | + }, true); |
| 65 | +
|
| 66 | + // Script loader: replaces dynamic import() which fails in srcdoc iframes. |
| 67 | + // Uses <script src> which respects <base> and bypasses CORS. |
| 68 | + if (!window.loadScript) { |
| 69 | + window.loadScript = function(url) { |
| 70 | + return new Promise(function(resolve) { |
| 71 | + var s = document.createElement("script"); |
| 72 | + s.src = url; |
| 73 | + s.onload = function() { |
| 74 | + resolve({ |
| 75 | + default: window.Emulator || window.IALoader || window.Loader || {}, |
| 76 | + __esModule: true |
| 77 | + }); |
| 78 | + }; |
| 79 | + s.onerror = function() { |
| 80 | + console.error("Failed to load script:", url); |
| 81 | + resolve({ default: {}, __esModule: true }); |
| 82 | + }; |
| 83 | + document.head.appendChild(s); |
| 84 | + }); |
| 85 | + }; |
| 86 | + } |
| 87 | + </script> |
| 88 | + <style> |
| 89 | + html, body { width: 100% !important; height: 100% !important; margin: 0 !important; padding: 0 !important; overflow: hidden !important; } |
| 90 | + #wrap, #emulate { width: 100% !important; height: 100% !important; margin: 0 !important; padding: 0 !important; max-width: none !important; } |
| 91 | + #canvasholder { width: 100% !important; height: 100% !important; } |
| 92 | + #canvas { width: 100% !important; height: 100% !important; max-width: 100% !important; max-height: 100% !important; object-fit: contain; } |
| 93 | + </style>`, |
| 94 | + ); |
| 95 | + } |
| 96 | + |
| 97 | + // Convert inline ES module scripts to classic scripts |
| 98 | + html = convertModuleScripts(html); |
| 99 | + |
| 100 | + // Fetch the emulation script server-side and serve from local endpoint |
| 101 | + html = await rewriteEmulationScript(html, serverPort); |
| 102 | + |
| 103 | + return html; |
| 104 | +} |
| 105 | + |
| 106 | +/** |
| 107 | + * Fetches emulation.min.js server-side, rewrites import() → loadScript(), |
| 108 | + * caches it, and points the HTML <script src> to our local endpoint. |
| 109 | + * This avoids: 1) import() failing in srcdoc, 2) CORS blocking fetch from srcdoc. |
| 110 | + */ |
| 111 | +async function rewriteEmulationScript( |
| 112 | + html: string, |
| 113 | + serverPort: number, |
| 114 | +): Promise<string> { |
| 115 | + // NOTE: We intentionally match only the first <script> tag whose src contains |
| 116 | + // "emulation.min.js". Archive.org embeds are expected to include a single |
| 117 | + // relevant emulation script, so rewriting the first match is sufficient. |
| 118 | + // If Archive.org's HTML structure changes to include multiple such scripts, |
| 119 | + // this logic may need to be revisited. |
| 120 | + const pattern = |
| 121 | + /<script\s+[^>]*src=["']([^"']*emulation\.min\.js[^"']*)["'][^>]*><\/script>/i; |
| 122 | + const match = html.match(pattern); |
| 123 | + if (!match) return html; |
| 124 | + |
| 125 | + const scriptTag = match[0]; |
| 126 | + let scriptUrl = match[1]; |
| 127 | + if (scriptUrl.startsWith("//")) { |
| 128 | + scriptUrl = "https:" + scriptUrl; |
| 129 | + } |
| 130 | + |
| 131 | + try { |
| 132 | + const response = await fetch(scriptUrl, { |
| 133 | + headers: { "User-Agent": "MCP-Arcade-Server/1.0" }, |
| 134 | + }); |
| 135 | + if (!response.ok) return html; |
| 136 | + |
| 137 | + let content = await response.text(); |
| 138 | + content = content.replace(/\bimport\s*\(/g, "window.loadScript("); |
| 139 | + cachedEmulationScript = content; |
| 140 | + |
| 141 | + const localUrl = `http://localhost:${serverPort}/scripts/emulation.js`; |
| 142 | + html = html.replace(scriptTag, `<script src="${localUrl}"></script>`); |
| 143 | + } catch { |
| 144 | + // If fetch fails, leave the original script tag |
| 145 | + } |
| 146 | + |
| 147 | + return html; |
| 148 | +} |
| 149 | + |
| 150 | +/** |
| 151 | + * Converts ES module scripts to classic scripts and rewrites inline |
| 152 | + * import() calls to use window.loadScript(). |
| 153 | + */ |
| 154 | +function convertModuleScripts(html: string): string { |
| 155 | + return html.replace( |
| 156 | + /(<script[^>]*>)([\s\S]*?)(<\/script[^>]*>)/gi, |
| 157 | + (match, openTag: string, content: string, closeTag: string) => { |
| 158 | + // Skip our injected scripts |
| 159 | + if (content.includes("window.loadScript")) return match; |
| 160 | + |
| 161 | + // Remove type="module" |
| 162 | + const newOpenTag = openTag.replace(/\s*type\s*=\s*["']module["']/gi, ""); |
| 163 | + |
| 164 | + // Rewrite dynamic import() to loadScript() |
| 165 | + let newContent = content.replace( |
| 166 | + /import\s*\(\s*(["'`])([^"'`]+)\1\s*\)/g, |
| 167 | + (_m: string, quote: string, path: string) => { |
| 168 | + if (path.startsWith("http://") || path.startsWith("https://")) |
| 169 | + return _m; |
| 170 | + return `window.loadScript(${quote}${path}${quote})`; |
| 171 | + }, |
| 172 | + ); |
| 173 | + |
| 174 | + // Convert static import statements |
| 175 | + newContent = newContent.replace( |
| 176 | + /import\s+(\{[^}]*\}|[^"']+)\s+from\s+(["'])([^"']+)\2/g, |
| 177 | + (_m: string, _imports: string, quote: string, path: string) => { |
| 178 | + if (path.startsWith("http://") || path.startsWith("https://")) |
| 179 | + return _m; |
| 180 | + return `window.loadScript(${quote}${path}${quote})`; |
| 181 | + }, |
| 182 | + ); |
| 183 | + |
| 184 | + return newOpenTag + newContent + closeTag; |
| 185 | + }, |
| 186 | + ); |
| 187 | +} |
0 commit comments