import { copyFileSync, existsSync, writeFileSync } from "node:fs"; import { execSync } from "node:child_process"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { build } from "tsdown"; import * as esbuild from "esbuild"; const __dirname = dirname(fileURLToPath(import.meta.url)); const packageRoot = join(__dirname, ".."); async function main() { // Pre-build: bundle asset-handler + mime into a standalone ESM runtime module. // This gets embedded as a string constant so createApp can include it in // generated workers, giving them the full handleAssetRequest implementation. const runtimeBundle = await esbuild.build({ entryPoints: [join(packageRoot, "src/asset-handler.ts")], bundle: true, write: false, format: "esm", platform: "browser", target: "es2022", minify: true }); const runtimeCode = runtimeBundle.outputFiles?.[0]?.text ?? ""; const escaped = JSON.stringify(runtimeCode); const generatedFile = join(packageRoot, "src/_asset-runtime-code.ts"); writeFileSync( generatedFile, `// AUTO-GENERATED by scripts/build.ts — do not edit\n` + `export const ASSET_RUNTIME_CODE = ${escaped};\n` ); await build({ clean: true, dts: true, entry: ["src/index.ts"], deps: { skipNodeModulesBundle: true, neverBundle: ["cloudflare:workers", "./esbuild.wasm"] }, format: "esm", sourcemap: true, fixedExtension: false }); // Copy esbuild.wasm from esbuild-wasm package into dist/ const possiblePaths = [ join(packageRoot, "node_modules/esbuild-wasm/esbuild.wasm"), join(packageRoot, "../../node_modules/esbuild-wasm/esbuild.wasm") ]; let wasmSource: string | null = null; for (const p of possiblePaths) { if (existsSync(p)) { wasmSource = p; break; } } if (!wasmSource) { console.error("Error: Could not find esbuild.wasm!"); process.exit(1); } const wasmDest = join(packageRoot, "dist/esbuild.wasm"); copyFileSync(wasmSource, wasmDest); console.log("Copied esbuild.wasm to dist/"); // then run oxfmt on the generated .d.ts files execSync("oxfmt --write ./dist/*.d.ts"); process.exit(0); } main().catch((err) => { // Build failures should fail console.error(err); process.exit(1); });