@ariestools/threads 8.1.9 → 8.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +4 -0
  2. package/dist/browser/common.d.ts +8 -1
  3. package/dist/browser/common.d.ts.map +1 -1
  4. package/dist/browser/index-browser.mjs +75 -35
  5. package/dist/browser/index-browser.mjs.map +4 -4
  6. package/dist/browser/master/index-browser.mjs +75 -35
  7. package/dist/browser/master/index-browser.mjs.map +4 -4
  8. package/dist/browser/master/pool-browser.d.ts +10 -1
  9. package/dist/browser/master/pool-browser.d.ts.map +1 -1
  10. package/dist/browser/master/pool-browser.mjs +34 -26
  11. package/dist/browser/master/pool-browser.mjs.map +3 -3
  12. package/dist/browser/master/pool-node.d.ts +10 -1
  13. package/dist/browser/master/pool-node.d.ts.map +1 -1
  14. package/dist/browser/master/pool-types.d.ts +21 -26
  15. package/dist/browser/master/pool-types.d.ts.map +1 -1
  16. package/dist/browser/types/master.d.ts +11 -11
  17. package/dist/browser/types/master.d.ts.map +1 -1
  18. package/dist/browser/types/messages.d.ts +23 -25
  19. package/dist/browser/types/messages.d.ts.map +1 -1
  20. package/dist/browser/worker/worker.browser.mjs +29 -8
  21. package/dist/browser/worker/worker.browser.mjs.map +3 -3
  22. package/dist/neutral/common.d.ts +8 -1
  23. package/dist/neutral/common.d.ts.map +1 -1
  24. package/dist/neutral/master/pool-browser.d.ts +10 -1
  25. package/dist/neutral/master/pool-browser.d.ts.map +1 -1
  26. package/dist/neutral/master/pool-node.d.ts +10 -1
  27. package/dist/neutral/master/pool-node.d.ts.map +1 -1
  28. package/dist/neutral/master/pool-types.d.ts +21 -26
  29. package/dist/neutral/master/pool-types.d.ts.map +1 -1
  30. package/dist/neutral/master/spawn.mjs +41 -9
  31. package/dist/neutral/master/spawn.mjs.map +4 -4
  32. package/dist/neutral/types/master.d.ts +11 -11
  33. package/dist/neutral/types/master.d.ts.map +1 -1
  34. package/dist/neutral/types/messages.d.ts +23 -25
  35. package/dist/neutral/types/messages.d.ts.map +1 -1
  36. package/dist/neutral/types/messages.mjs +19 -13
  37. package/dist/neutral/types/messages.mjs.map +3 -3
  38. package/dist/node/common.d.ts +8 -1
  39. package/dist/node/common.d.ts.map +1 -1
  40. package/dist/node/index-node.mjs +75 -35
  41. package/dist/node/index-node.mjs.map +4 -4
  42. package/dist/node/master/index-node.mjs +75 -35
  43. package/dist/node/master/index-node.mjs.map +4 -4
  44. package/dist/node/master/pool-browser.d.ts +10 -1
  45. package/dist/node/master/pool-browser.d.ts.map +1 -1
  46. package/dist/node/master/pool-node.d.ts +10 -1
  47. package/dist/node/master/pool-node.d.ts.map +1 -1
  48. package/dist/node/master/pool-node.mjs +34 -26
  49. package/dist/node/master/pool-node.mjs.map +3 -3
  50. package/dist/node/master/pool-types.d.ts +21 -26
  51. package/dist/node/master/pool-types.d.ts.map +1 -1
  52. package/dist/node/types/master.d.ts +11 -11
  53. package/dist/node/types/master.d.ts.map +1 -1
  54. package/dist/node/types/messages.d.ts +23 -25
  55. package/dist/node/types/messages.d.ts.map +1 -1
  56. package/dist/node/worker/worker.node.mjs +29 -8
  57. package/dist/node/worker/worker.node.mjs.map +3 -3
  58. package/package.json +9 -9
@@ -11,17 +11,25 @@ import { cpus } from "node:os";
11
11
  var defaultPoolSize = cpus().length;
12
12
 
13
13
  // src/master/pool-types.ts
14
- var PoolEventType = /* @__PURE__ */ ((PoolEventType2) => {
15
- PoolEventType2["initialized"] = "initialized";
16
- PoolEventType2["taskCanceled"] = "taskCanceled";
17
- PoolEventType2["taskCompleted"] = "taskCompleted";
18
- PoolEventType2["taskFailed"] = "taskFailed";
19
- PoolEventType2["taskQueued"] = "taskQueued";
20
- PoolEventType2["taskQueueDrained"] = "taskQueueDrained";
21
- PoolEventType2["taskStart"] = "taskStart";
22
- PoolEventType2["terminated"] = "terminated";
23
- return PoolEventType2;
24
- })(PoolEventType || {});
14
+ import { Enum } from "@ariestools/sdk/enum";
15
+ var PoolEventType = Enum({
16
+ /** All workers in the pool have initialized. */
17
+ initialized: "initialized",
18
+ /** A queued task was canceled before execution. */
19
+ taskCanceled: "taskCanceled",
20
+ /** A task completed successfully. */
21
+ taskCompleted: "taskCompleted",
22
+ /** A task failed during execution. */
23
+ taskFailed: "taskFailed",
24
+ /** A task was added to the queue. */
25
+ taskQueued: "taskQueued",
26
+ /** The pool has no remaining queued tasks. */
27
+ taskQueueDrained: "taskQueueDrained",
28
+ /** A worker started executing a task. */
29
+ taskStart: "taskStart",
30
+ /** The pool and its workers were terminated. */
31
+ terminated: "terminated"
32
+ });
25
33
 
26
34
  // src/symbols.ts
27
35
  var $errors = /* @__PURE__ */ Symbol("thread.errors");
