15 lines
2.5 KiB
JavaScript
15 lines
2.5 KiB
JavaScript
import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { createRequire } from "node:module"; import { parentPort, workerData } from "node:worker_threads"; import { pathToFileURL } from "node:url";
|
|
const facade = await import(workerData.facadePath); const envelope = await import(workerData.envelopePath);
|
|
// Emscripten emits an ESM runtime and a CommonJS pthread worker with `.js`
|
|
// suffixes. Stage them outside the repository package boundary with explicit
|
|
// extensions so Node applies the correct module interpretation.
|
|
const stage = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-surface-node-"));
|
|
const runtimeName = "FreeCADWebSurfaceRuntimeProbe.mjs";
|
|
const workerName = "FreeCADWebSurfaceRuntimeProbe.worker.cjs";
|
|
const runtimeSource = fs.readFileSync(path.join(workerData.buildDirectory, "FreeCADWebSurfaceRuntimeProbe.js"), "utf8").replaceAll("FreeCADWebSurfaceRuntimeProbe.worker.js", workerName);
|
|
const workerSource = fs.readFileSync(path.join(workerData.buildDirectory, "FreeCADWebSurfaceRuntimeProbe.worker.js"), "utf8").replaceAll("FreeCADWebSurfaceRuntimeProbe.js", runtimeName);
|
|
fs.writeFileSync(path.join(stage, runtimeName), runtimeSource);
|
|
fs.writeFileSync(path.join(stage, workerName), workerSource);
|
|
fs.copyFileSync(path.join(workerData.buildDirectory, "FreeCADWebSurfaceRuntimeProbe.wasm"), path.join(stage, "FreeCADWebSurfaceRuntimeProbe.wasm"));
|
|
globalThis.__dirname = `${stage}${path.sep}`; globalThis.require = createRequire(import.meta.url); const loader = await import(pathToFileURL(path.join(stage, runtimeName))); const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(stage, "FreeCADWebSurfaceRuntimeProbe.wasm")), locateFile: (file) => path.join(stage, file), print: () => {}, printErr: () => {} }); const queue = new envelope.FacadeSerialQueue(); parentPort.postMessage({ kind: "ready", action: facade.SURFACE_COMMAND }); parentPort.on("message", async (message) => { if (envelope.isFacadeCancel(message)) { if (!queue.cancel(message)) parentPort.postMessage(envelope.createFailure(message.requestId, "cancel_rejected", "request is not active")); return; } if (facade.isSurfaceRequest(message)) { const source = message.requestId === "surface-e-cancel" ? new Promise((resolve) => setTimeout(() => resolve(kernel), 25)) : kernel; parentPort.postMessage(await facade.dispatchSurface(queue, message, source)); return; } parentPort.postMessage(envelope.createFailure("invalid", "invalid_request", "Surface envelope invalid")); });
|