const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); const rootDir = path.resolve(__dirname, '..'); const frontendDir = path.join(rootDir, 'frontend'); const distDir = path.join(frontendDir, 'dist'); const workerDir = path.join(rootDir, 'src', 'worker'); const htmlTsFile = path.join(workerDir, 'html.ts'); console.log('Building frontend...'); try { // 1. Install and build frontend execSync('npm install', { cwd: frontendDir, stdio: 'inherit' }); execSync('npm run build', { cwd: frontendDir, stdio: 'inherit' }); console.log('Inlining assets...'); // 2. Read dist/index.html let html = fs.readFileSync(path.join(distDir, 'index.html'), 'utf8'); // 3. Find assets in dist/assets const assetsDir = path.join(distDir, 'assets'); const files = fs.readdirSync(assetsDir); let jsContent = ''; let cssContent = ''; for (const file of files) { const filePath = path.join(assetsDir, file); if (file.endsWith('.js')) { jsContent = fs.readFileSync(filePath, 'utf8'); } else if (file.endsWith('.css')) { cssContent = fs.readFileSync(filePath, 'utf8'); } } // 4. Inline CSS (replace ) html = html.replace(/]*rel=["']stylesheet["'][^>]*href=["']\/assets\/[^"']+["'][^>]*>/i, () => ``); html = html.replace(/]*rel=["']stylesheet["'][^>]*href=["']\/src\/[^"']+["'][^>]*>/i, () => ``); // 5. Inline JS (replace or similar) html = html.replace(/]*type=["']module["'][^>]*src=["']\/assets\/[^"']+["'][^>]*><\/script>/i, () => ``); html = html.replace(/]*type=["']module["'][^>]*src=["']\/src\/[^"']+["'][^>]*><\/script>/i, () => ``); // 6. Write to src/worker/html.ts const escapedHtml = html .replace(/\\/g, '\\\\') .replace(/`/g, '\\`') .replace(/\${/g, '\\${'); const htmlTsContent = `// Automatically generated by scripts/build-html.js. Do not edit directly. export const HTML = \`${escapedHtml}\`; `; if (!fs.existsSync(workerDir)) { fs.mkdirSync(workerDir, { recursive: true }); } fs.writeFileSync(htmlTsFile, htmlTsContent, 'utf8'); console.log('Frontend built and inlined successfully to src/worker/html.ts!'); } catch (error) { console.error('Failed to build and inline frontend:', error); process.exit(1); }