@@ -95,7 +103,7 @@ var WorkerPool = class {
95
103
  await Promise.all(workers.map((worker) => worker.init));
96
104
  this.eventSubject.next({
97
105
  size: workers.length,
98
- type: "initialized" /* initialized */
106
+ type: PoolEventType.initialized
99
107
  });
100
108
  } catch (error) {
101
109
  const initError = error instanceof Error ? error : new Error(String(error));
@@ -114,7 +122,7 @@ var WorkerPool = class {
114
122
  this.debug(`Running task #${task.id} on worker #${workerID}...`);
115
123
  this.eventSubject.next({
116
124
  taskID: task.id,
117
- type: "taskStart" /* taskStart */,
125
+ type: PoolEventType.taskStart,
118
126
  workerID
119
127
  });
120
128
  try {
@@ -123,7 +131,7 @@ var WorkerPool = class {
123
131
  this.eventSubject.next({
124
132
  returnValue,
125
133
  taskID: task.id,
126
- type: "taskCompleted" /* taskCompleted */,
134
+ type: PoolEventType.taskCompleted,
127
135
  workerID
128
136
  });
129
137
  } catch (ex) {
@@ -132,7 +140,7 @@ var WorkerPool = class {
132
140
  this.eventSubject.next({
133
141
  error,
134
142
  taskID: task.id,
135
- type: "taskFailed" /* taskFailed */,
143
+ type: PoolEventType.taskFailed,
136
144
  workerID
137
145
  });
138
146
  }
@@ -161,7 +169,7 @@ var WorkerPool = class {
161
169
  const nextTask = this.taskQueue.shift();
162
170
  if (!nextTask) {
163
171
  this.debug("Task queue is empty");
164
- this.eventSubject.next({ type: "taskQueueDrained" /* taskQueueDrained */ });
172
+ this.eventSubject.next({ type: PoolEventType.taskQueueDrained });
165
173
  return;
166
174
  }
167
175
  this.run(availableWorker, nextTask);
@@ -169,13 +177,13 @@ var WorkerPool = class {
169
177
  taskCompletion(taskID) {
170
178
  return new Promise((resolve, reject) => {
171
179
  const eventSubscription = this.events().subscribe((event) => {
172
- if (event.type === "taskCompleted" /* taskCompleted */ && event.taskID === taskID) {
180
+ if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) {
173
181
  eventSubscription.unsubscribe();
174
182
  resolve(event.returnValue);
175
- } else if (event.type === "taskFailed" /* taskFailed */ && event.taskID === taskID) {
183
+ } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) {
176
184
  eventSubscription.unsubscribe();
177
185
  reject(event.error);
178
- } else if (event.type === "terminated" /* terminated */) {
186
+ } else if (event.type === PoolEventType.terminated) {
179
187
  eventSubscription.unsubscribe();
180
188
  reject(new Error("Pool has been terminated before task was run."));
181
189
  }
@@ -193,7 +201,7 @@ var WorkerPool = class {
193
201
  const getCurrentlyRunningTasks = () => flatMap(this.workers, (worker) => worker.runningTasks);
194
202
  const taskFailures = [];
195
203
  const failureSubscription = this.eventObservable.subscribe((event) => {
196
- if (event.type === "taskFailed" /* taskFailed */) {
204
+ if (event.type === PoolEventType.taskFailed) {
197
205
  taskFailures.push(event.error);
198
206
  }
199
207
  });
@@ -201,7 +209,7 @@ var WorkerPool = class {
201
209
  const subscription = this.eventObservable.subscribe({
202
210
  error: reject,
203
211
  next(event) {
204
- if (event.type !== "taskQueueDrained" /* taskQueueDrained */) {
212
+ if (event.type !== PoolEventType.taskQueueDrained) {
205
213
  return;
206
214
  }
207
215
  subscription.unsubscribe();
@@ -220,10 +228,10 @@ var WorkerPool = class {
220
228
  const subscription = this.eventObservable.subscribe({
221
229
  error: reject,
222
230
  next(event) {
223
- if (event.type === "taskQueueDrained" /* taskQueueDrained */) {
231
+ if (event.type === PoolEventType.taskQueueDrained) {
224
232
  subscription.unsubscribe();
225
233
  resolve(settlementPromise);
226
- } else if (event.type === "taskFailed" /* taskFailed */) {
234
+ } else if (event.type === PoolEventType.taskFailed) {
227
235
  subscription.unsubscribe();
228
236
  reject(event.error);
229
237
  }
@@ -262,7 +270,7 @@ var WorkerPool = class {
262
270
  this.taskQueue = this.taskQueue.filter((someTask) => someTask !== task);
263
271
  this.eventSubject.next({
264
272
  taskID: task.id,
265
- type: "taskCanceled" /* taskCanceled */
273
+ type: PoolEventType.taskCanceled
266
274
  });
267
275
  },
268
276
  id: taskID,
@@ -278,7 +286,7 @@ var WorkerPool = class {
278
286
  this.taskQueue.push(task);
279
287
  this.eventSubject.next({
280
288
  taskID: task.id,
281
- type: "taskQueued" /* taskQueued */
289
+ type: PoolEventType.taskQueued
282
290
  });
283
291
  this.scheduleWork();
284
292
  return task;
@@ -290,7 +298,7 @@ var WorkerPool = class {
290
298
  }
291
299
  this.eventSubject.next({
292
300
  remainingQueue: [...this.taskQueue],
293
- type: "terminated" /* terminated */
301
+ type: PoolEventType.terminated
294
302
  });
295
303
  this.eventSubject.complete();
296
304
  await Promise.all(this.workers.map(async (worker) => Thread.terminate(await worker.init)));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/master/pool-node.ts", "../../../src/master/implementation.node.ts", "../../../src/master/pool-types.ts", "../../../src/symbols.ts", "../../../src/master/thread.ts"],
4
- "sourcesContent": ["/* eslint-disable import-x/export */\n/* eslint-disable unicorn/no-thenable */\n\n/* eslint-disable @typescript-eslint/member-ordering */\n/* eslint-disable unicorn/no-array-reduce */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-namespace */\n\n/// <reference lib=\"esnext\" />\n\nimport DebugLogger from 'debug'\nimport {\n multicast, Observable, Subject,\n} from 'observable-fns'\n\nimport { defaultPoolSize } from './implementation.node.ts'\nimport type {\n PoolEvent, QueuedTask, TaskRunFunction, WorkerDescriptor,\n} from './pool-types.ts'\nimport { PoolEventType } from './pool-types.ts'\nimport { Thread } from './thread.ts'\n\n/** Types and constants associated with Node.js worker pools. */\nexport declare namespace Pool {\n type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType>\n type EventType = PoolEventType\n}\n\nlet nextPoolID = 1\n\nfunction createArray(size: number): number[] {\n const array: number[] = []\n for (let index = 0; index < size; index++) {\n array.push(index)\n }\n return array\n}\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction flatMap<In, Out>(array: In[], mapper: (element: In) => Out[]): Out[] {\n return array.reduce<Out[]>((flattened, element) => [...flattened, ...mapper(element)], [])\n}\n\nfunction slugify(text: string) {\n return text.replaceAll(/\\W/g, ' ').trim().replaceAll(/\\s+/g, '-')\n}\n\nfunction spawnWorkers<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, count: number): WorkerDescriptor<ThreadType>[] {\n return createArray(count).map(\n (): WorkerDescriptor<ThreadType> => ({\n init: spawnWorker(),\n runningTasks: [],\n }),\n )\n}\n\n/**\n * Thread pool managing a set of worker threads.\n * Use it to queue tasks that are run on those threads with limited\n * concurrency.\n */\nexport interface Pool<ThreadType extends Thread> {\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Promise will be rejected if any task fails.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n completed(allowResolvingImmediately?: boolean): Promise<any>\n\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Failing tasks will not cause the promise to be rejected.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n settled(allowResolvingImmediately?: boolean): Promise<Error[]>\n\n /**\n * Returns an observable that yields pool events.\n */\n events(): Observable<PoolEvent<ThreadType>>\n\n /**\n * Queue a task and return a promise that resolves once the task has been dequeued,\n * started and finished.\n *\n * @param task An async function that takes a thread instance and invokes it.\n */\n queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return>\n\n /**\n * Terminate all pool threads.\n *\n * @param force Set to `true` to kill the thread even if it cannot be stopped gracefully.\n */\n terminate(force?: boolean): Promise<void>\n}\n\ninterface PoolOptions {\n /** Maximum no. of tasks to run on one worker thread at a time. Defaults to one. */\n concurrency?: number\n\n /** Maximum no. of jobs to be queued for execution before throwing an error. */\n maxQueuedJobs?: number\n\n /** Gives that pool a name to be used for debug logging, letting you distinguish between log output of different pools. */\n name?: string\n\n /** No. of worker threads to spawn and to be managed by the pool. */\n size?: number\n}\n\nclass WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {\n static EventType = PoolEventType\n\n private readonly debug: DebugLogger.Debugger\n private readonly eventObservable: Observable<PoolEvent<ThreadType>>\n private readonly options: PoolOptions\n private readonly workers: WorkerDescriptor<ThreadType>[]\n\n private readonly eventSubject = new Subject<PoolEvent<ThreadType>>()\n private initErrors: Error[] = []\n private isClosing = false\n private nextTaskID = 1\n private taskQueue: QueuedTask<ThreadType, any>[] = []\n\n constructor(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n const options: PoolOptions = typeof optionsOrSize === 'number' ? { size: optionsOrSize } : optionsOrSize || {}\n\n const { size = defaultPoolSize } = options\n\n this.debug = DebugLogger(`threads:pool:${slugify(options.name ?? String(nextPoolID++))}`)\n this.options = options\n this.workers = spawnWorkers(spawnWorker, size)\n\n this.eventObservable = multicast(Observable.from(this.eventSubject))\n\n const debug = this.debug\n const workers = this.workers\n void (async () => {\n try {\n await Promise.all(workers.map(worker => worker.init))\n this.eventSubject.next({\n size: workers.length,\n type: PoolEventType.initialized,\n })\n } catch (error) {\n const initError = error instanceof Error ? error : new Error(String(error))\n debug('Error while initializing pool worker:', initError)\n this.eventSubject.error(initError)\n this.initErrors.push(initError)\n }\n })()\n }\n\n private findIdlingWorker(): WorkerDescriptor<ThreadType> | undefined {\n const { concurrency = 1 } = this.options\n return this.workers.find(worker => worker.runningTasks.length < concurrency)\n }\n\n private async runPoolTask(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const workerID = this.workers.indexOf(worker) + 1\n\n this.debug(`Running task #${task.id} on worker #${workerID}...`)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskStart,\n workerID,\n })\n\n try {\n const returnValue = await task.run(await worker.init)\n\n this.debug(`Task #${task.id} completed successfully`)\n this.eventSubject.next({\n returnValue,\n taskID: task.id,\n type: PoolEventType.taskCompleted,\n workerID,\n })\n } catch (ex) {\n const error = ex as Error\n this.debug(`Task #${task.id} failed`)\n this.eventSubject.next({\n error,\n taskID: task.id,\n type: PoolEventType.taskFailed,\n workerID,\n })\n }\n }\n\n private run(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const runPromise = (async () => {\n const removeTaskFromWorkersRunningTasks = () => {\n worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise)\n }\n\n // Defer task execution by one tick to give handlers time to subscribe\n await delay(0)\n\n try {\n await this.runPoolTask(worker, task)\n } finally {\n removeTaskFromWorkersRunningTasks()\n\n if (!this.isClosing) {\n this.scheduleWork()\n }\n }\n })()\n\n worker.runningTasks.push(runPromise)\n }\n\n private scheduleWork() {\n this.debug('Attempt de-queueing a task in order to run it...')\n\n const availableWorker = this.findIdlingWorker()\n if (!availableWorker) return\n\n const nextTask = this.taskQueue.shift()\n if (!nextTask) {\n this.debug('Task queue is empty')\n this.eventSubject.next({ type: PoolEventType.taskQueueDrained })\n return\n }\n\n this.run(availableWorker, nextTask)\n }\n\n private taskCompletion(taskID: number) {\n return new Promise<any>((resolve, reject) => {\n const eventSubscription = this.events().subscribe((event) => {\n if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n resolve(event.returnValue)\n } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n reject(event.error)\n } else if (event.type === PoolEventType.terminated) {\n eventSubscription.unsubscribe()\n reject(new Error('Pool has been terminated before task was run.'))\n }\n })\n })\n }\n\n async settled(allowResolvingImmediately = false): Promise<Error[]> {\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n if (allowResolvingImmediately && this.taskQueue.length === 0) {\n await Promise.allSettled(flatMap(this.workers, worker => worker.runningTasks))\n return []\n }\n\n const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks)\n const taskFailures: Error[] = []\n\n const failureSubscription = this.eventObservable.subscribe((event) => {\n if (event.type === PoolEventType.taskFailed) {\n taskFailures.push(event.error)\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type !== PoolEventType.taskQueueDrained) {\n return\n }\n\n subscription.unsubscribe()\n resolve(void 0)\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n await Promise.allSettled(getCurrentlyRunningTasks())\n failureSubscription.unsubscribe()\n\n return taskFailures\n }\n\n async completed(allowResolvingImmediately = false) {\n const settlementPromise = this.settled(allowResolvingImmediately)\n\n const earlyExitPromise = new Promise<Error[]>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type === PoolEventType.taskQueueDrained) {\n subscription.unsubscribe()\n resolve(settlementPromise)\n } else if (event.type === PoolEventType.taskFailed) {\n subscription.unsubscribe()\n reject(event.error)\n }\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n const errors = await Promise.race([settlementPromise, earlyExitPromise])\n\n if (errors.length > 0) {\n throw errors[0]\n }\n }\n\n events() {\n return this.eventObservable\n }\n\n queue(taskFunction: TaskRunFunction<ThreadType, any>) {\n const { maxQueuedJobs = Infinity } = this.options\n\n if (this.isClosing) {\n throw new Error('Cannot schedule pool tasks after terminate() has been called.')\n }\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n\n const taskID = this.nextTaskID++\n const taskCompletion = this.taskCompletion(taskID)\n\n void (async () => {\n try {\n await taskCompletion\n } catch (error) {\n // Prevent unhandled rejections here as we assume the user will use\n // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors\n this.debug(`Task #${taskID} errored:`, error)\n }\n })()\n\n const task: QueuedTask<ThreadType, any> = {\n cancel: () => {\n if (!this.taskQueue.includes(task)) return\n this.taskQueue = this.taskQueue.filter(someTask => someTask !== task)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskCanceled,\n })\n },\n id: taskID,\n run: taskFunction,\n then: taskCompletion.then.bind(taskCompletion),\n }\n\n if (this.taskQueue.length >= maxQueuedJobs) {\n throw new Error(\n 'Maximum number of pool tasks queued. Refusing to queue another one.\\n'\n + 'This usually happens for one of two reasons: We are either at peak '\n + \"workload right now or some tasks just won't finish, thus blocking the pool.\",\n )\n }\n\n this.debug(`Queueing task #${task.id}...`)\n this.taskQueue.push(task)\n\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskQueued,\n })\n\n this.scheduleWork()\n return task\n }\n\n async terminate(force?: boolean) {\n this.isClosing = true\n if (force !== true) {\n await this.completed(true)\n }\n this.eventSubject.next({\n remainingQueue: [...this.taskQueue],\n type: PoolEventType.terminated,\n })\n this.eventSubject.complete()\n await Promise.all(this.workers.map(async worker => Thread.terminate(await worker.init)))\n }\n}\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nfunction PoolConstructor<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n // The function exists only so we don't need to use `new` to create a pool (we still can, though).\n // If the Pool is a class or not is an implementation detail that should not concern the user.\n return new WorkerPool(spawnWorker, optionsOrSize)\n}\n\n;(PoolConstructor as any).EventType = PoolEventType\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nexport const Pool = PoolConstructor as typeof PoolConstructor & { EventType: typeof PoolEventType }\n\nexport type { PoolEvent, QueuedTask } from './pool-types.ts'\nexport { PoolEventType } from './pool-types.ts'\nexport { Thread } from './thread.ts'\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable unicorn/text-encoding-identifier-case */\n/// <reference types=\"node\" />\n\nimport { cpus } from 'node:os'\nimport path from 'node:path'\nimport { cwd } from 'node:process'\nimport { isMainThread, Worker as NativeWorker } from 'node:worker_threads'\n\nimport type {\n ImplementationExport, ThreadsWorkerOptions, WorkerImplementation,\n} from '../types/master.ts'\n\n/** Default thread pool size based on the number of CPU cores. */\nexport const defaultPoolSize = cpus().length\n\n/** Options for optional process-signal integration with the worker registry. */\nexport interface WorkerSignalHandlersOptions {\n /**\n * When true, call `process.exit(0|1)` after workers terminate on a signal.\n * Default `false` \u2014 the host owns process lifetime.\n */\n exitProcess?: boolean\n /**\n * Signals to listen for. Defaults to `SIGINT` and `SIGTERM`.\n */\n signals?: NodeJS.Signals[]\n}\n\ntype SignalHandler = () => void\n\ninterface WorkerRegistry {\n allWorkers: NativeWorker[]\n /** Active signal \u2192 handler map for the optional opt-in integration. */\n signalHandlers: Map<NodeJS.Signals, SignalHandler>\n}\n\nfunction resolveScriptPath(scriptPath: string, baseURL?: string) {\n const makeAbsolute = (filePath: string) => {\n return path.isAbsolute(filePath) ? filePath : path.join(baseURL ?? cwd(), filePath)\n }\n\n const absolutePath = makeAbsolute(scriptPath)\n return absolutePath\n}\n\n/**\n * Shared registry so opt-in signal handlers can terminate every worker\n * created through this implementation without owning process lifetime.\n */\nconst registry: WorkerRegistry = {\n allWorkers: [],\n signalHandlers: new Map(),\n}\n\nasync function terminateAllWorkers(): Promise<void> {\n const workers = [...registry.allWorkers]\n registry.allWorkers = []\n await Promise.all(workers.map(worker => worker.terminate()))\n}\n\nfunction initWorkerThreadsWorker(): ImplementationExport {\n class Worker extends NativeWorker {\n private mappedEventListeners: WeakMap<EventListener, EventListener>\n\n constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource: boolean }) {\n const resolvedScriptPath = options?.fromSource === true ? null : resolveScriptPath(scriptPath, options?._baseURL)\n if (resolvedScriptPath === null) {\n // `options.fromSource` is true\n const sourceCode = scriptPath\n super(sourceCode, { ...options, eval: true })\n } else {\n super(resolvedScriptPath, options)\n }\n\n this.mappedEventListeners = new WeakMap()\n registry.allWorkers.push(this)\n this.once('exit', () => {\n registry.allWorkers = registry.allWorkers.filter(worker => worker !== this)\n })\n }\n\n addEventListener(eventName: string, rawListener: EventListener) {\n const listener = (message: any) => {\n rawListener({ data: message } as any)\n }\n this.mappedEventListeners.set(rawListener, listener)\n this.on(eventName, listener)\n }\n\n removeEventListener(eventName: string, rawListener: EventListener) {\n const listener = this.mappedEventListeners.get(rawListener) || rawListener\n this.off(eventName, listener)\n }\n }\n\n class BlobWorker extends Worker {\n constructor(blob: Uint8Array, options?: ThreadsWorkerOptions) {\n super(Buffer.from(blob).toString('utf-8'), { ...options, fromSource: true })\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation {\n return new Worker(source, { ...options, fromSource: true }) as any\n }\n }\n\n return {\n blob: BlobWorker as any,\n default: Worker as any,\n }\n}\n\nlet implementation: ImplementationExport\n\n/**\n * Get the Node.js-specific worker implementation using `worker_threads`, lazily initializing it on first call.\n * @returns The platform-specific worker implementation export.\n */\nexport function getWorkerImplementation(): ImplementationExport {\n if (implementation === undefined) {\n implementation = initWorkerThreadsWorker()\n }\n return implementation\n}\n\n/**\n * Check whether the current code is running inside a Node.js worker thread.\n * @returns True if running in a worker thread (not the main thread), false otherwise.\n */\nexport function isWorkerRuntime() {\n return !isMainThread\n}\n\n/**\n * Opt-in: terminate tracked workers when the process receives the given signals.\n *\n * Libraries must not own host process lifetime. Call this only from an\n * application entrypoint that wants automatic worker cleanup on signal.\n * Returns a disposer that removes the handlers (idempotent).\n *\n * By default does **not** call `process.exit` \u2014 the host chooses exit status\n * and may complete async cleanup after the disposer or after the signal.\n */\nexport function installWorkerSignalHandlers(\n options: WorkerSignalHandlersOptions = {},\n): () => void {\n // Ensure the registry is initialized even if no Worker has been constructed yet.\n getWorkerImplementation()\n\n const signals: NodeJS.Signals[] = options.signals ?? ['SIGINT', 'SIGTERM']\n const exitProcess = options.exitProcess === true\n\n // Idempotent: replace any prior installation for the same process.\n uninstallWorkerSignalHandlers()\n\n for (const signal of signals) {\n const handler: SignalHandler = () => {\n void (async () => {\n try {\n await terminateAllWorkers()\n if (exitProcess) process.exit(0)\n } catch {\n if (exitProcess) process.exit(1)\n }\n })()\n }\n process.on(signal, handler)\n registry.signalHandlers.set(signal, handler)\n }\n\n return uninstallWorkerSignalHandlers\n}\n\n/**\n * Remove handlers installed by {@link installWorkerSignalHandlers}.\n * Safe to call when none are installed.\n */\nexport function uninstallWorkerSignalHandlers(): void {\n for (const [signal, handler] of registry.signalHandlers) {\n process.off(signal, handler)\n }\n registry.signalHandlers.clear()\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nimport type { Thread } from './thread.ts'\n\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport enum PoolEventType {\n /** All workers in the pool have initialized. */\n initialized = 'initialized',\n /** A queued task was canceled before execution. */\n taskCanceled = 'taskCanceled',\n /** A task completed successfully. */\n taskCompleted = 'taskCompleted',\n /** A task failed during execution. */\n taskFailed = 'taskFailed',\n /** A task was added to the queue. */\n taskQueued = 'taskQueued',\n /** The pool has no remaining queued tasks. */\n taskQueueDrained = 'taskQueueDrained',\n /** A worker started executing a task. */\n taskStart = 'taskStart',\n /** The pool and its workers were terminated. */\n terminated = 'terminated',\n}\n\n/** A function that runs a task on a worker thread and returns a promise of the result. */\nexport type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>\n\n/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */\nexport type PoolEvent<ThreadType extends Thread>\n = | {\n type: PoolEventType.initialized\n size: number\n }\n | {\n type: PoolEventType.taskQueued\n taskID: number\n }\n | {\n type: PoolEventType.taskQueueDrained\n }\n | {\n type: PoolEventType.taskStart\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskCompleted\n returnValue: any\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskFailed\n error: Error\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskCanceled\n taskID: number\n }\n | {\n type: PoolEventType.terminated\n remainingQueue: QueuedTask<ThreadType, any>[]\n }\n\n/** Descriptor for a worker in a pool, tracking its initialization and running tasks. */\nexport interface WorkerDescriptor<ThreadType extends Thread> {\n /** Promise resolving to the initialized thread. */\n init: Promise<ThreadType>\n /** Tasks currently executing on the worker. */\n runningTasks: Promise<any>[]\n}\n\n/**\n * Task that has been `pool.queued()`-ed.\n */\nexport interface QueuedTask<ThreadType extends Thread, Return> {\n /** @private */\n id: number\n\n /** @private */\n run: TaskRunFunction<ThreadType, Return>\n\n /**\n * Queued tasks can be cancelled until the pool starts running them on a worker thread.\n */\n cancel(): void\n\n /**\n * `QueuedTask` is thenable, so you can `await` it.\n * Resolves when the task has successfully been executed. Rejects if the task fails.\n */\n then: Promise<Return>['then']\n}\n", "/** Symbol key for accessing a thread's error observable. */\nexport const $errors = Symbol('thread.errors')\n/** Symbol key for accessing a thread's event observable. */\nexport const $events = Symbol('thread.events')\n/** Symbol key for accessing a thread's terminate function. */\nexport const $terminate = Symbol('thread.terminate')\n/** Symbol key for marking an object as a transferable descriptor. */\nexport const $transferable = Symbol('thread.transferable')\n/** Symbol key for accessing the underlying worker instance of a thread. */\nexport const $worker = Symbol('thread.worker')\n", "import type { Observable } from 'observable-fns'\n\nimport {\n $errors, $events, $terminate,\n} from '../symbols.ts'\nimport type {\n PrivateThreadProps, Thread as ThreadType, WorkerEvent,\n} from '../types/master.ts'\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\nfunction readPrivateThreadProp<K extends keyof PrivateThreadProps>(\n thread: ThreadType,\n key: K,\n): PrivateThreadProps[K] | undefined {\n return Reflect.get(thread, key)\n}\n\n/** Re-exported Thread type from the master types module. */\nexport type Thread = ThreadType\n\n/** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */\nexport const Thread = {\n /** Return an observable that can be used to subscribe to all errors happening in the thread. */\n errors: <ThreadT extends ThreadType>(thread: ThreadT): Observable<Error> =>\n readPrivateThreadProp(thread, $errors) ?? fail('Error observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */\n events: <ThreadT extends ThreadType>(thread: ThreadT): Observable<WorkerEvent> =>\n readPrivateThreadProp(thread, $events) ?? fail('Events observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Terminate a thread. Remember to terminate every thread when you are done using it. */\n terminate: <ThreadT extends ThreadType>(thread: ThreadT) =>\n readPrivateThreadProp(thread, $terminate)?.() ?? fail('Terminate function not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n}\n"],
5
- "mappings": ";AAUA,OAAO,iBAAiB;AACxB;AAAA,EACE;AAAA,EAAW;AAAA,EAAY;AAAA,OAClB;;;ACTP,SAAS,YAAY;AAUd,IAAM,kBAAkB,KAAK,EAAE;;;ACT/B,IAAK,gBAAL,kBAAKA,mBAAL;AAEL,EAAAA,eAAA,iBAAc;AAEd,EAAAA,eAAA,kBAAe;AAEf,EAAAA,eAAA,mBAAgB;AAEhB,EAAAA,eAAA,gBAAa;AAEb,EAAAA,eAAA,gBAAa;AAEb,EAAAA,eAAA,sBAAmB;AAEnB,EAAAA,eAAA,eAAY;AAEZ,EAAAA,eAAA,gBAAa;AAhBH,SAAAA;AAAA,GAAA;;;ACJL,IAAM,UAAU,uBAAO,eAAe;AAEtC,IAAM,UAAU,uBAAO,eAAe;AAEtC,IAAM,aAAa,uBAAO,kBAAkB;;;ACInD,SAAS,KAAK,SAAwB;AACpC,QAAM,IAAI,MAAM,OAAO;AACzB;AAEA,SAAS,sBACP,QACA,KACmC;AACnC,SAAO,QAAQ,IAAI,QAAQ,GAAG;AAChC;AAMO,IAAM,SAAS;AAAA;AAAA,EAEpB,QAAQ,CAA6B,WACnC,sB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SAAK,UAAU,KAAK,IAAI;AAExB,SAAK,aAAa,KAAK;AAAA,MACrB,QAAQ,KAAK;AAAA,MACb;AAAA,IACF,CAAC;AAED,SAAK,aAAa;AAClB,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,UAAU,OAAiB;AAC/B,SAAK,YAAY;AACjB,QAAI,UAAU,MAAM;AAClB,YAAM,KAAK,UAAU,IAAI;AAAA,IAC3B;AACA,SAAK,aAAa,KAAK;AAAA,MACrB,gBAAgB,CAAC,GAAG,KAAK,SAAS;AAAA,MAClC;AAAA,IACF,CAAC;AACD,SAAK,aAAa,SAAS;AAC3B,UAAM,QAAQ,IAAI,KAAK,QAAQ,IAAI,OAAM,WAAU,OAAO,UAAU,MAAM,OAAO,IAAI,CAAC,CAAC;AAAA,EACzF;AACF;AAKA,SAAS,gBAA2C,aAAwC,eAAsC;AAGhI,SAAO,IAAI,WAAW,aAAa,aAAa;AAClD;AAEE,gBAAwB,YAAY;AAK/B,IAAM,OAAO;",
6
- "names": ["PoolEventType"]
4
+ "sourcesContent": ["/* eslint-disable import-x/export */\n/* eslint-disable unicorn/no-thenable */\n\n/* eslint-disable @typescript-eslint/member-ordering */\n/* eslint-disable unicorn/no-array-reduce */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-namespace */\n\n/// <reference lib=\"esnext\" />\n\nimport DebugLogger from 'debug'\nimport {\n multicast, Observable, Subject,\n} from 'observable-fns'\n\nimport { defaultPoolSize } from './implementation.node.ts'\nimport type {\n PoolEvent, QueuedTask, TaskRunFunction, WorkerDescriptor,\n} from './pool-types.ts'\nimport { PoolEventType } from './pool-types.ts'\nimport { Thread } from './thread.ts'\n\n/** Types and constants associated with Node.js worker pools. */\nexport declare namespace Pool {\n type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType>\n type EventType = PoolEventType\n}\n\nlet nextPoolID = 1\n\nfunction createArray(size: number): number[] {\n const array: number[] = []\n for (let index = 0; index < size; index++) {\n array.push(index)\n }\n return array\n}\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction flatMap<In, Out>(array: In[], mapper: (element: In) => Out[]): Out[] {\n return array.reduce<Out[]>((flattened, element) => [...flattened, ...mapper(element)], [])\n}\n\nfunction slugify(text: string) {\n return text.replaceAll(/\\W/g, ' ').trim().replaceAll(/\\s+/g, '-')\n}\n\nfunction spawnWorkers<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, count: number): WorkerDescriptor<ThreadType>[] {\n return createArray(count).map(\n (): WorkerDescriptor<ThreadType> => ({\n init: spawnWorker(),\n runningTasks: [],\n }),\n )\n}\n\n/**\n * Thread pool managing a set of worker threads.\n * Use it to queue tasks that are run on those threads with limited\n * concurrency.\n */\nexport interface Pool<ThreadType extends Thread> {\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Promise will be rejected if any task fails.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n completed(allowResolvingImmediately?: boolean): Promise<any>\n\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Failing tasks will not cause the promise to be rejected.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n settled(allowResolvingImmediately?: boolean): Promise<Error[]>\n\n /**\n * Returns an observable that yields pool events.\n */\n events(): Observable<PoolEvent<ThreadType>>\n\n /**\n * Queue a task and return a promise that resolves once the task has been dequeued,\n * started and finished.\n *\n * @param task An async function that takes a thread instance and invokes it.\n */\n queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return>\n\n /**\n * Terminate all pool threads.\n *\n * @param force Set to `true` to kill the thread even if it cannot be stopped gracefully.\n */\n terminate(force?: boolean): Promise<void>\n}\n\ninterface PoolOptions {\n /** Maximum no. of tasks to run on one worker thread at a time. Defaults to one. */\n concurrency?: number\n\n /** Maximum no. of jobs to be queued for execution before throwing an error. */\n maxQueuedJobs?: number\n\n /** Gives that pool a name to be used for debug logging, letting you distinguish between log output of different pools. */\n name?: string\n\n /** No. of worker threads to spawn and to be managed by the pool. */\n size?: number\n}\n\nclass WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {\n static EventType = PoolEventType\n\n private readonly debug: DebugLogger.Debugger\n private readonly eventObservable: Observable<PoolEvent<ThreadType>>\n private readonly options: PoolOptions\n private readonly workers: WorkerDescriptor<ThreadType>[]\n\n private readonly eventSubject = new Subject<PoolEvent<ThreadType>>()\n private initErrors: Error[] = []\n private isClosing = false\n private nextTaskID = 1\n private taskQueue: QueuedTask<ThreadType, any>[] = []\n\n constructor(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n const options: PoolOptions = typeof optionsOrSize === 'number' ? { size: optionsOrSize } : optionsOrSize || {}\n\n const { size = defaultPoolSize } = options\n\n this.debug = DebugLogger(`threads:pool:${slugify(options.name ?? String(nextPoolID++))}`)\n this.options = options\n this.workers = spawnWorkers(spawnWorker, size)\n\n this.eventObservable = multicast(Observable.from(this.eventSubject))\n\n const debug = this.debug\n const workers = this.workers\n void (async () => {\n try {\n await Promise.all(workers.map(worker => worker.init))\n this.eventSubject.next({\n size: workers.length,\n type: PoolEventType.initialized,\n })\n } catch (error) {\n const initError = error instanceof Error ? error : new Error(String(error))\n debug('Error while initializing pool worker:', initError)\n this.eventSubject.error(initError)\n this.initErrors.push(initError)\n }\n })()\n }\n\n private findIdlingWorker(): WorkerDescriptor<ThreadType> | undefined {\n const { concurrency = 1 } = this.options\n return this.workers.find(worker => worker.runningTasks.length < concurrency)\n }\n\n private async runPoolTask(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const workerID = this.workers.indexOf(worker) + 1\n\n this.debug(`Running task #${task.id} on worker #${workerID}...`)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskStart,\n workerID,\n })\n\n try {\n const returnValue = await task.run(await worker.init)\n\n this.debug(`Task #${task.id} completed successfully`)\n this.eventSubject.next({\n returnValue,\n taskID: task.id,\n type: PoolEventType.taskCompleted,\n workerID,\n })\n } catch (ex) {\n const error = ex as Error\n this.debug(`Task #${task.id} failed`)\n this.eventSubject.next({\n error,\n taskID: task.id,\n type: PoolEventType.taskFailed,\n workerID,\n })\n }\n }\n\n private run(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const runPromise = (async () => {\n const removeTaskFromWorkersRunningTasks = () => {\n worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise)\n }\n\n // Defer task execution by one tick to give handlers time to subscribe\n await delay(0)\n\n try {\n await this.runPoolTask(worker, task)\n } finally {\n removeTaskFromWorkersRunningTasks()\n\n if (!this.isClosing) {\n this.scheduleWork()\n }\n }\n })()\n\n worker.runningTasks.push(runPromise)\n }\n\n private scheduleWork() {\n this.debug('Attempt de-queueing a task in order to run it...')\n\n const availableWorker = this.findIdlingWorker()\n if (!availableWorker) return\n\n const nextTask = this.taskQueue.shift()\n if (!nextTask) {\n this.debug('Task queue is empty')\n this.eventSubject.next({ type: PoolEventType.taskQueueDrained })\n return\n }\n\n this.run(availableWorker, nextTask)\n }\n\n private taskCompletion(taskID: number) {\n return new Promise<any>((resolve, reject) => {\n const eventSubscription = this.events().subscribe((event) => {\n if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n resolve(event.returnValue)\n } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n reject(event.error)\n } else if (event.type === PoolEventType.terminated) {\n eventSubscription.unsubscribe()\n reject(new Error('Pool has been terminated before task was run.'))\n }\n })\n })\n }\n\n async settled(allowResolvingImmediately = false): Promise<Error[]> {\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n if (allowResolvingImmediately && this.taskQueue.length === 0) {\n await Promise.allSettled(flatMap(this.workers, worker => worker.runningTasks))\n return []\n }\n\n const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks)\n const taskFailures: Error[] = []\n\n const failureSubscription = this.eventObservable.subscribe((event) => {\n if (event.type === PoolEventType.taskFailed) {\n taskFailures.push(event.error)\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type !== PoolEventType.taskQueueDrained) {\n return\n }\n\n subscription.unsubscribe()\n resolve(void 0)\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n await Promise.allSettled(getCurrentlyRunningTasks())\n failureSubscription.unsubscribe()\n\n return taskFailures\n }\n\n async completed(allowResolvingImmediately = false) {\n const settlementPromise = this.settled(allowResolvingImmediately)\n\n const earlyExitPromise = new Promise<Error[]>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type === PoolEventType.taskQueueDrained) {\n subscription.unsubscribe()\n resolve(settlementPromise)\n } else if (event.type === PoolEventType.taskFailed) {\n subscription.unsubscribe()\n reject(event.error)\n }\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n const errors = await Promise.race([settlementPromise, earlyExitPromise])\n\n if (errors.length > 0) {\n throw errors[0]\n }\n }\n\n events() {\n return this.eventObservable\n }\n\n queue(taskFunction: TaskRunFunction<ThreadType, any>) {\n const { maxQueuedJobs = Infinity } = this.options\n\n if (this.isClosing) {\n throw new Error('Cannot schedule pool tasks after terminate() has been called.')\n }\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n\n const taskID = this.nextTaskID++\n const taskCompletion = this.taskCompletion(taskID)\n\n void (async () => {\n try {\n await taskCompletion\n } catch (error) {\n // Prevent unhandled rejections here as we assume the user will use\n // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors\n this.debug(`Task #${taskID} errored:`, error)\n }\n })()\n\n const task: QueuedTask<ThreadType, any> = {\n cancel: () => {\n if (!this.taskQueue.includes(task)) return\n this.taskQueue = this.taskQueue.filter(someTask => someTask !== task)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskCanceled,\n })\n },\n id: taskID,\n run: taskFunction,\n then: taskCompletion.then.bind(taskCompletion),\n }\n\n if (this.taskQueue.length >= maxQueuedJobs) {\n throw new Error(\n 'Maximum number of pool tasks queued. Refusing to queue another one.\\n'\n + 'This usually happens for one of two reasons: We are either at peak '\n + \"workload right now or some tasks just won't finish, thus blocking the pool.\",\n )\n }\n\n this.debug(`Queueing task #${task.id}...`)\n this.taskQueue.push(task)\n\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskQueued,\n })\n\n this.scheduleWork()\n return task\n }\n\n async terminate(force?: boolean) {\n this.isClosing = true\n if (force !== true) {\n await this.completed(true)\n }\n this.eventSubject.next({\n remainingQueue: [...this.taskQueue],\n type: PoolEventType.terminated,\n })\n this.eventSubject.complete()\n await Promise.all(this.workers.map(async worker => Thread.terminate(await worker.init)))\n }\n}\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nfunction PoolConstructor<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n // The function exists only so we don't need to use `new` to create a pool (we still can, though).\n // If the Pool is a class or not is an implementation detail that should not concern the user.\n return new WorkerPool(spawnWorker, optionsOrSize)\n}\n\n;(PoolConstructor as any).EventType = PoolEventType\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nexport const Pool = PoolConstructor as typeof PoolConstructor & { EventType: typeof PoolEventType }\n\nexport type { PoolEvent, QueuedTask } from './pool-types.ts'\nexport { PoolEventType } from './pool-types.ts'\nexport { Thread } from './thread.ts'\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable unicorn/text-encoding-identifier-case */\n/// <reference types=\"node\" />\n\nimport { cpus } from 'node:os'\nimport path from 'node:path'\nimport { cwd } from 'node:process'\nimport { isMainThread, Worker as NativeWorker } from 'node:worker_threads'\n\nimport type {\n ImplementationExport, ThreadsWorkerOptions, WorkerImplementation,\n} from '../types/master.ts'\n\n/** Default thread pool size based on the number of CPU cores. */\nexport const defaultPoolSize = cpus().length\n\n/** Options for optional process-signal integration with the worker registry. */\nexport interface WorkerSignalHandlersOptions {\n /**\n * When true, call `process.exit(0|1)` after workers terminate on a signal.\n * Default `false` \u2014 the host owns process lifetime.\n */\n exitProcess?: boolean\n /**\n * Signals to listen for. Defaults to `SIGINT` and `SIGTERM`.\n */\n signals?: NodeJS.Signals[]\n}\n\ntype SignalHandler = () => void\n\ninterface WorkerRegistry {\n allWorkers: NativeWorker[]\n /** Active signal \u2192 handler map for the optional opt-in integration. */\n signalHandlers: Map<NodeJS.Signals, SignalHandler>\n}\n\nfunction resolveScriptPath(scriptPath: string, baseURL?: string) {\n const makeAbsolute = (filePath: string) => {\n return path.isAbsolute(filePath) ? filePath : path.join(baseURL ?? cwd(), filePath)\n }\n\n const absolutePath = makeAbsolute(scriptPath)\n return absolutePath\n}\n\n/**\n * Shared registry so opt-in signal handlers can terminate every worker\n * created through this implementation without owning process lifetime.\n */\nconst registry: WorkerRegistry = {\n allWorkers: [],\n signalHandlers: new Map(),\n}\n\nasync function terminateAllWorkers(): Promise<void> {\n const workers = [...registry.allWorkers]\n registry.allWorkers = []\n await Promise.all(workers.map(worker => worker.terminate()))\n}\n\nfunction initWorkerThreadsWorker(): ImplementationExport {\n class Worker extends NativeWorker {\n private mappedEventListeners: WeakMap<EventListener, EventListener>\n\n constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource: boolean }) {\n const resolvedScriptPath = options?.fromSource === true ? null : resolveScriptPath(scriptPath, options?._baseURL)\n if (resolvedScriptPath === null) {\n // `options.fromSource` is true\n const sourceCode = scriptPath\n super(sourceCode, { ...options, eval: true })\n } else {\n super(resolvedScriptPath, options)\n }\n\n this.mappedEventListeners = new WeakMap()\n registry.allWorkers.push(this)\n this.once('exit', () => {\n registry.allWorkers = registry.allWorkers.filter(worker => worker !== this)\n })\n }\n\n addEventListener(eventName: string, rawListener: EventListener) {\n const listener = (message: any) => {\n rawListener({ data: message } as any)\n }\n this.mappedEventListeners.set(rawListener, listener)\n this.on(eventName, listener)\n }\n\n removeEventListener(eventName: string, rawListener: EventListener) {\n const listener = this.mappedEventListeners.get(rawListener) || rawListener\n this.off(eventName, listener)\n }\n }\n\n class BlobWorker extends Worker {\n constructor(blob: Uint8Array, options?: ThreadsWorkerOptions) {\n super(Buffer.from(blob).toString('utf-8'), { ...options, fromSource: true })\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation {\n return new Worker(source, { ...options, fromSource: true }) as any\n }\n }\n\n return {\n blob: BlobWorker as any,\n default: Worker as any,\n }\n}\n\nlet implementation: ImplementationExport\n\n/**\n * Get the Node.js-specific worker implementation using `worker_threads`, lazily initializing it on first call.\n * @returns The platform-specific worker implementation export.\n */\nexport function getWorkerImplementation(): ImplementationExport {\n if (implementation === undefined) {\n implementation = initWorkerThreadsWorker()\n }\n return implementation\n}\n\n/**\n * Check whether the current code is running inside a Node.js worker thread.\n * @returns True if running in a worker thread (not the main thread), false otherwise.\n */\nexport function isWorkerRuntime() {\n return !isMainThread\n}\n\n/**\n * Opt-in: terminate tracked workers when the process receives the given signals.\n *\n * Libraries must not own host process lifetime. Call this only from an\n * application entrypoint that wants automatic worker cleanup on signal.\n * Returns a disposer that removes the handlers (idempotent).\n *\n * By default does **not** call `process.exit` \u2014 the host chooses exit status\n * and may complete async cleanup after the disposer or after the signal.\n */\nexport function installWorkerSignalHandlers(\n options: WorkerSignalHandlersOptions = {},\n): () => void {\n // Ensure the registry is initialized even if no Worker has been constructed yet.\n getWorkerImplementation()\n\n const signals: NodeJS.Signals[] = options.signals ?? ['SIGINT', 'SIGTERM']\n const exitProcess = options.exitProcess === true\n\n // Idempotent: replace any prior installation for the same process.\n uninstallWorkerSignalHandlers()\n\n for (const signal of signals) {\n const handler: SignalHandler = () => {\n void (async () => {\n try {\n await terminateAllWorkers()\n if (exitProcess) process.exit(0)\n } catch {\n if (exitProcess) process.exit(1)\n }\n })()\n }\n process.on(signal, handler)\n registry.signalHandlers.set(signal, handler)\n }\n\n return uninstallWorkerSignalHandlers\n}\n\n/**\n * Remove handlers installed by {@link installWorkerSignalHandlers}.\n * Safe to call when none are installed.\n */\nexport function uninstallWorkerSignalHandlers(): void {\n for (const [signal, handler] of registry.signalHandlers) {\n process.off(signal, handler)\n }\n registry.signalHandlers.clear()\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nimport { Enum, type EnumValue } from '@ariestools/sdk/enum'\n\nimport type { Thread } from './thread.ts'\n\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport const PoolEventType = Enum({\n /** All workers in the pool have initialized. */\n initialized: 'initialized',\n /** A queued task was canceled before execution. */\n taskCanceled: 'taskCanceled',\n /** A task completed successfully. */\n taskCompleted: 'taskCompleted',\n /** A task failed during execution. */\n taskFailed: 'taskFailed',\n /** A task was added to the queue. */\n taskQueued: 'taskQueued',\n /** The pool has no remaining queued tasks. */\n taskQueueDrained: 'taskQueueDrained',\n /** A worker started executing a task. */\n taskStart: 'taskStart',\n /** The pool and its workers were terminated. */\n terminated: 'terminated',\n} as const)\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport type PoolEventType = EnumValue<typeof PoolEventType>\n\n/** A function that runs a task on a worker thread and returns a promise of the result. */\nexport type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>\n\n/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */\nexport type PoolEvent<ThreadType extends Thread>\n = | {\n type: (typeof PoolEventType)['initialized']\n size: number\n }\n | {\n type: (typeof PoolEventType)['taskQueued']\n taskID: number\n }\n | {\n type: (typeof PoolEventType)['taskQueueDrained']\n }\n | {\n type: (typeof PoolEventType)['taskStart']\n taskID: number\n workerID: number\n }\n | {\n type: (typeof PoolEventType)['taskCompleted']\n returnValue: any\n taskID: number\n workerID: number\n }\n | {\n type: (typeof PoolEventType)['taskFailed']\n error: Error\n taskID: number\n workerID: number\n }\n | {\n type: (typeof PoolEventType)['taskCanceled']\n taskID: number\n }\n | {\n type: (typeof PoolEventType)['terminated']\n remainingQueue: QueuedTask<ThreadType, any>[]\n }\n\n/** Descriptor for a worker in a pool, tracking its initialization and running tasks. */\nexport interface WorkerDescriptor<ThreadType extends Thread> {\n /** Promise resolving to the initialized thread. */\n init: Promise<ThreadType>\n /** Tasks currently executing on the worker. */\n runningTasks: Promise<any>[]\n}\n\n/**\n * Task that has been `pool.queued()`-ed.\n */\nexport interface QueuedTask<ThreadType extends Thread, Return> {\n /** @private */\n id: number\n\n /** @private */\n run: TaskRunFunction<ThreadType, Return>\n\n /**\n * Queued tasks can be cancelled until the pool starts running them on a worker thread.\n */\n cancel(): void\n\n /**\n * `QueuedTask` is thenable, so you can `await` it.\n * Resolves when the task has successfully been executed. Rejects if the task fails.\n */\n then: Promise<Return>['then']\n}\n", "/** Symbol key for accessing a thread's error observable. */\nexport const $errors = Symbol('thread.errors')\n/** Symbol key for accessing a thread's event observable. */\nexport const $events = Symbol('thread.events')\n/** Symbol key for accessing a thread's terminate function. */\nexport const $terminate = Symbol('thread.terminate')\n/** Symbol key for marking an object as a transferable descriptor. */\nexport const $transferable = Symbol('thread.transferable')\n/** Symbol key for accessing the underlying worker instance of a thread. */\nexport const $worker = Symbol('thread.worker')\n", "import type { Observable } from 'observable-fns'\n\nimport {\n $errors, $events, $terminate,\n} from '../symbols.ts'\nimport type {\n PrivateThreadProps, Thread as ThreadType, WorkerEvent,\n} from '../types/master.ts'\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\nfunction readPrivateThreadProp<K extends keyof PrivateThreadProps>(\n thread: ThreadType,\n key: K,\n): PrivateThreadProps[K] | undefined {\n return Reflect.get(thread, key)\n}\n\n/** Re-exported Thread type from the master types module. */\nexport type Thread = ThreadType\n\n/** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */\nexport const Thread = {\n /** Return an observable that can be used to subscribe to all errors happening in the thread. */\n errors: <ThreadT extends ThreadType>(thread: ThreadT): Observable<Error> =>\n readPrivateThreadProp(thread, $errors) ?? fail('Error observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */\n events: <ThreadT extends ThreadType>(thread: ThreadT): Observable<WorkerEvent> =>\n readPrivateThreadProp(thread, $events) ?? fail('Events observable not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n /** Terminate a thread. Remember to terminate every thread when you are done using it. */\n terminate: <ThreadT extends ThreadType>(thread: ThreadT) =>\n readPrivateThreadProp(thread, $terminate)?.() ?? fail('Terminate function not found. Make sure to pass a thread instance as returned by the spawn() promise.'),\n}\n"],
5
+ "mappings": ";AAUA,OAAO,iBAAiB;AACxB;AAAA,EACE;AAAA,EAAW;AAAA,EAAY;AAAA,OAClB;;;ACTP,SAAS,YAAY;AAUd,IAAM,kBAAkB,KAAK,EAAE;;;ACZtC,SAAS,YAA4B;AAK9B,IAAM,gBAAgB,KAAK;AAAA;AAAA,EAEhC,aAAa;AAAA;AAAA,EAEb,cAAc;AAAA;AAAA,EAEd,eAAe;AAAA;AAAA,EAEf,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,kBAAkB;AAAA;AAAA,EAElB,WAAW;AAAA;AAAA,EAEX,YAAY;AACd,CAAU;;;ACvBH,IAAM,UAAU,uBAAO,eAAe;AAEtC,IAAM,UAAU,uBAAO,eAAe;AAEtC,IAAM,aAAa,uBAAO,kBAAkB;;;ACInD,SAAS,KAAK,SAAwB;AACpC,QAAM,IAAI,MAAM,OAAO;AACzB;AAEA,SAAS,sBACP,QACA,KACmC;AACnC,SAAO,QAAQ,IAAI,QAAQ,GAAG;AAChC;AAMO,IAAM,SAAS;AAAA;AAAA,EAEpB,QAAQ,CAA6B,WACnC,sBAAsB,QAAQ,OAAO,KAAK,KAAK,qGAAqG;AAAA;AAAA,EAEtJ,QAAQ,CAA6B,WACnC,sBAAsB,QAAQ,OAAO,KAAK,KAAK,sGAAsG;AAAA;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KAAK,EAAE,KAAK;AACzC,SAAK,UAAU,KAAK,IAAI;AAExB,SAAK,aAAa,KAAK;AAAA,MACrB,QAAQ,KAAK;AAAA,MACb,MAAM,cAAc;AAAA,IACtB,CAAC;AAED,SAAK,aAAa;AAClB,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,UAAU,OAAiB;AAC/B,SAAK,YAAY;AACjB,QAAI,UAAU,MAAM;AAClB,YAAM,KAAK,UAAU,IAAI;AAAA,IAC3B;AACA,SAAK,aAAa,KAAK;AAAA,MACrB,gBAAgB,CAAC,GAAG,KAAK,SAAS;AAAA,MAClC,MAAM,cAAc;AAAA,IACtB,CAAC;AACD,SAAK,aAAa,SAAS;AAC3B,UAAM,QAAQ,IAAI,KAAK,QAAQ,IAAI,OAAM,WAAU,OAAO,UAAU,MAAM,OAAO,IAAI,CAAC,CAAC;AAAA,EACzF;AACF;AAKA,SAAS,gBAA2C,aAAwC,eAAsC;AAGhI,SAAO,IAAI,WAAW,aAAa,aAAa;AAClD;AAEE,gBAAwB,YAAY;AAK/B,IAAM,OAAO;",
6
+ "names": []
7
7
  }
@@ -1,53 +1,48 @@
1
+ import { Enum, type EnumValue } from '@ariestools/sdk/enum';
1
2
  import type { Thread } from './thread.ts';
2
3
  /** Pool event type. Specifies the type of each `PoolEvent`. */
3
- export declare enum PoolEventType {
4
- /** All workers in the pool have initialized. */
5
- initialized = "initialized",
6
- /** A queued task was canceled before execution. */
7
- taskCanceled = "taskCanceled",
8
- /** A task completed successfully. */
9
- taskCompleted = "taskCompleted",
10
- /** A task failed during execution. */
11
- taskFailed = "taskFailed",
12
- /** A task was added to the queue. */
13
- taskQueued = "taskQueued",
14
- /** The pool has no remaining queued tasks. */
15
- taskQueueDrained = "taskQueueDrained",
16
- /** A worker started executing a task. */
17
- taskStart = "taskStart",
18
- /** The pool and its workers were terminated. */
19
- terminated = "terminated"
20
- }
4
+ export declare const PoolEventType: Enum<{
5
+ initialized: 'initialized';
6
+ taskCanceled: 'taskCanceled';
7
+ taskCompleted: 'taskCompleted';
8
+ taskFailed: 'taskFailed';
9
+ taskQueued: 'taskQueued';
10
+ taskQueueDrained: 'taskQueueDrained';
11
+ taskStart: 'taskStart';
12
+ terminated: 'terminated';
13
+ }>;
14
+ /** Pool event type. Specifies the type of each `PoolEvent`. */
15
+ export type PoolEventType = EnumValue<typeof PoolEventType>;
21
16
  /** A function that runs a task on a worker thread and returns a promise of the result. */
22
17
  export type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>;
23
18
  /** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */
24
19
  export type PoolEvent<ThreadType extends Thread> = {
25
- type: PoolEventType.initialized;
20
+ type: (typeof PoolEventType)['initialized'];
26
21
  size: number;
27
22
  } | {
28
- type: PoolEventType.taskQueued;
23
+ type: (typeof PoolEventType)['taskQueued'];
29
24
  taskID: number;
30
25
  } | {
31
- type: PoolEventType.taskQueueDrained;
26
+ type: (typeof PoolEventType)['taskQueueDrained'];
32
27
  } | {
33
- type: PoolEventType.taskStart;
28
+ type: (typeof PoolEventType)['taskStart'];
34
29
  taskID: number;
35
30
  workerID: number;
36
31
  } | {
37
- type: PoolEventType.taskCompleted;
32
+ type: (typeof PoolEventType)['taskCompleted'];
38
33
  returnValue: any;
39
34
  taskID: number;
40
35
  workerID: number;
41
36
  } | {
42
- type: PoolEventType.taskFailed;
37
+ type: (typeof PoolEventType)['taskFailed'];
43
38
  error: Error;
44
39
  taskID: number;
45
40
  workerID: number;
46
41
  } | {
47
- type: PoolEventType.taskCanceled;
42
+ type: (typeof PoolEventType)['taskCanceled'];
48
43
  taskID: number;
49
44
  } | {
50
- type: PoolEventType.terminated;
45
+ type: (typeof PoolEventType)['terminated'];
51
46
  remainingQueue: QueuedTask<ThreadType, any>[];
52
47
  };
53
48
  /** Descriptor for a worker in a pool, tracking its initialization and running tasks. */
@@ -1 +1 @@
1
- {"version":3,"file":"pool-types.d.ts","sourceRoot":"","sources":["../../../src/master/pool-types.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,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA;IACzB,+CAA+C;IAC/C,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAA;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,UAAU,CAAC,UAAU,SAAS,MAAM,EAAE,MAAM;IAC3D,eAAe;IACf,EAAE,EAAE,MAAM,CAAA;IAEV,eAAe;IACf,GAAG,EAAE,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;IAExC;;OAEG;IACH,MAAM,IAAI,IAAI,CAAA;IAEd;;;OAGG;IACH,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;CAC9B"}
@@ -1,3 +1,4 @@
1
+ import { Enum, type EnumValue } from '@ariestools/sdk/enum';
1
2
  import type { Observable } from 'observable-fns';
2
3
  import type { ObservablePromise } from '../observable-promise.ts';
3
4
  import type { $errors, $events, $terminate, $worker } from '../symbols.ts';
@@ -98,32 +99,31 @@ export interface ImplementationExport {
98
99
  default: typeof WorkerImplementation;
99
100
  }
100
101
  /** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */
101
- export declare enum WorkerEventType {
102
- /** The threads implementation encountered an internal error. */
103
- internalError = "internalError",
104
- /** The worker emitted a message. */
105
- message = "message",
106
- /** The worker terminated. */
107
- termination = "termination"
108
- }
102
+ export declare const WorkerEventType: Enum<{
103
+ internalError: 'internalError';
104
+ message: 'message';
105
+ termination: 'termination';
106
+ }>;
107
+ /** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */
108
+ export type WorkerEventType = EnumValue<typeof WorkerEventType>;
109
109
  /** Event indicating an internal error occurred in the worker. */
110
110
  export interface WorkerInternalErrorEvent {
111
111
  /** Error raised by the worker implementation. */
112
112
  error: Error;
113
113
  /** Event discriminant. */
114
- type: WorkerEventType.internalError;
114
+ type: (typeof WorkerEventType)['internalError'];
115
115
  }
116
116
  /** Event containing a message received from the worker. */
117
117
  export interface WorkerMessageEvent<Data> {
118
118
  /** Message data received from the worker. */
119
119
  data: Data;
120
120
  /** Event discriminant. */
121
- type: WorkerEventType.message;
121
+ type: (typeof WorkerEventType)['message'];
122
122
  }
123
123
  /** Event indicating the worker has been terminated. */
124
124
  export interface WorkerTerminationEvent {
125
125
  /** Event discriminant. */
126
- type: WorkerEventType.termination;
126
+ type: (typeof WorkerEventType)['termination'];
127
127
  }
128
128
  /** Union of all possible worker event types. */
129
129
  export type WorkerEvent = WorkerInternalErrorEvent | WorkerMessageEvent<any> | WorkerTerminationEvent;
@@ -1 +1 @@
1
- {"version":3,"file":"master.d.ts","sourceRoot":"","sources":["../../../src/types/master.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAEhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,KAAK,EACV,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EACtC,MAAM,eAAe,CAAA;AACtB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAE5D,UAAU,0BAA0B;IAClC,WAAW,IAAI,GAAG,CAAA;CACnB;AACD,UAAU,cAAc,CAAC,CAAC;IACxB,SAAS,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,GAAG,EAAE,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,GAAG,0BAA0B,CAAA;IACvH,SAAS,CAAC,SAAS,EAAE;QAAE,QAAQ,CAAC,IAAI,GAAG,CAAC;QAAC,KAAK,CAAC,CAAC,KAAK,EAAE,GAAG,GAAG,GAAG,CAAC;QAAC,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC,GAAG,GAAG,CAAA;KAAE,GAAG,0BAA0B,CAAA;CACtH;AAED,2EAA2E;AAC3E,MAAM,MAAM,UAAU,CAAC,IAAI,IACvB,IAAI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B,EAAC;IACvD,mDAAmD;IACnD,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,oBAAoB,CAAA;CACtF;AAED,iEAAiE;AACjE,MAAM,WAAW,oBAAoB;IACnC,gDAAgD;IAChD,IAAI,EAAE,OAAO,UAAU,CAAA;IACvB,wDAAwD;IACxD,OAAO,EAAE,OAAO,oBAAoB,CAAA;CACrC;AAED,qFAAqF;AACrF,eAAO,MAAM,eAAe;mBAEX,eAAe;aAErB,SAAS;iBAEL,aAAa;EACjB,CAAA;AACX,qFAAqF;AACrF,MAAM,MAAM,eAAe,GAAG,SAAS,CAAC,OAAO,eAAe,CAAC,CAAA;AAE/D,iEAAiE;AACjE,MAAM,WAAW,wBAAwB;IACvC,iDAAiD;IACjD,KAAK,EAAE,KAAK,CAAA;IACZ,0BAA0B;IAC1B,IAAI,EAAE,CAAC,OAAO,eAAe,CAAC,CAAC,eAAe,CAAC,CAAA;CAChD;AAED,2DAA2D;AAC3D,MAAM,WAAW,kBAAkB,CAAC,IAAI;IACtC,6CAA6C;IAC7C,IAAI,EAAE,IAAI,CAAA;IACV,0BAA0B;IAC1B,IAAI,EAAE,CAAC,OAAO,eAAe,CAAC,CAAC,SAAS,CAAC,CAAA;CAC1C;AAED,uDAAuD;AACvD,MAAM,WAAW,sBAAsB;IACrC,0BAA0B;IAC1B,IAAI,EAAE,CAAC,OAAO,eAAe,CAAC,CAAC,aAAa,CAAC,CAAA;CAC9C;AAED,gDAAgD;AAChD,MAAM,MAAM,WAAW,GAAG,wBAAwB,GAAG,kBAAkB,CAAC,GAAG,CAAC,GAAG,sBAAsB,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { Enum, type EnumValue } from '@ariestools/sdk/enum';
1
2
  /** Serialized representation of an Error for transmission between threads. */
2
3
  export interface SerializedError {
3
4
  /** Marker distinguishing serialized errors from ordinary values. */
@@ -10,23 +11,23 @@ export interface SerializedError {
10
11
  stack?: string;
11
12
  }
12
13
  /** Types of messages that the master thread can send to a worker. */
13
- export declare enum MasterMessageType {
14
- /** Cancel a previously submitted job. */
15
- cancel = "cancel",
16
- /** Run a job in the worker. */
17
- run = "run"
18
- }
14
+ export declare const MasterMessageType: Enum<{
15
+ cancel: 'cancel';
16
+ run: 'run';
17
+ }>;
18
+ /** Types of messages that the master thread can send to a worker. */
19
+ export type MasterMessageType = EnumValue<typeof MasterMessageType>;
19
20
  /** Message sent by the master to cancel a running job. */
20
21
  export type MasterJobCancelMessage = {
21
22
  /** Message discriminant. */
22
- type: MasterMessageType.cancel;
23
+ type: (typeof MasterMessageType)['cancel'];
23
24
  /** Unique identifier of the job to cancel. */
24
25
  uid: number;
25
26
  };
26
27
  /** Message sent by the master to run a function in the worker. */
27
28
  export type MasterJobRunMessage = {
28
29
  /** Message discriminant. */
29
- type: MasterMessageType.run;
30
+ type: (typeof MasterMessageType)['run'];
30
31
  /** Unique identifier assigned to the job. */
31
32
  uid: number;
32
33
  /** Exposed module method to invoke, or omitted for an exposed function. */
@@ -35,22 +36,19 @@ export type MasterJobRunMessage = {
35
36
  args: any[];
36
37
  };
37
38
  /** Types of messages that a worker thread can send to the master. */
38
- export declare enum WorkerMessageType {
39
- /** A job failed. */
40
- error = "error",
41
- /** The worker exposed its callable API. */
42
- init = "init",
43
- /** A job produced a result. */
44
- result = "result",
45
- /** A job started running. */
46
- running = "running",
47
- /** An error escaped the worker job handler. */
48
- uncaughtError = "uncaughtError"
49
- }
39
+ export declare const WorkerMessageType: Enum<{
40
+ error: 'error';
41
+ init: 'init';
42
+ result: 'result';
43
+ running: 'running';
44
+ uncaughtError: 'uncaughtError';
45
+ }>;
46
+ /** Types of messages that a worker thread can send to the master. */
47
+ export type WorkerMessageType = EnumValue<typeof WorkerMessageType>;
50
48
  /** Message sent by a worker when an uncaught error occurs. */
51
49
  export type WorkerUncaughtErrorMessage = {
52
50
  /** Message discriminant. */
53
- type: WorkerMessageType.uncaughtError;
51
+ type: (typeof WorkerMessageType)['uncaughtError'];
54
52
  /** Uncaught error details. */
55
53
  error: {
56
54
  message: string;
@@ -61,7 +59,7 @@ export type WorkerUncaughtErrorMessage = {
61
59
  /** Message sent by a worker after calling `expose()` to signal its API to the master. */
62
60
  export type WorkerInitMessage = {
63
61
  /** Message discriminant. */
64
- type: WorkerMessageType.init;
62
+ type: (typeof WorkerMessageType)['init'];
65
63
  /** Shape of the function or module exposed by the worker. */
66
64
  exposed: {
67
65
  type: 'function';
@@ -73,7 +71,7 @@ export type WorkerInitMessage = {
73
71
  /** Message sent by a worker when a job encounters an error. */
74
72
  export type WorkerJobErrorMessage = {
75
73
  /** Message discriminant. */
76
- type: WorkerMessageType.error;
74
+ type: (typeof WorkerMessageType)['error'];
77
75
  /** Unique identifier of the failed job. */
78
76
  uid: number;
79
77
  /** Serialized failure raised by the job. */
@@ -82,7 +80,7 @@ export type WorkerJobErrorMessage = {
82
80
  /** Message sent by a worker containing a job's result value. */
83
81
  export type WorkerJobResultMessage = {
84
82
  /** Message discriminant. */
85
- type: WorkerMessageType.result;
83
+ type: (typeof WorkerMessageType)['result'];
86
84
  /** Unique identifier of the completed or updated job. */
87
85
  uid: number;
88
86
  /** Whether an observable job has finished emitting values. */
@@ -93,7 +91,7 @@ export type WorkerJobResultMessage = {
93
91
  /** Message sent by a worker when a job starts executing. */
94
92
  export type WorkerJobStartMessage = {
95
93
  /** Message discriminant. */
96
- type: WorkerMessageType.running;
94
+ type: (typeof WorkerMessageType)['running'];
97
95
  /** Unique identifier of the started job. */
98
96
  uid: number;
99
97
  /** Asynchronous result protocol used by the job. */
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../src/types/messages.ts"],"names":[],"mappings":"AAGA,8EAA8E;AAC9E,MAAM,WAAW,eAAe;IAC9B,oEAAoE;IACpE,cAAc,EAAE,SAAS,CAAA;IACzB,qBAAqB;IACrB,OAAO,EAAE,MAAM,CAAA;IACf,wBAAwB;IACxB,IAAI,EAAE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