68 lines
2.0 KiB
JavaScript
68 lines
2.0 KiB
JavaScript
import { createHash } from 'node:crypto'
|
|
import { readFile } from 'node:fs/promises'
|
|
import { basename, join } from 'node:path'
|
|
|
|
function rewriteImportMap(html, importMapOverrides) {
|
|
if (!importMapOverrides || typeof importMapOverrides !== 'object') {
|
|
return html
|
|
}
|
|
|
|
return html.replace(
|
|
/(<script\s+type=["']importmap["']>\s*)([\s\S]*?)(\s*<\/script>)/i,
|
|
(fullMatch, prefix, jsonText, suffix) => {
|
|
try {
|
|
const parsed = JSON.parse(jsonText)
|
|
const nextImports = {
|
|
...(parsed.imports || {}),
|
|
...importMapOverrides,
|
|
}
|
|
const nextPayload = JSON.stringify({ ...parsed, imports: nextImports }, null, 4)
|
|
return `${prefix}${nextPayload}${suffix}`
|
|
} catch {
|
|
return fullMatch
|
|
}
|
|
},
|
|
)
|
|
}
|
|
|
|
export async function compileEarthRuntime({ earthDir, importMapOverrides = null }) {
|
|
const result = await Bun.build({
|
|
entrypoints: [join(earthDir, 'js/main.js'), join(earthDir, 'js/earth-preload.js')],
|
|
target: 'browser',
|
|
format: 'esm',
|
|
splitting: true,
|
|
packages: 'external',
|
|
minify: true,
|
|
naming: { entry: 'runtime-[name]-[hash].js', chunk: 'runtime-[hash].js' },
|
|
})
|
|
if (!result.success) {
|
|
throw new AggregateError(result.logs, 'Earth runtime build failed')
|
|
}
|
|
|
|
const assets = new Map(
|
|
await Promise.all(
|
|
result.outputs.map(async (output) => {
|
|
const source = await output.text()
|
|
return [
|
|
basename(output.path),
|
|
{
|
|
source,
|
|
etag: `"${createHash('sha256').update(source).digest('hex')}"`,
|
|
},
|
|
]
|
|
}),
|
|
),
|
|
)
|
|
|
|
let html = await readFile(join(earthDir, 'index.html'), 'utf8')
|
|
for (const entry of ['main', 'earth-preload']) {
|
|
const filename = [...assets.keys()].find((name) => name.startsWith(`runtime-${entry}-`))
|
|
if (filename) {
|
|
html = html.replace(new RegExp(`src="(?:\\./)?js/${entry}\\.js"`), `src="./js/${filename}"`)
|
|
}
|
|
}
|
|
html = rewriteImportMap(html, importMapOverrides)
|
|
|
|
return { assets, html }
|
|
}
|