defuss-multicore 0.0.1 → 0.0.3

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Isomorphic multicore execution + loop-unrolled linear algebra for JavaScript/TypeScript.
4
4
 
5
- - **Web Workers** in the browser, **worker_threads** in Node.js — same API
5
+ - **Web Workers** in the browser, **worker_threads** in Node.js - same API
6
6
  - Auto-splits arrays/TypedArrays across CPU cores
7
7
  - JIT loop-unrolled vector/matrix ops (4x/8x/16x unroll factors, auto-selected)
8
8
  - Parallel `map`, `filter`, `reduce` for any array
@@ -47,7 +47,7 @@ for await (const r of parallel(data)) { ... } // stream as workers finish
47
47
 
48
48
  - Array/TypedArray args are **auto-split** across cores
49
49
  - Scalar args are **broadcast** to every worker
50
- - Returns `ParallelResult<R>` — both `PromiseLike<R[]>` and `AsyncIterable<R>`
50
+ - Returns `ParallelResult<R>` - both `PromiseLike<R[]>` and `AsyncIterable<R>`
51
51
 
52
52
  #### `MulticoreOptions<R>`
53
53
 
@@ -55,15 +55,15 @@ for await (const r of parallel(data)) { ... } // stream as workers finish
55
55
  |-------------|---------------------------|------------------------|-------------|
56
56
  | `cores` | `number` | `navigator.hardwareConcurrency` | Number of worker threads |
57
57
  | `threshold` | `number` | `1024` | Min array length before parallelizing (falls back to main thread below this) |
58
- | `reduce` | `(a: R, b: R) => R` | — | Reduce partial results into a single value |
58
+ | `reduce` | `(a: R, b: R) => R` | - | Reduce partial results into a single value |
59
59
  | `eager` | `boolean` | `false` | Pre-spawn workers immediately instead of on first call |
60
60
 
61
61
  #### `CallOptions` (per-call overrides)
62
62
 
63
63
  | Option | Type | Default | Description |
64
64
  |------------|----------------|----------|-------------|
65
- | `cores` | `number` | — | Override core count for this call |
66
- | `signal` | `AbortSignal` | — | Cancel in-flight workers |
65
+ | `cores` | `number` | - | Override core count for this call |
66
+ | `signal` | `AbortSignal` | - | Cancel in-flight workers |
67
67
  | `transfer` | `boolean` | `true` | Auto-detect and transfer ArrayBuffer ownership (zero-copy) |
68
68
 
69
69
  ### `map(array, fn, options?)`
@@ -98,7 +98,7 @@ const sum = await reduce(hugeArray, (a, b) => a + b, 0);
98
98
 
99
99
  ### `dotProduct(as, bs)`
100
100
 
101
- Batch dot product of vector pairs. JIT loop-unrolled (up to 16× unroll).
101
+ Batch dot product of vector pairs. JIT loop-unrolled (up to 16x unroll).
102
102
 
103
103
  ```ts
104
104
  import { dotProduct } from "defuss-multicore";
@@ -117,7 +117,7 @@ Matrix multiplication with transpose optimization + loop unrolling.
117
117
  ```ts
118
118
  import { matmul } from "defuss-multicore";
119
119
 
120
- // A: M×K, B: K×N → C: M×N
120
+ // A: MxK, B: KxN => C: MxN
121
121
  const C: Float64Array[] = matmul(A, B);
122
122
  ```
123
123
 
@@ -133,7 +133,7 @@ const diff = matsub(A, B);
133
133
  const quot = matdiv(A, B);
134
134
  ```
135
135
 
136
- All matrix ops use `Matrix<Float64Array>` — an array of row vectors (`Float64Array[]`).
136
+ All matrix ops use `Matrix<Float64Array>` - an array of row vectors (`Float64Array[]`).
137
137
 
138
138
  ### `getPoolSize()`
139
139
 
@@ -161,32 +161,32 @@ All benchmarks measured on Node.js (worker_threads) on Apple Silicon (10 cores).
161
161
 
162
162
  ### Loop-Unrolled Ops vs Naive Baseline
163
163
 
