UNPKG

@xylabs/threads

Version:

Web workers & worker threads as simple as a function call

79 lines (78 loc) 2.51 kB
// src/master/implementation.node.ts import { cpus } from "node:os"; import path from "node:path"; import { cwd } from "node:process"; import { isMainThread, Worker as NativeWorker } from "node:worker_threads"; var defaultPoolSize = cpus().length; function resolveScriptPath(scriptPath, baseURL) { const makeAbsolute = (filePath) => { return path.isAbsolute(filePath) ? filePath : path.join(baseURL ?? cwd(), filePath); }; const absolutePath = makeAbsolute(scriptPath); return absolutePath; } function initWorkerThreadsWorker() { let allWorkers = []; class Worker extends NativeWorker { mappedEventListeners; constructor(scriptPath, options) { const resolvedScriptPath = options?.fromSource ? null : resolveScriptPath(scriptPath, options?._baseURL); if (resolvedScriptPath === null) { const sourceCode = scriptPath; super(sourceCode, { ...options, eval: true }); } else { super(resolvedScriptPath, options); } this.mappedEventListeners = /* @__PURE__ */ new WeakMap(); allWorkers.push(this); } addEventListener(eventName, rawListener) { const listener = (message) => { rawListener({ data: message }); }; this.mappedEventListeners.set(rawListener, listener); this.on(eventName, listener); } removeEventListener(eventName, rawListener) { const listener = this.mappedEventListeners.get(rawListener) || rawListener; this.off(eventName, listener); } } const terminateWorkersAndMaster = () => { Promise.all(allWorkers.map((worker) => worker.terminate())).then( () => process.exit(0), () => process.exit(1) ); allWorkers = []; }; process.on("SIGINT", () => terminateWorkersAndMaster()); process.on("SIGTERM", () => terminateWorkersAndMaster()); class BlobWorker extends Worker { constructor(blob, options) { super(Buffer.from(blob).toString("utf-8"), { ...options, fromSource: true }); } static fromText(source, options) { return new Worker(source, { ...options, fromSource: true }); } } return { blob: BlobWorker, default: Worker }; } var implementation; function getWorkerImplementation() { if (implementation === void 0) { implementation = initWorkerThreadsWorker(); } return implementation; } function isWorkerRuntime() { return !isMainThread; } export { defaultPoolSize, getWorkerImplementation, isWorkerRuntime }; //# sourceMappingURL=implementation.node.mjs.map