@vertexvis/web-workers 0.2.2-canary.3 → 0.3.0-canary.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/MIGRATION.md ADDED
@@ -0,0 +1,187 @@
1
+ # Migrating to native worker URLs
2
+
3
+ This release removes the custom `worker:` loader and stops publishing
4
+ `@vertexvis/rollup-plugin-web-workers`. New applications should use `threadsx`
5
+ directly. Existing applications can keep the three remaining helpers in
6
+ `@vertexvis/web-workers`, but no longer need the loader or its Blob-worker
7
+ pipeline.
8
+
9
+ This is a documentation recommendation, not an npm deprecation notice for
10
+ `@vertexvis/web-workers`.
11
+
12
+ ## Prerequisites
13
+
14
+ Remove the old Rollup plugin and install `threadsx`. If your application still
15
+ depends on `threads`, remove that package too:
16
+
17
+ ```sh
18
+ yarn remove @vertexvis/rollup-plugin-web-workers
19
+ yarn add threadsx@^2
20
+
21
+ # or
22
+ npm uninstall @vertexvis/rollup-plugin-web-workers
23
+ npm install threadsx@^2
24
+ ```
25
+
26
+ For applications still using `threads`, also remove it and change direct
27
+ worker imports from `threads/worker` to `threadsx/worker`.
28
+
29
+ Your TypeScript configuration must preserve ES module syntax so the bundler can
30
+ recognize `new Worker(new URL(..., import.meta.url))`; use a module setting
31
+ such as `"module": "esnext"`. Ensure your bundler emits the worker entry as a
32
+ separate file; see the Rollup example below.
33
+
34
+ ## Replace the loader and single-worker helpers
35
+
36
+ Before:
37
+
38
+ ```ts
39
+ import { loadWorker } from 'worker:./worker';
40
+
41
+ const { spawnWorker } = await loadWorker<AddFn>();
42
+ const add = await spawnWorker();
43
+ ```
44
+
45
+ After:
46
+
47
+ ```ts
48
+ import { spawn, Worker } from 'threadsx';
49
+
50
+ const add = await spawn<AddFn>(
51
+ new Worker(new URL('./worker', import.meta.url))
52
+ );
53
+ ```
54
+
55
+ Replace `makeWorker()` with `new Worker(new URL('./worker', import.meta.url))`.
56
+ Terminate the thread through `threadsx` directly:
57
+
58
+ ```ts
59
+ import { Thread } from 'threadsx';
60
+
61
+ await Thread.terminate(add);
62
+ ```
63
+
64
+ ## Replace pools
65
+
66
+ Before:
67
+
68
+ ```ts
69
+ const { spawnPool } = await loadWorker<AddFn>();
70
+ const pool = spawnPool({ size: 4 });
71
+ ```
72
+
73
+ After:
74
+
75
+ ```ts
76
+ import { Pool, spawn, Worker } from 'threadsx';
77
+
78
+ const pool = Pool(
79
+ () => spawn<AddFn>(new Worker(new URL('./worker', import.meta.url))),
80
+ { size: 4 }
81
+ );
82
+ ```
83
+
84
+ Pool options (`size`, `concurrency`, `maxQueuedJobs`, and `name`) are unchanged.
85
+ Terminate with `await pool.terminate()`.
86
+
87
+ ## Transferable arguments
88
+
89
+ If you keep using this package, `defineWorker` still makes transferable values
90
+ returned by a worker automatic. The removed `spawnWorker` wrapper also converted
91
+ arguments automatically; call `makeTransferable` yourself for arguments
92
+ containing transferable values:
93
+
94
+ ```ts
95
+ import { makeTransferable } from '@vertexvis/web-workers';
96
+
97
+ const result = await worker(makeTransferable({ pixels }));
98
+ ```
99
+
100
+ If you keep using `TerminateController`, construct it directly and register
101
+ resources after spawning them:
102
+
103
+ ```ts
104
+ import { TerminateController } from '@vertexvis/web-workers';
105
+
106
+ const controller = new TerminateController();
107
+ controller.addThread(worker);
108
+ controller.addPool(pool);
109
+ await controller.terminate();
110
+ ```
111
+
112
+ ## Move off the wrapper completely
113
+
114
+ Replace `defineWorker` with `expose` from `threadsx/worker`. When returning
115
+ transferable values, use `Transfer` with an explicit transfer list:
116
+
117
+ ```ts
118
+ // worker.ts
119
+ import { Transfer } from 'threadsx';
120
+ import { expose } from 'threadsx/worker';
121
+
122
+ export type EchoFn = (pixels: Uint8Array) => Promise<Uint8Array>;
123
+
124
+ expose(async (pixels: Uint8Array) =>
125
+ Transfer(pixels, [pixels.buffer])
126
+ );
127
+ ```
128
+
129
+ Use `Transfer` on the calling side when sending transferable arguments. Use
130
+ `Thread.terminate` or `pool.terminate` for cleanup:
131
+
132
+ ```ts
133
+ // main.ts
134
+ import { spawn, Thread, Transfer, Worker } from 'threadsx';
135
+ import type { EchoFn } from './worker';
136
+
137
+ const echo = await spawn<EchoFn>(
138
+ new Worker(new URL('./worker', import.meta.url))
139
+ );
140
+ try {
141
+ const pixels = new Uint8Array([1, 2, 3]);
142
+ const result = await echo(Transfer(pixels, [pixels.buffer]));
143
+ console.log(result);
144
+ } finally {
145
+ await Thread.terminate(echo);
146
+ }
147
+ ```
148
+
149
+ Transfer ownership makes `pixels` unusable on the calling side until it is
150
+ transferred back. Ordinary cloneable values need no `Transfer` wrapper.
151
+
152
+ ## Rollup projects
153
+
154
+ Rollup itself leaves `new URL('./worker.js', import.meta.url)` in the output and
155
+ does not emit a worker file for that URL. Build the main and worker entries
156
+ together, keep the generated filenames stable, and use a module worker:
157
+
158
+ ```ts
159
+ // main.ts
160
+ import { spawn, Worker } from 'threadsx';
161
+ import type { AddFn } from './worker';
162
+
163
+ const add = await spawn<AddFn>(
164
+ new Worker(new URL('./worker.js', import.meta.url), { type: 'module' })
165
+ );
166
+ ```
167
+
168
+ ```js
169
+ // rollup.config.js
170
+ import { nodeResolve } from '@rollup/plugin-node-resolve';
171
+ import typescript from 'rollup-plugin-typescript2';
172
+
173
+ export default {
174
+ input: { main: 'src/main.ts', worker: 'src/worker.ts' },
175
+ output: {
176
+ dir: 'dist',
177
+ format: 'es',
178
+ entryFileNames: '[name].js',
179
+ },
180
+ plugins: [nodeResolve({ browser: true }), typescript()],
181
+ };
182
+ ```
183
+
184
+ This puts `main.js` and `worker.js` beside each other. If your build changes
185
+ their locations or filenames, update the URL accordingly. Bundlers that
186
+ recognize worker URLs may handle the worker entry automatically; check their
187
+ own worker configuration.
package/README.md CHANGED
@@ -1,171 +1,62 @@
1
1
  # @vertexvis/web-workers
