defuss-multicore 0.0.3 → 0.1.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.d.cts CHANGED
@@ -1,61 +1,6 @@
1
- /** Union of all typed array constructors supported for parallel ops */
2
- type TypedArray = Float32Array | Float64Array | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array;
3
- /** Any array-like container of numbers */
4
- type NumericArray = number[] | TypedArray;
5
- /** A matrix is an array of row vectors (each row is a NumericArray) */
6
- type Matrix<T extends NumericArray = Float32Array> = T[];
7
- /** Batch of vectors (same shape as Matrix - alias for clarity) */
8
- type Vectors<T extends NumericArray = Float32Array> = T[];
9
- interface PoolConfig {
10
- /** Maximum number of workers in the pool (default: core count) */
11
- maxWorkers?: number;
12
- /** Kill idle workers after this many ms (default: 30 000) */
13
- idleTimeoutMs?: number;
14
- }
15
- /** Abstract interface implemented by pool-browser and pool-node */
16
- interface WorkerPool {
17
- readonly size: number;
18
- execute(args: unknown[], transfer?: ArrayBuffer[], signal?: AbortSignal): Promise<unknown>;
19
- warmup(count?: number): void;
20
- terminate(): Promise<void>;
21
- }
22
- interface MulticoreOptions<R = unknown> {
23
- /** Override core count (default: all available cores) */
24
- cores?: number;
25
- /** Combine partial results into a single value on the main thread */
26
- reduce?: (a: R, b: R) => R;
27
- /** Pre-spawn worker pool at definition time (default: lazy) */
28
- eager?: boolean;
29
- /** Minimum array length to use workers; below this, run on main thread (default: 1024) */
30
- threshold?: number;
31
- }
32
- /** Per-call overrides passed as trailing argument */
33
- interface CallOptions {
34
- /** Override core count for this call */
35
- cores?: number;
36
- /** AbortSignal to cancel in-flight workers */
37
- signal?: AbortSignal;
38
- /** Force or disable Transferable detection (default: auto) */
39
- transfer?: boolean;
40
- }
41
- /**
42
- * Dual interface: use as `PromiseLike` (await => R[]) or as `AsyncIterable`
43
- * (for-await-of => yields each R as workers complete).
44
- */
45
- interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {
46
- }
47
- /**
48
- * Same as ParallelResult but when `reduce` is set, await resolves to a single R.
49
- */
50
- interface ReducedParallelResult<R> extends AsyncIterable<R>, PromiseLike<R> {
51
- }
52
- /** The callable returned by `multicore(fn)` - same arg types, parallel return */
53
- type ParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>;
54
- type ReducedParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ReducedParallelResult<ReturnType<T>>;
55
- interface OpOptions extends CallOptions {
56
- /** Force a specific unroll factor (default: auto-select by dimension) */
57
- unroll?: 4 | 8 | 16;
58
- }
1
+ import { C as CallOptions, P as ParallelResult, M as MulticoreOptions, N as NumericArray, V as Vectors, O as OpOptions, a as Matrix, E as ExecutionOptions, T as TransferItem, b as TaskHandlers, c as PoolStats, d as TaskResult, e as TaskTiming } from './worker-CneL12oi.cjs';
2
+ export { f as ParallelFn, g as PoolConfig, R as ReducedParallelFn, h as ReducedParallelResult, i as Transferred, j as TypedArray, W as WorkerPool, t as transfer } from './worker-CneL12oi.cjs';
3
+ import { Worker as Worker$1 } from 'node:worker_threads';
59
4
 
60
5
  /**
61
6
  * Returns the number of available CPU cores.
@@ -65,50 +10,27 @@ interface OpOptions extends CallOptions {
65
10
  */
66
11
  declare const getCoreCount: () => number;
67
12
 
