Offload functions to worker threads with shared memory primitives for Node.js.
1import { Readable } from 'node:stream';
2import type { Task, Runner } from './runner.ts';
3
4type TaskResult<I> = I extends Task<infer T> ? T : never;
5
6/** Options controlling how {@link map} dispatches tasks to a {@link Runner}. */
7export interface MapOptions {
8 /** Maximum number of in-flight tasks at once. Defaults to `1`. */
9 concurrency?: number;
10 /** Signal that, when aborted, stops pulling from `items` and ends iteration. */
11 signal?: AbortSignal;
12}
13
14/**
15 * Dispatches tasks yielded by `items` to a worker pool with bounded concurrency,
16 * emitting results in completion order.
17 *
18 * Accepts a union of task types (e.g. `Task<string> | Task<number>`) and emits
19 * the corresponding union of results.
20 *
21 * @param run - A {@link Runner} returned by {@link workers}.
22 * @param items - Iterable or async iterable of inert tasks to dispatch. Use {@link inert} to yield tasks from an async generator without triggering auto-await.
23 * @param opts - Concurrency and cancellation options.
24 * @returns Async iterable of task results in completion order.
25 */
26export function map<I extends Task<any>>(
27 run: Runner,
28 items: Iterable<I> | AsyncIterable<I>,
29 opts?: MapOptions,
30): AsyncIterable<TaskResult<I>> {
31 return Readable.from(items).map(run, opts) as AsyncIterable<TaskResult<I>>;
32}