2
2
 
3
- A package for defining, bundling, and loading web workers. The [Threads] package
4
- is used internally to provide worker creation and pooling behavior.
5
- [Transferables] are automatically passed when sending data to and from web
6
- workers.
3
+ This package remains available for applications already using its
4
+ `defineWorker`, `makeTransferable`, or `TerminateController` helpers. For new
5
+ code, use [threadsx] directly. Its `expose`, `Transfer`, `spawn`, `Pool`, and
6
+ `Thread` APIs cover the worker lifecycle without this wrapper.
7
7
 
8
- Use this package in combination with [@vertexvis/rollup-plugin-web-workers] to
9
- bundle your workers with Rollup.
8
+ This is a recommendation to migrate, not an npm deprecation notice. The
9
+ remaining helpers continue to work in this release. The `worker:` loader and
10
+ `@vertexvis/rollup-plugin-web-workers` have been removed; see the
11
+ [migration guide](./MIGRATION.md) before upgrading.
10
12
 
11
- ## Install
13
+ ## Remaining helpers
12
14
 
13
- ```
14
- // Yarn
15
- yarn add @vertexvis/web-workers
16
-
17
- // NPM
18
- npm install @vertexvis/web-workers
19
- ```
20
-
21
- ## Usage
22
-
23
- ### Defining a Web Worker
24
-
25
- Create a JS/TS file and wrap your worker implementation with `defineWorker`.
15
+ `defineWorker(implementation)` calls `threadsx`'s `expose` and automatically
16
+ marks transferable values in worker results for transfer. `makeTransferable`
17
+ recursively marks transferable values in an argument. `TerminateController`
18
+ collects spawned threads and pools so they can be terminated together.
26
19
 
27
20
  ```ts
28
- // ./worker.ts
21
+ // worker.ts
29
22
  import { defineWorker } from '@vertexvis/web-workers';
30
23
 
31
24
  export type AddFn = (a: number, b: number) => Promise<number>;
32
-
33
- const add: AddFn = async (a, b) => {
34
- return a + b;
35
- }
36
-
37
- defineWorker(add);
25
+ defineWorker(async (a: number, b: number) => a + b);
38
26
  ```
39
27
 
40
- ### Loading and Spawning a Web Worker
41
-
42
- Use the `worker:` path prefix to bundle a web worker. The Rollup plugin will
43
- transform the import and expose a `loadWorker` function to load the bundled
44
- worker module. The worker module exports functions for spawning workers and
45
- worker pools.
46
-
47
- See [@vertexvis/rollup-plugin-web-workers] to bundle workers with Rollup.
48
-
49
28
  ```ts
50
- // ./main.ts
29
+ // main.ts
30
+ import { spawn, Thread, Worker } from 'threadsx';
51
31
  import type { AddFn } from './worker';
52
- import { loadWorker } from 'worker:./worker';
53
32
 
54
- async function main(): Promise<void> {
55
- const { spawnWorker, makeController } = await loadWorker<AddFn>();
56
-
57
- const controller = makeController(); // optional controller to stop worker.
58
- const add = await spawnWorker(controller);
59
- const sum = await add(1, 2)
60
- console.log('sum', sum); // 3
61
-
62
- controller.terminate();
63
- }
33
+ const add = await spawn<AddFn>(
34
+ new Worker(new URL('./worker', import.meta.url))
35
+ );
36
+ console.log(await add(1, 2));
37
+ await Thread.terminate(add);
64
38
  ```
65
39
 
66
- ### Worker Pools
67
-
68
- Spawn worker pools to create a set of workers that pull work from a queue.
40
+ `threadsx` can also create pools directly:
69
41
 
70
42
  ```ts
43
+ import { Pool, spawn, Worker } from 'threadsx';
71
44
  import type { AddFn } from './worker';
72
- import { loadWorker } from 'worker:./worker';
73
-
74
- async function main(): Promise<void> {
75
- const { spawnPool, makeController } = await loadWorker<AddFn>();
76
-
77
- const controller = makeController();
78
- const pool = await spawnPool({ controller });
79
- pool
80
- .queue((sum) => add(1, 2))
81
- .then((sum) => console.log('sum', sum)); // 3
82
45
 
83
- controller.terminate();
46
+ const pool = Pool(
47
+ () => spawn<AddFn>(new Worker(new URL('./worker', import.meta.url))),
48
+ { size: 4 }
49
+ );
50
+ try {
51
+ console.log(await pool.queue((add) => add(1, 2)));
52
+ } finally {
53
+ await pool.terminate();
84
54
  }
85
55
  ```
86
56
 