164
- Single-threaded comparison — same thread, unrolled kernels vs naive loops:
164
+ Single-threaded comparison - same thread, unrolled kernels vs naive loops:
165
165
 
166
166
  | Operation | Size | Speedup |
167
167
  |-----------|------|---------|
168
- | **matmul** | 200 × 300 × 200 | **2.36×** |
169
- | **matadd** | 1000 × 1000 | **2.11×** |
170
- | **matmul** | 500 × 500 | **2.06×** |
171
- | **dotProduct** | 100K × 768-dim | **1.46×** |
172
- | **matsub** | 1000 × 1000 | 0.49× |
173
- | **matdiv** | 1000 × 1000 | 0.37× |
168
+ | **matmul** | 200 x 300 x 200 | **2.36x** |
169
+ | **matadd** | 1000 x 1000 | **2.11x** |
170
+ | **matmul** | 500 x 500 | **2.06x** |
171
+ | **dotProduct** | 100K x 768-dim | **1.46x** |
172
+ | **matsub** | 1000 x 1000 | 0.49x |
173
+ | **matdiv** | 1000 x 1000 | 0.37x |
174
174
 
175
- Loop unrolling shines on **compute-heavy inner loops** like matrix multiplication, where the unrolled kernel avoids branch overhead and allows the CPU to pipeline instructions. Element-wise ops (add/sub/div) benefit less because the operation per element is trivial — the memory access pattern dominates.
175
+ Loop unrolling shines on **compute-heavy inner loops** like matrix multiplication, where the unrolled kernel avoids branch overhead and allows the CPU to pipeline instructions. Element-wise ops (add/sub/div) benefit less because the operation per element is trivial - the memory access pattern dominates.
176
176
 
177
177
  ### Multicore Workers vs Single-Thread
178
178
 
179
- Worker parallelism — dispatching across all CPU cores vs running on the main thread:
179
+ Worker parallelism - dispatching across all CPU cores vs running on the main thread:
180
180
 
181
181
  | Workload | Size | Speedup |
182
182
  |----------|------|---------|
183
- | **Key stretching** (PBKDF2-like) | 100K × 1000 rounds | **4.89×** |
184
- | **CRC32** (network packets) | 10K × 4KB | **1.31×** |
185
- | **CRC32** (small messages) | 500K × 64B | 0.80× |
186
- | **Transform** (sin+cos) | 5M items | 0.60× |
187
- | **FNV-1a** hash | 1M × 128B | 0.44× |
188
- | **Filter** elements | 2M items | 0.39× |
189
- | **Sum** (accumulate) | 10M items | 0.06× |
183
+ | **Key stretching** (PBKDF2-like) | 100K x 1000 rounds | **4.89x** |
184
+ | **CRC32** (network packets) | 10K x 4KB | **1.31x** |
185
+ | **CRC32** (small messages) | 500K x 64B | 0.80x |
186
+ | **Transform** (sin+cos) | 5M items | 0.60x |
187
+ | **FNV-1a** hash | 1M x 128B | 0.44x |
188
+ | **Filter** elements | 2M items | 0.39x |
189
+ | **Sum** (accumulate) | 10M items | 0.06x |
190
190
 
191
191
  ## When to Use `multicore()`
192
192
 
@@ -194,30 +194,30 @@ The benchmarks tell a clear story: **worker parallelism pays off when each chunk
194
194
 
195
195
  ### DO: Parallelize These
196
196
 
197
- - **Key derivation / password hashing** — thousands of rounds per item (4.9× speedup)
198
- - **Batch checksumming** (CRC32, SHA, etc.) of large messages — enough work per chunk to amortize dispatch
199
- - **Heavy per-element computation** — image processing, physics simulation, compression
197
+ - **Key derivation / password hashing** - thousands of rounds per item (4.9x speedup)
198
+ - **Batch checksumming** (CRC32, SHA, etc.) of large messages - enough work per chunk to amortize dispatch
199
+ - **Heavy per-element computation** - image processing, physics simulation, compression
200
200
  - **Any workload where each chunk runs >5ms** on a single core
201
201
 
202
202
  ### DON'T: Parallelize These
203
203
 
