fix: use static import + initSync for WASM in service worker
Chrome MV3 service workers do not support dynamic import(). Switch to static import of the wasm-pack JS glue and use initSync() with fetch() to load the WASM binary at runtime. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -21,27 +21,30 @@ const totpSecretCache: Map<string, string> = new Map();
|
||||
|
||||
// --- WASM initialization ---
|
||||
|
||||
// We use a dynamic import so webpack treats idfoto_wasm.js as a separate chunk.
|
||||
// The WASM file (idfoto_wasm_bg.wasm) is loaded by the JS glue code.
|
||||
type WasmModule = typeof import('idfoto-wasm');
|
||||
// Chrome MV3 service workers do NOT support dynamic import().
|
||||
// Instead we load the WASM binary via fetch() and use the synchronous
|
||||
// initSync() function exported by wasm-pack's --target web output.
|
||||
// The JS glue is imported statically so webpack bundles it into
|
||||
// the service worker script.
|
||||
|
||||
// @ts-ignore TS2307 — resolved by webpack alias / copy
|
||||
import initSync, * as wasmBindings from '../../wasm/idfoto_wasm.js';
|
||||
|
||||
type WasmModule = typeof wasmBindings;
|
||||
let wasm: WasmModule | null = null;
|
||||
|
||||
async function initWasm(): Promise<WasmModule> {
|
||||
if (wasm) return wasm;
|
||||
|
||||
// wasm-pack --target web produces an ES module with an `default` init function
|
||||
// that loads the .wasm file. In a Chrome MV3 service worker we import the JS
|
||||
// glue and call init() with the wasm URL.
|
||||
const mod = await import(
|
||||
// @ts-ignore TS2307 — resolved at runtime by the service worker, not by TS/webpack
|
||||
/* webpackIgnore: true */ './idfoto_wasm.js'
|
||||
) as WasmModule & { default: (input?: string | URL) => Promise<void> };
|
||||
// Fetch the .wasm binary and instantiate synchronously
|
||||
const wasmResponse = await fetch(chrome.runtime.getURL('idfoto_wasm_bg.wasm'));
|
||||
const wasmBytes = await wasmResponse.arrayBuffer();
|
||||
initSync({ module: new WebAssembly.Module(wasmBytes) });
|
||||
|
||||
await mod.default('./idfoto_wasm_bg.wasm');
|
||||
vault.setWasm(mod);
|
||||
wasm = mod;
|
||||
vault.setWasm(wasmBindings);
|
||||
wasm = wasmBindings;
|
||||
wasmReady = true;
|
||||
return mod;
|
||||
return wasm;
|
||||
}
|
||||
|
||||
// --- Storage helpers ---
|
||||
|
||||
Reference in New Issue
Block a user