@hybrid-compute/worker 0.37.3 → 0.38.1

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/dist/index.js ADDED
@@ -0,0 +1,276 @@
1
+ import { NoBackendError } from '@hybrid-compute/core';
2
+ import { WorkerTaskError } from './errors.js';
3
+ import { describeValue, isPlainObject, messageOf } from './utils.js';
4
+ export * from './errors.js';
5
+ export * from './expose.js';
6
+ export * from './types.js';
7
+ /** Whether this runtime has Web Workers. */
8
+ const hasWorkers = () => typeof Worker === 'function';
9
+ /**
10
+ * Check the options and return them normalised.
11
+ *
12
+ * @throws {TypeError} For a missing or wrongly typed option.
13
+ * @throws {RangeError} For a negative timeout.
14
+ */
15
+ const toSettings = (options) => {
16
+ if (!isPlainObject(options)) {
17
+ throw new TypeError(`createThreadedCompute expects an options object, got ${describeValue(options)}`);
18
+ }
19
+ const { url, canRunTasks, timeout } = options;
20
+ if (!(url instanceof URL) && (typeof url !== 'string' || url === '')) {
21
+ throw new TypeError(`url must be a URL or a non-empty string, got ${describeValue(url)}`);
22
+ }
23
+ if (!Array.isArray(canRunTasks) ||
24
+ !canRunTasks.every((name) => typeof name === 'string' && name !== '')) {
25
+ throw new TypeError(`canRunTasks must be an array of task names, got ${describeValue(canRunTasks)}`);
26
+ }
27
+ if (timeout !== undefined &&
28
+ (typeof timeout !== 'number' || !Number.isFinite(timeout))) {
29
+ throw new TypeError(`timeout must be a number of milliseconds, got ${describeValue(timeout)}`);
30
+ }
31
+ if (typeof timeout === 'number' && timeout < 0) {
32
+ throw new RangeError(`timeout must be 0 (no timeout) or more, got ${timeout}`);
33
+ }
34
+ return {
35
+ url: url,
36
+ tasks: new Set(canRunTasks),
37
+ timeout: timeout ?? 0
38
+ };
39
+ };
40
+ /**
41
+ * ThreadedCompute is a backend that runs tasks in a dedicated module Web
42
+ * Worker, so heavy work doesn't block the main thread.
43
+ *
44
+ * It starts the worker on the first task, not when it's created, sends each
45
+ * task with an id and matches the replies by id. Write the worker script with
46
+ * {@link exposeTasks}, or by hand following {@link WorkerTaskMessageInterface}
47
+ * and {@link WorkerResultMessageInterface}.
48
+ *
49
+ * Every failure (an `error` in the reply, a crash, the timeout) rejects with a
50
+ * {@link WorkerTaskError}. If the worker crashes, a new one starts on the next
51
+ * task. Call {@link ThreadedCompute.close} when you're done with it.
52
+ *
53
+ * Web Workers only exist in browsers (and Deno and Bun): where there is no
54
+ * global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
55
+ * another backend.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const threaded = createThreadedCompute({
60
+ * url: new URL('./worker.js', import.meta.url),
61
+ * canRunTasks: ['add']
62
+ * });
63
+ *
64
+ * const result = await threaded.runTask<number, number>('add', 5);
65
+ * ```
66
+ *
67
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
68
+ */
69
+ export class ThreadedCompute {
70
+ /**
71
+ * Creates the backend. It checks the options, and starts no worker until
72
+ * the first task.
73
+ *
74
+ * @param options - The worker script, the tasks it can run and,
75
+ * optionally, a timeout.
76
+ *
77
+ * @throws {TypeError} For a missing or wrongly typed option.
78
+ * @throws {RangeError} For a negative timeout.
79
+ */
80
+ constructor(options) {
81
+ this.pending = new Map();
82
+ this.nextId = 1;
83
+ this.settings = toSettings(options);
84
+ }
85
+ /**
86
+ * Determines if this backend can run the given task.
87
+ *
88
+ * @param taskName - Name of the task.
89
+ * @returns `true` if the task is in `canRunTasks` and this runtime has Web
90
+ * Workers.
91
+ */
92
+ canRun(taskName) {
93
+ return hasWorkers() && this.settings.tasks.has(taskName);
94
+ }
95
+ /**
96
+ * Runs a task in the worker and waits for its reply.
97
+ *
98
+ * @typeParam Input - The input type of the task.
99
+ * @typeParam Output - The output type of the task.
100
+ *
101
+ * @param taskName - The name of the task to run.
102
+ * @param input - The input for the task. It's copied with the structured
103
+ * clone algorithm, so it can't hold functions or DOM nodes.
104
+ * @param options - Options for this call. With a `signal`, `runTask`
105
+ * rejects with the signal's reason as soon as it aborts, and the worker is
106
+ * told to cancel the task.
107
+ * @returns A Promise resolving to the reply's `result`. It rejects with a
108
+ * `NoBackendError` (from `@hybrid-compute/core`) if the task isn't in
109
+ * `canRunTasks`, a `TypeError` if this runtime has no Web Workers, a
110
+ * {@link WorkerTaskError} if the task fails, and with the signal's reason
111
+ * if the call is cancelled.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * const result = await threaded.runTask('square', 9); // 81
116
+ * ```
117
+ */
118
+ async runTask(taskName, input, options) {
119
+ if (!this.settings.tasks.has(taskName)) {
120
+ throw new NoBackendError(taskName, 'worker', `The worker can't run task '${taskName}'; it isn't in canRunTasks`);
121
+ }
122
+ if (!hasWorkers()) {
123
+ throw new TypeError('Web Workers are not available in this runtime; @hybrid-compute/worker needs a global Worker');
124
+ }
125
+ const signal = options?.signal;
126
+ if (signal?.aborted)
127
+ throw signal.reason;
128
+ const worker = this.start(taskName);
129
+ const { timeout } = this.settings;
130
+ const id = this.nextId++;
131
+ return new Promise((resolve, reject) => {
132
+ let timer;
133
+ const finish = () => {
134
+ clearTimeout(timer);
135
+ signal?.removeEventListener('abort', onAbort);
136
+ this.pending.delete(id);
137
+ };
138
+ // Settled before the worker replied: tell the worker to stop
139
+ const cancel = () => {
140
+ const message = { id, cancel: true };
141
+ worker.postMessage(message);
142
+ };
143
+ const onAbort = () => {
144
+ finish();
145
+ cancel();
146
+ reject(signal?.reason);
147
+ };
148
+ if (timeout > 0) {
149
+ timer = setTimeout(() => {
150
+ finish();
151
+ cancel();
152
+ reject(new WorkerTaskError(taskName, `Worker task '${taskName}' timed out after ${timeout} ms`));
153
+ }, timeout);
154
+ }
155
+ signal?.addEventListener('abort', onAbort, { once: true });
156
+ this.pending.set(id, {
157
+ taskName,
158
+ resolve: (value) => {
159
+ finish();
160
+ resolve(value);
161
+ },
162
+ reject: (reason) => {
163
+ finish();
164
+ reject(reason);
165
+ }
166
+ });
167
+ const message = {
168
+ id,
169
+ task: taskName,
170
+ input
171
+ };
172
+ try {
173
+ worker.postMessage(message);
174
+ }
175
+ catch (error) {
176
+ this.pending
177
+ .get(id)
178
+ ?.reject(new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't send its input to the worker`, { cause: error }));
179
+ }
180
+ });
181
+ }
182
+ /**
183
+ * Terminates the worker, if one is running. Tasks still waiting for a
184
+ * reply reject with a {@link WorkerTaskError}. The next task starts a new
185
+ * worker.
186
+ */
187
+ close() {
188
+ const { worker } = this;
189
+ this.worker = undefined;
190
+ worker?.terminate();
191
+ this.rejectPending('the worker was closed');
192
+ }
193
+ /** The running worker, starting one first if needed. */
194
+ start(taskName) {
195
+ if (this.worker)
196
+ return this.worker;
197
+ let worker;
198
+ try {
199
+ worker = new Worker(this.settings.url, { type: 'module' });
200
+ }
201
+ catch (error) {
202
+ throw new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't start the worker ${String(this.settings.url)}`, { cause: error });
203
+ }
204
+ worker.addEventListener('message', (event) => this.onMessage(event));
205
+ // An uncaught error, or a script that fails to load: the worker is in an
206
+ // unknown state, so reject what it was doing and start over next time
207
+ worker.addEventListener('error', (event) => {
208
+ if (this.worker !== worker)
209
+ return;
210
+ const detail = event.message;
211
+ this.worker = undefined;
212
+ worker.terminate();
213
+ this.rejectPending(detail
214
+ ? `the worker threw: ${detail}`
215
+ : 'the worker failed: its script did not load, or threw while starting', event);
216
+ });
217
+ // A reply that couldn't be deserialised: nothing tells which task it
218
+ // was for, so reject them all instead of letting one wait forever
219
+ worker.addEventListener('messageerror', (event) => {
220
+ if (this.worker !== worker)
221
+ return;
222
+ this.rejectPending('a reply from the worker could not be read', event);
223
+ });
224
+ this.worker = worker;
225
+ return worker;
226
+ }
227
+ /** Match a reply to its task by id; ignore anything that can't be matched. */
228
+ onMessage(event) {
229
+ const reply = event.data;
230
+ if (!isPlainObject(reply) || typeof reply.id !== 'number')
231
+ return;
232
+ const task = this.pending.get(reply.id);
233
+ if (!task)
234
+ return;
235
+ const { taskName } = task;
236
+ const { error } = reply;
237
+ if (error !== undefined && error !== null) {
238
+ const text = messageOf(error);
239
+ task.reject(new WorkerTaskError(taskName, `Worker task '${taskName}' failed${text ? `: ${text}` : ''}`, { detail: error }));
240
+ }
241
+ else if ('result' in reply) {
242
+ task.resolve(reply.result);
243
+ }
244
+ else {
245
+ task.reject(new WorkerTaskError(taskName, `Worker task '${taskName}' got a reply with neither a result nor an error`));
246
+ }
247
+ }
248
+ /** Reject every task still waiting for a reply. */
249
+ rejectPending(why, cause) {
250
+ for (const task of [...this.pending.values()]) {
251
+ task.reject(new WorkerTaskError(task.taskName, `Worker task '${task.taskName}' got no reply: ${why}`, { cause }));
252
+ }
253
+ }
254
+ }
255
+ /**
256
+ * Creates a ThreadedCompute backend.
257
+ *
258
+ * @param options - The worker script, the tasks it can run and,
259
+ * optionally, a timeout.
260
+ * @returns A new `ThreadedCompute` instance.
261
+ *
262
+ * @throws {TypeError} For a missing or wrongly typed option.
263
+ * @throws {RangeError} For a negative timeout.
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * const backend = createThreadedCompute({
268
+ * url: new URL('./worker.js', import.meta.url),
269
+ * canRunTasks: ['resizeImage']
270
+ * });
271
+ * ```
272
+ */
273
+ export function createThreadedCompute(options) {
274
+ return new ThreadedCompute(options);
275
+ }
276
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,CA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AE,KAAK,EAAE,GAAG,KAAK,CAAC;QAExB,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YAC1C,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;YAE9B,IAAI,CAAC,MAAM,CACT,IAAI,eAAe,CACjB,QAAQ,EACR,gBAAgB,QAAQ,WAAW,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAC5D,EAAE,MAAM,EAAE,KAAK,EAAE,CAClB,CACF,CAAC;QACJ,CAAC;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;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,qBAAqB,CACnC,OAAwC;IAExC,OAAO,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,93 @@
1
+ import type { TaskContextInterface } from '@hybrid-compute/core';
2
+ /**
3
+ * Options for {@link createThreadedCompute}.
4
+ *
5
+ * @property url - The worker script, started as a module worker. Usually
6
+ * `new URL('./worker.js', import.meta.url)`, so bundlers find it.
7
+ * @property canRunTasks - The tasks the worker script can run. Only these are
8
+ * sent to it.
9
+ * @property timeout - How long to wait for a reply, in milliseconds, before
10
+ * rejecting with a `WorkerTaskError`. Defaults to `0`: no timeout, since
11
+ * workers are for long running work.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const options: ThreadedComputeOptionsInterface = {
16
+ * url: new URL('./worker.js', import.meta.url),
17
+ * canRunTasks: ['resizeImage'],
18
+ * timeout: 10_000
19
+ * };
20
+ * ```
21
+ */
22
+ export interface ThreadedComputeOptionsInterface {
23
+ url: string | URL;
24
+ canRunTasks: readonly string[];
25
+ timeout?: number;
26
+ }
27
+ /**
28
+ * What the worker script receives for each task: the task name, its input
29
+ * and an `id`, which the reply must repeat. The input is copied with the
30
+ * structured clone algorithm, so it can't hold functions or DOM nodes.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * const message: WorkerTaskMessageInterface = { id: 1, task: 'double', input: 21 };
35
+ * ```
36
+ *
37
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
38
+ */
39
+ export interface WorkerTaskMessageInterface<Input = unknown> {
40
+ id: number;
41
+ task: string;
42
+ input: Input;
43
+ }
44
+ /**
45
+ * What the worker script receives when a task is cancelled or times out:
46
+ * the task's `id` and `cancel: true`. {@link exposeTasks} aborts the task's
47
+ * signal; a hand written worker script can ignore it.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const message: WorkerCancelMessageInterface = { id: 1, cancel: true };
52
+ * ```
53
+ */
54
+ export interface WorkerCancelMessageInterface {
55
+ id: number;
56
+ cancel: true;
57
+ }
58
+ /**
59
+ * What the worker script sends back: the task's `id` with either a `result`
60
+ * or an `error`. An `error` (a message string, or an object with a `message`)
61
+ * rejects the task with a `WorkerTaskError`.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * self.postMessage({ id: 1, result: 42 } satisfies WorkerResultMessageInterface);
66
+ * ```
67
+ */
68
+ export interface WorkerResultMessageInterface<Output = unknown> {
69
+ id: number;
70
+ result?: Output;
71
+ error?: unknown;
72
+ }
73
+ /**
74
+ * A task in the worker script, for {@link exposeTasks}. It gets the input and
75
+ * a context with a `signal`, which aborts when the caller cancels the task or
76
+ * its timeout passes.
77
+ *
78
+ * @typeParam Input - The input type of the task.
79
+ * @typeParam Output - The output type of the task.
80
+ */
81
+ export type WorkerTaskType<Input = never, Output = unknown> = (input: Input, context: Required<TaskContextInterface>) => Output | Promise<Output>;
82
+ /**
83
+ * Where {@link exposeTasks} listens and replies. Defaults to the worker's
84
+ * global scope (`self`); pass another one to adapt it, for example to a
85
+ * `MessagePort`.
86
+ */
87
+ export interface WorkerScopeInterface {
88
+ addEventListener(type: 'message', listener: (event: {
89
+ data: unknown;
90
+ }) => void): void;
91
+ postMessage(message: unknown): void;
92
+ }
93
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +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;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,+BAA+B;IAC9C,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,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/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,6 @@
1
+ /** What a value is, for error messages: null, an array, or its typeof. */
2
+ export declare const describeValue: (value: unknown) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "null" | "an array" | "an empty string";
3
+ export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
4
+ /** The message for an `error` value: a string, or an object's message. */
5
+ export declare const messageOf: (error: unknown) => string;
6
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,0IAQ3C,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,OAAO,OAAO,KACb,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CACoC,CAAC;AAEvE,0EAA0E;AAC1E,eAAO,MAAM,SAAS,GAAI,OAAO,OAAO,WAYvC,CAAC"}
package/dist/utils.js ADDED
@@ -0,0 +1,26 @@
1
+ /** What a value is, for error messages: null, an array, or its typeof. */
2
+ export const describeValue = (value) => {
3
+ if (value === null)
4
+ return 'null';
5
+ if (Array.isArray(value))
6
+ return 'an array';
7
+ if (value === '')
8
+ return 'an empty string';
9
+ return typeof value;
10
+ };
11
+ export const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
12
+ /** The message for an `error` value: a string, or an object's message. */
13
+ export const messageOf = (error) => {
14
+ if (typeof error === 'string')
15
+ return error;
16
+ if (isPlainObject(error) && typeof error.message === 'string') {
17
+ return error.message;
18
+ }
19
+ try {
20
+ return JSON.stringify(error);
21
+ }
22
+ catch {
23
+ return String(error);
24
+ }
25
+ };
26
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAAc,EAAE,EAAE;IAC9C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,UAAU,CAAC;IAE5C,IAAI,KAAK,KAAK,EAAE;QAAE,OAAO,iBAAiB,CAAC;IAE3C,OAAO,OAAO,KAAK,CAAC;AACtB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,KAAc,EACoB,EAAE,CACpC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,0EAA0E;AAC1E,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5C,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC9D,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hybrid-compute/worker",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "description": "Threaded compute backend for executing tasks in Web Workers.",
5
5
  "keywords": [
6
6
  "web-worker",
@@ -27,6 +27,10 @@
27
27
  "type": "module",
28
28
  "exports": "./dist/index.js",
29
29
  "types": "./dist/index.d.ts",
30
+ "files": [
31
+ "dist",
32
+ "CHANGELOG.md"
33
+ ],
30
34
  "scripts": {
31
35
  "clean": "rm -rf dist *.tsbuildinfo",
32
36
  "typecheck": "tsc -p tsconfig.json",
package/.release-it.json DELETED
@@ -1,83 +0,0 @@
1
- {
2
- "git": {
3
- "requireCleanWorkingDir": false,
4
- "tagName": "@hybrid-compute/worker@${version}",
5
- "commitMessage": "chore: 🤖 ${name}@${version}",
6
- "commitArgs": ["-s"]
7
- },
8
- "github": {
9
- "release": true,
10
- "releaseName": "@hybrid-compute/worker@${version}",
11
- "tokenRef": "GH_TOKEN"
12
- },
13
- "npm": {
14
- "publish": true,
15
- "skipChecks": true
16
- },
17
- "hooks": {
18
- "after:bump": [
19
- "node ../../scripts/sync-sibling-ranges.mjs ${name} ${version}",
20
- "node ../../scripts/sync-lockfile.mjs"
21
- ],
22
- "after:release": "echo Successfully released ${name} v${version}."
23
- },
24
- "plugins": {
25
- "@release-it/conventional-changelog": {
26
- "header": "# Changelog",
27
- "preset": {
28
- "name": "conventionalcommits",
29
- "types": [
30
- {
31
- "type": "chore",
32
- "section": "Tasks"
33
- },
34
- {
35
- "type": "docs",
36
- "section": "Documentation"
37
- },
38
- {
39
- "type": "feat",
40
- "section": "Feature"
41
- },
42
- {
43
- "type": "fix",
44
- "section": "Bug"
45
- },
46
- {
47
- "type": "perf",
48
- "section": "Performance change"
49
- },
50
- {
51
- "type": "refactor",
52
- "section": "Refactoring"
53
- },
54
- {
55
- "type": "release",
56
- "section": "Create a release commit",
57
- "hidden": true
58
- },
59
- {
60
- "type": "style",
61
- "section": "Markup, white-space, formatting, missing semi-colons...",
62
- "hidden": true
63
- },
64
- {
65
- "type": "test",
66
- "section": "Adding missing tests",
67
- "hidden": true
68
- }
69
- ]
70
- },
71
- "infile": "CHANGELOG.md",
72
- "tagOpts": {
73
- "prefix": "@hybrid-compute/worker@"
74
- },
75
- "commitsOpts": {
76
- "path": "."
77
- },
78
- "gitRawCommitsOpts": {
79
- "path": "."
80
- }
81
- }
82
- }
83
- }
package/eslint.config.mjs DELETED
@@ -1,3 +0,0 @@
1
- import SharedConfig from '../../eslint.config.mjs';
2
-
3
- export default SharedConfig;