@hybrid-compute/worker 0.38.1 → 0.40.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 +27 -0
- package/README.md +2 -1
- package/dist/errors.d.ts +0 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +4 -3
- package/dist/errors.js.map +1 -1
- package/dist/expose.js +1 -1
- package/dist/expose.js.map +1 -1
- package/dist/index.d.ts +23 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +49 -14
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +15 -5
- package/dist/types.d.ts.map +1 -1
- package/package.json +13 -4
- package/src/errors.ts +48 -0
- package/src/expose.ts +130 -0
- package/src/index.ts +438 -0
- package/src/types.ts +112 -0
- package/src/utils.ts +30 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.40.0](https://github.com/phun-ky/hybrid-compute/compare/%40hybrid-compute%2Fworker%400.39.0...%40hybrid-compute%2Fworker%400.40.0) (2026-10-20)
|
|
4
|
+
|
|
5
|
+
### Documentation
|
|
6
|
+
|
|
7
|
+
* ✏️ use createWorker in every worker example, and explain why bundlers need it ([b407e8d](https://github.com/phun-ky/hybrid-compute/commit/b407e8d22a32526c9dfe59842078a45cbe20dfa7)), references [#132](https://github.com/phun-ky/hybrid-compute/issues/132)
|
|
8
|
+
|
|
9
|
+
### Feature
|
|
10
|
+
|
|
11
|
+
* 🎸 add createWorker, so bundlers build the worker script ([7cd67f1](https://github.com/phun-ky/hybrid-compute/commit/7cd67f16c01867953cb8984069103cfa48cedd21)), closes [#132](https://github.com/phun-ky/hybrid-compute/issues/132)
|
|
12
|
+
|
|
13
|
+
### Adding missing tests
|
|
14
|
+
|
|
15
|
+
* 💍 make worker's timeout test robust under load, and never leave a thread running ([f612e52](https://github.com/phun-ky/hybrid-compute/commit/f612e52b0b295424af5e2072a32e6ad48fd64fc0)), references [#88](https://github.com/phun-ky/hybrid-compute/issues/88)
|
|
16
|
+
* 💍 property-based tests with fast-check ([5f74311](https://github.com/phun-ky/hybrid-compute/commit/5f743113eb7cc9969964cd828d8c0f6971ca45e3)), references [#88](https://github.com/phun-ky/hybrid-compute/issues/88)
|
|
17
|
+
|
|
18
|
+
## [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)
|
|
19
|
+
|
|
20
|
+
### ⚠ BREAKING CHANGES
|
|
21
|
+
|
|
22
|
+
* the packages are compiled to ES2022 instead of ES2020.
|
|
23
|
+
They need Node.js 22 (as engines already says) or a browser from 2022 or
|
|
24
|
+
|
|
25
|
+
### Tasks
|
|
26
|
+
|
|
27
|
+
* 🤖 @hybrid-compute/core@0.40.0 ([7a36295](https://github.com/phun-ky/hybrid-compute/commit/7a3629597fa33cd43867ccf283f8d4a4cfd4052f))
|
|
28
|
+
* 🤖 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)
|
|
29
|
+
|
|
3
30
|
## [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
31
|
|
|
5
32
|
### Bug
|
package/README.md
CHANGED
|
@@ -57,7 +57,8 @@ On the main thread:
|
|
|
57
57
|
import { createThreadedCompute } from '@hybrid-compute/worker';
|
|
58
58
|
|
|
59
59
|
const threaded = createThreadedCompute({
|
|
60
|
-
|
|
60
|
+
createWorker: () =>
|
|
61
|
+
new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }),
|
|
61
62
|
canRunTasks: ['add']
|
|
62
63
|
});
|
|
63
64
|
|
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.
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
}
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;
|
|
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.
|
|
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, {
|
package/dist/expose.js.map
CHANGED
|
@@ -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,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EAAE;QAC9C,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,QAAQ;YAAE,OAAO;QAEhE,IAAI,IAAI,CAAC,MAAM,KAAK,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.d.ts
CHANGED
|
@@ -20,16 +20,29 @@ export * from './types.js';
|
|
|
20
20
|
* global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
|
|
21
21
|
* another backend.
|
|
22
22
|
*
|
|
23
|
-
* @example
|
|
23
|
+
* @example With a bundler
|
|
24
24
|
* ```ts
|
|
25
|
+
* // Vite and webpack build the worker script when they see this literal
|
|
26
|
+
* // new Worker(new URL(...)), so keep it written out in full
|
|
25
27
|
* const threaded = createThreadedCompute({
|
|
26
|
-
*
|
|
28
|
+
* createWorker: () =>
|
|
29
|
+
* new Worker(new URL('./add.worker.ts', import.meta.url), {
|
|
30
|
+
* type: 'module'
|
|
31
|
+
* }),
|
|
27
32
|
* canRunTasks: ['add']
|
|
28
33
|
* });
|
|
29
34
|
*
|
|
30
35
|
* const result = await threaded.runTask<number, number>('add', 5);
|
|
31
36
|
* ```
|
|
32
37
|
*
|
|
38
|
+
* @example Without a bundler
|
|
39
|
+
* ```ts
|
|
40
|
+
* const threaded = createThreadedCompute({
|
|
41
|
+
* url: '/workers/add.worker.js',
|
|
42
|
+
* canRunTasks: ['add']
|
|
43
|
+
* });
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
33
46
|
* @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
|
|
34
47
|
*/
|
|
35
48
|
export declare class ThreadedCompute implements ComputeBackendInterface {
|
|
@@ -41,8 +54,8 @@ export declare class ThreadedCompute implements ComputeBackendInterface {
|
|
|
41
54
|
* Creates the backend. It checks the options, and starts no worker until
|
|
42
55
|
* the first task.
|
|
43
56
|
*
|
|
44
|
-
* @param options - The worker script, the tasks
|
|
45
|
-
* optionally, a timeout.
|
|
57
|
+
* @param options - The worker script (`url` or `createWorker`), the tasks
|
|
58
|
+
* it can run and, optionally, a timeout.
|
|
46
59
|
*
|
|
47
60
|
* @throws {TypeError} For a missing or wrongly typed option.
|
|
48
61
|
* @throws {RangeError} For a negative timeout.
|
|
@@ -96,8 +109,8 @@ export declare class ThreadedCompute implements ComputeBackendInterface {
|
|
|
96
109
|
/**
|
|
97
110
|
* Creates a ThreadedCompute backend.
|
|
98
111
|
*
|
|
99
|
-
* @param options - The worker script, the tasks it
|
|
100
|
-
* optionally, a timeout.
|
|
112
|
+
* @param options - The worker script (`url` or `createWorker`), the tasks it
|
|
113
|
+
* can run and, optionally, a timeout.
|
|
101
114
|
* @returns A new `ThreadedCompute` instance.
|
|
102
115
|
*
|
|
103
116
|
* @throws {TypeError} For a missing or wrongly typed option.
|
|
@@ -106,7 +119,10 @@ export declare class ThreadedCompute implements ComputeBackendInterface {
|
|
|
106
119
|
* @example
|
|
107
120
|
* ```ts
|
|
108
121
|
* const backend = createThreadedCompute({
|
|
109
|
-
*
|
|
122
|
+
* createWorker: () =>
|
|
123
|
+
* new Worker(new URL('./resize.worker.ts', import.meta.url), {
|
|
124
|
+
* type: 'module'
|
|
125
|
+
* }),
|
|
110
126
|
* canRunTasks: ['resizeImage']
|
|
111
127
|
* });
|
|
112
128
|
* ```
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,u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;GAoBG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,+BAA+B,mBAGzC"}
|
package/dist/index.js
CHANGED
|
@@ -16,10 +16,18 @@ const toSettings = (options) => {
|
|
|
16
16
|
if (!isPlainObject(options)) {
|
|
17
17
|
throw new TypeError(`createThreadedCompute expects an options object, got ${describeValue(options)}`);
|
|
18
18
|
}
|
|
19
|
-
const { url, canRunTasks, timeout } = options;
|
|
20
|
-
if (
|
|
19
|
+
const { url, createWorker, canRunTasks, timeout } = options;
|
|
20
|
+
if ((url === undefined) === (createWorker === undefined)) {
|
|
21
|
+
throw new TypeError('Give either url or createWorker: url for a worker script served as it is, createWorker when a bundler builds it');
|
|
22
|
+
}
|
|
23
|
+
if (url !== undefined &&
|
|
24
|
+
!(url instanceof URL) &&
|
|
25
|
+
(typeof url !== 'string' || url === '')) {
|
|
21
26
|
throw new TypeError(`url must be a URL or a non-empty string, got ${describeValue(url)}`);
|
|
22
27
|
}
|
|
28
|
+
if (createWorker !== undefined && typeof createWorker !== 'function') {
|
|
29
|
+
throw new TypeError(`createWorker must be a function that returns a new Worker, got ${describeValue(createWorker)}`);
|
|
30
|
+
}
|
|
23
31
|
if (!Array.isArray(canRunTasks) ||
|
|
24
32
|
!canRunTasks.every((name) => typeof name === 'string' && name !== '')) {
|
|
25
33
|
throw new TypeError(`canRunTasks must be an array of task names, got ${describeValue(canRunTasks)}`);
|
|
@@ -32,7 +40,11 @@ const toSettings = (options) => {
|
|
|
32
40
|
throw new RangeError(`timeout must be 0 (no timeout) or more, got ${timeout}`);
|
|
33
41
|
}
|
|
34
42
|
return {
|
|
35
|
-
|
|
43
|
+
// One way to start a worker, whichever option was given
|
|
44
|
+
createWorker: createWorker ??
|
|
45
|
+
(() => new Worker(url, { type: 'module' })),
|
|
46
|
+
// For error messages
|
|
47
|
+
source: createWorker === undefined ? `the worker ${String(url)}` : 'createWorker',
|
|
36
48
|
tasks: new Set(canRunTasks),
|
|
37
49
|
timeout: timeout ?? 0
|
|
38
50
|
};
|
|
@@ -54,32 +66,47 @@ const toSettings = (options) => {
|
|
|
54
66
|
* global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
|
|
55
67
|
* another backend.
|
|
56
68
|
*
|
|
57
|
-
* @example
|
|
69
|
+
* @example With a bundler
|
|
58
70
|
* ```ts
|
|
71
|
+
* // Vite and webpack build the worker script when they see this literal
|
|
72
|
+
* // new Worker(new URL(...)), so keep it written out in full
|
|
59
73
|
* const threaded = createThreadedCompute({
|
|
60
|
-
*
|
|
74
|
+
* createWorker: () =>
|
|
75
|
+
* new Worker(new URL('./add.worker.ts', import.meta.url), {
|
|
76
|
+
* type: 'module'
|
|
77
|
+
* }),
|
|
61
78
|
* canRunTasks: ['add']
|
|
62
79
|
* });
|
|
63
80
|
*
|
|
64
81
|
* const result = await threaded.runTask<number, number>('add', 5);
|
|
65
82
|
* ```
|
|
66
83
|
*
|
|
84
|
+
* @example Without a bundler
|
|
85
|
+
* ```ts
|
|
86
|
+
* const threaded = createThreadedCompute({
|
|
87
|
+
* url: '/workers/add.worker.js',
|
|
88
|
+
* canRunTasks: ['add']
|
|
89
|
+
* });
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
67
92
|
* @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
|
|
68
93
|
*/
|
|
69
94
|
export class ThreadedCompute {
|
|
95
|
+
settings;
|
|
96
|
+
worker;
|
|
97
|
+
pending = new Map();
|
|
98
|
+
nextId = 1;
|
|
70
99
|
/**
|
|
71
100
|
* Creates the backend. It checks the options, and starts no worker until
|
|
72
101
|
* the first task.
|
|
73
102
|
*
|
|
74
|
-
* @param options - The worker script, the tasks
|
|
75
|
-
* optionally, a timeout.
|
|
103
|
+
* @param options - The worker script (`url` or `createWorker`), the tasks
|
|
104
|
+
* it can run and, optionally, a timeout.
|
|
76
105
|
*
|
|
77
106
|
* @throws {TypeError} For a missing or wrongly typed option.
|
|
78
107
|
* @throws {RangeError} For a negative timeout.
|
|
79
108
|
*/
|
|
80
109
|
constructor(options) {
|
|
81
|
-
this.pending = new Map();
|
|
82
|
-
this.nextId = 1;
|
|
83
110
|
this.settings = toSettings(options);
|
|
84
111
|
}
|
|
85
112
|
/**
|
|
@@ -196,10 +223,15 @@ export class ThreadedCompute {
|
|
|
196
223
|
return this.worker;
|
|
197
224
|
let worker;
|
|
198
225
|
try {
|
|
199
|
-
worker =
|
|
226
|
+
worker = this.settings.createWorker();
|
|
200
227
|
}
|
|
201
228
|
catch (error) {
|
|
202
|
-
throw new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't start
|
|
229
|
+
throw new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't start ${this.settings.source}`, { cause: error });
|
|
230
|
+
}
|
|
231
|
+
if (typeof worker?.postMessage !== 'function' ||
|
|
232
|
+
typeof worker.addEventListener !== 'function' ||
|
|
233
|
+
typeof worker.terminate !== 'function') {
|
|
234
|
+
throw new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't start: createWorker returned ${describeValue(worker)}, not a Worker`);
|
|
203
235
|
}
|
|
204
236
|
worker.addEventListener('message', (event) => this.onMessage(event));
|
|
205
237
|
// An uncaught error, or a script that fails to load: the worker is in an
|
|
@@ -255,8 +287,8 @@ export class ThreadedCompute {
|
|
|
255
287
|
/**
|
|
256
288
|
* Creates a ThreadedCompute backend.
|
|
257
289
|
*
|
|
258
|
-
* @param options - The worker script, the tasks it
|
|
259
|
-
* optionally, a timeout.
|
|
290
|
+
* @param options - The worker script (`url` or `createWorker`), the tasks it
|
|
291
|
+
* can run and, optionally, a timeout.
|
|
260
292
|
* @returns A new `ThreadedCompute` instance.
|
|
261
293
|
*
|
|
262
294
|
* @throws {TypeError} For a missing or wrongly typed option.
|
|
@@ -265,7 +297,10 @@ export class ThreadedCompute {
|
|
|
265
297
|
* @example
|
|
266
298
|
* ```ts
|
|
267
299
|
* const backend = createThreadedCompute({
|
|
268
|
-
*
|
|
300
|
+
* createWorker: () =>
|
|
301
|
+
* new Worker(new URL('./resize.worker.ts', import.meta.url), {
|
|
302
|
+
* type: 'module'
|
|
303
|
+
* }),
|
|
269
304
|
* canRunTasks: ['resizeImage']
|
|
270
305
|
* });
|
|
271
306
|
* ```
|
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,OAAO,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,SAAS,CACjB,wDAAwD,aAAa,CAAC,OAAO,CAAC,EAAE,CACjF,CAAC;IACJ,CAAC;IAED,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;
|
|
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,MA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AC;aAAM,IAAI,QAAQ,IAAI,KAAK,EAAE,CAAC;YAC7B,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7B,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CACT,IAAI,eAAe,CACjB,QAAQ,EACR,gBAAgB,QAAQ,kDAAkD,CAC3E,CACF,CAAC;QACJ,CAAC;IACH,CAAC;IAED,mDAAmD;IAC3C,aAAa,CAAC,GAAW,EAAE,KAAe;QAChD,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;YAC9C,IAAI,CAAC,MAAM,CACT,IAAI,eAAe,CACjB,IAAI,CAAC,QAAQ,EACb,gBAAgB,IAAI,CAAC,QAAQ,mBAAmB,GAAG,EAAE,EACrD,EAAE,KAAK,EAAE,CACV,CACF,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,qBAAqB,CACnC,OAAwC;IAExC,OAAO,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import type { TaskContextInterface } from '@hybrid-compute/core';
|
|
2
2
|
/**
|
|
3
|
-
* Options for {@link createThreadedCompute}.
|
|
3
|
+
* Options for {@link createThreadedCompute}. Give exactly one of `url` and
|
|
4
|
+
* `createWorker`.
|
|
4
5
|
*
|
|
5
|
-
* @property
|
|
6
|
-
*
|
|
6
|
+
* @property createWorker - A function that returns a new module `Worker`.
|
|
7
|
+
* Use it with a bundler: Vite and webpack build the worker script only when
|
|
8
|
+
* they see `new Worker(new URL('./x.worker.ts', import.meta.url), ...)`
|
|
9
|
+
* written out in full. It's called on the first task, and again to start a
|
|
10
|
+
* new worker after a crash or {@link ThreadedCompute.close}.
|
|
11
|
+
* @property url - The worker script, for a script served as it is, without a
|
|
12
|
+
* bundler. It's started as a module worker.
|
|
7
13
|
* @property canRunTasks - The tasks the worker script can run. Only these are
|
|
8
14
|
* sent to it.
|
|
9
15
|
* @property timeout - How long to wait for a reply, in milliseconds, before
|
|
@@ -13,14 +19,18 @@ import type { TaskContextInterface } from '@hybrid-compute/core';
|
|
|
13
19
|
* @example
|
|
14
20
|
* ```ts
|
|
15
21
|
* const options: ThreadedComputeOptionsInterface = {
|
|
16
|
-
*
|
|
22
|
+
* createWorker: () =>
|
|
23
|
+
* new Worker(new URL('./resize.worker.ts', import.meta.url), {
|
|
24
|
+
* type: 'module'
|
|
25
|
+
* }),
|
|
17
26
|
* canRunTasks: ['resizeImage'],
|
|
18
27
|
* timeout: 10_000
|
|
19
28
|
* };
|
|
20
29
|
* ```
|
|
21
30
|
*/
|
|
22
31
|
export interface ThreadedComputeOptionsInterface {
|
|
23
|
-
|
|
32
|
+
createWorker?: () => Worker;
|
|
33
|
+
url?: string | URL;
|
|
24
34
|
canRunTasks: readonly string[];
|
|
25
35
|
timeout?: number;
|
|
26
36
|
}
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEjE
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,WAAW,+BAA+B;IAC9C,YAAY,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACnB,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,0BAA0B,CAAC,KAAK,GAAG,OAAO;IACzD,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,KAAK,CAAC;CACd;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,4BAA4B;IAC3C,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,IAAI,CAAC;CACd;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,4BAA4B,CAAC,MAAM,GAAG,OAAO;IAC5D,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,cAAc,CAAC,KAAK,GAAG,KAAK,EAAE,MAAM,GAAG,OAAO,IAAI,CAC5D,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,QAAQ,CAAC,oBAAoB,CAAC,KACpC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAE9B;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC,gBAAgB,CACd,IAAI,EAAE,SAAS,EACf,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAC3C,IAAI,CAAC;IACR,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;CACrC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hybrid-compute/worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.40.0",
|
|
4
4
|
"description": "Threaded compute backend for executing tasks in Web Workers.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"web-worker",
|
|
@@ -25,22 +25,31 @@
|
|
|
25
25
|
"license": "MIT",
|
|
26
26
|
"author": "Alexander Vassbotn Røyne-Helgesen <alexander@phun-ky.net>",
|
|
27
27
|
"type": "module",
|
|
28
|
-
"exports":
|
|
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",
|
|
37
46
|
"release": "release-it",
|
|
38
47
|
"test": "tsx --test **/__tests__/**/*.spec.ts",
|
|
39
48
|
"pretest:ci": "rm -rf coverage && mkdir -p coverage",
|
|
40
|
-
"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\""
|
|
49
|
+
"test:ci": "glob-bin -c \"node --enable-source-maps --import tsx --test --no-warnings --experimental-test-coverage --test-coverage-lines=99 --test-coverage-functions=100 --test-coverage-branches=95 --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.
|
|
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,438 @@
|
|
|
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, createWorker, canRunTasks, timeout } = options;
|
|
44
|
+
|
|
45
|
+
if ((url === undefined) === (createWorker === undefined)) {
|
|
46
|
+
throw new TypeError(
|
|
47
|
+
'Give either url or createWorker: url for a worker script served as it is, createWorker when a bundler builds it'
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (
|
|
52
|
+
url !== undefined &&
|
|
53
|
+
!(url instanceof URL) &&
|
|
54
|
+
(typeof url !== 'string' || url === '')
|
|
55
|
+
) {
|
|
56
|
+
throw new TypeError(
|
|
57
|
+
`url must be a URL or a non-empty string, got ${describeValue(url)}`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (createWorker !== undefined && typeof createWorker !== 'function') {
|
|
62
|
+
throw new TypeError(
|
|
63
|
+
`createWorker must be a function that returns a new Worker, got ${describeValue(createWorker)}`
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (
|
|
68
|
+
!Array.isArray(canRunTasks) ||
|
|
69
|
+
!canRunTasks.every((name) => typeof name === 'string' && name !== '')
|
|
70
|
+
) {
|
|
71
|
+
throw new TypeError(
|
|
72
|
+
`canRunTasks must be an array of task names, got ${describeValue(canRunTasks)}`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (
|
|
77
|
+
timeout !== undefined &&
|
|
78
|
+
(typeof timeout !== 'number' || !Number.isFinite(timeout))
|
|
79
|
+
) {
|
|
80
|
+
throw new TypeError(
|
|
81
|
+
`timeout must be a number of milliseconds, got ${describeValue(timeout)}`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (typeof timeout === 'number' && timeout < 0) {
|
|
86
|
+
throw new RangeError(
|
|
87
|
+
`timeout must be 0 (no timeout) or more, got ${timeout}`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
// One way to start a worker, whichever option was given
|
|
93
|
+
createWorker:
|
|
94
|
+
(createWorker as (() => Worker) | undefined) ??
|
|
95
|
+
(() => new Worker(url as string | URL, { type: 'module' })),
|
|
96
|
+
// For error messages
|
|
97
|
+
source:
|
|
98
|
+
createWorker === undefined ? `the worker ${String(url)}` : 'createWorker',
|
|
99
|
+
tasks: new Set(canRunTasks as string[]) as ReadonlySet<string>,
|
|
100
|
+
timeout: (timeout as number | undefined) ?? 0
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* ThreadedCompute is a backend that runs tasks in a dedicated module Web
|
|
106
|
+
* Worker, so heavy work doesn't block the main thread.
|
|
107
|
+
*
|
|
108
|
+
* It starts the worker on the first task, not when it's created, sends each
|
|
109
|
+
* task with an id and matches the replies by id. Write the worker script with
|
|
110
|
+
* {@link exposeTasks}, or by hand following {@link WorkerTaskMessageInterface}
|
|
111
|
+
* and {@link WorkerResultMessageInterface}.
|
|
112
|
+
*
|
|
113
|
+
* Every failure (an `error` in the reply, a crash, the timeout) rejects with a
|
|
114
|
+
* {@link WorkerTaskError}. If the worker crashes, a new one starts on the next
|
|
115
|
+
* task. Call {@link ThreadedCompute.close} when you're done with it.
|
|
116
|
+
*
|
|
117
|
+
* Web Workers only exist in browsers (and Deno and Bun): where there is no
|
|
118
|
+
* global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
|
|
119
|
+
* another backend.
|
|
120
|
+
*
|
|
121
|
+
* @example With a bundler
|
|
122
|
+
* ```ts
|
|
123
|
+
* // Vite and webpack build the worker script when they see this literal
|
|
124
|
+
* // new Worker(new URL(...)), so keep it written out in full
|
|
125
|
+
* const threaded = createThreadedCompute({
|
|
126
|
+
* createWorker: () =>
|
|
127
|
+
* new Worker(new URL('./add.worker.ts', import.meta.url), {
|
|
128
|
+
* type: 'module'
|
|
129
|
+
* }),
|
|
130
|
+
* canRunTasks: ['add']
|
|
131
|
+
* });
|
|
132
|
+
*
|
|
133
|
+
* const result = await threaded.runTask<number, number>('add', 5);
|
|
134
|
+
* ```
|
|
135
|
+
*
|
|
136
|
+
* @example Without a bundler
|
|
137
|
+
* ```ts
|
|
138
|
+
* const threaded = createThreadedCompute({
|
|
139
|
+
* url: '/workers/add.worker.js',
|
|
140
|
+
* canRunTasks: ['add']
|
|
141
|
+
* });
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
|
|
145
|
+
*/
|
|
146
|
+
export class ThreadedCompute implements ComputeBackendInterface {
|
|
147
|
+
private readonly settings: ReturnType<typeof toSettings>;
|
|
148
|
+
private worker?: Worker;
|
|
149
|
+
private readonly pending = new Map<number, PendingTaskType>();
|
|
150
|
+
private nextId = 1;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Creates the backend. It checks the options, and starts no worker until
|
|
154
|
+
* the first task.
|
|
155
|
+
*
|
|
156
|
+
* @param options - The worker script (`url` or `createWorker`), the tasks
|
|
157
|
+
* it can run and, optionally, a timeout.
|
|
158
|
+
*
|
|
159
|
+
* @throws {TypeError} For a missing or wrongly typed option.
|
|
160
|
+
* @throws {RangeError} For a negative timeout.
|
|
161
|
+
*/
|
|
162
|
+
constructor(options: ThreadedComputeOptionsInterface) {
|
|
163
|
+
this.settings = toSettings(options);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Determines if this backend can run the given task.
|
|
168
|
+
*
|
|
169
|
+
* @param taskName - Name of the task.
|
|
170
|
+
* @returns `true` if the task is in `canRunTasks` and this runtime has Web
|
|
171
|
+
* Workers.
|
|
172
|
+
*/
|
|
173
|
+
canRun(taskName: string): boolean {
|
|
174
|
+
return hasWorkers() && this.settings.tasks.has(taskName);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Runs a task in the worker and waits for its reply.
|
|
179
|
+
*
|
|
180
|
+
* @typeParam Input - The input type of the task.
|
|
181
|
+
* @typeParam Output - The output type of the task.
|
|
182
|
+
*
|
|
183
|
+
* @param taskName - The name of the task to run.
|
|
184
|
+
* @param input - The input for the task. It's copied with the structured
|
|
185
|
+
* clone algorithm, so it can't hold functions or DOM nodes.
|
|
186
|
+
* @param options - Options for this call. With a `signal`, `runTask`
|
|
187
|
+
* rejects with the signal's reason as soon as it aborts, and the worker is
|
|
188
|
+
* told to cancel the task.
|
|
189
|
+
* @returns A Promise resolving to the reply's `result`. It rejects with a
|
|
190
|
+
* `NoBackendError` (from `@hybrid-compute/core`) if the task isn't in
|
|
191
|
+
* `canRunTasks`, a `TypeError` if this runtime has no Web Workers, a
|
|
192
|
+
* {@link WorkerTaskError} if the task fails, and with the signal's reason
|
|
193
|
+
* if the call is cancelled.
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```ts
|
|
197
|
+
* const result = await threaded.runTask('square', 9); // 81
|
|
198
|
+
* ```
|
|
199
|
+
*/
|
|
200
|
+
async runTask<Input, Output>(
|
|
201
|
+
taskName: string,
|
|
202
|
+
input: Input,
|
|
203
|
+
options?: RunTaskOptionsInterface
|
|
204
|
+
): Promise<Output> {
|
|
205
|
+
if (!this.settings.tasks.has(taskName)) {
|
|
206
|
+
throw new NoBackendError(
|
|
207
|
+
taskName,
|
|
208
|
+
'worker',
|
|
209
|
+
`The worker can't run task '${taskName}'; it isn't in canRunTasks`
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (!hasWorkers()) {
|
|
214
|
+
throw new TypeError(
|
|
215
|
+
'Web Workers are not available in this runtime; @hybrid-compute/worker needs a global Worker'
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const signal = options?.signal;
|
|
220
|
+
|
|
221
|
+
if (signal?.aborted) throw signal.reason;
|
|
222
|
+
|
|
223
|
+
const worker = this.start(taskName);
|
|
224
|
+
const { timeout } = this.settings;
|
|
225
|
+
const id = this.nextId++;
|
|
226
|
+
|
|
227
|
+
return new Promise<Output>((resolve, reject) => {
|
|
228
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
229
|
+
|
|
230
|
+
const finish = () => {
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
signal?.removeEventListener('abort', onAbort);
|
|
233
|
+
this.pending.delete(id);
|
|
234
|
+
};
|
|
235
|
+
// Settled before the worker replied: tell the worker to stop
|
|
236
|
+
const cancel = () => {
|
|
237
|
+
const message: WorkerCancelMessageInterface = { id, cancel: true };
|
|
238
|
+
|
|
239
|
+
worker.postMessage(message);
|
|
240
|
+
};
|
|
241
|
+
const onAbort = () => {
|
|
242
|
+
finish();
|
|
243
|
+
cancel();
|
|
244
|
+
reject(signal?.reason);
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
if (timeout > 0) {
|
|
248
|
+
timer = setTimeout(() => {
|
|
249
|
+
finish();
|
|
250
|
+
cancel();
|
|
251
|
+
reject(
|
|
252
|
+
new WorkerTaskError(
|
|
253
|
+
taskName,
|
|
254
|
+
`Worker task '${taskName}' timed out after ${timeout} ms`
|
|
255
|
+
)
|
|
256
|
+
);
|
|
257
|
+
}, timeout);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
261
|
+
this.pending.set(id, {
|
|
262
|
+
taskName,
|
|
263
|
+
resolve: (value) => {
|
|
264
|
+
finish();
|
|
265
|
+
resolve(value as Output);
|
|
266
|
+
},
|
|
267
|
+
reject: (reason) => {
|
|
268
|
+
finish();
|
|
269
|
+
reject(reason);
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
const message: WorkerTaskMessageInterface<Input> = {
|
|
274
|
+
id,
|
|
275
|
+
task: taskName,
|
|
276
|
+
input
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
worker.postMessage(message);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
this.pending
|
|
283
|
+
.get(id)
|
|
284
|
+
?.reject(
|
|
285
|
+
new WorkerTaskError(
|
|
286
|
+
taskName,
|
|
287
|
+
`Worker task '${taskName}' couldn't send its input to the worker`,
|
|
288
|
+
{ cause: error }
|
|
289
|
+
)
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Terminates the worker, if one is running. Tasks still waiting for a
|
|
297
|
+
* reply reject with a {@link WorkerTaskError}. The next task starts a new
|
|
298
|
+
* worker.
|
|
299
|
+
*/
|
|
300
|
+
close(): void {
|
|
301
|
+
const { worker } = this;
|
|
302
|
+
|
|
303
|
+
this.worker = undefined;
|
|
304
|
+
worker?.terminate();
|
|
305
|
+
this.rejectPending('the worker was closed');
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The running worker, starting one first if needed. */
|
|
309
|
+
private start(taskName: string): Worker {
|
|
310
|
+
if (this.worker) return this.worker;
|
|
311
|
+
|
|
312
|
+
let worker: Worker;
|
|
313
|
+
|
|
314
|
+
try {
|
|
315
|
+
worker = this.settings.createWorker();
|
|
316
|
+
} catch (error) {
|
|
317
|
+
throw new WorkerTaskError(
|
|
318
|
+
taskName,
|
|
319
|
+
`Worker task '${taskName}' couldn't start ${this.settings.source}`,
|
|
320
|
+
{ cause: error }
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (
|
|
325
|
+
typeof worker?.postMessage !== 'function' ||
|
|
326
|
+
typeof worker.addEventListener !== 'function' ||
|
|
327
|
+
typeof worker.terminate !== 'function'
|
|
328
|
+
) {
|
|
329
|
+
throw new WorkerTaskError(
|
|
330
|
+
taskName,
|
|
331
|
+
`Worker task '${taskName}' couldn't start: createWorker returned ${describeValue(worker)}, not a Worker`
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
worker.addEventListener('message', (event) => this.onMessage(event));
|
|
336
|
+
// An uncaught error, or a script that fails to load: the worker is in an
|
|
337
|
+
// unknown state, so reject what it was doing and start over next time
|
|
338
|
+
worker.addEventListener('error', (event) => {
|
|
339
|
+
if (this.worker !== worker) return;
|
|
340
|
+
|
|
341
|
+
const detail = (event as Partial<ErrorEvent>).message;
|
|
342
|
+
|
|
343
|
+
this.worker = undefined;
|
|
344
|
+
worker.terminate();
|
|
345
|
+
this.rejectPending(
|
|
346
|
+
detail
|
|
347
|
+
? `the worker threw: ${detail}`
|
|
348
|
+
: 'the worker failed: its script did not load, or threw while starting',
|
|
349
|
+
event
|
|
350
|
+
);
|
|
351
|
+
});
|
|
352
|
+
// A reply that couldn't be deserialised: nothing tells which task it
|
|
353
|
+
// was for, so reject them all instead of letting one wait forever
|
|
354
|
+
worker.addEventListener('messageerror', (event) => {
|
|
355
|
+
if (this.worker !== worker) return;
|
|
356
|
+
|
|
357
|
+
this.rejectPending('a reply from the worker could not be read', event);
|
|
358
|
+
});
|
|
359
|
+
this.worker = worker;
|
|
360
|
+
|
|
361
|
+
return worker;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Match a reply to its task by id; ignore anything that can't be matched. */
|
|
365
|
+
private onMessage(event: MessageEvent) {
|
|
366
|
+
const reply: unknown = event.data;
|
|
367
|
+
|
|
368
|
+
if (!isPlainObject(reply) || typeof reply.id !== 'number') return;
|
|
369
|
+
|
|
370
|
+
const task = this.pending.get(reply.id);
|
|
371
|
+
|
|
372
|
+
if (!task) return;
|
|
373
|
+
|
|
374
|
+
const { taskName } = task;
|
|
375
|
+
const { error } = reply;
|
|
376
|
+
|
|
377
|
+
if (error !== undefined && error !== null) {
|
|
378
|
+
const text = messageOf(error);
|
|
379
|
+
|
|
380
|
+
task.reject(
|
|
381
|
+
new WorkerTaskError(
|
|
382
|
+
taskName,
|
|
383
|
+
`Worker task '${taskName}' failed${text ? `: ${text}` : ''}`,
|
|
384
|
+
{ detail: error }
|
|
385
|
+
)
|
|
386
|
+
);
|
|
387
|
+
} else if ('result' in reply) {
|
|
388
|
+
task.resolve(reply.result);
|
|
389
|
+
} else {
|
|
390
|
+
task.reject(
|
|
391
|
+
new WorkerTaskError(
|
|
392
|
+
taskName,
|
|
393
|
+
`Worker task '${taskName}' got a reply with neither a result nor an error`
|
|
394
|
+
)
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Reject every task still waiting for a reply. */
|
|
400
|
+
private rejectPending(why: string, cause?: unknown) {
|
|
401
|
+
for (const task of [...this.pending.values()]) {
|
|
402
|
+
task.reject(
|
|
403
|
+
new WorkerTaskError(
|
|
404
|
+
task.taskName,
|
|
405
|
+
`Worker task '${task.taskName}' got no reply: ${why}`,
|
|
406
|
+
{ cause }
|
|
407
|
+
)
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Creates a ThreadedCompute backend.
|
|
415
|
+
*
|
|
416
|
+
* @param options - The worker script (`url` or `createWorker`), the tasks it
|
|
417
|
+
* can run and, optionally, a timeout.
|
|
418
|
+
* @returns A new `ThreadedCompute` instance.
|
|
419
|
+
*
|
|
420
|
+
* @throws {TypeError} For a missing or wrongly typed option.
|
|
421
|
+
* @throws {RangeError} For a negative timeout.
|
|
422
|
+
*
|
|
423
|
+
* @example
|
|
424
|
+
* ```ts
|
|
425
|
+
* const backend = createThreadedCompute({
|
|
426
|
+
* createWorker: () =>
|
|
427
|
+
* new Worker(new URL('./resize.worker.ts', import.meta.url), {
|
|
428
|
+
* type: 'module'
|
|
429
|
+
* }),
|
|
430
|
+
* canRunTasks: ['resizeImage']
|
|
431
|
+
* });
|
|
432
|
+
* ```
|
|
433
|
+
*/
|
|
434
|
+
export function createThreadedCompute(
|
|
435
|
+
options: ThreadedComputeOptionsInterface
|
|
436
|
+
) {
|
|
437
|
+
return new ThreadedCompute(options);
|
|
438
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { TaskContextInterface } from '@hybrid-compute/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Options for {@link createThreadedCompute}. Give exactly one of `url` and
|
|
5
|
+
* `createWorker`.
|
|
6
|
+
*
|
|
7
|
+
* @property createWorker - A function that returns a new module `Worker`.
|
|
8
|
+
* Use it with a bundler: Vite and webpack build the worker script only when
|
|
9
|
+
* they see `new Worker(new URL('./x.worker.ts', import.meta.url), ...)`
|
|
10
|
+
* written out in full. It's called on the first task, and again to start a
|
|
11
|
+
* new worker after a crash or {@link ThreadedCompute.close}.
|
|
12
|
+
* @property url - The worker script, for a script served as it is, without a
|
|
13
|
+
* bundler. It's started as a module worker.
|
|
14
|
+
* @property canRunTasks - The tasks the worker script can run. Only these are
|
|
15
|
+
* sent to it.
|
|
16
|
+
* @property timeout - How long to wait for a reply, in milliseconds, before
|
|
17
|
+
* rejecting with a `WorkerTaskError`. Defaults to `0`: no timeout, since
|
|
18
|
+
* workers are for long running work.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* const options: ThreadedComputeOptionsInterface = {
|
|
23
|
+
* createWorker: () =>
|
|
24
|
+
* new Worker(new URL('./resize.worker.ts', import.meta.url), {
|
|
25
|
+
* type: 'module'
|
|
26
|
+
* }),
|
|
27
|
+
* canRunTasks: ['resizeImage'],
|
|
28
|
+
* timeout: 10_000
|
|
29
|
+
* };
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export interface ThreadedComputeOptionsInterface {
|
|
33
|
+
createWorker?: () => Worker;
|
|
34
|
+
url?: string | URL;
|
|
35
|
+
canRunTasks: readonly string[];
|
|
36
|
+
timeout?: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* What the worker script receives for each task: the task name, its input
|
|
41
|
+
* and an `id`, which the reply must repeat. The input is copied with the
|
|
42
|
+
* structured clone algorithm, so it can't hold functions or DOM nodes.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* const message: WorkerTaskMessageInterface = { id: 1, task: 'double', input: 21 };
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
|
|
50
|
+
*/
|
|
51
|
+
export interface WorkerTaskMessageInterface<Input = unknown> {
|
|
52
|
+
id: number;
|
|
53
|
+
task: string;
|
|
54
|
+
input: Input;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What the worker script receives when a task is cancelled or times out:
|
|
59
|
+
* the task's `id` and `cancel: true`. {@link exposeTasks} aborts the task's
|
|
60
|
+
* signal; a hand written worker script can ignore it.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```ts
|
|
64
|
+
* const message: WorkerCancelMessageInterface = { id: 1, cancel: true };
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export interface WorkerCancelMessageInterface {
|
|
68
|
+
id: number;
|
|
69
|
+
cancel: true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* What the worker script sends back: the task's `id` with either a `result`
|
|
74
|
+
* or an `error`. An `error` (a message string, or an object with a `message`)
|
|
75
|
+
* rejects the task with a `WorkerTaskError`.
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* self.postMessage({ id: 1, result: 42 } satisfies WorkerResultMessageInterface);
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export interface WorkerResultMessageInterface<Output = unknown> {
|
|
83
|
+
id: number;
|
|
84
|
+
result?: Output;
|
|
85
|
+
error?: unknown;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A task in the worker script, for {@link exposeTasks}. It gets the input and
|
|
90
|
+
* a context with a `signal`, which aborts when the caller cancels the task or
|
|
91
|
+
* its timeout passes.
|
|
92
|
+
*
|
|
93
|
+
* @typeParam Input - The input type of the task.
|
|
94
|
+
* @typeParam Output - The output type of the task.
|
|
95
|
+
*/
|
|
96
|
+
export type WorkerTaskType<Input = never, Output = unknown> = (
|
|
97
|
+
input: Input,
|
|
98
|
+
context: Required<TaskContextInterface>
|
|
99
|
+
) => Output | Promise<Output>;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Where {@link exposeTasks} listens and replies. Defaults to the worker's
|
|
103
|
+
* global scope (`self`); pass another one to adapt it, for example to a
|
|
104
|
+
* `MessagePort`.
|
|
105
|
+
*/
|
|
106
|
+
export interface WorkerScopeInterface {
|
|
107
|
+
addEventListener(
|
|
108
|
+
type: 'message',
|
|
109
|
+
listener: (event: { data: unknown }) => void
|
|
110
|
+
): void;
|
|
111
|
+
postMessage(message: unknown): void;
|
|
112
|
+
}
|
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
|
+
};
|