UNPKG

nanolith

Version:

Multi-threading in no time with seamless TypeScript support.

1 lines 1.27 kB
import{parentPort,workerData}from"worker_threads";import{assertIsNotMainThread}from"../utilities/index.js";import{listenForStream,prepareWritableToPortStream}from"../streams/index.js";export const ParentThread=Object.freeze({sendMessage:function(e,r){assertIsNotMainThread("ParentThread.sendMessage");const t={type:0,data:e};parentPort.postMessage(t,r)},onMessage:function(e){assertIsNotMainThread("ParentThread.onMessage");const r=async r=>{0===r.type&&await e(r.data)};return parentPort.on("message",r),()=>parentPort.off("message",r)},onMessengerReceived:function(e){assertIsNotMainThread("ParentThread.onMessengerReceived");const{messengers:r}=workerData,t=async t=>{3===t.type&&await e(r[t.data.__messengerID])};return parentPort.on("message",t),()=>parentPort.off("message",t)},waitForMessage:async function(e){return assertIsNotMainThread("ParentThread.waitForMessage"),new Promise((r=>{const t=async a=>{if(0!==a.type)return;const{data:s}=a;await e(s)&&(r(s),parentPort.off("message",t))};parentPort.on("message",t)}))},onStream:function(e){return assertIsNotMainThread("ParentThread.onStream"),listenForStream(parentPort,e)},createStream:async function(e){return assertIsNotMainThread("ParentThread.stream"),prepareWritableToPortStream(parentPort,e??{})}});