From 3e44ae3c160f28f4c1087c80da712c7a86608693 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Tue, 23 Apr 2024 14:26:27 +0800 Subject: [PATCH] fix(cli): non-fs polyfilled browser worker binding (#2067) --- cli/src/api/templates/wasi-worker-template.ts | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/cli/src/api/templates/wasi-worker-template.ts b/cli/src/api/templates/wasi-worker-template.ts index 682d9ccc..dbca29c0 100644 --- a/cli/src/api/templates/wasi-worker-template.ts +++ b/cli/src/api/templates/wasi-worker-template.ts @@ -65,16 +65,13 @@ globalThis.onmessage = function (e) { export const createWasiBrowserWorkerBinding = (fs: boolean) => { const fsImport = fs - ? `import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs' + ? `import { instantiateNapiModuleSync, MessageHandler, WASI, createFsProxy } from '@napi-rs/wasm-runtime' +import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs' const fs = createFsProxy(__memfsExported)` - : '\nconst fs = null' - return `import { instantiateNapiModuleSync, MessageHandler, WASI, createFsProxy } from '@napi-rs/wasm-runtime' -${fsImport} - -const handler = new MessageHandler({ - onLoad({ wasmModule, wasmMemory }) { - const wasi = new WASI({ + : `import { instantiateNapiModuleSync, MessageHandler, WASI } from '@napi-rs/wasm-runtime'` + const wasiCreation = fs + ? `const wasi = new WASI({ fs, preopens: { '/': '/', @@ -87,7 +84,22 @@ const handler = new MessageHandler({ // eslint-disable-next-line no-console console.error.apply(console, arguments) }, - }) + })` + : `const wasi = new WASI({ + print: function () { + // eslint-disable-next-line no-console + console.log.apply(console, arguments) + }, + printErr: function() { + // eslint-disable-next-line no-console + console.error.apply(console, arguments) + }, + })` + return `${fsImport} + +const handler = new MessageHandler({ + onLoad({ wasmModule, wasmMemory }) { + ${wasiCreation} return instantiateNapiModuleSync(wasmModule, { childThread: true, wasi,