87
- `pool.queue()` will return a promise that will resolve with the task's result.
88
- Use `Promise.then()` to handle the result vs using `await` when scheduling work
89
- within a loop. This is because `await` will block until the task completes.
90
-
91
- You can customize the number of workers spawned and concurrency by passing in
92
- options to `spawnPool`.
93
-
94
- ```ts
95
- interface CreatePoolOptions {
96
- // The number of concurrent tasks to run per worker. Defaults to 1.
97
- concurrency?: number;
98
-
99
- // Max number of tasks to queue. If count is reached, an error is thrown.
100
- maxQueuedJobs?: number;
101
-
102
- // The name of the pool for debugging.
103
- name?: string;
104
-
105
- // The number of workers to spawn. Defaults to number of CPU cores.
106
- size?: number;
107
-
108
- // A controller to terminate the pool.
109
- controller?: WorkerController;
110
- }
111
- ```
112
-
113
- ### Worker Termination
114
-
115
- A `WorkerController` is used to terminate a worker. A worker module exports a
116
- `makeController` function to create a controller. You can pass a controller to
117
- multiple workers and pools to terminate them together.
118
-
119
-
120
- ```ts
121
- import type { Worker1Fn } from './worker1';
122
- import { loadWorker as loadWorker1 } from 'worker:./worker1';
123
-
124
- import type { Worker2Fn } from './worker1';
125
- import { loadWorker as loadWorker2 } from 'worker:./worker2';
126
-
127
- async function main(): Promise<void> {
128
- const { spawnWorker, makeController } = await loadWorker1<Worker1Fn>();
129
- const { spawnPool } = await loadWorker2<Worker2Fn>();
130
-
131
- const controller = makeController();
132
-
133
- const worker = await spawnWorker(controller);
134
- const pool = await spawnPool({ controller });
135
-
136
- // Terminate the worker and pool.
137
- await controller.terminate();
138
- }
139
- ```
140
-
141
- ## Bundling Workers
142
-
143
- See [@vertexvis/rollup-plugin-web-workers] for more details.
144
-
145
- ```js
146
- import { nodeResolve } from '@rollup/plugin-node-resolve';
147
- import typescript2 from 'rollup-plugin-typescript2';
148
- import terser from '@rollup/plugin-terser';
149
- import workers from '@vertexvis/rollup-plugin-web-workers';
150
-
151
- export default {
152
- input: 'src/main.ts',
153
- output: {
154
- dir: './dist',
155
- format: 'esm',
156
- },
157
- plugins: [
158
- nodeResolve(),
159
- workers({
160
- // Workers are bundled separately. Pass a list of plugins to use when
161
- // bundling the worker.
162
- plugins: [nodeResolve(), typescript2(), terser()]
163
- }),
164
- typescript2(),
165
- ]
166
- }
167
- ```
57
+ For new worker implementations, prefer `expose` from `threadsx/worker`. Use
58
+ `Transfer` when you need to move an `ArrayBuffer` or other transferable value.
59
+ The [migration guide](./MIGRATION.md) shows both a direct `threadsx` path and
60
+ the changes needed to keep using this package.
168
61
 
169
- [Threads]: https://threads.js.org/
170
- [Transferables]: https://developer.mozilla.org/en-US/docs/Web/API/Transferable
171
- [@vertexvis/rollup-plugin-web-workers]: https://www.npmjs.com/package/@vertexvis/rollup-plugin-web-workers
62
+ [threadsx]: https://github.com/jmaleonard/threadsx
package/dist/bundle.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var threads = require('threads');
3
+ var threadsx = require('threadsx');
4
4
 
