@hybrid-compute/worker 0.38.1 → 0.39.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.39.0](https://github.com/phun-ky/hybrid-compute/compare/%40hybrid-compute%2Fworker%400.38.1...%40hybrid-compute%2Fworker%400.39.0) (2026-10-20)
4
+
5
+ ### ⚠ BREAKING CHANGES
6
+
7
+ * the packages are compiled to ES2022 instead of ES2020.
8
+ They need Node.js 22 (as engines already says) or a browser from 2022 or
9
+
10
+ ### Tasks
11
+
12
+ * 🤖 @hybrid-compute/core@0.40.0 ([7a36295](https://github.com/phun-ky/hybrid-compute/commit/7a3629597fa33cd43867ccf283f8d4a4cfd4052f))
13
+ * 🤖 compile to ES2022, publish src, and add an exports map ([da90b30](https://github.com/phun-ky/hybrid-compute/commit/da90b30788ad52b33bd99f7739d8d32191024464)), references [#87](https://github.com/phun-ky/hybrid-compute/issues/87)
14
+
3
15
  ## [0.38.1](https://github.com/phun-ky/hybrid-compute/compare/%40hybrid-compute%2Fworker%400.38.0...%40hybrid-compute%2Fworker%400.38.1) (2026-10-20)
4
16
 
5
17
  ### Bug
package/dist/errors.d.ts CHANGED
@@ -22,8 +22,6 @@ export declare class WorkerTaskError extends Error {
22
22
  readonly taskName: string;
23
23
  /** The worker script's `error` value as it was sent, if it sent one. */
24
24
  readonly detail?: unknown;
25
- /** The underlying error or event, such as a worker crash, if there is one. */
26
- readonly cause?: unknown;
27
25
  /**
28
26
  * @param taskName - The name of the task that failed.
29
27
  * @param message - What went wrong.
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,wCAAwC;IACxC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,wEAAwE;IACxE,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAE1B,8EAA8E;IAC9E,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;;OAKG;gBAED,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAO;CAUtD"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,wCAAwC;IACxC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,wEAAwE;IACxE,SAAiB,MAAM,CAAC,EAAE,OAAO,CAAC;IAElC;;;;;OAKG;gBAED,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAO;CAYtD"}
package/dist/errors.js CHANGED
@@ -18,6 +18,8 @@
18
18
  * ```
19
19
  */
20
20
  export class WorkerTaskError extends Error {
21
+ /** The name of the task that failed. */
22
+ taskName;
21
23
  /**
22
24
  * @param taskName - The name of the task that failed.
23
25
  * @param message - What went wrong.
@@ -25,11 +27,10 @@ export class WorkerTaskError extends Error {
25
27
  * error, where there is one.
26
28
  */
27
29
  constructor(taskName, message, details = {}) {
28
- super(message);
30
+ // Error's own cause option (ES2022), only when there is a cause
31
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
29
32
  this.name = 'WorkerTaskError';
30
33
  this.taskName = taskName;
31
- if (details.cause !== undefined)
32
- this.cause = details.cause;
33
34
  if ('detail' in details)
34
35
  this.detail = details.detail;
35
36
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAUxC;;;;;OAKG;IACH,YACE,QAAgB,EAChB,OAAe,EACf,UAAiD,EAAE;QAEnD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,OAAO,CAAC,KAAK,KAAK,SAAS;YAAE,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAE5D,IAAI,QAAQ,IAAI,OAAO;YAAE,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACxD,CAAC;CACF"}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,wCAAwC;IAC/B,QAAQ,CAAS;IAK1B;;;;;OAKG;IACH,YACE,QAAgB,EAChB,OAAe,EACf,UAAiD,EAAE;QAEnD,gEAAgE;QAChE,KAAK,CACH,OAAO,EACP,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CACnE,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,QAAQ,IAAI,OAAO;YAAE,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACxD,CAAC;CACF"}
package/dist/expose.js CHANGED
@@ -79,7 +79,7 @@ export function exposeTasks(tasks, scope) {
79
79
  const controller = new AbortController();
80
80
  running.set(id, controller);
81
81
  try {
82
- if (!Object.prototype.hasOwnProperty.call(tasks, name)) {
82
+ if (!Object.hasOwn(tasks, name)) {
83
83
  throw new Error(`No task '${name}' in this worker`);
84
84
  }
85
85
  const result = await tasks[name](input, {
@@ -1 +1 @@
1
- {"version":3,"file":"expose.js","sourceRoot":"","sources":["../src/expose.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE1D,mEAAmE;AACnE,MAAM,YAAY,GAAG,CAAC,KAAc,EAAE,EAAE;IACtC,IAAI,KAAK,YAAY,KAAK;QACxB,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAEtD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5C,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACpC,CAAC,CAAC;AACF,kEAAkE;AAClE,MAAM,WAAW,GAAG,GAAyB,EAAE;IAC7C,MAAM,KAAK,GAAG,UAAsD,CAAC;IAErE,IACE,CAAC,CAAC,mBAAmB,IAAI,UAAU,CAAC;QACpC,OAAO,KAAK,CAAC,gBAAgB,KAAK,UAAU;QAC5C,OAAO,KAAK,CAAC,WAAW,KAAK,UAAU,EACvC,CAAC;QACD,MAAM,IAAI,SAAS,CACjB,iFAAiF,CAClF,CAAC;IACJ,CAAC;IAED,OAAO,KAA6B,CAAC;AACvC,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,UAAU,WAAW,CACzB,KAA+C,EAC/C,KAA4B;IAE5B,IACE,CAAC,aAAa,CAAC,KAAK,CAAC;QACrB,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,UAAU,CAAC,EACjE,CAAC;QACD,MAAM,IAAI,SA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IAAI,EAAE,CAAC;YACzB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC;YAE9B,OAAO;QACT,CAAC;QAED,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO;QAE1C,KAAK,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC"}
package/dist/index.js CHANGED
@@ -67,6 +67,10 @@ const toSettings = (options) => {
67
67
  * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
68
68
  */
69
69
  export class ThreadedCompute {
70
+ settings;
71
+ worker;
72
+ pending = new Map();
73
+ nextId = 1;
70
74
  /**
71
75
  * Creates the backend. It checks the options, and starts no worker until
72
76
  * the first task.
@@ -78,8 +82,6 @@ export class ThreadedCompute {
78
82
  * @throws {RangeError} For a negative timeout.
79
83
  */
80
84
  constructor(options) {
81
- this.pending = new Map();
82
- this.nextId = 1;
83
85
  this.settings = toSettings(options);
84
86
  }
85
87
  /**
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAGf,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAM9C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAErE,cAAc,aAAa,CAAC;AAE5B,cAAc,aAAa,CAAC;AAE5B,cAAc,YAAY,CAAC;AAS3B,4CAA4C;AAC5C,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,OAAO,MAAM,KAAK,UAAU,CAAC;AACtD;;;;;GAKG;AACH,MAAM,UAAU,GAAG,CAAC,OAAgB,EAAE,EAAE;IACtC,IAAI,CAAC,aAAa,CAAC,O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AO,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hybrid-compute/worker",
3
- "version": "0.38.1",
3
+ "version": "0.39.0",
4
4
  "description": "Threaded compute backend for executing tasks in Web Workers.",
5
5
  "keywords": [
6
6
  "web-worker",
@@ -25,12 +25,21 @@
25
25
  "license": "MIT",
26
26
  "author": "Alexander Vassbotn Røyne-Helgesen <alexander@phun-ky.net>",
27
27
  "type": "module",
28
- "exports": "./dist/index.js",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
29
35
  "types": "./dist/index.d.ts",
30
36
  "files": [
31
37
  "dist",
38
+ "src",
39
+ "!src/**/__tests__",
32
40
  "CHANGELOG.md"
33
41
  ],
42
+ "sideEffects": false,
34
43
  "scripts": {
35
44
  "clean": "rm -rf dist *.tsbuildinfo",
36
45
  "typecheck": "tsc -p tsconfig.json",
@@ -40,7 +49,7 @@
40
49
  "test:ci": "glob-bin -c \"node --import tsx --test --no-warnings --experimental-test-coverage --test-coverage-include='src/**/*.ts' --test-coverage-exclude='src/**/__tests__/**' --test-coverage-exclude='src/types.ts' --test-reporter=cobertura --test-reporter-destination=coverage/cobertura-coverage.xml --test-reporter=spec --test-reporter-destination=stdout\" \"**/__tests__/**/*.spec.ts\""
41
50
  },
42
51
  "dependencies": {
43
- "@hybrid-compute/core": "^0.39.0"
52
+ "@hybrid-compute/core": "^0.40.0"
44
53
  },
45
54
  "devDependencies": {
46
55
  "eslint": "^9.27.0",
package/src/errors.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Why a worker task failed: the worker script replied with an `error`, the
3
+ * reply was unusable, the worker crashed or couldn't start, the input couldn't
4
+ * be sent, the timeout passed, or the backend was closed.
5
+ *
6
+ * A task cancelled with an `AbortSignal` rejects with the signal's reason
7
+ * instead, so a `WorkerTaskError` always means something went wrong.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * try {
12
+ * await threaded.runTask('resizeImage', blob);
13
+ * } catch (error) {
14
+ * if (error instanceof WorkerTaskError) {
15
+ * console.warn(`${error.taskName} failed`, error.detail);
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export class WorkerTaskError extends Error {
21
+ /** The name of the task that failed. */
22
+ readonly taskName: string;
23
+
24
+ /** The worker script's `error` value as it was sent, if it sent one. */
25
+ declare readonly detail?: unknown;
26
+
27
+ /**
28
+ * @param taskName - The name of the task that failed.
29
+ * @param message - What went wrong.
30
+ * @param details - The worker script's error value and the underlying
31
+ * error, where there is one.
32
+ */
33
+ constructor(
34
+ taskName: string,
35
+ message: string,
36
+ details: { detail?: unknown; cause?: unknown } = {}
37
+ ) {
38
+ // Error's own cause option (ES2022), only when there is a cause
39
+ super(
40
+ message,
41
+ details.cause === undefined ? undefined : { cause: details.cause }
42
+ );
43
+ this.name = 'WorkerTaskError';
44
+ this.taskName = taskName;
45
+
46
+ if ('detail' in details) this.detail = details.detail;
47
+ }
48
+ }
package/src/expose.ts ADDED
@@ -0,0 +1,130 @@
1
+ import type { WorkerScopeInterface, WorkerTaskType } from './types.js';
2
+ import { describeValue, isPlainObject } from './utils.js';
3
+
4
+ /** An error as a value the structured clone algorithm can copy. */
5
+ const toErrorValue = (error: unknown) => {
6
+ if (error instanceof Error)
7
+ return { name: error.name, message: error.message };
8
+
9
+ if (typeof error === 'string') return error;
10
+
11
+ return { message: String(error) };
12
+ };
13
+ /** The worker's global scope, or a TypeError outside a worker. */
14
+ const workerScope = (): WorkerScopeInterface => {
15
+ const scope = globalThis as unknown as Partial<WorkerScopeInterface>;
16
+
17
+ if (
18
+ !('WorkerGlobalScope' in globalThis) ||
19
+ typeof scope.addEventListener !== 'function' ||
20
+ typeof scope.postMessage !== 'function'
21
+ ) {
22
+ throw new TypeError(
23
+ 'exposeTasks must be called in a worker script, or be given a scope to listen on'
24
+ );
25
+ }
26
+
27
+ return scope as WorkerScopeInterface;
28
+ };
29
+
30
+ /**
31
+ * Answers tasks from {@link ThreadedCompute} in a worker script: it listens
32
+ * for task messages, runs the task with that name, and replies with its
33
+ * result, or with an error if the task throws, rejects or doesn't exist.
34
+ *
35
+ * Each task gets the input and a context with a `signal`, which aborts when
36
+ * the caller cancels the task or its timeout passes. A task that checks the
37
+ * signal can stop early; its reply is then not sent.
38
+ *
39
+ * @param tasks - The tasks, by name. List the same names in `canRunTasks`.
40
+ * @param scope - Where to listen and reply. Defaults to the worker's global
41
+ * scope.
42
+ *
43
+ * @throws {TypeError} If `tasks` isn't an object of functions, or if it's
44
+ * called outside a worker without a `scope`.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * // worker.js
49
+ * import { exposeTasks } from '@hybrid-compute/worker';
50
+ *
51
+ * exposeTasks({
52
+ * double: (n: number) => n * 2,
53
+ * slowSum: async (numbers: number[], { signal }) => {
54
+ * let sum = 0;
55
+ *
56
+ * for (const n of numbers) {
57
+ * signal.throwIfAborted();
58
+ * sum += n;
59
+ * }
60
+ *
61
+ * return sum;
62
+ * }
63
+ * });
64
+ * ```
65
+ */
66
+ export function exposeTasks(
67
+ tasks: Readonly<Record<string, WorkerTaskType>>,
68
+ scope?: WorkerScopeInterface
69
+ ): void {
70
+ if (
71
+ !isPlainObject(tasks) ||
72
+ !Object.values(tasks).every((task) => typeof task === 'function')
73
+ ) {
74
+ throw new TypeError(
75
+ `exposeTasks expects an object of task functions, got ${describeValue(tasks)}`
76
+ );
77
+ }
78
+
79
+ const target = scope ?? workerScope();
80
+ const running = new Map<number, AbortController>();
81
+ const reply = (message: Record<string, unknown>) => {
82
+ try {
83
+ target.postMessage(message);
84
+ } catch (error) {
85
+ // A result the structured clone algorithm can't copy
86
+ target.postMessage({
87
+ id: message.id,
88
+ error: {
89
+ name: 'DataCloneError',
90
+ message: `the result couldn't be sent: ${error instanceof Error ? error.message : String(error)}`
91
+ }
92
+ });
93
+ }
94
+ };
95
+ const run = async (id: number, name: string, input: unknown) => {
96
+ const controller = new AbortController();
97
+
98
+ running.set(id, controller);
99
+
100
+ try {
101
+ if (!Object.hasOwn(tasks, name)) {
102
+ throw new Error(`No task '${name}' in this worker`);
103
+ }
104
+
105
+ const result = await tasks[name](input as never, {
106
+ signal: controller.signal
107
+ });
108
+
109
+ if (!controller.signal.aborted) reply({ id, result });
110
+ } catch (error) {
111
+ if (!controller.signal.aborted) reply({ id, error: toErrorValue(error) });
112
+ } finally {
113
+ running.delete(id);
114
+ }
115
+ };
116
+
117
+ target.addEventListener('message', ({ data }) => {
118
+ if (!isPlainObject(data) || typeof data.id !== 'number') return;
119
+
120
+ if (data.cancel === true) {
121
+ running.get(data.id)?.abort();
122
+
123
+ return;
124
+ }
125
+
126
+ if (typeof data.task !== 'string') return;
127
+
128
+ void run(data.id, data.task, data.input);
129
+ });
130
+ }
package/src/index.ts ADDED
@@ -0,0 +1,389 @@
1
+ import {
2
+ NoBackendError,
3
+ type ComputeBackendInterface,
4
+ type RunTaskOptionsInterface
5
+ } from '@hybrid-compute/core';
6
+
7
+ import { WorkerTaskError } from './errors.js';
8
+ import type {
9
+ ThreadedComputeOptionsInterface,
10
+ WorkerCancelMessageInterface,
11
+ WorkerTaskMessageInterface
12
+ } from './types.js';
13
+ import { describeValue, isPlainObject, messageOf } from './utils.js';
14
+
15
+ export * from './errors.js';
16
+
17
+ export * from './expose.js';
18
+
19
+ export * from './types.js';
20
+
21
+ /** A task waiting for its reply from the worker. */
22
+ type PendingTaskType = {
23
+ taskName: string;
24
+ resolve: (value: unknown) => void;
25
+ reject: (reason: unknown) => void;
26
+ };
27
+
28
+ /** Whether this runtime has Web Workers. */
29
+ const hasWorkers = () => typeof Worker === 'function';
30
+ /**
31
+ * Check the options and return them normalised.
32
+ *
33
+ * @throws {TypeError} For a missing or wrongly typed option.
34
+ * @throws {RangeError} For a negative timeout.
35
+ */
36
+ const toSettings = (options: unknown) => {
37
+ if (!isPlainObject(options)) {
38
+ throw new TypeError(
39
+ `createThreadedCompute expects an options object, got ${describeValue(options)}`
40
+ );
41
+ }
42
+
43
+ const { url, canRunTasks, timeout } = options;
44
+
45
+ if (!(url instanceof URL) && (typeof url !== 'string' || url === '')) {
46
+ throw new TypeError(
47
+ `url must be a URL or a non-empty string, got ${describeValue(url)}`
48
+ );
49
+ }
50
+
51
+ if (
52
+ !Array.isArray(canRunTasks) ||
53
+ !canRunTasks.every((name) => typeof name === 'string' && name !== '')
54
+ ) {
55
+ throw new TypeError(
56
+ `canRunTasks must be an array of task names, got ${describeValue(canRunTasks)}`
57
+ );
58
+ }
59
+
60
+ if (
61
+ timeout !== undefined &&
62
+ (typeof timeout !== 'number' || !Number.isFinite(timeout))
63
+ ) {
64
+ throw new TypeError(
65
+ `timeout must be a number of milliseconds, got ${describeValue(timeout)}`
66
+ );
67
+ }
68
+
69
+ if (typeof timeout === 'number' && timeout < 0) {
70
+ throw new RangeError(
71
+ `timeout must be 0 (no timeout) or more, got ${timeout}`
72
+ );
73
+ }
74
+
75
+ return {
76
+ url: url as string | URL,
77
+ tasks: new Set(canRunTasks as string[]) as ReadonlySet<string>,
78
+ timeout: (timeout as number | undefined) ?? 0
79
+ };
80
+ };
81
+
82
+ /**
83
+ * ThreadedCompute is a backend that runs tasks in a dedicated module Web
84
+ * Worker, so heavy work doesn't block the main thread.
85
+ *
86
+ * It starts the worker on the first task, not when it's created, sends each
87
+ * task with an id and matches the replies by id. Write the worker script with
88
+ * {@link exposeTasks}, or by hand following {@link WorkerTaskMessageInterface}
89
+ * and {@link WorkerResultMessageInterface}.
90
+ *
91
+ * Every failure (an `error` in the reply, a crash, the timeout) rejects with a
92
+ * {@link WorkerTaskError}. If the worker crashes, a new one starts on the next
93
+ * task. Call {@link ThreadedCompute.close} when you're done with it.
94
+ *
95
+ * Web Workers only exist in browsers (and Deno and Bun): where there is no
96
+ * global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
97
+ * another backend.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * const threaded = createThreadedCompute({
102
+ * url: new URL('./worker.js', import.meta.url),
103
+ * canRunTasks: ['add']
104
+ * });
105
+ *
106
+ * const result = await threaded.runTask<number, number>('add', 5);
107
+ * ```
108
+ *
109
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
110
+ */
111
+ export class ThreadedCompute implements ComputeBackendInterface {
112
+ private readonly settings: ReturnType<typeof toSettings>;
113
+ private worker?: Worker;
114
+ private readonly pending = new Map<number, PendingTaskType>();
115
+ private nextId = 1;
116
+
117
+ /**
118
+ * Creates the backend. It checks the options, and starts no worker until
119
+ * the first task.
120
+ *
121
+ * @param options - The worker script, the tasks it can run and,
122
+ * optionally, a timeout.
123
+ *
124
+ * @throws {TypeError} For a missing or wrongly typed option.
125
+ * @throws {RangeError} For a negative timeout.
126
+ */
127
+ constructor(options: ThreadedComputeOptionsInterface) {
128
+ this.settings = toSettings(options);
129
+ }
130
+
131
+ /**
132
+ * Determines if this backend can run the given task.
133
+ *
134
+ * @param taskName - Name of the task.
135
+ * @returns `true` if the task is in `canRunTasks` and this runtime has Web
136
+ * Workers.
137
+ */
138
+ canRun(taskName: string): boolean {
139
+ return hasWorkers() && this.settings.tasks.has(taskName);
140
+ }
141
+
142
+ /**
143
+ * Runs a task in the worker and waits for its reply.
144
+ *
145
+ * @typeParam Input - The input type of the task.
146
+ * @typeParam Output - The output type of the task.
147
+ *
148
+ * @param taskName - The name of the task to run.
149
+ * @param input - The input for the task. It's copied with the structured
150
+ * clone algorithm, so it can't hold functions or DOM nodes.
151
+ * @param options - Options for this call. With a `signal`, `runTask`
152
+ * rejects with the signal's reason as soon as it aborts, and the worker is
153
+ * told to cancel the task.
154
+ * @returns A Promise resolving to the reply's `result`. It rejects with a
155
+ * `NoBackendError` (from `@hybrid-compute/core`) if the task isn't in
156
+ * `canRunTasks`, a `TypeError` if this runtime has no Web Workers, a
157
+ * {@link WorkerTaskError} if the task fails, and with the signal's reason
158
+ * if the call is cancelled.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * const result = await threaded.runTask('square', 9); // 81
163
+ * ```
164
+ */
165
+ async runTask<Input, Output>(
166
+ taskName: string,
167
+ input: Input,
168
+ options?: RunTaskOptionsInterface
169
+ ): Promise<Output> {
170
+ if (!this.settings.tasks.has(taskName)) {
171
+ throw new NoBackendError(
172
+ taskName,
173
+ 'worker',
174
+ `The worker can't run task '${taskName}'; it isn't in canRunTasks`
175
+ );
176
+ }
177
+
178
+ if (!hasWorkers()) {
179
+ throw new TypeError(
180
+ 'Web Workers are not available in this runtime; @hybrid-compute/worker needs a global Worker'
181
+ );
182
+ }
183
+
184
+ const signal = options?.signal;
185
+
186
+ if (signal?.aborted) throw signal.reason;
187
+
188
+ const worker = this.start(taskName);
189
+ const { timeout } = this.settings;
190
+ const id = this.nextId++;
191
+
192
+ return new Promise<Output>((resolve, reject) => {
193
+ let timer: ReturnType<typeof setTimeout> | undefined;
194
+
195
+ const finish = () => {
196
+ clearTimeout(timer);
197
+ signal?.removeEventListener('abort', onAbort);
198
+ this.pending.delete(id);
199
+ };
200
+ // Settled before the worker replied: tell the worker to stop
201
+ const cancel = () => {
202
+ const message: WorkerCancelMessageInterface = { id, cancel: true };
203
+
204
+ worker.postMessage(message);
205
+ };
206
+ const onAbort = () => {
207
+ finish();
208
+ cancel();
209
+ reject(signal?.reason);
210
+ };
211
+
212
+ if (timeout > 0) {
213
+ timer = setTimeout(() => {
214
+ finish();
215
+ cancel();
216
+ reject(
217
+ new WorkerTaskError(
218
+ taskName,
219
+ `Worker task '${taskName}' timed out after ${timeout} ms`
220
+ )
221
+ );
222
+ }, timeout);
223
+ }
224
+
225
+ signal?.addEventListener('abort', onAbort, { once: true });
226
+ this.pending.set(id, {
227
+ taskName,
228
+ resolve: (value) => {
229
+ finish();
230
+ resolve(value as Output);
231
+ },
232
+ reject: (reason) => {
233
+ finish();
234
+ reject(reason);
235
+ }
236
+ });
237
+
238
+ const message: WorkerTaskMessageInterface<Input> = {
239
+ id,
240
+ task: taskName,
241
+ input
242
+ };
243
+
244
+ try {
245
+ worker.postMessage(message);
246
+ } catch (error) {
247
+ this.pending
248
+ .get(id)
249
+ ?.reject(
250
+ new WorkerTaskError(
251
+ taskName,
252
+ `Worker task '${taskName}' couldn't send its input to the worker`,
253
+ { cause: error }
254
+ )
255
+ );
256
+ }
257
+ });
258
+ }
259
+
260
+ /**
261
+ * Terminates the worker, if one is running. Tasks still waiting for a
262
+ * reply reject with a {@link WorkerTaskError}. The next task starts a new
263
+ * worker.
264
+ */
265
+ close(): void {
266
+ const { worker } = this;
267
+
268
+ this.worker = undefined;
269
+ worker?.terminate();
270
+ this.rejectPending('the worker was closed');
271
+ }
272
+
273
+ /** The running worker, starting one first if needed. */
274
+ private start(taskName: string): Worker {
275
+ if (this.worker) return this.worker;
276
+
277
+ let worker: Worker;
278
+
279
+ try {
280
+ worker = new Worker(this.settings.url, { type: 'module' });
281
+ } catch (error) {
282
+ throw new WorkerTaskError(
283
+ taskName,
284
+ `Worker task '${taskName}' couldn't start the worker ${String(this.settings.url)}`,
285
+ { cause: error }
286
+ );
287
+ }
288
+
289
+ worker.addEventListener('message', (event) => this.onMessage(event));
290
+ // An uncaught error, or a script that fails to load: the worker is in an
291
+ // unknown state, so reject what it was doing and start over next time
292
+ worker.addEventListener('error', (event) => {
293
+ if (this.worker !== worker) return;
294
+
295
+ const detail = (event as Partial<ErrorEvent>).message;
296
+
297
+ this.worker = undefined;
298
+ worker.terminate();
299
+ this.rejectPending(
300
+ detail
301
+ ? `the worker threw: ${detail}`
302
+ : 'the worker failed: its script did not load, or threw while starting',
303
+ event
304
+ );
305
+ });
306
+ // A reply that couldn't be deserialised: nothing tells which task it
307
+ // was for, so reject them all instead of letting one wait forever
308
+ worker.addEventListener('messageerror', (event) => {
309
+ if (this.worker !== worker) return;
310
+
311
+ this.rejectPending('a reply from the worker could not be read', event);
312
+ });
313
+ this.worker = worker;
314
+
315
+ return worker;
316
+ }
317
+
318
+ /** Match a reply to its task by id; ignore anything that can't be matched. */
319
+ private onMessage(event: MessageEvent) {
320
+ const reply: unknown = event.data;
321
+
322
+ if (!isPlainObject(reply) || typeof reply.id !== 'number') return;
323
+
324
+ const task = this.pending.get(reply.id);
325
+
326
+ if (!task) return;
327
+
328
+ const { taskName } = task;
329
+ const { error } = reply;
330
+
331
+ if (error !== undefined && error !== null) {
332
+ const text = messageOf(error);
333
+
334
+ task.reject(
335
+ new WorkerTaskError(
336
+ taskName,
337
+ `Worker task '${taskName}' failed${text ? `: ${text}` : ''}`,
338
+ { detail: error }
339
+ )
340
+ );
341
+ } else if ('result' in reply) {
342
+ task.resolve(reply.result);
343
+ } else {
344
+ task.reject(
345
+ new WorkerTaskError(
346
+ taskName,
347
+ `Worker task '${taskName}' got a reply with neither a result nor an error`
348
+ )
349
+ );
350
+ }
351
+ }
352
+
353
+ /** Reject every task still waiting for a reply. */
354
+ private rejectPending(why: string, cause?: unknown) {
355
+ for (const task of [...this.pending.values()]) {
356
+ task.reject(
357
+ new WorkerTaskError(
358
+ task.taskName,
359
+ `Worker task '${task.taskName}' got no reply: ${why}`,
360
+ { cause }
361
+ )
362
+ );
363
+ }
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Creates a ThreadedCompute backend.
369
+ *
370
+ * @param options - The worker script, the tasks it can run and,
371
+ * optionally, a timeout.
372
+ * @returns A new `ThreadedCompute` instance.
373
+ *
374
+ * @throws {TypeError} For a missing or wrongly typed option.
375
+ * @throws {RangeError} For a negative timeout.
376
+ *
377
+ * @example
378
+ * ```ts
379
+ * const backend = createThreadedCompute({
380
+ * url: new URL('./worker.js', import.meta.url),
381
+ * canRunTasks: ['resizeImage']
382
+ * });
383
+ * ```
384
+ */
385
+ export function createThreadedCompute(
386
+ options: ThreadedComputeOptionsInterface
387
+ ) {
388
+ return new ThreadedCompute(options);
389
+ }
package/src/types.ts ADDED
@@ -0,0 +1,102 @@
1
+ import type { TaskContextInterface } from '@hybrid-compute/core';
2
+
3
+ /**
4
+ * Options for {@link createThreadedCompute}.
5
+ *
6
+ * @property url - The worker script, started as a module worker. Usually
7
+ * `new URL('./worker.js', import.meta.url)`, so bundlers find it.
8
+ * @property canRunTasks - The tasks the worker script can run. Only these are
9
+ * sent to it.
10
+ * @property timeout - How long to wait for a reply, in milliseconds, before
11
+ * rejecting with a `WorkerTaskError`. Defaults to `0`: no timeout, since
12
+ * workers are for long running work.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const options: ThreadedComputeOptionsInterface = {
17
+ * url: new URL('./worker.js', import.meta.url),
18
+ * canRunTasks: ['resizeImage'],
19
+ * timeout: 10_000
20
+ * };
21
+ * ```
22
+ */
23
+ export interface ThreadedComputeOptionsInterface {
24
+ url: string | URL;
25
+ canRunTasks: readonly string[];
26
+ timeout?: number;
27
+ }
28
+
29
+ /**
30
+ * What the worker script receives for each task: the task name, its input
31
+ * and an `id`, which the reply must repeat. The input is copied with the
32
+ * structured clone algorithm, so it can't hold functions or DOM nodes.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const message: WorkerTaskMessageInterface = { id: 1, task: 'double', input: 21 };
37
+ * ```
38
+ *
39
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
40
+ */
41
+ export interface WorkerTaskMessageInterface<Input = unknown> {
42
+ id: number;
43
+ task: string;
44
+ input: Input;
45
+ }
46
+
47
+ /**
48
+ * What the worker script receives when a task is cancelled or times out:
49
+ * the task's `id` and `cancel: true`. {@link exposeTasks} aborts the task's
50
+ * signal; a hand written worker script can ignore it.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * const message: WorkerCancelMessageInterface = { id: 1, cancel: true };
55
+ * ```
56
+ */
57
+ export interface WorkerCancelMessageInterface {
58
+ id: number;
59
+ cancel: true;
60
+ }
61
+
62
+ /**
63
+ * What the worker script sends back: the task's `id` with either a `result`
64
+ * or an `error`. An `error` (a message string, or an object with a `message`)
65
+ * rejects the task with a `WorkerTaskError`.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * self.postMessage({ id: 1, result: 42 } satisfies WorkerResultMessageInterface);
70
+ * ```
71
+ */
72
+ export interface WorkerResultMessageInterface<Output = unknown> {
73
+ id: number;
74
+ result?: Output;
75
+ error?: unknown;
76
+ }
77
+
78
+ /**
79
+ * A task in the worker script, for {@link exposeTasks}. It gets the input and
80
+ * a context with a `signal`, which aborts when the caller cancels the task or
81
+ * its timeout passes.
82
+ *
83
+ * @typeParam Input - The input type of the task.
84
+ * @typeParam Output - The output type of the task.
85
+ */
86
+ export type WorkerTaskType<Input = never, Output = unknown> = (
87
+ input: Input,
88
+ context: Required<TaskContextInterface>
89
+ ) => Output | Promise<Output>;
90
+
91
+ /**
92
+ * Where {@link exposeTasks} listens and replies. Defaults to the worker's
93
+ * global scope (`self`); pass another one to adapt it, for example to a
94
+ * `MessagePort`.
95
+ */
96
+ export interface WorkerScopeInterface {
97
+ addEventListener(
98
+ type: 'message',
99
+ listener: (event: { data: unknown }) => void
100
+ ): void;
101
+ postMessage(message: unknown): void;
102
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** What a value is, for error messages: null, an array, or its typeof. */
2
+ export const describeValue = (value: unknown) => {
3
+ if (value === null) return 'null';
4
+
5
+ if (Array.isArray(value)) return 'an array';
6
+
7
+ if (value === '') return 'an empty string';
8
+
9
+ return typeof value;
10
+ };
11
+
12
+ export const isPlainObject = (
13
+ value: unknown
14
+ ): value is Record<string, unknown> =>
15
+ typeof value === 'object' && value !== null && !Array.isArray(value);
16
+
17
+ /** The message for an `error` value: a string, or an object's message. */
18
+ export const messageOf = (error: unknown) => {
19
+ if (typeof error === 'string') return error;
20
+
21
+ if (isPlainObject(error) && typeof error.message === 'string') {
22
+ return error.message;
23
+ }
24
+
25
+ try {
26
+ return JSON.stringify(error);
27
+ } catch {
28
+ return String(error);
29
+ }
30
+ };