Offload functions to worker threads with shared memory primitives for Node.js.
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat: worker entry point and execute utility

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

+49
+25
src/execute.ts
··· 1 + import type { Worker } from 'node:worker_threads'; 2 + 3 + let nextCallId = 0; 4 + const pending = new Map<number, { resolve: (value: any) => void; reject: (reason: any) => void }>(); 5 + 6 + export function setupWorker(worker: Worker): void { 7 + worker.on('message', (msg: { callId: number; value?: any; error?: string }) => { 8 + const call = pending.get(msg.callId); 9 + if (!call) return; 10 + pending.delete(msg.callId); 11 + if (msg.error !== undefined) { 12 + call.reject(new Error(msg.error)); 13 + } else { 14 + call.resolve(msg.value); 15 + } 16 + }); 17 + } 18 + 19 + export function execute<T>(worker: Worker, id: string, args: unknown[]): Promise<T> { 20 + const callId = nextCallId++; 21 + return new Promise<T>((resolve, reject) => { 22 + pending.set(callId, { resolve, reject }); 23 + worker.postMessage({ callId, id, args }); 24 + }); 25 + }
+24
src/worker-entry.ts
··· 1 + import { parentPort } from 'node:worker_threads'; 2 + import { registry } from './registry.ts'; 3 + 4 + const imported = new Set<string>(); 5 + 6 + parentPort!.on('message', async (msg: { callId: number; id: string; args: unknown[] }) => { 7 + const { callId, id, args } = msg; 8 + try { 9 + const url = id.slice(0, id.lastIndexOf('#')); 10 + if (!imported.has(url)) { 11 + await import(url); 12 + imported.add(url); 13 + } 14 + 15 + const fn = registry.get(id); 16 + if (!fn) throw new Error(`Moroutine not found: ${id}`); 17 + 18 + const value = await fn(...args); 19 + parentPort!.postMessage({ callId, value }); 20 + } catch (err) { 21 + const message = err instanceof Error ? err.message : String(err); 22 + parentPort!.postMessage({ callId, error: message }); 23 + } 24 + });