5
5
  class TerminateController {
6
6
  constructor() {
@@ -15,7 +15,7 @@ class TerminateController {
15
15
  }
16
16
  async terminate(force = false) {
17
17
  await Promise.all([
18
- ...this.threads.map((t) => threads.Thread.terminate(t)),
18
+ ...this.threads.map((t) => threadsx.Thread.terminate(t)),
19
19
  ...this.pools.map((p) => p.terminate(force)),
20
20
  ]);
21
21
  }
@@ -64,19 +64,19 @@ function isTypedArray(obj) {
64
64
  instanceOf(obj, 'BigUint64Array'));
65
65
  }
66
66
  /**
67
- * A function that will recursively inspect an object and return a Threads
67
+ * A function that will recursively inspect an object and return a threadsx
68
68
  * `Transfer` that contains all the `Transferable`s in the given object.
69
69
  *
70
70
  * @param obj The object to make transferable.
71
- * @returns A `Transfer` from Threads.
71
+ * @returns A `Transfer` from threadsx.
72
72
  */
73
73
  function makeTransferable(obj) {
74
74
  if (isTransferable(obj)) {
75
- return threads.Transfer(obj);
75
+ return threadsx.Transfer(obj);
76
76
  }
77
77
  else if (obj != null && typeof obj === 'object') {
78
78
  const transferables = findTransferables(obj);
79
- return threads.Transfer(obj, transferables);
79
+ return threadsx.Transfer(obj, transferables);
80
80
  }
81
81
  else {
82
82
  return obj;
@@ -112,12 +112,12 @@ function findTransferables(obj) {
112
112
 
113
113
  /**
114
114
  * Defines a web worker implementation. This function wraps the `expose` method
115
- * of Threads and handles automatic conversion of Transferable types.
115
+ * of threadsx and handles automatic conversion of Transferable types.
116
116
  *
117
117
  * @param impl The worker implementation.
118
118
  * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable
119
119
  */
120
- function defineWorker(impl, { expose = threads.expose } = {}) {
120
+ function defineWorker(impl, { expose = threadsx.expose } = {}) {
121
121
  function wrap(f) {
122
122
  return async (...args) => {
123
123
  const res = await f(...args);
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.cjs","sources":["../src/terminate.ts","../src/globalThis.ts","../src/transferable.ts","../src/worker.ts"],"sourcesContent":["import { Thread } from 'threads';\n\ninterface WorkerPoolLike {\n terminate(force?: boolean): Promise<void>;\n}\n\nexport class TerminateController {\n private threads: Thread[] = [];\n private pools: WorkerPoolLike[] = [];\n\n public addThread(thread: Thread): void {\n this.threads.push(thread);\n }\n\n public addPool(pool: WorkerPoolLike): void {\n this.pools.push(pool);\n }\n\n public async terminate(force = false): Promise<void> {\n await Promise.all([\n ...this.threads.map((t) => Thread.terminate(t)),\n ...this.pools.map((p) => p.terminate(force)),\n ]);\n }\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getGlobal(): any {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\n\nexport default getGlobal();\n","import { Transfer } from 'threads';\n\nimport globalThis from './globalThis';\n\ntype TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n | BigInt64Array\n | BigUint64Array;\n\nfunction instanceOf(obj: unknown, className: string): boolean {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Type = globalThis[className];\n return Type != null && obj instanceof Type;\n}\n\nfunction isTransferable(obj: unknown): obj is Transferable {\n return (\n instanceOf(obj, 'ArrayBuffer') ||\n instanceOf(obj, 'MessagePort') ||\n instanceOf(obj, 'ImageBitmap') ||\n instanceOf(obj, 'OffscreenCanvas')\n );\n}\n\nfunction isTypedArray(obj: unknown): obj is TypedArray {\n return (\n instanceOf(obj, 'Int8Array') ||\n instanceOf(obj, 'Uint8Array') ||\n instanceOf(obj, 'Uint8ClampedArray') ||\n instanceOf(obj, 'Int16Array') ||\n instanceOf(obj, 'Uint16Array') ||\n instanceOf(obj, 'Int32Array') ||\n instanceOf(obj, 'Uint32Array') ||\n instanceOf(obj, 'Float32Array') ||\n instanceOf(obj, 'Float64Array') ||\n instanceOf(obj, 'BigInt64Array') ||\n instanceOf(obj, 'BigUint64Array')\n );\n}\n\n/**\n * A function that will recursively inspect an object and return a Threads\n * `Transfer` that contains all the `Transferable`s in the given object.\n *\n * @param obj The object to make transferable.\n * @returns A `Transfer` from Threads.\n */\nexport function makeTransferable<T>(obj: T): ReturnType<typeof Transfer> | T {\n if (isTransferable(obj)) {\n return Transfer(obj);\n } else if (obj != null && typeof obj === 'object') {\n const transferables = findTransferables(obj);\n return Transfer(obj, transferables);\n } else {\n return obj;\n }\n}\n\nfunction findTransferables<T>(obj: T): Transferable[] {\n if (isTransferable(obj)) {\n return [obj];\n } else if (typeof obj === 'object') {\n if (Array.isArray(obj)) {\n const result: Transferable[] = [];\n obj.forEach((o) => result.push(...findTransferables(o)));\n return result;\n } else if (isTypedArray(obj)) {\n return [obj.buffer];\n } else if (obj != null) {\n return Object.values(obj).reduce((acc, value) => {\n acc.push(...findTransferables(value));\n return acc;\n }, []);\n } else {\n return [];\n }\n } else {\n return [];\n }\n}\n","import { expose as threadsExpose } from 'threads';\n\nimport { makeTransferable } from './transferable';\n\ntype Exposed = Parameters<typeof threadsExpose>[0];\ntype WorkerFunction = Extract<Exposed, (...args: any[]) => any>;\ntype WorkerModule = Exclude<Exposed, WorkerFunction>;\n\ninterface DefineWorkerOptions {\n expose?: typeof threadsExpose;\n}\n\n/**\n * Defines a web worker implementation. This function wraps the `expose` method\n * of Threads and handles automatic conversion of Transferable types.\n *\n * @param impl The worker implementation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable\n */\nexport function defineWorker(\n impl: Exposed,\n { expose = threadsExpose }: DefineWorkerOptions = {}\n): void {\n function wrap(f: WorkerFunction): WorkerFunction {\n return async (...args: unknown[]) => {\n const res = await f(...args);\n return makeTransferable(res);\n };\n }\n\n if (typeof impl === 'function') {\n return expose(wrap(impl));\n } else {\n const mod = Object.entries(impl).reduce((mod, [key, fn]) => {\n mod[key] = wrap(fn);\n return mod;\n }, {} as WorkerModule);\n return expose(mod);\n }\n}\n"],"names":["Thread","globalThis","Transfer","threadsExpose"],"mappings":";;;;MAMa,mBAAmB,CAAA;AAAhC,IAAA,WAAA,GAAA;QACU,IAAA,CAAA,OAAO,GAAa,EAAE;QACtB,IAAA,CAAA,KAAK,GAAqB,EAAE;IAgBtC;AAdS,IAAA,SAAS,CAAC,MAAc,EAAA;AAC7B,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC3B;AAEO,IAAA,OAAO,CAAC,IAAoB,EAAA;AACjC,QAAA,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;IACvB;AAEO,IAAA,MAAM,SAAS,CAAC,KAAK,GAAG,KAAK,EAAA;QAClC,MAAM,OAAO,CAAC,GAAG,CAAC;AAChB,YAAA,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAKA,cAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC/C,YAAA,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC7C,SAAA,CAAC;IACJ;AACD;;ACxBD;AACA,SAAS,SAAS,GAAA;AAChB,IAAA,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;AACrC,QAAA,OAAO,UAAU;IACnB;AAAO,SAAA,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;AACtC,QAAA,OAAO,IAAI;IACb;AAAO,SAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACxC,QAAA,OAAO,MAAM;IACf;AAAO,SAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACxC,QAAA,OAAO,MAAM;IACf;AACA,IAAA,MAAM,IAAI,KAAK,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AAC7B,QAAA,OAAO,OAAO,GAAG,IAAe,KAAI;YAClC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC;AAC5B,YAAA,OAAO,gBAAgB,CAAC,GAAG,CAAC;AAC9B,QAAA,CAAC;IACH;AAEA,IAAA,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;AAC9B,QAAA,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3B;SAAO;QACL,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,KAAI;YACzD,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;AACnB,YAAA,OAAO,GAAG;QACZ,CAAC,EAAE,EAAkB,CAAC;AACtB,QAAA,OAAO,MAAM,CAAC,GAAG,CAAC;IACpB;AACF;;;;;;"}
1
+ {"version":3,"file":"bundle.cjs","sources":["../src/terminate.ts","../src/globalThis.ts","../src/transferable.ts","../src/worker.ts"],"sourcesContent":["import { Thread } from 'threadsx';\n\ninterface WorkerPoolLike {\n terminate(force?: boolean): Promise<void>;\n}\n\nexport class TerminateController {\n private threads: Thread[] = [];\n private pools: WorkerPoolLike[] = [];\n\n public addThread(thread: Thread): void {\n this.threads.push(thread);\n }\n\n public addPool(pool: WorkerPoolLike): void {\n this.pools.push(pool);\n }\n\n public async terminate(force = false): Promise<void> {\n await Promise.all([\n ...this.threads.map((t) => Thread.terminate(t)),\n ...this.pools.map((p) => p.terminate(force)),\n ]);\n }\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getGlobal(): any {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\n\nexport default getGlobal();\n","import { Transfer } from 'threadsx';\n\nimport globalThis from './globalThis';\n\ntype TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n | BigInt64Array\n | BigUint64Array;\n\nfunction instanceOf(obj: unknown, className: string): boolean {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Type = globalThis[className];\n return Type != null && obj instanceof Type;\n}\n\nfunction isTransferable(obj: unknown): obj is Transferable {\n return (\n instanceOf(obj, 'ArrayBuffer') ||\n instanceOf(obj, 'MessagePort') ||\n instanceOf(obj, 'ImageBitmap') ||\n instanceOf(obj, 'OffscreenCanvas')\n );\n}\n\nfunction isTypedArray(obj: unknown): obj is TypedArray {\n return (\n instanceOf(obj, 'Int8Array') ||\n instanceOf(obj, 'Uint8Array') ||\n instanceOf(obj, 'Uint8ClampedArray') ||\n instanceOf(obj, 'Int16Array') ||\n instanceOf(obj, 'Uint16Array') ||\n instanceOf(obj, 'Int32Array') ||\n instanceOf(obj, 'Uint32Array') ||\n instanceOf(obj, 'Float32Array') ||\n instanceOf(obj, 'Float64Array') ||\n instanceOf(obj, 'BigInt64Array') ||\n instanceOf(obj, 'BigUint64Array')\n );\n}\n\n/**\n * A function that will recursively inspect an object and return a threadsx\n * `Transfer` that contains all the `Transferable`s in the given object.\n *\n * @param obj The object to make transferable.\n * @returns A `Transfer` from threadsx.\n */\nexport function makeTransferable<T>(obj: T): ReturnType<typeof Transfer> | T {\n if (isTransferable(obj)) {\n return Transfer(obj);\n } else if (obj != null && typeof obj === 'object') {\n const transferables = findTransferables(obj);\n return Transfer(obj, transferables);\n } else {\n return obj;\n }\n}\n\nfunction findTransferables<T>(obj: T): Transferable[] {\n if (isTransferable(obj)) {\n return [obj];\n } else if (typeof obj === 'object') {\n if (Array.isArray(obj)) {\n const result: Transferable[] = [];\n obj.forEach((o) => result.push(...findTransferables(o)));\n return result;\n } else if (isTypedArray(obj)) {\n return [obj.buffer];\n } else if (obj != null) {\n return Object.values(obj).reduce((acc, value) => {\n acc.push(...findTransferables(value));\n return acc;\n }, []);\n } else {\n return [];\n }\n } else {\n return [];\n }\n}\n","import { expose as threadsExpose } from 'threadsx';\n\nimport { makeTransferable } from './transferable';\n\ntype Exposed = Parameters<typeof threadsExpose>[0];\ntype WorkerFunction = Extract<Exposed, (...args: any[]) => any>;\ntype WorkerModule = Exclude<Exposed, WorkerFunction>;\n\ninterface DefineWorkerOptions {\n expose?: typeof threadsExpose;\n}\n\n/**\n * Defines a web worker implementation. This function wraps the `expose` method\n * of threadsx and handles automatic conversion of Transferable types.\n *\n * @param impl The worker implementation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable\n */\nexport function defineWorker(\n impl: Exposed,\n { expose = threadsExpose }: DefineWorkerOptions = {}\n): void {\n function wrap(f: WorkerFunction): WorkerFunction {\n return async (...args: unknown[]) => {\n const res = await f(...args);\n return makeTransferable(res);\n };\n }\n\n if (typeof impl === 'function') {\n return expose(wrap(impl));\n } else {\n const mod = Object.entries(impl).reduce((mod, [key, fn]) => {\n mod[key] = wrap(fn);\n return mod;\n }, {} as WorkerModule);\n return expose(mod);\n }\n}\n"],"names":["Thread","globalThis","Transfer","threadsExpose"],"mappings":";;;;MAMa,mBAAmB,CAAA;AAAhC,IAAA,WAAA,GAAA;QACU,IAAA,CAAA,OAAO,GAAa,EAAE;QACtB,IAAA,CAAA,KAAK,GAAqB,EAAE;IAgBtC;AAdS,IAAA,SAAS,CAAC,MAAc,EAAA;AAC7B,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC3B;AAEO,IAAA,OAAO,CAAC,IAAoB,EAAA;AACjC,QAAA,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;IACvB;AAEO,IAAA,MAAM,SAAS,CAAC,KAAK,GAAG,KAAK,EAAA;QAClC,MAAM,OAAO,CAAC,GAAG,CAAC;AAChB,YAAA,GAAG,IAA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
- import { Thread, Transfer, expose } from 'threads';
1
+ import { Thread, Transfer, expose } from 'threadsx';
2
2
 
3
3
  class TerminateController {
4
4
  constructor() {
@@ -62,11 +62,11 @@ function isTypedArray(obj) {
62
62
  instanceOf(obj, 'BigUint64Array'));
63
63
  }
64
64
  /**
65
- * A function that will recursively inspect an object and return a Threads
65
+ * A function that will recursively inspect an object and return a threadsx
66
66
  * `Transfer` that contains all the `Transferable`s in the given object.
67
67
  *
68
68
  * @param obj The object to make transferable.
69
- * @returns A `Transfer` from Threads.
69
+ * @returns A `Transfer` from threadsx.
70
70
  */
71
71
  function makeTransferable(obj) {
72
72
  if (isTransferable(obj)) {
@@ -110,7 +110,7 @@ function findTransferables(obj) {
110
110
 
111
111
  /**
112
112
  * Defines a web worker implementation. This function wraps the `expose` method
113
- * of Threads and handles automatic conversion of Transferable types.
113
+ * of threadsx and handles automatic conversion of Transferable types.
114
114
  *
115
115
  * @param impl The worker implementation.
116
116
  * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.esm.js","sources":["../src/terminate.ts","../src/globalThis.ts","../src/transferable.ts","../src/worker.ts"],"sourcesContent":["import { Thread } from 'threads';\n\ninterface WorkerPoolLike {\n terminate(force?: boolean): Promise<void>;\n}\n\nexport class TerminateController {\n private threads: Thread[] = [];\n private pools: WorkerPoolLike[] = [];\n\n public addThread(thread: Thread): void {\n this.threads.push(thread);\n }\n\n public addPool(pool: WorkerPoolLike): void {\n this.pools.push(pool);\n }\n\n public async terminate(force = false): Promise<void> {\n await Promise.all([\n ...this.threads.map((t) => Thread.terminate(t)),\n ...this.pools.map((p) => p.terminate(force)),\n ]);\n }\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getGlobal(): any {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\n\nexport default getGlobal();\n","import { Transfer } from 'threads';\n\nimport globalThis from './globalThis';\n\ntype TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n | BigInt64Array\n | BigUint64Array;\n\nfunction instanceOf(obj: unknown, className: string): boolean {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Type = globalThis[className];\n return Type != null && obj instanceof Type;\n}\n\nfunction isTransferable(obj: unknown): obj is Transferable {\n return (\n instanceOf(obj, 'ArrayBuffer') ||\n instanceOf(obj, 'MessagePort') ||\n instanceOf(obj, 'ImageBitmap') ||\n instanceOf(obj, 'OffscreenCanvas')\n );\n}\n\nfunction isTypedArray(obj: unknown): obj is TypedArray {\n return (\n instanceOf(obj, 'Int8Array') ||\n instanceOf(obj, 'Uint8Array') ||\n instanceOf(obj, 'Uint8ClampedArray') ||\n instanceOf(obj, 'Int16Array') ||\n instanceOf(obj, 'Uint16Array') ||\n instanceOf(obj, 'Int32Array') ||\n instanceOf(obj, 'Uint32Array') ||\n instanceOf(obj, 'Float32Array') ||\n instanceOf(obj, 'Float64Array') ||\n instanceOf(obj, 'BigInt64Array') ||\n instanceOf(obj, 'BigUint64Array')\n );\n}\n\n/**\n * A function that will recursively inspect an object and return a Threads\n * `Transfer` that contains all the `Transferable`s in the given object.\n *\n * @param obj The object to make transferable.\n * @returns A `Transfer` from Threads.\n */\nexport function makeTransferable<T>(obj: T): ReturnType<typeof Transfer> | T {\n if (isTransferable(obj)) {\n return Transfer(obj);\n } else if (obj != null && typeof obj === 'object') {\n const transferables = findTransferables(obj);\n return Transfer(obj, transferables);\n } else {\n return obj;\n }\n}\n\nfunction findTransferables<T>(obj: T): Transferable[] {\n if (isTransferable(obj)) {\n return [obj];\n } else if (typeof obj === 'object') {\n if (Array.isArray(obj)) {\n const result: Transferable[] = [];\n obj.forEach((o) => result.push(...findTransferables(o)));\n return result;\n } else if (isTypedArray(obj)) {\n return [obj.buffer];\n } else if (obj != null) {\n return Object.values(obj).reduce((acc, value) => {\n acc.push(...findTransferables(value));\n return acc;\n }, []);\n } else {\n return [];\n }\n } else {\n return [];\n }\n}\n","import { expose as threadsExpose } from 'threads';\n\nimport { makeTransferable } from './transferable';\n\ntype Exposed = Parameters<typeof threadsExpose>[0];\ntype WorkerFunction = Extract<Exposed, (...args: any[]) => any>;\ntype WorkerModule = Exclude<Exposed, WorkerFunction>;\n\ninterface DefineWorkerOptions {\n expose?: typeof threadsExpose;\n}\n\n/**\n * Defines a web worker implementation. This function wraps the `expose` method\n * of Threads and handles automatic conversion of Transferable types.\n *\n * @param impl The worker implementation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable\n */\nexport function defineWorker(\n impl: Exposed,\n { expose = threadsExpose }: DefineWorkerOptions = {}\n): void {\n function wrap(f: WorkerFunction): WorkerFunction {\n return async (...args: unknown[]) => {\n const res = await f(...args);\n return makeTransferable(res);\n };\n }\n\n if (typeof impl === 'function') {\n return expose(wrap(impl));\n } else {\n const mod = Object.entries(impl).reduce((mod, [key, fn]) => {\n mod[key] = wrap(fn);\n return mod;\n }, {} as WorkerModule);\n return expose(mod);\n }\n}\n"],"names":["globalThis","expose","threadsExpose"],"mappings":";;MAMa,mBAAmB,CAAA;AAAhC,IAAA,WAAA,GAAA;QACU,IAAA,CAAA,OAAO,GAAa,EAAE;QACtB,IAAA,CAAA,KAAK,GAAqB,EAAE;IAgBtC;AAdS,IAAA,SAAS,CAAC,MAAc,EAAA;AAC7B,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC3B;AAEO,IAAA,OAAO,CAAC,IAAoB,EAAA;AACjC,QAAA,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;IACvB;AAEO,IAAA,MAAM,SAAS,CAAC,KAAK,GAAG,KAAK,EAAA;QAClC,MAAM,OAAO,CAAC,GAAG,CAAC;A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+ {"version":3,"file":"bundle.esm.js","sources":["../src/terminate.ts","../src/globalThis.ts","../src/transferable.ts","../src/worker.ts"],"sourcesContent":["import { Thread } from 'threadsx';\n\ninterface WorkerPoolLike {\n terminate(force?: boolean): Promise<void>;\n}\n\nexport class TerminateController {\n private threads: Thread[] = [];\n private pools: WorkerPoolLike[] = [];\n\n public addThread(thread: Thread): void {\n this.threads.push(thread);\n }\n\n public addPool(pool: WorkerPoolLike): void {\n this.pools.push(pool);\n }\n\n public async terminate(force = false): Promise<void> {\n await Promise.all([\n ...this.threads.map((t) => Thread.terminate(t)),\n ...this.pools.map((p) => p.terminate(force)),\n ]);\n }\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getGlobal(): any {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof window !== 'undefined') {\n return window;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\n\nexport default getGlobal();\n","import { Transfer } from 'threadsx';\n\nimport globalThis from './globalThis';\n\ntype TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n | BigInt64Array\n | BigUint64Array;\n\nfunction instanceOf(obj: unknown, className: string): boolean {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Type = globalThis[className];\n return Type != null && obj instanceof Type;\n}\n\nfunction isTransferable(obj: unknown): obj is Transferable {\n return (\n instanceOf(obj, 'ArrayBuffer') ||\n instanceOf(obj, 'MessagePort') ||\n instanceOf(obj, 'ImageBitmap') ||\n instanceOf(obj, 'OffscreenCanvas')\n );\n}\n\nfunction isTypedArray(obj: unknown): obj is TypedArray {\n return (\n instanceOf(obj, 'Int8Array') ||\n instanceOf(obj, 'Uint8Array') ||\n instanceOf(obj, 'Uint8ClampedArray') ||\n instanceOf(obj, 'Int16Array') ||\n instanceOf(obj, 'Uint16Array') ||\n instanceOf(obj, 'Int32Array') ||\n instanceOf(obj, 'Uint32Array') ||\n instanceOf(obj, 'Float32Array') ||\n instanceOf(obj, 'Float64Array') ||\n instanceOf(obj, 'BigInt64Array') ||\n instanceOf(obj, 'BigUint64Array')\n );\n}\n\n/**\n * A function that will recursively inspect an object and return a threadsx\n * `Transfer` that contains all the `Transferable`s in the given object.\n *\n * @param obj The object to make transferable.\n * @returns A `Transfer` from threadsx.\n */\nexport function makeTransferable<T>(obj: T): ReturnType<typeof Transfer> | T {\n if (isTransferable(obj)) {\n return Transfer(obj);\n } else if (obj != null && typeof obj === 'object') {\n const transferables = findTransferables(obj);\n return Transfer(obj, transferables);\n } else {\n return obj;\n }\n}\n\nfunction findTransferables<T>(obj: T): Transferable[] {\n if (isTransferable(obj)) {\n return [obj];\n } else if (typeof obj === 'object') {\n if (Array.isArray(obj)) {\n const result: Transferable[] = [];\n obj.forEach((o) => result.push(...findTransferables(o)));\n return result;\n } else if (isTypedArray(obj)) {\n return [obj.buffer];\n } else if (obj != null) {\n return Object.values(obj).reduce((acc, value) => {\n acc.push(...findTransferables(value));\n return acc;\n }, []);\n } else {\n return [];\n }\n } else {\n return [];\n }\n}\n","import { expose as threadsExpose } from 'threadsx';\n\nimport { makeTransferable } from './transferable';\n\ntype Exposed = Parameters<typeof threadsExpose>[0];\ntype WorkerFunction = Extract<Exposed, (...args: any[]) => any>;\ntype WorkerModule = Exclude<Exposed, WorkerFunction>;\n\ninterface DefineWorkerOptions {\n expose?: typeof threadsExpose;\n}\n\n/**\n * Defines a web worker implementation. This function wraps the `expose` method\n * of threadsx and handles automatic conversion of Transferable types.\n *\n * @param impl The worker implementation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable\n */\nexport function defineWorker(\n impl: Exposed,\n { expose = threadsExpose }: DefineWorkerOptions = {}\n): void {\n function wrap(f: WorkerFunction): WorkerFunction {\n return async (...args: unknown[]) => {\n const res = await f(...args);\n return makeTransferable(res);\n };\n }\n\n if (typeof impl === 'function') {\n return expose(wrap(impl));\n } else {\n const mod = Object.entries(impl).reduce((mod, [key, fn]) => {\n mod[key] = wrap(fn);\n return mod;\n }, {} as WorkerModule);\n return expose(mod);\n }\n}\n"],"names":["globalThis","expose","threadsExpose"],"mappings":";;MAMa,mBAAmB,CAAA;AAAhC,IAAA,WAAA,GAAA;QACU,IAAA,CAAA,OAAO,GAAa,EAAE;QACtB,IAAA,CAAA,KAAK,GAAqB,EAAE;IAgBtC;AAdS,IAAA,SAAS,CAAC,MAAc,EAAA;AAC7B,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC3B;AAEO,IAAA,OAAO,CAAC,IAAoB,EAAA;AACjC,QAAA,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;IACvB;AAEO,IAAA,MAAM,SAAS,CAAC,KAAK,GAAG,KAAK,EAAA;QAClC,MAAM,OAAO,CAAC,GAAG,CAAC;AAChB,YAAA,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC/C,YAAA,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC7C,SAAA,CAAC;IACJ;AACD;;ACxBD;AACA,SAAS,SAAS,GAAA;AAChB,IAAA,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;AACrC,QAAA,OAAO,UAAU;IACnB;AAAO,SAAA,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;AACtC,QAAA,OAAO,IAAI;IACb;AAAO,SAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACxC,QAAA,OAAO,MAAM;IACf;AAAO,SAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACxC,QAAA,OAAO,MAAM;IACf;AACA,IAAA,MAAM,IAAI,KAAK,CAAC,gC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,OAAO,OAAO,GAAG,IAAe,KAAI;YAClC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC;AAC5B,YAAA,OAAO,gBAAgB,CAAC,GAAG,CAAC;AAC9B,QAAA,CAAC;IACH;AAEA,IAAA,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;AAC9B,QAAA,OAAOD,QAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3B;SAAO;QACL,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,KAAI;YACzD,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;AACnB,YAAA,OAAO,GAAG;QACZ,CAAC,EAAE,EAAkB,CAAC;AACtB,QAAA,OAAOA,QAAM,CAAC,GAAG,CAAC;IACpB;AACF;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC"}
@@ -1,4 +1,4 @@
1
- import { Thread } from 'threads';
1
+ import { Thread } from 'threadsx';
2
2
  interface WorkerPoolLike {
3
3
  terminate(force?: boolean): Promise<void>;
4
4
  }
@@ -1 +1 @@
1
- {"version":3,"file":"terminate.d.ts","sourceRoot":"","sources":["../src/terminate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,UAAU,cAAc;IACtB,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3C;AAED,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,KAAK,CAAwB;IAE9B,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI;IAI7B,SAAS,CAAC,KAAK,UAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CAMrD"}
1
+ {"version":3,"file":"terminate.d.ts","sourceRoot":"","sources":["../src/terminate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,UAAU,cAAc;IACtB,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3C;AAED,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,KAAK,CAAwB;IAE9B,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI;IAI7B,SAAS,CAAC,KAAK,UAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CAMrD"}
@@ -1,10 +1,10 @@
1
- import { Transfer } from 'threads';
1
+ import { Transfer } from 'threadsx';
2
2
  /**
3
- * A function that will recursively inspect an object and return a Threads
3
+ * A function that will recursively inspect an object and return a threadsx
4
4
  * `Transfer` that contains all the `Transferable`s in the given object.
5
5
  *
6
6
  * @param obj The object to make transferable.
7
- * @returns A `Transfer` from Threads.
7
+ * @returns A `Transfer` from threadsx.
8
8
  */
9
9
  export declare function makeTransferable<T>(obj: T): ReturnType<typeof Transfer> | T;
10
10
  //# sourceMappingURL=transferable.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"transferable.d.ts","sourceRoot":"","sources":["../src/transferable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAgDnC;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,UAAU,CAAC,OAAO,QAAQ,CAAC,GAAG,CAAC,CAS3E"}
1
+ {"version":3,"file":"transferable.d.ts","sourceRoot":"","sources":["../src/transferable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAgDpC;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,UAAU,CAAC,OAAO,QAAQ,CAAC,GAAG,CAAC,CAS3E"}
package/dist/worker.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { expose as threadsExpose } from 'threads';
1
+ import { expose as threadsExpose } from 'threadsx';
2
2
  type Exposed = Parameters<typeof threadsExpose>[0];
3
3
  interface DefineWorkerOptions {
4
4
  expose?: typeof threadsExpose;
5
5
  }
6
6
  /**
7
7
  * Defines a web worker implementation. This function wraps the `expose` method
8
- * of Threads and handles automatic conversion of Transferable types.
8
+ * of threadsx and handles automatic conversion of Transferable types.
9
9
  *
10
10
  * @param impl The worker implementation.
11
11
  * @see https://developer.mozilla.org/en-US/docs/Web/API/Transferable
@@ -1 +1 @@
1
- {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,aAAa,EAAE,MAAM,SAAS,CAAC;AAIlD,KAAK,OAAO,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;AAInD,UAAU,mBAAmB;IAC3B,MAAM,CAAC,EAAE,OAAO,aAAa,CAAC;CAC/B;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,OAAO,EACb,EAAE,MAAsB,EAAE,GAAE,mBAAwB,GACnD,IAAI,CAiBN"}
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,aAAa,EAAE,MAAM,UAAU,CAAC;AAInD,KAAK,OAAO,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;AAInD,UAAU,mBAAmB;IAC3B,MAAM,CAAC,EAAE,OAAO,aAAa,CAAC;CAC/B;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,OAAO,EACb,EAAE,MAAsB,EAAE,GAAE,mBAAwB,GACnD,IAAI,CAiBN"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@vertexvis/web-workers",
3
- "version": "0.2.2-canary.3",
3
+ "version": "0.3.0-canary.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
- "description": "A wrapper around ThreadsJS to make bundling and using web workers even simpler.",
6
+ "description": "Compatibility helpers for threadsx web workers; use threadsx directly for new code.",
7
7
  "keywords": [
8
8
  "thread",
9
9
  "worker",
@@ -22,19 +22,32 @@
22
22
  "main": "./dist/bundle.cjs",
23
23
  "module": "./dist/bundle.esm.js",
24
24
  "typings": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/bundle.esm.js",
29
+ "require": "./dist/bundle.cjs",
30
+ "default": "./dist/bundle.esm.js"
31
+ }
32
+ },
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
25
36
  "publishConfig": {
26
37
  "registry": "https://registry.npmjs.org",
27
38
  "access": "public"
28
39
  },
29
40
  "sideEffects": false,
30
41
  "files": [
31
- "dist/*",
32
- "!dist/**/__tests__"
42
+ "dist/bundle.*",
43
+ "dist/*.d.ts",
44
+ "dist/*.d.ts.map",
45
+ "MIGRATION.md"
33
46
  ],
34
47
  "scripts": {
35
48
  "clean": "rm -fr ./dist && mkdir ./dist",
36
49
  "prebuild": "yarn clean",
37
- "build": "rollup --config ./rollup.config.js && cp ./extensions.d.ts ./dist",
50
+ "build": "rollup --config ./rollup.config.js",
38
51
  "format": "yarn lint --fix",
39
52
  "lint": "eslint .",
40
53
  "start": "jest --watch",
@@ -44,12 +57,12 @@
44
57
  "devDependencies": {
45
58
  "jest": "^29.7.0",
46
59
  "jest-environment-jsdom": "^29.7.0",
47
- "threads": "^1.7.0",
60
+ "threadsx": "^2.1.0",
48
61
  "tslib": "^2.8.1"
49
62
  },
50
63
  "peerDependencies": {
51
- "threads": "^1",
64
+ "threadsx": "^2",
52
65
  "tslib": "^2"
53
66
  },
54
- "gitHead": "9d657481b4bf9a9a8390116ceec9417a5eb17163"
67
+ "gitHead": "aa10860e21b1ad7a3734830440e59a41b8f0b17c"
55
68
  }
@@ -1 +0,0 @@
1
- //# sourceMappingURL=browser.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/__mocks__/browser.ts"],"names":[],"mappings":""}
@@ -1,133 +0,0 @@
1
- /**
2
- * Provides static analysis for import paths that are prefixed with `worker:`.
3
- */
4
- declare module 'worker:*' {
5
- import type { Worker } from 'threads';
6
-
7
- interface SpawnPoolOptions {
8
- /**
9
- * Maximum number of tasks to run on one worker thread at a time. Defaults
10
- * to one.
11
- **/
12
- concurrency?: number;
13
-
14
- /**
15
- * Maximum number of jobs to be queued for execution before throwing an
16
- * error.
17
- **/
18
- maxQueuedJobs?: number;
19
-
20
- /**
21
- * Gives that pool a name to be used for debug logging, letting you
22
- * distinguish between log output of different pools.
23
- **/
24
- name?: string;
25
-
26
- /**
27
- * No. of worker threads to spawn and to be managed by the pool.
28
- **/
29
- size?: number;
30
-
31
- /**
32
- * A controller that can be used to terminate the pool.
33
- */
34
- terminate?: TerminateController;
35
- }
36
-
37
- /**
38
- * Thread pool managing a set of worker threads.
39
- * Use it to queue tasks that are run on those threads with limited
40
- * concurrency.
41
- */
42
- interface Pool<ThreadType> {
43
- /**
44
- * Returns a promise that resolves once the task queue is emptied. Promise
45
- * will be rejected if any task fails.
46
- *
47
- * @param allowResolvingImmediately Set to `true` to resolve immediately if
48
- * task queue is currently empty.
49
- */
50
- completed(allowResolvingImmediately?: boolean): Promise<unknown>;
51
- /**
52
- * Returns a promise that resolves once the task queue is emptied. Failing
53
- * tasks will not cause the promise to be rejected.
54
- *
55
- * @param allowResolvingImmediately Set to `true` to resolve immediately if
56
- * task queue is currently empty.
57
- */
58
- settled(allowResolvingImmediately?: boolean): Promise<Error[]>;
59
- /**
60
- * Queue a task and return a promise that resolves once the task has been
61
- * dequeued, started and finished.
62
- *
63
- * @param task An async function that takes a thread instance and invokes
64
- * it.
65
- */
66
- queue<Return>(task: (thread: ThreadType) => Return): QueuedTask<Return>;
67
- }
68
-
69
- interface QueuedTask<Return> {
70
- /**
71
- * `QueuedTask` is thenable, so you can `await` it. Resolves when the task
72
- * has successfully been executed. Rejects if the task fails.
73
- */
74
- then: Promise<Return>['then'];
75
-
76
- /**
77
- * Queued tasks can be cancelled until the pool starts running them on a
78
- * worker thread.
79
- */
80
- cancel(): void;
81
- }
82
-
83
- interface TerminateController {
84
- /**
85
- * Terminates any workers or pools that have been assigned to this
86
- * controller.
87
- *
88
- * @param force Set to `true` to kill the thread even if it cannot be
89
- * stopped gracefully.
90
- */
91
- terminate(force?: boolean): Promise<void>;
92
- }
93
-
94
- interface WorkerModule<T> {
95
- /**
96
- * Returns a web worker primitive. Note, you generally want to use
97
- * {@link WorkerModule.spawnWorker} to spawn a worker with its exposed
98
- * interface.
99
- */
100
- makeWorker(): Worker;
101
-
102
- /**
103
- * Returns a controller that can be used to terminate a series of workers.
104
- */
105
- makeController(): TerminateController;
106
-
107
- /**
108
- * Spawns a pool of web workers. By default, will spawn a number of workers
109
- * that is equal to the hardware concurrency of the user's device.
110
- *
111
- * @param options Options for instantiating the worker pool.
112
- * @returns A worker pool.
113
- *
114
- * @see {@link WorkerModule.spawnWorker} to spawn a single worker.
115
- */
116
- spawnPool(options?: SpawnPoolOptions): Pool<T>;
117
-
118
- /**
119
- * Instantiates a new web worker and returns a promise that is resolved with
120
- * the worker's interface.
121
- *
122
- * @param terminate A controller to terminate the worker.
123
- * @see {@link WorkerModule.spawnPool} to spawn pool of workers.
124
- */
125
- spawnWorker(terminate?: TerminateController): Promise<T>;
126
- }
127
-
128
- /**
129
- * Loads the worker bundle and returns a `WorkerModule` that contains methods
130
- * for spawning a web worker or creating worker pools.
131
- */
132
- export function loadWorker<T = unknown>(): Promise<WorkerModule<T>>;
133
- }