204
- - **Simple reductions** (sum, min, max) — main-thread loop is faster than worker dispatch
205
- - **Trivial transforms** (multiply, add constant) — memory-bandwidth bound, not CPU-bound
206
- - **Small arrays** (<1024 elements) — the `threshold` option exists for this reason
207
- - **Single function calls** — multicore is for **batches**, not individual invocations
208
- - **I/O-bound work** — fetch, file reads, DB queries are already async; workers add overhead
204
+ - **Simple reductions** (sum, min, max) - main-thread loop is faster than worker dispatch
205
+ - **Trivial transforms** (multiply, add constant) - memory-bandwidth bound, not CPU-bound
206
+ - **Small arrays** (<1024 elements) - the `threshold` option exists for this reason
207
+ - **Single function calls** - multicore is for **batches**, not individual invocations
208
+ - **I/O-bound work** - fetch, file reads, DB queries are already async; workers add overhead
209
209
 
210
210
  ### DO: Use Loop-Unrolled Ops
211
211
 
212
- - **`matmul`** for matrix multiplication, neural network layers (2×+ speedup)
213
- - **`matadd`** for accumulating matrices (2.1×)
214
- - **`dotProduct`** for embedding similarity, cosine distance, attention scores (1.5×+ speedup)
212
+ - **`matmul`** for matrix multiplication, neural network layers (2x+ speedup)
213
+ - **`matadd`** for accumulating matrices (2.1x)
214
+ - **`dotProduct`** for embedding similarity, cosine distance, attention scores (1.5x+ speedup)
215
215
 
216
216
  ### Key Principles
217
217
 
218
- 1. **Measure first.** The `threshold` option exists so small inputs fall back to the main thread automatically. But "small" depends on your workload — a 10K-element array of simple additions is too small; a 10K-element array of 1000-round hash stretches is perfect.
218
+ 1. **Measure first.** The `threshold` option exists so small inputs fall back to the main thread automatically. But "small" depends on your workload - a 10K-element array of simple additions is too small; a 10K-element array of 1000-round hash stretches is perfect.
219
219
 
220
- 2. **Worker functions must be pure.** They run in isolated contexts — no closures, no imports, no DOM access. Everything the function needs must be passed as arguments or computed inline.
220
+ 2. **Worker functions must be pure.** They run in isolated contexts - no closures, no imports, no DOM access. Everything the function needs must be passed as arguments or computed inline.
221
221
 
222
222
  3. **Transferables are auto-detected.** ArrayBuffers are transferred (zero-copy) by default. Disable with `{ transfer: false }` if you need to reuse the buffer after the call.
