2023-11-02 13:57:11 +09:00
|
|
|
import fs from "node:fs";
|
|
|
|
import { createRequire } from "node:module";
|
2024-04-10 10:08:57 +09:00
|
|
|
import { WASI } from "node:wasi";
|
2023-11-02 13:57:11 +09:00
|
|
|
import { parentPort, Worker } from "node:worker_threads";
|
|
|
|
|
|
|
|
const require = createRequire(import.meta.url);
|
|
|
|
|
2024-04-10 10:08:57 +09:00
|
|
|
const { instantiateNapiModuleSync, MessageHandler, getDefaultContext } = require("@napi-rs/wasm-runtime");
|
|
|
|
|
2023-11-02 13:57:11 +09:00
|
|
|
if (parentPort) {
|
|
|
|
parentPort.on("message", (data) => {
|
|
|
|
globalThis.onmessage({ data });
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Object.assign(globalThis, {
|
|
|
|
self: globalThis,
|
|
|
|
require,
|
|
|
|
Worker,
|
|
|
|
importScripts: function (f) {
|
|
|
|
;(0, eval)(fs.readFileSync(f, "utf8") + "//# sourceURL=" + f);
|
|
|
|
},
|
|
|
|
postMessage: function (msg) {
|
|
|
|
if (parentPort) {
|
|
|
|
parentPort.postMessage(msg);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2024-04-10 10:08:57 +09:00
|
|
|
const emnapiContext = getDefaultContext()
|
|
|
|
|
2023-11-02 13:57:11 +09:00
|
|
|
const handler = new MessageHandler({
|
|
|
|
onLoad({ wasmModule, wasmMemory }) {
|
2024-04-10 10:08:57 +09:00
|
|
|
const wasi = new WASI({
|
|
|
|
version: 'preview1',
|
|
|
|
env: process.env,
|
|
|
|
preopens: {
|
|
|
|
'/': '/',
|
|
|
|
},
|
|
|
|
});
|
2023-11-02 13:57:11 +09:00
|
|
|
|
|
|
|
return instantiateNapiModuleSync(wasmModule, {
|
|
|
|
childThread: true,
|
|
|
|
wasi,
|
2024-04-10 10:08:57 +09:00
|
|
|
context: emnapiContext,
|
2023-11-02 13:57:11 +09:00
|
|
|
overwriteImports(importObject) {
|
|
|
|
importObject.env = {
|
|
|
|
...importObject.env,
|
|
|
|
...importObject.napi,
|
|
|
|
...importObject.emnapi,
|
|
|
|
memory: wasmMemory
|
|
|
|
};
|
|
|
|
},
|
|
|
|
});
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
globalThis.onmessage = function (e) {
|
|
|
|
handler.handle(e);
|
|
|
|
};
|