68
- /**
69
- * Higher-order function that wraps a pure function for parallel execution.
70
- *
71
- * - Array/TypedArray args are auto-split across CPU cores
72
- * - Scalar args are broadcast to every worker
73
- * - Returns a function with the same arg types; return type becomes `ParallelResult<R>`
74
- *
75
- * @example
76
- * ```ts
77
- * const sum = multicore((chunk: number[]) => chunk.reduce((a, b) => a + b, 0));
78
- * const results = await sum(largeArray); // number[]
79
- * for await (const r of sum(largeArray)) { ... } // streaming
80
- * ```
81
- */
82
- declare const multicore: <T extends (...args: any[]) => any>(fn: T, options?: MulticoreOptions<ReturnType<T>>) => ((...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>);
13
+ type Fn = (...args: any[]) => any;
14
+ interface MulticoreFunction<T extends Fn, V = Awaited<ReturnType<T>>[]> {
15
+ (...args: [...Parameters<T>, CallOptions?]): ParallelResult<Awaited<ReturnType<T>>, V>;
16
+ /** Unambiguous options for optional/default/rest parameters and arbitrary payloads. */
17
+ withOptions(options: CallOptions, ...args: Parameters<T>): ParallelResult<Awaited<ReturnType<T>>, V>;
18
+ warmup(): Promise<void>;
19
+ close(): Promise<void>;
20
+ terminate(): Promise<void>;
21
+ }
22
+ declare function multicore<T extends Fn>(fn: T, options: MulticoreOptions<Awaited<ReturnType<T>>> & {
23
+ reduce: (a: Awaited<ReturnType<T>>, b: Awaited<ReturnType<T>>) => Awaited<ReturnType<T>>;
24
+ }): MulticoreFunction<T, Awaited<ReturnType<T>>>;
25
+ declare function multicore<T extends Fn>(fn: T, options?: MulticoreOptions<Awaited<ReturnType<T>>>): MulticoreFunction<T>;
83
26
 
84
- /**
85
- * Parallel `Array.prototype.map` - distributes work across CPU cores.
86
- *
87
- * @example
88
- * ```ts
89
- * const doubled = await map(hugeArray, (x) => x * 2);
90
- * ```
91
- */
92
- declare const map: <T, U>(array: T[], fn: (item: T) => U, options?: CallOptions) => ParallelResult<U[]>;
93
- /**
94
- * Parallel `Array.prototype.filter` - distributes predicate across CPU cores.
95
- *
96
- * @example
97
- * ```ts
98
- * const evens = await filter(hugeArray, (x) => x % 2 === 0);
99
- * ```
100
- */
101
- declare const filter: <T>(array: T[], fn: (item: T) => boolean, options?: CallOptions) => ParallelResult<T[]>;
102
- /**
103
- * Parallel `Array.prototype.reduce` - each worker reduces its chunk,
104
- * then main thread reduces the partial results.
105
- *
106
- * @example
107
- * ```ts
108
- * const total = await reduce(hugeArray, (a, b) => a + b, 0);
109
- * ```
110
- */
111
- declare const reduce: <T>(array: T[], fn: (a: T, b: T) => T, initial: T, options?: CallOptions) => Promise<T>;
27
+ /** Pure, synchronous, item-only callback; awaited output is flat, streaming output is chunked. */
28
+ declare function map<T, U>(array: T[], fn: (item: T) => U, options?: CallOptions): ParallelResult<U[], U[]>;
29
+ declare function filter<T>(array: T[], fn: (item: T) => boolean, options?: CallOptions): ParallelResult<T[], T[]>;
30
+ /** Associative reducer only. initial is applied exactly once; regrouping may change floating-point rounding. */
31
+ declare function reduce<T>(array: T[], fn: (a: T, b: T) => T, initial: T, options?: CallOptions): Promise<T>;
32
+ /** Explicitly release pools cached for this callback (optionally one core configuration). */
33
+ declare function releaseArrayWorkers(fn: Function, cores?: number): Promise<void>;
112
34
 
113
35
  /**
114
36
  * Batch dot product of vector pairs.
@@ -158,5 +80,45 @@ declare const matsub: <T extends NumericArray>(A: Matrix<T>, B: Matrix<T>, optio
158
80
  */
159
81
  declare const matdiv: <T extends NumericArray>(A: Matrix<T>, B: Matrix<T>, options?: OpOptions) => Matrix<T>;
160
82
 
161
- export { dotProduct, filter, getCoreCount as getPoolSize, map, matadd, matdiv, matmul, matsub, multicore, reduce };
162
- export type { CallOptions, Matrix, MulticoreOptions, NumericArray, OpOptions, ParallelFn, ParallelResult, PoolConfig, ReducedParallelFn, ReducedParallelResult, TypedArray, Vectors, WorkerPool };
83
+ interface TaskPoolOptions {
84
+ worker: () => Worker | Worker$1;
85
+ maxWorkers?: number;
86
+ /** Waiting jobs beyond available worker slots. Default 128; overflow rejects. */
87
+ maxQueue?: number;
88
+ idleTimeoutMs?: number;
89
+ startupTimeoutMs?: number;
90
+ onTask?: (timing: TaskTiming) => void;
91
+ }
92
+ interface RunOptions extends ExecutionOptions {
93
+ signal?: AbortSignal;
94
+ transfer?: readonly TransferItem[];
95
+ }
96
+ interface BatchOptions<I> extends ExecutionOptions {
97
+ signal?: AbortSignal;
98
+ chunkSize?: number;
99
+ /** Maximum outstanding chunks for this batch. Default pool size. */
100
+ concurrency?: number;
101
+ transfer?: (payload: I, index: number) => readonly TransferItem[];
102
+ }
103
+ type Name<T> = Extract<keyof T, string>;
104
+ type Input<T extends TaskHandlers, K extends Name<T>> = Parameters<T[K]>[0];
105
+ type Output<T extends TaskHandlers, K extends Name<T>> = TaskResult<ReturnType<T[K]>>;
106
+ interface TaskPool<T extends TaskHandlers> {
107
+ readonly size: number;
108
+ readonly stats: PoolStats;
109
+ run<K extends Name<T>>(task: K, payload: Input<T, K>, options?: RunOptions): Promise<Output<T, K>>;
110
+ batch<K extends Name<T>>(task: K, jobs: readonly Input<T, K>[], options?: BatchOptions<Input<T, K>>): Promise<Output<T, K>[]>;
111
+ /** Completion order across chunks, input order within a chunk; original indices accompany values. */
112
+ stream<K extends Name<T>>(task: K, jobs: readonly Input<T, K>[], options?: BatchOptions<Input<T, K>>): AsyncIterable<{
113
+ index: number;
114
+ value: Output<T, K>;
115
+ }>;
116
+ warmup(count?: number): Promise<void>;
117
+ close(): Promise<void>;
118
+ terminate(): Promise<void>;
119
+ }
120
+ /** A reusable bounded pool. run() never silently falls back to the calling thread. */
121
+ declare function createPool<T extends TaskHandlers>(options: TaskPoolOptions): TaskPool<T>;
122
+
123
+ export { CallOptions, ExecutionOptions, Matrix, MulticoreOptions, NumericArray, OpOptions, ParallelResult, PoolStats, TaskHandlers, TaskResult, TaskTiming, TransferItem, Vectors, createPool, dotProduct, filter, getCoreCount as getPoolSize, map, matadd, matdiv, matmul, matsub, multicore, reduce, releaseArrayWorkers };
124
+ export type { BatchOptions, MulticoreFunction, RunOptions, TaskPool, TaskPoolOptions };
package/dist/index.d.mts CHANGED
@@ -1,61 +1,6 @@
1
- /** Union of all typed array constructors supported for parallel ops */
2
- type TypedArray = Float32Array | Float64Array | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array;
3
- /** Any array-like container of numbers */
4
- type NumericArray = number[] | TypedArray;
5
- /** A matrix is an array of row vectors (each row is a NumericArray) */
6
- type Matrix<T extends NumericArray = Float32Array> = T[];
7
- /** Batch of vectors (same shape as Matrix - alias for clarity) */
8
- type Vectors<T extends NumericArray = Float32Array> = T[];
9
- interface PoolConfig {
10
- /** Maximum number of workers in the pool (default: core count) */
11
- maxWorkers?: number;
12
- /** Kill idle workers after this many ms (default: 30 000) */
13
- idleTimeoutMs?: number;
14
- }
15
- /** Abstract interface implemented by pool-browser and pool-node */
16
- interface WorkerPool {
17
- readonly size: number;
18
- execute(args: unknown[], transfer?: ArrayBuffer[], signal?: AbortSignal): Promise<unknown>;
19
- warmup(count?: number): void;
20
- terminate(): Promise<void>;
21
- }
22
- interface MulticoreOptions<R = unknown> {
23
- /** Override core count (default: all available cores) */
24
- cores?: number;
25
- /** Combine partial results into a single value on the main thread */
26
- reduce?: (a: R, b: R) => R;
27
- /** Pre-spawn worker pool at definition time (default: lazy) */
28
- eager?: boolean;
29
- /** Minimum array length to use workers; below this, run on main thread (default: 1024) */
30
- threshold?: number;
31
- }
32
- /** Per-call overrides passed as trailing argument */
33
- interface CallOptions {
34
- /** Override core count for this call */
35
- cores?: number;
36
- /** AbortSignal to cancel in-flight workers */
37
- signal?: AbortSignal;
38
- /** Force or disable Transferable detection (default: auto) */
39
- transfer?: boolean;
40
- }
41
- /**
42
- * Dual interface: use as `PromiseLike` (await => R[]) or as `AsyncIterable`
43
- * (for-await-of => yields each R as workers complete).
44
- */
45
- interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {
46
- }
47
- /**
48
- * Same as ParallelResult but when `reduce` is set, await resolves to a single R.
49
- */
50
- interface ReducedParallelResult<R> extends AsyncIterable<R>, PromiseLike<R> {
51
- }
52
- /** The callable returned by `multicore(fn)` - same arg types, parallel return */
53
- type ParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>;
54
- type ReducedParallelFn<T extends (...args: unknown[]) => unknown> = (...args: [...Parameters<T>, CallOptions?]) => ReducedParallelResult<ReturnType<T>>;
55
- interface OpOptions extends CallOptions {
56
- /** Force a specific unroll factor (default: auto-select by dimension) */
57
- unroll?: 4 | 8 | 16;
58
- }
1
+ import { C as CallOptions, P as ParallelResult, M as MulticoreOptions, N as NumericArray, V as Vectors, O as OpOptions, a as Matrix, E as ExecutionOptions, T as TransferItem, b as TaskHandlers, c as PoolStats, d as TaskResult, e as TaskTiming } from './worker-CneL12oi.mjs';
2
+ export { f as ParallelFn, g as PoolConfig, R as ReducedParallelFn, h as ReducedParallelResult, i as Transferred, j as TypedArray, W as WorkerPool, t as transfer } from './worker-CneL12oi.mjs';
3
+ import { Worker as Worker$1 } from 'node:worker_threads';
59
4
 
60
5
  /**
61
6
  * Returns the number of available CPU cores.
@@ -65,50 +10,27 @@ interface OpOptions extends CallOptions {
65
10
  */
66
11
  declare const getCoreCount: () => number;
67
12
 
68
- /**
69
- * Higher-order function that wraps a pure function for parallel execution.
70
- *
71
- * - Array/TypedArray args are auto-split across CPU cores
72
- * - Scalar args are broadcast to every worker
73
- * - Returns a function with the same arg types; return type becomes `ParallelResult<R>`
74
- *
75
- * @example
76
- * ```ts
77
- * const sum = multicore((chunk: number[]) => chunk.reduce((a, b) => a + b, 0));
78
- * const results = await sum(largeArray); // number[]
79
- * for await (const r of sum(largeArray)) { ... } // streaming
80
- * ```
81
- */
82
- declare const multicore: <T extends (...args: any[]) => any>(fn: T, options?: MulticoreOptions<ReturnType<T>>) => ((...args: [...Parameters<T>, CallOptions?]) => ParallelResult<ReturnType<T>>);
13
+ type Fn = (...args: any[]) => any;
14
+ interface MulticoreFunction<T extends Fn, V = Awaited<ReturnType<T>>[]> {
15
+ (...args: [...Parameters<T>, CallOptions?]): ParallelResult<Awaited<ReturnType<T>>, V>;
16
+ /** Unambiguous options for optional/default/rest parameters and arbitrary payloads. */
17
+ withOptions(options: CallOptions, ...args: Parameters<T>): ParallelResult<Awaited<ReturnType<T>>, V>;
18
+ warmup(): Promise<void>;
19
+ close(): Promise<void>;
20
+ terminate(): Promise<void>;
21
+ }
22
+ declare function multicore<T extends Fn>(fn: T, options: MulticoreOptions<Awaited<ReturnType<T>>> & {
23
+ reduce: (a: Awaited<ReturnType<T>>, b: Awaited<ReturnType<T>>) => Awaited<ReturnType<T>>;
24
+ }): MulticoreFunction<T, Awaited<ReturnType<T>>>;
25
+ declare function multicore<T extends Fn>(fn: T, options?: MulticoreOptions<Awaited<ReturnType<T>>>): MulticoreFunction<T>;
83
26
 
84
- /**
85
- * Parallel `Array.prototype.map` - distributes work across CPU cores.
86
- *
87
- * @example
88
- * ```ts
89
- * const doubled = await map(hugeArray, (x) => x * 2);
90
- * ```
91
- */
92
- declare const map: <T, U>(array: T[], fn: (item: T) => U, options?: CallOptions) => ParallelResult<U[]>;
93
- /**
94
- * Parallel `Array.prototype.filter` - distributes predicate across CPU cores.
95
- *
96
- * @example
97
- * ```ts
98
- * const evens = await filter(hugeArray, (x) => x % 2 === 0);
99
- * ```
100
- */
101
- declare const filter: <T>(array: T[], fn: (item: T) => boolean, options?: CallOptions) => ParallelResult<T[]>;
102
- /**
103
- * Parallel `Array.prototype.reduce` - each worker reduces its chunk,
104
- * then main thread reduces the partial results.
105
- *
106
- * @example
107
- * ```ts
108
- * const total = await reduce(hugeArray, (a, b) => a + b, 0);
109
- * ```
110
- */
111
- declare const reduce: <T>(array: T[], fn: (a: T, b: T) => T, initial: T, options?: CallOptions) => Promise<T>;
27
+ /** Pure, synchronous, item-only callback; awaited output is flat, streaming output is chunked. */
28
+ declare function map<T, U>(array: T[], fn: (item: T) => U, options?: CallOptions): ParallelResult<U[], U[]>;
29
+ declare function filter<T>(array: T[], fn: (item: T) => boolean, options?: CallOptions): ParallelResult<T[], T[]>;
30
+ /** Associative reducer only. initial is applied exactly once; regrouping may change floating-point rounding. */
31
+ declare function reduce<T>(array: T[], fn: (a: T, b: T) => T, initial: T, options?: CallOptions): Promise<T>;
32
+ /** Explicitly release pools cached for this callback (optionally one core configuration). */
33
+ declare function releaseArrayWorkers(fn: Function, cores?: number): Promise<void>;
112
34
 
113
35
  /**
114
36
  * Batch dot product of vector pairs.
@@ -158,5 +80,45 @@ declare const matsub: <T extends NumericArray>(A: Matrix<T>, B: Matrix<T>, optio
158
80
  */
159
81
  declare const matdiv: <T extends NumericArray>(A: Matrix<T>, B: Matrix<T>, options?: OpOptions) => Matrix<T>;
160
82
 
161
- export { dotProduct, filter, getCoreCount as getPoolSize, map, matadd, matdiv, matmul, matsub, multicore, reduce };
162
- export type { CallOptions, Matrix, MulticoreOptions, NumericArray, OpOptions, ParallelFn, ParallelResult, PoolConfig, ReducedParallelFn, ReducedParallelResult, TypedArray, Vectors, WorkerPool };
83
+ interface TaskPoolOptions {
84
+ worker: () => Worker | Worker$1;
85
+ maxWorkers?: number;
86
+ /** Waiting jobs beyond available worker slots. Default 128; overflow rejects. */
87
+ maxQueue?: number;
88
+ idleTimeoutMs?: number;
89
+ startupTimeoutMs?: number;
90
+ onTask?: (timing: TaskTiming) => void;
91
+ }
92
+ interface RunOptions extends ExecutionOptions {
93
+ signal?: AbortSignal;
94
+ transfer?: readonly TransferItem[];
95
+ }
96
+ interface BatchOptions<I> extends ExecutionOptions {
97
+ signal?: AbortSignal;
98
+ chunkSize?: number;
99
+ /** Maximum outstanding chunks for this batch. Default pool size. */
100
+ concurrency?: number;
101
+ transfer?: (payload: I, index: number) => readonly TransferItem[];
102
+ }
103
+ type Name<T> = Extract<keyof T, string>;
104
+ type Input<T extends TaskHandlers, K extends Name<T>> = Parameters<T[K]>[0];
105
+ type Output<T extends TaskHandlers, K extends Name<T>> = TaskResult<ReturnType<T[K]>>;
106
+ interface TaskPool<T extends TaskHandlers> {
107
+ readonly size: number;
108
+ readonly stats: PoolStats;
109
+ run<K extends Name<T>>(task: K, payload: Input<T, K>, options?: RunOptions): Promise<Output<T, K>>;
110
+ batch<K extends Name<T>>(task: K, jobs: readonly Input<T, K>[], options?: BatchOptions<Input<T, K>>): Promise<Output<T, K>[]>;
111
+ /** Completion order across chunks, input order within a chunk; original indices accompany values. */
112
+ stream<K extends Name<T>>(task: K, jobs: readonly Input<T, K>[], options?: BatchOptions<Input<T, K>>): AsyncIterable<{
113
+ index: number;
114
+ value: Output<T, K>;
115
+ }>;
116
+ warmup(count?: number): Promise<void>;
117
+ close(): Promise<void>;
118
+ terminate(): Promise<void>;
119
+ }
120
+ /** A reusable bounded pool. run() never silently falls back to the calling thread. */
121
+ declare function createPool<T extends TaskHandlers>(options: TaskPoolOptions): TaskPool<T>;
122
+
123
+ export { CallOptions, ExecutionOptions, Matrix, MulticoreOptions, NumericArray, OpOptions, ParallelResult, PoolStats, TaskHandlers, TaskResult, TaskTiming, TransferItem, Vectors, createPool, dotProduct, filter, getCoreCount as getPoolSize, map, matadd, matdiv, matmul, matsub, multicore, reduce, releaseArrayWorkers };
124
+ export type { BatchOptions, MulticoreFunction, RunOptions, TaskPool, TaskPoolOptions };