import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' const [, , sourceHtmlArg, outputPrefixArg] = process.argv if (!sourceHtmlArg || !outputPrefixArg) { throw new Error( 'Usage: node scripts/extract-page.mjs \n' + 'Example: npm run extract:page -- ./snapshots/about.html about\n' + 'Writes src/generated/-page-body.html, -assets.json, -inline-scripts.txt' ) } const currentFile = fileURLToPath(import.meta.url) const rootDir = path.resolve(path.dirname(currentFile), '..') const sourceHtmlPath = path.resolve(rootDir, sourceHtmlArg) const outDir = path.resolve(rootDir, 'src', 'generated') const html = fs.readFileSync(sourceHtmlPath, 'utf8') const bodyMatch = html.match(/]*>([\s\S]*?)<\/body>/i) if (!bodyMatch) throw new Error(`Failed to extract from ${sourceHtmlArg}`) let bodyHtml = bodyMatch[1] bodyHtml = bodyHtml.replace(/]*>[\s\S]*?<\/script>/gi, '') const links = Array.from(html.matchAll(/]+href="([^"]+)"[^>]*>/gi)).map((m) => m[1]) const scripts = Array.from(html.matchAll(/]+src="([^"]+)"[^>]*><\/script>/gi)).map( (m) => m[1] ) const inlineScripts = Array.from( html.matchAll(/]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi) ) .map((m) => m[1].trim()) .filter(Boolean) fs.writeFileSync(path.join(outDir, `${outputPrefixArg}-page-body.html`), bodyHtml, 'utf8') fs.writeFileSync( path.join(outDir, `${outputPrefixArg}-assets.json`), JSON.stringify({ scripts, links }, null, 2), 'utf8' ) fs.writeFileSync( path.join(outDir, `${outputPrefixArg}-inline-scripts.txt`), inlineScripts.join('\n/*__INLINE_SPLIT__*/\n'), 'utf8' ) console.log(`Generated files for ${outputPrefixArg}`)