diff --git a/packages/natives/scripts/build-wasm.ts b/packages/natives/scripts/build-wasm.ts index 4b04d13c4..92dccd5fd 100644 --- a/packages/natives/scripts/build-wasm.ts +++ b/packages/natives/scripts/build-wasm.ts @@ -41,8 +41,21 @@ if (optResult.exitCode !== 0) { await fs.copyFile(wasmSrc, wasmDst); } -// Copy JS bindings -await fs.copyFile(path.join(pkgDir, "pi_natives.js"), path.join(wasmDir, "pi_natives.js")); +// Copy and patch JS bindings for Bun compiled binary compatibility +// wasm-bindgen uses `new URL('file.wasm', import.meta.url)` which doesn't work +// in Bun's single-file executable. We use asset import + import.meta.resolve() instead. +const jsDst = path.join(wasmDir, "pi_natives.js"); +await fs.copyFile(path.join(pkgDir, "pi_natives.js"), jsDst); +let jsContent = await Bun.file(jsDst).text(); +jsContent = jsContent.replace( + "/* @ts-self-types=", + 'import wasmPath from "./pi_natives_bg.wasm";\n\n/* @ts-self-types=' +); +jsContent = jsContent.replace( + "const wasmUrl = new URL('pi_natives_bg.wasm', import.meta.url);", + "const wasmUrl = import.meta.resolve(wasmPath);" +); +await Bun.write(jsDst, jsContent); // Copy d.ts bindings await fs.copyFile(path.join(pkgDir, "pi_natives.d.ts"), path.join(wasmDir, "pi_natives.d.ts")); diff --git a/packages/natives/wasm/pi_natives.js b/packages/natives/wasm/pi_natives.js index 3bdf015fe..655c871c8 100644 --- a/packages/natives/wasm/pi_natives.js +++ b/packages/natives/wasm/pi_natives.js @@ -1,5 +1,7 @@ /* @ts-self-types="./pi_natives.d.ts" */ +import wasmPath from "./pi_natives_bg.wasm"; + /** * A compiled regex matcher that can be reused across multiple searches. */ @@ -651,6 +653,6 @@ const cachedTextEncoder = new TextEncoder(); let WASM_VECTOR_LEN = 0; -const wasmUrl = new URL('pi_natives_bg.wasm', import.meta.url); +const wasmUrl = import.meta.resolve(wasmPath); const wasmInstantiated = await WebAssembly.instantiateStreaming(fetch(wasmUrl), __wbg_get_imports()); const wasm = wasmInstantiated.instance.exports;