223
223
 
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ const serializeFunction = (fn) => {
21
21
  'use strict';
22
22
 
23
23
  const __fn = ${fnString};
24
+ let __nodeParentPort = null;
24
25
 
25
26
  const __isTypedArray = (v) =>
26
27
  ArrayBuffer.isView(v) && !(v instanceof DataView);
@@ -39,18 +40,27 @@ const __getTransferables = (value) => {
39
40
  return [];
40
41
  };
41
42
 
43
+ const __dispatch = (msg, transfer) => {
44
+ if (typeof postMessage === 'function') {
45
+ postMessage(msg, transfer ?? []);
46
+ return;
47
+ }
48
+
49
+ if (__nodeParentPort) {
50
+ __nodeParentPort.postMessage(msg, transfer ?? []);
51
+ return;
52
+ }
53
+
54
+ throw new Error('Node worker parentPort is not ready.');
55
+ };
56
+
42
57
  const __handleMessage = (data) => {
43
58
  if (data.type === 'execute') {
44
59
  try {
45
60
  const result = __fn(...data.args);
46
61
  const transfer = __getTransferables(result);
47
62
  const msg = { type: 'result', id: data.id, value: result };
48
- if (typeof postMessage === 'function') {
49
- postMessage(msg, transfer);
50
- } else {
51
- const { parentPort } = require('node:worker_threads');
52
- parentPort.postMessage(msg, transfer);
53
- }
63
+ __dispatch(msg, transfer);
54
64
  } catch (err) {
55
65
  const msg = {
56
66
  type: 'error',
@@ -58,12 +68,7 @@ const __handleMessage = (data) => {
58
68
  error: err instanceof Error ? err.message : String(err),
59
69
  stack: err instanceof Error ? err.stack : undefined,
60
70
  };
61
- if (typeof postMessage === 'function') {
62
- postMessage(msg);
63
- } else {
64
- const { parentPort } = require('node:worker_threads');
65
- parentPort.postMessage(msg);
66
- }
71
+ __dispatch(msg);
67
72
  }
68
73
  }
69
74
  // 'abort' type is a no-op; the caller terminates the worker externally
@@ -75,15 +80,17 @@ if (typeof self !== 'undefined' && typeof self.onmessage !== 'undefined') {
75
80
  }
76
81
 
77
82
  // Node.js worker_threads
78
- if (typeof require !== 'undefined') {
79
- try {
80
- const { parentPort } = require('node:worker_threads');
81
- if (parentPort) {
82
- parentPort.on('message', __handleMessage);
83
- }
84
- } catch (_) {
85
- // Not in worker_threads context \u2014 ignore
86
- }
83
+ if (typeof postMessage !== 'function') {
84
+ import('node:worker_threads')
85
+ .then(({ parentPort }) => {
86
+ __nodeParentPort = parentPort ?? null;
87
+ if (__nodeParentPort) {
88
+ __nodeParentPort.on('message', __handleMessage);
89
+ }
90
+ })
91
+ .catch(() => {
92
+ // Not in worker_threads context - ignore
93
+ });
87
94
  }
88
95
  `.trim();
89
96
  };
@@ -164,12 +171,16 @@ const getCoreCount = () => {
164
171
  if (typeof navigator !== "undefined" && navigator.hardwareConcurrency) {
165
172
  return navigator.hardwareConcurrency;
166
173
  }
174
+ const nodeProcess = typeof process !== "undefined" ? process : null;
167
175
  try {
168
- const os = require("node:os");
169
- return os.cpus().length;
176
+ const getBuiltinModule = nodeProcess?.getBuiltinModule;
177
+ if (typeof getBuiltinModule === "function") {
178
+ const os = getBuiltinModule("node:os");
179
+ return os.cpus().length;
180
+ }
170
181
  } catch {
171
- return 4;
172
182
  }
183
+ return 4;
173
184
  };
174
185
 
175
186
  const isBrowser = () => typeof globalThis !== "undefined" && typeof globalThis.Worker === "function";
@@ -180,8 +191,17 @@ const getPoolFactory = async () => {
180
191
  const { createBrowserPool } = await Promise.resolve().then(function () { return require('./pool-browser-BsBdOUwc.cjs'); });
181
192
  createPoolFn = createBrowserPool;
182
193
  } else {
183
- const { createNodePool } = await Promise.resolve().then(function () { return require('./pool-node-DKGzL78_.cjs'); });
184
- createPoolFn = createNodePool;
194
+ try {
195
+ const [{ createNodePool }, { Worker }] = await Promise.all([
196
+ Promise.resolve().then(function () { return require('./pool-node-DUsc5lQk.cjs'); }),
197
+ import('node:worker_threads')
198
+ ]);
199
+ createPoolFn = (script, config) => createNodePool(script, Worker, config);
200
+ } catch {
201
+ throw new Error(
202
+ "[defuss-multicore] node:worker_threads not available. Are you running in Node.js?"
203
+ );
204
+ }
185
205
  }
186
206
  return createPoolFn;
187
207
  };
package/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@ type TypedArray = Float32Array | Float64Array | Int8Array | Int16Array | Int32Ar
4
4
  type NumericArray = number[] | TypedArray;
5
5
  /** A matrix is an array of row vectors (each row is a NumericArray) */
6
6
  type Matrix<T extends NumericArray = Float32Array> = T[];
7
- /** Batch of vectors (same shape as Matrix — alias for clarity) */
7
+ /** Batch of vectors (same shape as Matrix - alias for clarity) */
8
8
  type Vectors<T extends NumericArray = Float32Array> = T[];
9
9
  interface PoolConfig {
10
10
  /** Maximum number of workers in the pool (default: core count) */
@@ -39,8 +39,8 @@ interface CallOptions {
39
39
  transfer?: boolean;
40
40
  }
41
41
  /**
42
- * Dual interface: use as `PromiseLike` (await → R[]) or as `AsyncIterable`
43
- * (for-await-of → yields each R as workers complete).
42
+ * Dual interface: use as `PromiseLike` (await => R[]) or as `AsyncIterable`
43
+ * (for-await-of => yields each R as workers complete).
44
44
  */
45
45
  interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {
46
46
  }
@@ -49,7 +49,7 @@ interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {
49
49
  */
50
50
  interface ReducedParallelResult<R> extends AsyncIterable<R>, PromiseLike<R> {
51
51
  }
52
- /** The callable returned by `multicore(fn)` — same arg types, parallel return */
52
+ /** The callable returned by `multicore(fn)` - same arg types, parallel return */
53
53
  type ParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>;
54
54
  type ReducedParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ReducedParallelResult<ReturnType<T>>;
55
55
  interface OpOptions extends CallOptions {
@@ -82,7 +82,7 @@ declare const getCoreCount: () => number;
82
82
  declare const multicore: <T extends (...args: any[]) => any>(fn: T, options?: MulticoreOptions<ReturnType<T>>) => ((...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>);
83
83
 
84
84
  /**
85
- * Parallel `Array.prototype.map` — distributes work across CPU cores.
85
+ * Parallel `Array.prototype.map` - distributes work across CPU cores.
86
86
  *
87
87
  * @example
88
88
  * ```ts
@@ -91,7 +91,7 @@ declare const multicore: <T extends (...args: any[]) => any>(fn: T, options?: Mu
91
91
  */
92
92
  declare const map: <T, U>(array: T[], fn: (item: T) => U, options?: CallOptions) => ParallelResult<U[]>;
93
93
  /**
94
- * Parallel `Array.prototype.filter` — distributes predicate across CPU cores.
94
+ * Parallel `Array.prototype.filter` - distributes predicate across CPU cores.
95
95
  *
96
96
  * @example
97
97
  * ```ts
@@ -100,7 +100,7 @@ declare const map: <T, U>(array: T[], fn: (item: T) => U, options?: CallOptions)
100
100
  */
101
101
  declare const filter: <T>(array: T[], fn: (item: T) => boolean, options?: CallOptions) => ParallelResult<T[]>;
102
102
  /**
103
- * Parallel `Array.prototype.reduce` — each worker reduces its chunk,
103
+ * Parallel `Array.prototype.reduce` - each worker reduces its chunk,
104
104
  * then main thread reduces the partial results.
105
105
  *
106
106
  * @example
@@ -125,12 +125,12 @@ declare const reduce: <T>(array: T[], fn: (a: T, b: T) => T, initial: T, options
125
125
  declare const dotProduct: <T extends NumericArray>(vectorsA: Vectors<T>, vectorsB: Vectors<T>, options?: OpOptions) => Float32Array;
126
126
 
127
127
  /**
128
- * Matrix multiplication. C = A × B
128
+ * Matrix multiplication. C = A x B
129
129
  *
130
130
  * Row-parallel: each "worker" computes a slice of C's rows.
131
131
  * Inner dot product uses the unrolled kernel (4/8/16) for the k-dimension.
132
132
  *
133
- * Complexity: O(M × N × K) with M = A.rows, K = A.cols = B.rows, N = B.cols.
133
+ * Complexity: O(M x N x K) with M = A.rows, K = A.cols = B.rows, N = B.cols.
134
134
  */
135
135
  declare const matmul: <T extends NumericArray>(A: Matrix<T>, B: Matrix<T>, options?: OpOptions) => Matrix<T>;
136
136
 
package/dist/index.d.mts CHANGED
@@ -4,7 +4,7 @@ type TypedArray = Float32Array | Float64Array | Int8Array | Int16Array | Int32Ar
4
4
  type NumericArray = number[] | TypedArray;
5
5
  /** A matrix is an array of row vectors (each row is a NumericArray) */
6
6
  type Matrix<T extends NumericArray = Float32Array> = T[];
7
- /** Batch of vectors (same shape as Matrix — alias for clarity) */
7
+ /** Batch of vectors (same shape as Matrix - alias for clarity) */
8
8
  type Vectors<T extends NumericArray = Float32Array> = T[];
9
9
  interface PoolConfig {
10
10
  /** Maximum number of workers in the pool (default: core count) */
@@ -39,8 +39,8 @@ interface CallOptions {
39
39
  transfer?: boolean;
40
40
  }
41
41
  /**
42
- * Dual interface: use as `PromiseLike` (await → R[]) or as `AsyncIterable`
43
- * (for-await-of → yields each R as workers complete).
42
+ * Dual interface: use as `PromiseLike` (await => R[]) or as `AsyncIterable`
43
+ * (for-await-of => yields each R as workers complete).
44
44
  */
45
45
  interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {
46
46
  }
@@ -49,7 +49,7 @@ interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {
49
49
  */
50
50
  interface ReducedParallelResult<R> extends AsyncIterable<R>, PromiseLike<R> {
51
51
  }
52
- /** The callable returned by `multicore(fn)` — same arg types, parallel return */
52
+ /** The callable returned by `multicore(fn)` - same arg types, parallel return */
53
53
  type ParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>;
54
54
  type ReducedParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ReducedParallelResult<ReturnType<T>>;
55
55
  interface OpOptions extends CallOptions {
@@ -82,7 +82,7 @@ declare const getCoreCount: () => number;
82
82
  declare const multicore: <T extends (...args: any[]) => any>(fn: T, options?: MulticoreOptions<ReturnType<T>>) => ((...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>);
83
83
 
84
84
  /**
85
- * Parallel `Array.prototype.map` — distributes work across CPU cores.
85
+ * Parallel `Array.prototype.map` - distributes work across CPU cores.
86
86
  *
87
87
  * @example
88
88
  * ```ts
@@ -91,7 +91,7 @@ declare const multicore: <T extends (...args: any[]) => any>(fn: T, options?: Mu
91
91
  */
92
92
  declare const map: <T, U>(array: T[], fn: (item: T) => U, options?: CallOptions) => ParallelResult<U[]>;
93
93
  /**
94
- * Parallel `Array.prototype.filter` — distributes predicate across CPU cores.
94
+ * Parallel `Array.prototype.filter` - distributes predicate across CPU cores.
95
95
  *
96
96
  * @example
97
97
  * ```ts
@@ -100,7 +100,7 @@ declare const map: <T, U>(array: T[], fn: (item: T) => U, options?: CallOptions)
100
100
  */
101
101
  declare const filter: <T>(array: T[], fn: (item: T) => boolean, options?: CallOptions) => ParallelResult<T[]>;
102
102
  /**
103
- * Parallel `Array.prototype.reduce` — each worker reduces its chunk,
103
+ * Parallel `Array.prototype.reduce` - each worker reduces its chunk,
104
104
  * then main thread reduces the partial results.
105
105
  *
106
106
  * @example
@@ -125,12 +125,12 @@ declare const reduce: <T>(array: T[], fn: (a: T, b: T) => T, initial: T, options
125
125
  declare const dotProduct: <T extends NumericArray>(vectorsA: Vectors<T>, vectorsB: Vectors<T>, options?: OpOptions) => Float32Array;
126
126
 
127
127
  /**
128
- * Matrix multiplication. C = A × B
128
+ * Matrix multiplication. C = A x B
129
129
  *
130
130
  * Row-parallel: each "worker" computes a slice of C's rows.
131
131
  * Inner dot product uses the unrolled kernel (4/8/16) for the k-dimension.
132
132
  *
133
- * Complexity: O(M × N × K) with M = A.rows, K = A.cols = B.rows, N = B.cols.
133
+ * Complexity: O(M x N x K) with M = A.rows, K = A.cols = B.rows, N = B.cols.
134
134
  */
135
135
  declare const matmul: <T extends NumericArray>(A: Matrix<T>, B: Matrix<T>, options?: OpOptions) => Matrix<T>;
136
136
 
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire as _pkgrollCR}from"node:module";const require=_pkgrollCR(import.meta.url);const isTypedArray = (v) => ArrayBuffer.isView(v) && !(v instanceof DataView);
1
+ const isTypedArray = (v) => ArrayBuffer.isView(v) && !(v instanceof DataView);
2
2
  const isCallOptions = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !ArrayBuffer.isView(v) && ("cores" in v || "signal" in v || "transfer" in v);
3
3
 
4
4
  const warnIfClosure = (fn) => {
@@ -19,6 +19,7 @@ const serializeFunction = (fn) => {
19
19
  'use strict';
20
20
 
21
21
  const __fn = ${fnString};
22
+ let __nodeParentPort = null;
22
23
 
23
24
  const __isTypedArray = (v) =>
24
25
  ArrayBuffer.isView(v) && !(v instanceof DataView);
@@ -37,18 +38,27 @@ const __getTransferables = (value) => {
37
38
  return [];
38
39
  };
39
40
 
41
+ const __dispatch = (msg, transfer) => {
42
+ if (typeof postMessage === 'function') {
43
+ postMessage(msg, transfer ?? []);
44
+ return;
45
+ }
46
+
47
+ if (__nodeParentPort) {
48
+ __nodeParentPort.postMessage(msg, transfer ?? []);
49
+ return;
50
+ }
51
+
52
+ throw new Error('Node worker parentPort is not ready.');
53
+ };
54
+
40
55
  const __handleMessage = (data) => {
41
56
  if (data.type === 'execute') {
42
57
  try {
43
58
  const result = __fn(...data.args);
44
59
  const transfer = __getTransferables(result);
45
60
  const msg = { type: 'result', id: data.id, value: result };
46
- if (typeof postMessage === 'function') {
47
- postMessage(msg, transfer);
48
- } else {
49
- const { parentPort } = require('node:worker_threads');
50
- parentPort.postMessage(msg, transfer);
51
- }
61
+ __dispatch(msg, transfer);
52
62
  } catch (err) {
53
63
  const msg = {
54
64
  type: 'error',
@@ -56,12 +66,7 @@ const __handleMessage = (data) => {
56
66
  error: err instanceof Error ? err.message : String(err),
57
67
  stack: err instanceof Error ? err.stack : undefined,
58
68
  };
59
- if (typeof postMessage === 'function') {
60
- postMessage(msg);
61
- } else {
62
- const { parentPort } = require('node:worker_threads');
63
- parentPort.postMessage(msg);
64
- }
69
+ __dispatch(msg);
65
70
  }
66
71
  }
67
72
  // 'abort' type is a no-op; the caller terminates the worker externally
@@ -73,15 +78,17 @@ if (typeof self !== 'undefined' && typeof self.onmessage !== 'undefined') {
73
78
  }
74
79
 
75
80
  // Node.js worker_threads
76
- if (typeof require !== 'undefined') {
77
- try {
78
- const { parentPort } = require('node:worker_threads');
79
- if (parentPort) {
80
- parentPort.on('message', __handleMessage);
81
- }
82
- } catch (_) {
83
- // Not in worker_threads context \u2014 ignore
84
- }
81
+ if (typeof postMessage !== 'function') {
82
+ import('node:worker_threads')
83
+ .then(({ parentPort }) => {
84
+ __nodeParentPort = parentPort ?? null;
85
+ if (__nodeParentPort) {
86
+ __nodeParentPort.on('message', __handleMessage);
87
+ }
88
+ })
89
+ .catch(() => {
90
+ // Not in worker_threads context - ignore
91
+ });
85
92
  }
86
93
  `.trim();
87
94
  };
@@ -162,12 +169,16 @@ const getCoreCount = () => {
162
169
  if (typeof navigator !== "undefined" && navigator.hardwareConcurrency) {
163
170
  return navigator.hardwareConcurrency;
164
171
  }
172
+ const nodeProcess = typeof process !== "undefined" ? process : null;
165
173
  try {
166
- const os = require("node:os");
167
- return os.cpus().length;
174
+ const getBuiltinModule = nodeProcess?.getBuiltinModule;
175
+ if (typeof getBuiltinModule === "function") {
176
+ const os = getBuiltinModule("node:os");
177
+ return os.cpus().length;
178
+ }
168
179
  } catch {
169
- return 4;
170
180
  }
181
+ return 4;
171
182
  };
172
183
 
173
184
  const isBrowser = () => typeof globalThis !== "undefined" && typeof globalThis.Worker === "function";
@@ -178,8 +189,17 @@ const getPoolFactory = async () => {
178
189
  const { createBrowserPool } = await import('./pool-browser-IHMOtzRq.mjs');
179
190
  createPoolFn = createBrowserPool;
180
191
  } else {
181
- const { createNodePool } = await import('./pool-node-Chmgg6NZ.mjs');
182
- createPoolFn = createNodePool;
192
+ try {
193
+ const [{ createNodePool }, { Worker }] = await Promise.all([
194
+ import('./pool-node-CmCaEceF.mjs'),
195
+ import('node:worker_threads')
196
+ ]);
197
+ createPoolFn = (script, config) => createNodePool(script, Worker, config);
198
+ } catch {
199
+ throw new Error(
200
+ "[defuss-multicore] node:worker_threads not available. Are you running in Node.js?"
201
+ );
202
+ }
183
203
  }
184
204
  return createPoolFn;
185
205
  };
@@ -1,17 +1,7 @@
1
1
  import { c as createPool } from './pool-DhG3ybwo.mjs';
2
- import { createRequire } from 'node:module';
3
2
  import './index.mjs';
4
3
 
5
- const createNodePool = (script, config) => {
6
- let WorkerClass;
7
- try {
8
- const _require = createRequire(import.meta.url);
9
- WorkerClass = _require("node:worker_threads").Worker;
10
- } catch {
11
- throw new Error(
12
- "[defuss-multicore] node:worker_threads not available. Are you running in Node.js?"
13
- );
14
- }
4
+ const createNodePool = (script, WorkerClass, config) => {
15
5
  const hooks = {
16
6
  createWorker(script2) {
17
7
  return new WorkerClass(script2, { eval: true });
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ var pool = require('./pool-DqNSYahJ.cjs');
4
+ require('./index.cjs');
5
+
6
+ const createNodePool = (script, WorkerClass, config) => {
7
+ const hooks = {
8
+ createWorker(script2) {
9
+ return new WorkerClass(script2, { eval: true });
10
+ },
11
+ postMessage(worker, data, transfer) {
12
+ worker.postMessage(data, transfer);
13
+ },
14
+ terminateWorker(worker) {
15
+ worker.terminate();
16
+ },
17
+ onMessage(worker, handler) {
18
+ worker.on("message", handler);
19
+ },
20
+ onError(worker, handler) {
21
+ worker.on("error", handler);
22
+ }
23
+ };
24
+ return pool.createPool(script, config ?? {}, hooks);
25
+ };
26
+
27
+ exports.createNodePool = createNodePool;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "defuss-multicore",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -70,4 +70,4 @@
70
70
  "typescript": "^5.9.3",
71
71
  "vitest": "^4.1.2"
72
72
  }
73
- }
73
+ }
@@ -1,38 +0,0 @@
1
- 'use strict';
2
-
3
- var pool = require('./pool-DqNSYahJ.cjs');
4
- var node_module = require('node:module');
5
- require('./index.cjs');
6
-
7
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
8
- const createNodePool = (script, config) => {
9
- let WorkerClass;
10
- try {
11
- const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('pool-node-DKGzL78_.cjs', document.baseURI).href)));
12
- WorkerClass = _require("node:worker_threads").Worker;
13
- } catch {
14
- throw new Error(
15
- "[defuss-multicore] node:worker_threads not available. Are you running in Node.js?"
16
- );
17
- }
18
- const hooks = {
19
- createWorker(script2) {
20
- return new WorkerClass(script2, { eval: true });
21
- },
22
- postMessage(worker, data, transfer) {
23
- worker.postMessage(data, transfer);
24
- },
25
- terminateWorker(worker) {
26
- worker.terminate();
27
- },
28
- onMessage(worker, handler) {
29
- worker.on("message", handler);
30
- },
31
- onError(worker, handler) {
32
- worker.on("error", handler);
33
- }
34
- };
35
- return pool.createPool(script, config ?? {}, hooks);
36
- };
37
-
38
- exports.createNodePool = createNodePool;