@procedures/collections 0.46.0 → 0.47.2

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.
Files changed (233) hide show
  1. package/CHANGELOG.md +42 -8
  2. package/README.md +30 -0
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/index.d.ts +1 -58
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +3 -94
  7. package/dist/index.js.map +1 -1
  8. package/dist/storage/index.d.ts +2 -2
  9. package/dist/storage/index.d.ts.map +1 -1
  10. package/dist/storage/index.js +1 -1
  11. package/dist/storage/index.js.map +1 -1
  12. package/dist/storage/memory.d.ts +1 -1
  13. package/dist/storage/memory.d.ts.map +1 -1
  14. package/dist/storage/memory.js +1 -1
  15. package/dist/storage/memory.js.map +1 -1
  16. package/dist/testing/index.d.ts +1 -1
  17. package/dist/testing/index.d.ts.map +1 -1
  18. package/dist/testing/index.js +1 -1
  19. package/dist/testing/index.js.map +1 -1
  20. package/dist/testing/storage-contract.js +1 -1
  21. package/dist/testing/storage-contract.js.map +1 -1
  22. package/dist/undo/index.d.ts +1 -1
  23. package/dist/undo/index.js +1 -1
  24. package/dist/undo/undo-log.d.ts +1 -1
  25. package/dist/undo/undo-log.js +1 -1
  26. package/package.json +6 -6
  27. package/src/index.ts +338 -213
  28. package/src/storage/index.ts +2 -2
  29. package/src/storage/memory.ts +1 -1
  30. package/src/testing/index.ts +1 -1
  31. package/src/testing/storage-contract.ts +1 -1
  32. package/src/undo/index.ts +1 -1
  33. package/src/undo/undo-log.ts +1 -1
  34. package/dist/async/async-queue.d.ts +0 -170
  35. package/dist/async/async-queue.d.ts.map +0 -1
  36. package/dist/async/async-queue.js +0 -404
  37. package/dist/async/async-queue.js.map +0 -1
  38. package/dist/async/channels.d.ts +0 -211
  39. package/dist/async/channels.d.ts.map +0 -1
  40. package/dist/async/channels.js +0 -393
  41. package/dist/async/channels.js.map +0 -1
  42. package/dist/async/settled.d.ts +0 -23
  43. package/dist/async/settled.d.ts.map +0 -1
  44. package/dist/async/settled.js +0 -32
  45. package/dist/async/settled.js.map +0 -1
  46. package/dist/behaviors/bounded.d.ts +0 -79
  47. package/dist/behaviors/bounded.d.ts.map +0 -1
  48. package/dist/behaviors/bounded.js +0 -393
  49. package/dist/behaviors/bounded.js.map +0 -1
  50. package/dist/behaviors/composite.d.ts +0 -17
  51. package/dist/behaviors/composite.d.ts.map +0 -1
  52. package/dist/behaviors/composite.js +0 -93
  53. package/dist/behaviors/composite.js.map +0 -1
  54. package/dist/behaviors/evented.d.ts +0 -154
  55. package/dist/behaviors/evented.d.ts.map +0 -1
  56. package/dist/behaviors/evented.js +0 -299
  57. package/dist/behaviors/evented.js.map +0 -1
  58. package/dist/behaviors/lru.d.ts +0 -84
  59. package/dist/behaviors/lru.d.ts.map +0 -1
  60. package/dist/behaviors/lru.js +0 -376
  61. package/dist/behaviors/lru.js.map +0 -1
  62. package/dist/behaviors/readonly.d.ts +0 -73
  63. package/dist/behaviors/readonly.d.ts.map +0 -1
  64. package/dist/behaviors/readonly.js +0 -189
  65. package/dist/behaviors/readonly.js.map +0 -1
  66. package/dist/behaviors/safe.d.ts +0 -163
  67. package/dist/behaviors/safe.d.ts.map +0 -1
  68. package/dist/behaviors/safe.js +0 -176
  69. package/dist/behaviors/safe.js.map +0 -1
  70. package/dist/behaviors/synchronized.d.ts +0 -88
  71. package/dist/behaviors/synchronized.d.ts.map +0 -1
  72. package/dist/behaviors/synchronized.js +0 -285
  73. package/dist/behaviors/synchronized.js.map +0 -1
  74. package/dist/behaviors/ttl.d.ts +0 -118
  75. package/dist/behaviors/ttl.d.ts.map +0 -1
  76. package/dist/behaviors/ttl.js +0 -354
  77. package/dist/behaviors/ttl.js.map +0 -1
  78. package/dist/contracts/model.d.ts +0 -29
  79. package/dist/contracts/model.d.ts.map +0 -1
  80. package/dist/contracts/model.js +0 -26
  81. package/dist/contracts/model.js.map +0 -1
  82. package/dist/core/effects.d.ts +0 -176
  83. package/dist/core/effects.d.ts.map +0 -1
  84. package/dist/core/effects.js +0 -180
  85. package/dist/core/effects.js.map +0 -1
  86. package/dist/core/events.d.ts +0 -192
  87. package/dist/core/events.d.ts.map +0 -1
  88. package/dist/core/events.js +0 -291
  89. package/dist/core/events.js.map +0 -1
  90. package/dist/core/middleware.d.ts +0 -231
  91. package/dist/core/middleware.d.ts.map +0 -1
  92. package/dist/core/middleware.js +0 -161
  93. package/dist/core/middleware.js.map +0 -1
  94. package/dist/core/policies.d.ts +0 -220
  95. package/dist/core/policies.d.ts.map +0 -1
  96. package/dist/core/policies.js +0 -48
  97. package/dist/core/policies.js.map +0 -1
  98. package/dist/core/traits.d.ts +0 -142
  99. package/dist/core/traits.d.ts.map +0 -1
  100. package/dist/core/traits.js +0 -8
  101. package/dist/core/traits.js.map +0 -1
  102. package/dist/fx/collectors.d.ts +0 -193
  103. package/dist/fx/collectors.d.ts.map +0 -1
  104. package/dist/fx/collectors.js +0 -375
  105. package/dist/fx/collectors.js.map +0 -1
  106. package/dist/fx/iter.d.ts +0 -166
  107. package/dist/fx/iter.d.ts.map +0 -1
  108. package/dist/fx/iter.js +0 -421
  109. package/dist/fx/iter.js.map +0 -1
  110. package/dist/impl/array-deque.d.ts +0 -112
  111. package/dist/impl/array-deque.d.ts.map +0 -1
  112. package/dist/impl/array-deque.js +0 -380
  113. package/dist/impl/array-deque.js.map +0 -1
  114. package/dist/impl/array-list.d.ts +0 -101
  115. package/dist/impl/array-list.d.ts.map +0 -1
  116. package/dist/impl/array-list.js +0 -387
  117. package/dist/impl/array-list.js.map +0 -1
  118. package/dist/impl/hash-map.d.ts +0 -149
  119. package/dist/impl/hash-map.d.ts.map +0 -1
  120. package/dist/impl/hash-map.js +0 -473
  121. package/dist/impl/hash-map.js.map +0 -1
  122. package/dist/impl/hash-set.d.ts +0 -125
  123. package/dist/impl/hash-set.d.ts.map +0 -1
  124. package/dist/impl/hash-set.js +0 -264
  125. package/dist/impl/hash-set.js.map +0 -1
  126. package/dist/impl/linked-hash-map.d.ts +0 -141
  127. package/dist/impl/linked-hash-map.d.ts.map +0 -1
  128. package/dist/impl/linked-hash-map.js +0 -442
  129. package/dist/impl/linked-hash-map.js.map +0 -1
  130. package/dist/impl/linked-list.d.ts +0 -109
  131. package/dist/impl/linked-list.d.ts.map +0 -1
  132. package/dist/impl/linked-list.js +0 -494
  133. package/dist/impl/linked-list.js.map +0 -1
  134. package/dist/impl/priority-queue.d.ts +0 -139
  135. package/dist/impl/priority-queue.d.ts.map +0 -1
  136. package/dist/impl/priority-queue.js +0 -343
  137. package/dist/impl/priority-queue.js.map +0 -1
  138. package/dist/impl/tree-map.d.ts +0 -153
  139. package/dist/impl/tree-map.d.ts.map +0 -1
  140. package/dist/impl/tree-map.js +0 -788
  141. package/dist/impl/tree-map.js.map +0 -1
  142. package/dist/impl/tree-set.d.ts +0 -112
  143. package/dist/impl/tree-set.d.ts.map +0 -1
  144. package/dist/impl/tree-set.js +0 -374
  145. package/dist/impl/tree-set.js.map +0 -1
  146. package/dist/interfaces/collection.d.ts +0 -119
  147. package/dist/interfaces/collection.d.ts.map +0 -1
  148. package/dist/interfaces/collection.js +0 -8
  149. package/dist/interfaces/collection.js.map +0 -1
  150. package/dist/interfaces/list.d.ts +0 -247
  151. package/dist/interfaces/list.d.ts.map +0 -1
  152. package/dist/interfaces/list.js +0 -8
  153. package/dist/interfaces/list.js.map +0 -1
  154. package/dist/interfaces/map.d.ts +0 -344
  155. package/dist/interfaces/map.d.ts.map +0 -1
  156. package/dist/interfaces/map.js +0 -8
  157. package/dist/interfaces/map.js.map +0 -1
  158. package/dist/interfaces/queue.d.ts +0 -304
  159. package/dist/interfaces/queue.d.ts.map +0 -1
  160. package/dist/interfaces/queue.js +0 -8
  161. package/dist/interfaces/queue.js.map +0 -1
  162. package/dist/interfaces/set.d.ts +0 -137
  163. package/dist/interfaces/set.d.ts.map +0 -1
  164. package/dist/interfaces/set.js +0 -8
  165. package/dist/interfaces/set.js.map +0 -1
  166. package/dist/order/index.d.ts +0 -7
  167. package/dist/order/index.d.ts.map +0 -1
  168. package/dist/order/index.js +0 -7
  169. package/dist/order/index.js.map +0 -1
  170. package/dist/order/rank.d.ts +0 -100
  171. package/dist/order/rank.d.ts.map +0 -1
  172. package/dist/order/rank.js +0 -286
  173. package/dist/order/rank.js.map +0 -1
  174. package/dist/storage/listeners.d.ts +0 -39
  175. package/dist/storage/listeners.d.ts.map +0 -1
  176. package/dist/storage/listeners.js +0 -65
  177. package/dist/storage/listeners.js.map +0 -1
  178. package/dist/testing/check.d.ts +0 -25
  179. package/dist/testing/check.d.ts.map +0 -1
  180. package/dist/testing/check.js +0 -85
  181. package/dist/testing/check.js.map +0 -1
  182. package/dist/utils/defaults.d.ts +0 -135
  183. package/dist/utils/defaults.d.ts.map +0 -1
  184. package/dist/utils/defaults.js +0 -322
  185. package/dist/utils/defaults.js.map +0 -1
  186. package/dist/utils/factories.d.ts +0 -144
  187. package/dist/utils/factories.d.ts.map +0 -1
  188. package/dist/utils/factories.js +0 -293
  189. package/dist/utils/factories.js.map +0 -1
  190. package/dist/utils/helpers.d.ts +0 -137
  191. package/dist/utils/helpers.d.ts.map +0 -1
  192. package/dist/utils/helpers.js +0 -221
  193. package/dist/utils/helpers.js.map +0 -1
  194. package/src/async/async-queue.ts +0 -481
  195. package/src/async/channels.ts +0 -450
  196. package/src/async/settled.ts +0 -41
  197. package/src/behaviors/bounded.ts +0 -485
  198. package/src/behaviors/composite.ts +0 -99
  199. package/src/behaviors/evented.ts +0 -464
  200. package/src/behaviors/lru.ts +0 -447
  201. package/src/behaviors/readonly.ts +0 -236
  202. package/src/behaviors/safe.ts +0 -372
  203. package/src/behaviors/synchronized.ts +0 -316
  204. package/src/behaviors/ttl.ts +0 -462
  205. package/src/contracts/model.ts +0 -44
  206. package/src/core/effects.ts +0 -323
  207. package/src/core/events.ts +0 -356
  208. package/src/core/middleware.ts +0 -415
  209. package/src/core/policies.ts +0 -316
  210. package/src/core/traits.ts +0 -164
  211. package/src/fx/collectors.ts +0 -500
  212. package/src/fx/iter.ts +0 -536
  213. package/src/impl/array-deque.ts +0 -463
  214. package/src/impl/array-list.ts +0 -490
  215. package/src/impl/hash-map.ts +0 -623
  216. package/src/impl/hash-set.ts +0 -342
  217. package/src/impl/linked-hash-map.ts +0 -572
  218. package/src/impl/linked-list.ts +0 -606
  219. package/src/impl/priority-queue.ts +0 -448
  220. package/src/impl/tree-map.ts +0 -912
  221. package/src/impl/tree-set.ts +0 -469
  222. package/src/interfaces/collection.ts +0 -141
  223. package/src/interfaces/list.ts +0 -281
  224. package/src/interfaces/map.ts +0 -405
  225. package/src/interfaces/queue.ts +0 -353
  226. package/src/interfaces/set.ts +0 -158
  227. package/src/order/index.ts +0 -6
  228. package/src/order/rank.ts +0 -271
  229. package/src/storage/listeners.ts +0 -72
  230. package/src/testing/check.ts +0 -81
  231. package/src/utils/defaults.ts +0 -345
  232. package/src/utils/factories.ts +0 -357
  233. package/src/utils/helpers.ts +0 -248
@@ -1,450 +0,0 @@
1
- /**
2
- * Go-style channels for CSP (Communicating Sequential Processes).
3
- *
4
- * Provides typed, bidirectional communication channels inspired by Go.
5
- * Perfect for coordinating async operations and implementing concurrent patterns.
6
- *
7
- * @example
8
- * const ch = channel<number>()
9
- *
10
- * // Sender
11
- * await ch.send(42)
12
- *
13
- * // Receiver
14
- * const value = await ch.receive()
15
- *
16
- * // Select from multiple channels
17
- * const result = await select(
18
- * ch1.case((v) => console.log('ch1:', v)),
19
- * ch2.case((v) => console.log('ch2:', v))
20
- * )
21
- */
22
-
23
- import { asyncQueue, type AsyncQueue } from "./async-queue.js";
24
-
25
- /**
26
- * Channel<T> - Bidirectional communication channel.
27
- *
28
- * Inspired by Go channels. Provides send/receive operations
29
- * that can block until the other side is ready.
30
- */
31
- export class Channel<T> {
32
- private queue: AsyncQueue<T>;
33
- private _isClosed = false;
34
-
35
- constructor(bufferSize: number = 0) {
36
- // A buffer size of 0 is an unbuffered channel: send waits for a receiver (a rendezvous).
37
- // (Before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17.)
38
- this.queue = asyncQueue<T>({ capacity: bufferSize });
39
- }
40
-
41
- /**
42
- * Sends a value through the channel.
43
- * Blocks if channel buffer is full.
44
- *
45
- * @throws Error if channel is closed
46
- */
47
- async send(value: T): Promise<void> {
48
- if (this._isClosed) {
49
- throw new Error("Cannot send on closed channel");
50
- }
51
- await this.queue.put(value);
52
- }
53
-
54
- /**
55
- * Receives a value from the channel.
56
- * Blocks if no value is available.
57
- *
58
- * @throws Error if channel is closed and empty
59
- */
60
- async receive(): Promise<T> {
61
- return await this.queue.take();
62
- }
63
-
64
- /**
65
- * This method waits for one value, as `receive` does, and gives it to `onValue`. When the
66
- * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in
67
- * the call that sends the value or closes the channel.
68
- *
69
- * The function that it returns withdraws the wait, so no later value goes to it.
70
- *
71
- * @returns A function that withdraws the wait. It returns true when the wait had no value yet.
72
- */
73
- waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {
74
- return this.queue.waitTake(onValue, onClosed);
75
- }
76
-
77
- /**
78
- * Attempts to send without blocking.
79
- * Returns false if channel is full.
80
- */
81
- trySend(value: T): boolean {
82
- if (this._isClosed) return false;
83
- return this.queue.tryPut(value);
84
- }
85
-
86
- /**
87
- * Attempts to receive without blocking.
88
- * Returns undefined if no value is available.
89
- */
90
- tryReceive(): T | undefined {
91
- return this.queue.tryTake();
92
- }
93
-
94
- /**
95
- * Closes the channel. No more values can be sent.
96
- * Receivers can still drain remaining values.
97
- */
98
- close(): void {
99
- this._isClosed = true;
100
- this.queue.close();
101
- }
102
-
103
- get isClosed(): boolean {
104
- return this._isClosed;
105
- }
106
-
107
- get size(): number {
108
- return this.queue.size;
109
- }
110
-
111
- /**
112
- * Creates a select case for this channel.
113
- * Used with the select() function for multiplexing.
114
- */
115
- case<R>(handler: (value: T) => R): SelectCase<R> {
116
- return {
117
- channel: this,
118
- handler,
119
- tryReceive: () => this.tryReceive(),
120
- receive: () => this.receive(),
121
- wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),
122
- };
123
- }
124
-
125
- /**
126
- * Async iteration over channel values.
127
- * Stops when channel is closed and empty.
128
- */
129
- async *[Symbol.asyncIterator](): AsyncIterator<T> {
130
- while (true) {
131
- try {
132
- yield await this.receive();
133
- } catch (e) {
134
- // Channel closed
135
- break;
136
- }
137
- }
138
- }
139
- }
140
-
141
- /**
142
- * SelectCase represents a case in a select statement.
143
- */
144
- export interface SelectCase<R> {
145
- channel: Channel<any>;
146
- handler: (value: any) => R;
147
- tryReceive: () => any;
148
- receive: () => Promise<any>;
149
- /**
150
- * A wait for one value that `select` can withdraw: `Channel.waitReceive`. A case without it
151
- * uses the `waitReceive` method of its channel.
152
- */
153
- wait?: (onValue: (value: any) => void, onClosed: (error: Error) => void) => () => boolean;
154
- }
155
-
156
- /** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */
157
- type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;
158
-
159
- /**
160
- * This function gives the first value of the waits, with the index of its wait. It rejects with
161
- * the error of the first wait whose channel is closed and empty. It withdraws each other wait in
162
- * the same call, so a later value stays in its channel. (Before, the receives of the cases that
163
- * lost stayed in their channels and dropped the next value of each: audit O56.)
164
- */
165
- function firstOf(waits: readonly Wait[]): Promise<{ index: number; value: unknown }> {
166
- return new Promise((resolve, reject) => {
167
- const withdraws: Array<() => boolean> = [];
168
- let settled = false;
169
- const end = (): void => {
170
- settled = true;
171
- for (const withdraw of withdraws) withdraw();
172
- };
173
- // A wait can call back at once, in its own call, when its channel has a value or is closed
174
- try {
175
- for (let index = 0; index < waits.length && !settled; index++) {
176
- withdraws.push(
177
- waits[index]!(
178
- (value) => {
179
- if (settled) return;
180
- end();
181
- resolve({ index, value });
182
- },
183
- (error) => {
184
- if (settled) return;
185
- end();
186
- reject(error);
187
- },
188
- ),
189
- );
190
- }
191
- } catch (error) {
192
- // A wait that throws: the waits before it are withdrawn
193
- if (!settled) end();
194
- reject(error);
195
- }
196
- });
197
- }
198
-
199
- /**
200
- * Selects from multiple channels (like Go's select statement).
201
- *
202
- * Waits for the first channel to have a value available,
203
- * then calls its handler and returns the result.
204
- *
205
- * The first case with a value at once wins. The cases that lose keep no receive: a value that
206
- * comes later stays in its channel for the next receiver. When the channel of a case is closed
207
- * and empty, the returned promise rejects.
208
- *
209
- * @example
210
- * const result = await select(
211
- * ch1.case((v) => `ch1: ${v}`),
212
- * ch2.case((v) => `ch2: ${v}`),
213
- * timeout(1000).case(() => 'timeout')
214
- * )
215
- */
216
- export async function select<R>(...cases: SelectCase<R>[]): Promise<R> {
217
- const { index, value } = await firstOf(
218
- cases.map((c): Wait => c.wait ?? ((onValue, onClosed) => c.channel.waitReceive(onValue, onClosed))),
219
- );
220
- // The handler runs after the race, not in the call of the sender
221
- return cases[index]!.handler(value);
222
- }
223
-
224
- /**
225
- * Creates a timeout channel that sends after the specified duration.
226
- *
227
- * @example
228
- * const result = await select(
229
- * dataChannel.case((v) => v),
230
- * timeout(5000).case(() => 'timeout!')
231
- * )
232
- */
233
- export function timeout(ms: number): Channel<void> {
234
- const ch = new Channel<void>();
235
- setTimeout(() => {
236
- ch.send(undefined).catch(() => {}); // Ignore if closed
237
- ch.close();
238
- }, ms);
239
- return ch;
240
- }
241
-
242
- /**
243
- * Creates a ticker channel that sends at regular intervals.
244
- *
245
- * @example
246
- * const tick = ticker(1000) // Every second
247
- * for await (const t of tick) {
248
- * console.log('Tick:', t)
249
- * }
250
- */
251
- export function ticker(ms: number): Channel<number> & { stop: () => void } {
252
- const ch = new Channel<number>(1);
253
- let count = 0;
254
-
255
- const intervalId = setInterval(() => {
256
- ch.trySend(count++);
257
- }, ms);
258
-
259
- return Object.assign(ch, {
260
- stop: () => {
261
- clearInterval(intervalId);
262
- ch.close();
263
- },
264
- });
265
- }
266
-
267
- /**
268
- * Pipeline: pipes values from input channel through transform to output channel.
269
- *
270
- * @example
271
- * const input = channel<number>()
272
- * const output = pipeline(input, (x) => x * 2)
273
- *
274
- * await input.send(5)
275
- * const result = await output.receive() // 10
276
- */
277
- export function pipeline<T, U>(
278
- input: Channel<T>,
279
- transform: (value: T) => U | Promise<U>,
280
- bufferSize: number = 0
281
- ): Channel<U> {
282
- const output = new Channel<U>(bufferSize);
283
-
284
- // The output closes also when the transform fails, so its reader does not wait forever. The
285
- // error goes to the console, as in workerPool. (Before, it was an unhandled rejection: audit pass 2.)
286
- (async () => {
287
- try {
288
- for await (const value of input) {
289
- const transformed = await transform(value);
290
- await output.send(transformed);
291
- }
292
- } finally {
293
- output.close();
294
- }
295
- })().catch((error: unknown) => console.error("pipeline error:", error));
296
-
297
- return output;
298
- }
299
-
300
- /**
301
- * Fan-out: distributes values from one input channel to multiple output channels.
302
- *
303
- * @example
304
- * const input = channel<number>()
305
- * const [out1, out2, out3] = fanOut(input, 3)
306
- *
307
- * // Each output gets a copy of every input value
308
- */
309
- export function fanOut<T>(input: Channel<T>, count: number, bufferSize: number = 0): Channel<T>[] {
310
- const outputs = Array.from({ length: count }, () => new Channel<T>(bufferSize));
311
-
312
- (async () => {
313
- try {
314
- for await (const value of input) {
315
- await Promise.all(outputs.map((ch) => ch.send(value)));
316
- }
317
- } finally {
318
- outputs.forEach((ch) => ch.close());
319
- }
320
- })().catch((error: unknown) => console.error("fanOut error:", error));
321
-
322
- return outputs;
323
- }
324
-
325
- /**
326
- * Fan-in: merges multiple input channels into one output channel.
327
- *
328
- * @example
329
- * const ch1 = channel<number>()
330
- * const ch2 = channel<number>()
331
- * const merged = fanIn(ch1, ch2)
332
- *
333
- * // merged receives values from both ch1 and ch2
334
- */
335
- export function fanIn<T>(...inputs: Channel<T>[]): Channel<T> {
336
- const output = new Channel<T>();
337
-
338
- const workers = inputs.map(async (input) => {
339
- for await (const value of input) {
340
- await output.send(value);
341
- }
342
- });
343
-
344
- // All the workers settle, then the output closes, also after a failed send
345
- Promise.allSettled(workers).then((results) => {
346
- output.close();
347
- for (const result of results) if (result.status === "rejected") console.error("fanIn error:", result.reason);
348
- });
349
-
350
- return output;
351
- }
352
-
353
- /**
354
- * Merge: like fanIn but closes output when first input closes.
355
- *
356
- * It takes one value at a time, from the inputs in turn, and keeps no receive on an input while
357
- * it waits for the reader of the output. So each value of each input reaches the output one
358
- * time, in the order of its input, or stays in its input.
359
- */
360
- export function merge<T>(...inputs: Channel<T>[]): Channel<T> {
361
- const output = new Channel<T>();
362
-
363
- (async () => {
364
- // The input after the input of the last value comes first, so a busy input starves no other
365
- let start = 0;
366
- while (true) {
367
- const order = inputs.map((_, offset) => (start + offset) % inputs.length);
368
- let next: { index: number; value: unknown };
369
- try {
370
- next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));
371
- } catch {
372
- // An input is closed and empty
373
- break;
374
- }
375
- const index = order[next.index]!;
376
- start = (index + 1) % inputs.length;
377
- try {
378
- await output.send(next.value as T);
379
- } catch {
380
- // The reader closed the output
381
- break;
382
- }
383
- }
384
- output.close();
385
- })();
386
-
387
- return output;
388
- }
389
-
390
- /**
391
- * Buffered channel with specified capacity.
392
- */
393
- export function buffered<T>(capacity: number): Channel<T> {
394
- return new Channel<T>(capacity);
395
- }
396
-
397
- /**
398
- * Unbuffered channel (rendezvous point).
399
- * Sends block until receiver is ready.
400
- */
401
- export function unbuffered<T>(): Channel<T> {
402
- return new Channel<T>(0);
403
- }
404
-
405
- /**
406
- * Factory function to create a channel.
407
- *
408
- * @example
409
- * const ch = channel<number>()
410
- * const bufferedCh = channel<string>(10)
411
- */
412
- export function channel<T>(bufferSize: number = 0): Channel<T> {
413
- return new Channel<T>(bufferSize);
414
- }
415
-
416
- /**
417
- * WorkerPool: distributes work across multiple workers.
418
- *
419
- * @example
420
- * const pool = workerPool(
421
- * jobChannel,
422
- * async (job) => await processJob(job),
423
- * { workers: 4 }
424
- * )
425
- *
426
- * // 4 workers concurrently process jobs from jobChannel
427
- */
428
- export function workerPool<T, R>(
429
- jobs: Channel<T>,
430
- worker: (job: T) => Promise<R>,
431
- options: { workers: number; bufferSize?: number } = { workers: 1 }
432
- ): Channel<R> {
433
- const results = new Channel<R>(options.bufferSize || 0);
434
- const { workers: workerCount } = options;
435
-
436
- const workers = Array.from({ length: workerCount }, async () => {
437
- for await (const job of jobs) {
438
- try {
439
- const result = await worker(job);
440
- await results.send(result);
441
- } catch (error) {
442
- console.error("Worker error:", error);
443
- }
444
- }
445
- });
446
-
447
- Promise.all(workers).then(() => results.close());
448
-
449
- return results;
450
- }
@@ -1,41 +0,0 @@
1
- /**
2
- * asSettled - The results of running promises, in the order that they settle.
3
- *
4
- * @example
5
- * const pages = urls.map((url) => fetch(url));
6
- * for await (const result of asSettled(pages)) {
7
- * if (result.status === "fulfilled") show(result.index, result.value);
8
- * else report(result.index, result.reason);
9
- * }
10
- */
11
-
12
- /** One result of `asSettled`: the index of its promise in the input, and how the promise settled. */
13
- export type Settled<T> = { readonly index: number } & PromiseSettledResult<T>;
14
-
15
- /**
16
- * This function gives the result of each promise when it settles, in settle order, not in input
17
- * order. The promises run already: this function starts nothing. Each result has the index of its
18
- * promise in the input. A rejected promise gives `status: "rejected"` and its reason: the
19
- * generator does not throw it. When the consumer stops early, the other promises continue, and
20
- * their rejections are not reported as unhandled.
21
- */
22
- export async function* asSettled<T>(promises: Iterable<Promise<T>>): AsyncGenerator<Settled<T>, void, undefined> {
23
- const pending = new Map<number, Promise<Settled<T>>>();
24
- let next = 0;
25
- for (const promise of promises) {
26
- const index = next;
27
- next += 1;
28
- pending.set(
29
- index,
30
- Promise.resolve(promise).then(
31
- (value): Settled<T> => ({ index, status: "fulfilled", value }),
32
- (reason: unknown): Settled<T> => ({ index, status: "rejected", reason })
33
- )
34
- );
35
- }
36
- while (pending.size > 0) {
37
- const settled = await Promise.race(pending.values());
38
- pending.delete(settled.index);
39
- yield settled;
40
- }
41
- }