@procedures/collections 0.0.0-stage → 0.2.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.
Files changed (205) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +394 -2
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/async/async-queue.d.ts +155 -0
  6. package/dist/async/async-queue.d.ts.map +1 -0
  7. package/dist/async/async-queue.js +342 -0
  8. package/dist/async/async-queue.js.map +1 -0
  9. package/dist/async/channels.d.ts +188 -0
  10. package/dist/async/channels.d.ts.map +1 -0
  11. package/dist/async/channels.js +314 -0
  12. package/dist/async/channels.js.map +1 -0
  13. package/dist/behaviors/bounded.d.ts +79 -0
  14. package/dist/behaviors/bounded.d.ts.map +1 -0
  15. package/dist/behaviors/bounded.js +384 -0
  16. package/dist/behaviors/bounded.js.map +1 -0
  17. package/dist/behaviors/composite.d.ts +17 -0
  18. package/dist/behaviors/composite.d.ts.map +1 -0
  19. package/dist/behaviors/composite.js +93 -0
  20. package/dist/behaviors/composite.js.map +1 -0
  21. package/dist/behaviors/evented.d.ts +154 -0
  22. package/dist/behaviors/evented.d.ts.map +1 -0
  23. package/dist/behaviors/evented.js +299 -0
  24. package/dist/behaviors/evented.js.map +1 -0
  25. package/dist/behaviors/lru.d.ts +84 -0
  26. package/dist/behaviors/lru.d.ts.map +1 -0
  27. package/dist/behaviors/lru.js +376 -0
  28. package/dist/behaviors/lru.js.map +1 -0
  29. package/dist/behaviors/readonly.d.ts +73 -0
  30. package/dist/behaviors/readonly.d.ts.map +1 -0
  31. package/dist/behaviors/readonly.js +177 -0
  32. package/dist/behaviors/readonly.js.map +1 -0
  33. package/dist/behaviors/safe.d.ts +163 -0
  34. package/dist/behaviors/safe.d.ts.map +1 -0
  35. package/dist/behaviors/safe.js +176 -0
  36. package/dist/behaviors/safe.js.map +1 -0
  37. package/dist/behaviors/synchronized.d.ts +88 -0
  38. package/dist/behaviors/synchronized.d.ts.map +1 -0
  39. package/dist/behaviors/synchronized.js +285 -0
  40. package/dist/behaviors/synchronized.js.map +1 -0
  41. package/dist/behaviors/ttl.d.ts +118 -0
  42. package/dist/behaviors/ttl.d.ts.map +1 -0
  43. package/dist/behaviors/ttl.js +354 -0
  44. package/dist/behaviors/ttl.js.map +1 -0
  45. package/dist/contracts/model.d.ts +29 -0
  46. package/dist/contracts/model.d.ts.map +1 -0
  47. package/dist/contracts/model.js +26 -0
  48. package/dist/contracts/model.js.map +1 -0
  49. package/dist/core/effects.d.ts +176 -0
  50. package/dist/core/effects.d.ts.map +1 -0
  51. package/dist/core/effects.js +180 -0
  52. package/dist/core/effects.js.map +1 -0
  53. package/dist/core/events.d.ts +192 -0
  54. package/dist/core/events.d.ts.map +1 -0
  55. package/dist/core/events.js +291 -0
  56. package/dist/core/events.js.map +1 -0
  57. package/dist/core/middleware.d.ts +231 -0
  58. package/dist/core/middleware.d.ts.map +1 -0
  59. package/dist/core/middleware.js +161 -0
  60. package/dist/core/middleware.js.map +1 -0
  61. package/dist/core/policies.d.ts +220 -0
  62. package/dist/core/policies.d.ts.map +1 -0
  63. package/dist/core/policies.js +48 -0
  64. package/dist/core/policies.js.map +1 -0
  65. package/dist/core/traits.d.ts +142 -0
  66. package/dist/core/traits.d.ts.map +1 -0
  67. package/dist/core/traits.js +8 -0
  68. package/dist/core/traits.js.map +1 -0
  69. package/dist/fx/collectors.d.ts +193 -0
  70. package/dist/fx/collectors.d.ts.map +1 -0
  71. package/dist/fx/collectors.js +375 -0
  72. package/dist/fx/collectors.js.map +1 -0
  73. package/dist/fx/iter.d.ts +166 -0
  74. package/dist/fx/iter.d.ts.map +1 -0
  75. package/dist/fx/iter.js +421 -0
  76. package/dist/fx/iter.js.map +1 -0
  77. package/dist/impl/array-deque.d.ts +112 -0
  78. package/dist/impl/array-deque.d.ts.map +1 -0
  79. package/dist/impl/array-deque.js +380 -0
  80. package/dist/impl/array-deque.js.map +1 -0
  81. package/dist/impl/array-list.d.ts +101 -0
  82. package/dist/impl/array-list.d.ts.map +1 -0
  83. package/dist/impl/array-list.js +387 -0
  84. package/dist/impl/array-list.js.map +1 -0
  85. package/dist/impl/hash-map.d.ts +149 -0
  86. package/dist/impl/hash-map.d.ts.map +1 -0
  87. package/dist/impl/hash-map.js +473 -0
  88. package/dist/impl/hash-map.js.map +1 -0
  89. package/dist/impl/hash-set.d.ts +125 -0
  90. package/dist/impl/hash-set.d.ts.map +1 -0
  91. package/dist/impl/hash-set.js +264 -0
  92. package/dist/impl/hash-set.js.map +1 -0
  93. package/dist/impl/linked-hash-map.d.ts +141 -0
  94. package/dist/impl/linked-hash-map.d.ts.map +1 -0
  95. package/dist/impl/linked-hash-map.js +442 -0
  96. package/dist/impl/linked-hash-map.js.map +1 -0
  97. package/dist/impl/linked-list.d.ts +109 -0
  98. package/dist/impl/linked-list.d.ts.map +1 -0
  99. package/dist/impl/linked-list.js +494 -0
  100. package/dist/impl/linked-list.js.map +1 -0
  101. package/dist/impl/priority-queue.d.ts +139 -0
  102. package/dist/impl/priority-queue.d.ts.map +1 -0
  103. package/dist/impl/priority-queue.js +343 -0
  104. package/dist/impl/priority-queue.js.map +1 -0
  105. package/dist/impl/tree-map.d.ts +153 -0
  106. package/dist/impl/tree-map.d.ts.map +1 -0
  107. package/dist/impl/tree-map.js +788 -0
  108. package/dist/impl/tree-map.js.map +1 -0
  109. package/dist/impl/tree-set.d.ts +112 -0
  110. package/dist/impl/tree-set.d.ts.map +1 -0
  111. package/dist/impl/tree-set.js +374 -0
  112. package/dist/impl/tree-set.js.map +1 -0
  113. package/dist/index.d.ts +106 -0
  114. package/dist/index.d.ts.map +1 -0
  115. package/dist/index.js +139 -0
  116. package/dist/index.js.map +1 -0
  117. package/dist/interfaces/collection.d.ts +119 -0
  118. package/dist/interfaces/collection.d.ts.map +1 -0
  119. package/dist/interfaces/collection.js +8 -0
  120. package/dist/interfaces/collection.js.map +1 -0
  121. package/dist/interfaces/list.d.ts +247 -0
  122. package/dist/interfaces/list.d.ts.map +1 -0
  123. package/dist/interfaces/list.js +8 -0
  124. package/dist/interfaces/list.js.map +1 -0
  125. package/dist/interfaces/map.d.ts +344 -0
  126. package/dist/interfaces/map.d.ts.map +1 -0
  127. package/dist/interfaces/map.js +8 -0
  128. package/dist/interfaces/map.js.map +1 -0
  129. package/dist/interfaces/queue.d.ts +304 -0
  130. package/dist/interfaces/queue.d.ts.map +1 -0
  131. package/dist/interfaces/queue.js +8 -0
  132. package/dist/interfaces/queue.js.map +1 -0
  133. package/dist/interfaces/set.d.ts +137 -0
  134. package/dist/interfaces/set.d.ts.map +1 -0
  135. package/dist/interfaces/set.js +8 -0
  136. package/dist/interfaces/set.js.map +1 -0
  137. package/dist/register.d.ts +8 -0
  138. package/dist/register.d.ts.map +1 -0
  139. package/dist/register.js +8 -0
  140. package/dist/register.js.map +1 -0
  141. package/dist/storage/index.d.ts +15 -0
  142. package/dist/storage/index.d.ts.map +1 -0
  143. package/dist/storage/index.js +14 -0
  144. package/dist/storage/index.js.map +1 -0
  145. package/dist/storage/interface.d.ts +141 -0
  146. package/dist/storage/interface.d.ts.map +1 -0
  147. package/dist/storage/interface.js +23 -0
  148. package/dist/storage/interface.js.map +1 -0
  149. package/dist/storage/memory.d.ts +68 -0
  150. package/dist/storage/memory.d.ts.map +1 -0
  151. package/dist/storage/memory.js +154 -0
  152. package/dist/storage/memory.js.map +1 -0
  153. package/dist/utils/defaults.d.ts +135 -0
  154. package/dist/utils/defaults.d.ts.map +1 -0
  155. package/dist/utils/defaults.js +322 -0
  156. package/dist/utils/defaults.js.map +1 -0
  157. package/dist/utils/factories.d.ts +144 -0
  158. package/dist/utils/factories.d.ts.map +1 -0
  159. package/dist/utils/factories.js +293 -0
  160. package/dist/utils/factories.js.map +1 -0
  161. package/dist/utils/helpers.d.ts +137 -0
  162. package/dist/utils/helpers.d.ts.map +1 -0
  163. package/dist/utils/helpers.js +221 -0
  164. package/dist/utils/helpers.js.map +1 -0
  165. package/package.json +68 -3
  166. package/src/async/async-queue.ts +417 -0
  167. package/src/async/channels.ts +374 -0
  168. package/src/behaviors/bounded.ts +477 -0
  169. package/src/behaviors/composite.ts +99 -0
  170. package/src/behaviors/evented.ts +464 -0
  171. package/src/behaviors/lru.ts +447 -0
  172. package/src/behaviors/readonly.ts +224 -0
  173. package/src/behaviors/safe.ts +372 -0
  174. package/src/behaviors/synchronized.ts +316 -0
  175. package/src/behaviors/ttl.ts +462 -0
  176. package/src/contracts/model.ts +44 -0
  177. package/src/core/effects.ts +323 -0
  178. package/src/core/events.ts +356 -0
  179. package/src/core/middleware.ts +415 -0
  180. package/src/core/policies.ts +316 -0
  181. package/src/core/traits.ts +164 -0
  182. package/src/fx/collectors.ts +500 -0
  183. package/src/fx/iter.ts +536 -0
  184. package/src/impl/array-deque.ts +463 -0
  185. package/src/impl/array-list.ts +490 -0
  186. package/src/impl/hash-map.ts +623 -0
  187. package/src/impl/hash-set.ts +342 -0
  188. package/src/impl/linked-hash-map.ts +572 -0
  189. package/src/impl/linked-list.ts +606 -0
  190. package/src/impl/priority-queue.ts +448 -0
  191. package/src/impl/tree-map.ts +912 -0
  192. package/src/impl/tree-set.ts +469 -0
  193. package/src/index.ts +277 -0
  194. package/src/interfaces/collection.ts +141 -0
  195. package/src/interfaces/list.ts +281 -0
  196. package/src/interfaces/map.ts +405 -0
  197. package/src/interfaces/queue.ts +353 -0
  198. package/src/interfaces/set.ts +158 -0
  199. package/src/register.ts +8 -0
  200. package/src/storage/index.ts +16 -0
  201. package/src/storage/interface.ts +179 -0
  202. package/src/storage/memory.ts +180 -0
  203. package/src/utils/defaults.ts +345 -0
  204. package/src/utils/factories.ts +357 -0
  205. package/src/utils/helpers.ts +248 -0
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@procedures/collections",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
4
+ "version": "0.2.0",
5
+ "description": "Collections for TypeScript: ArrayList, LinkedList, ArrayDeque, HashMap, LinkedHashMap, TreeMap (red-black), PriorityQueue, LRU and TTL maps, async queues, channels and collectors, tested with fast-check.",
6
+ "keywords": [
7
+ "collections",
8
+ "data-structures",
9
+ "hashmap",
10
+ "treemap",
11
+ "red-black-tree",
12
+ "priority-queue",
13
+ "lru-cache",
14
+ "ttl-cache",
15
+ "deque",
16
+ "linked-list",
17
+ "async-queue",
18
+ "channel",
19
+ "typescript"
20
+ ],
21
+ "homepage": "https://mark1russell7.github.io/client/",
22
+ "bugs": {
23
+ "url": "https://github.com/mark1russell7/client/issues"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/mark1russell7/client.git",
28
+ "directory": "packages/client-collections"
29
+ },
30
+ "license": "MIT",
31
+ "author": "Mark Russell (https://github.com/mark1russell7)",
32
+ "type": "module",
33
+ "main": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "src",
44
+ "!src/**/*.test.ts",
45
+ "!src/**/*.test.tsx",
46
+ "!src/**/__tests__",
47
+ "CHANGELOG.md"
48
+ ],
49
+ "sideEffects": false,
50
+ "engines": {
51
+ "node": ">=22"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public",
55
+ "provenance": true
56
+ },
57
+ "devDependencies": {
58
+ "typescript": "^7.0.2",
59
+ "@types/node": "^22.0.0",
60
+ "@mark1russell7/cue": "^1.0.0",
61
+ "vitest": "^5.0.3",
62
+ "fast-check": "^4.10.2"
63
+ },
64
+ "scripts": {
65
+ "build": "tsc -b",
66
+ "typecheck": "tsc --noEmit",
67
+ "clean": "rm -rf dist .tsbuildinfo",
68
+ "test": "vitest run",
69
+ "test:watch": "vitest"
70
+ }
6
71
  }
@@ -0,0 +1,417 @@
1
+ /**
2
+ * AsyncQueue - An async iterable queue with backpressure support.
3
+ *
4
+ * Designed for producer-consumer patterns where producers can wait when
5
+ * the queue is full and consumers can wait when the queue is empty.
6
+ * Implements AsyncIterable for use with for-await-of loops.
7
+ *
8
+ * @example
9
+ * const queue = asyncQueue<number>({ capacity: 10 })
10
+ *
11
+ * // Producer
12
+ * await queue.put(42) // Waits if queue is full
13
+ *
14
+ * // Consumer
15
+ * const value = await queue.take() // Waits if queue is empty
16
+ *
17
+ * // Async iteration
18
+ * for await (const value of queue) {
19
+ * console.log(value)
20
+ * }
21
+ */
22
+
23
+ import type { AsyncQueue as IAsyncQueue } from "../interfaces/queue.js";
24
+
25
+ /**
26
+ * Options for creating an AsyncQueue.
27
+ */
28
+ export interface AsyncQueueOptions {
29
+ /**
30
+ * Maximum capacity. Infinity for unbounded queue.
31
+ * @default Infinity
32
+ */
33
+ capacity?: number;
34
+
35
+ /**
36
+ * Timeout for put/take operations in milliseconds.
37
+ * @default undefined (no timeout)
38
+ */
39
+ timeout?: number;
40
+ }
41
+
42
+ /**
43
+ * Resolver for waiting operations.
44
+ */
45
+ interface Resolver<T> {
46
+ resolve: (value: T) => void;
47
+ reject: (reason: any) => void;
48
+ timeoutId?: ReturnType<typeof setTimeout>;
49
+ }
50
+
51
+ /** A waiting put: it keeps its element until the queue takes it. */
52
+ interface Putter<T> extends Resolver<void> {
53
+ element: T;
54
+ }
55
+
56
+ /**
57
+ * AsyncQueue<T> - Thread-safe async queue with backpressure.
58
+ *
59
+ * Features:
60
+ * - Blocking put() when full (backpressure)
61
+ * - Blocking take() when empty
62
+ * - AsyncIterable support
63
+ * - Graceful closing
64
+ * - Timeouts
65
+ *
66
+ * Perfect for:
67
+ * - Producer-consumer patterns
68
+ * - Rate limiting
69
+ * - Task queues
70
+ * - Stream processing
71
+ */
72
+ export class AsyncQueue<T> implements IAsyncQueue<T> {
73
+ private buffer: T[] = [];
74
+ private putters: Putter<T>[] = [];
75
+ private takers: Resolver<T>[] = [];
76
+ private _isClosed = false;
77
+ private readonly capacity: number;
78
+ private readonly defaultTimeout?: number;
79
+
80
+ constructor(options: AsyncQueueOptions = {}) {
81
+ this.capacity = options.capacity ?? Infinity;
82
+ if (options.timeout !== undefined) {
83
+ this.defaultTimeout = options.timeout;
84
+ }
85
+ }
86
+
87
+ // ========================================================================
88
+ // Size and state
89
+ // ========================================================================
90
+
91
+ get size(): number {
92
+ return this.buffer.length;
93
+ }
94
+
95
+ get isEmpty(): boolean {
96
+ return this.buffer.length === 0;
97
+ }
98
+
99
+ get isFull(): boolean {
100
+ return this.buffer.length >= this.capacity;
101
+ }
102
+
103
+ get isClosed(): boolean {
104
+ return this._isClosed;
105
+ }
106
+
107
+ get remainingCapacity(): number {
108
+ return this.capacity === Infinity ? Infinity : this.capacity - this.buffer.length;
109
+ }
110
+
111
+ // ========================================================================
112
+ // Blocking operations
113
+ // ========================================================================
114
+
115
+ /**
116
+ * Adds an element to the queue.
117
+ * If the queue is full, waits until space is available. With a capacity of 0, it waits until
118
+ * a taker takes the element (a rendezvous).
119
+ *
120
+ * @throws Error if queue is closed
121
+ * @throws Error if timeout expires
122
+ */
123
+ async put(element: T, timeout?: number): Promise<void> {
124
+ if (this._isClosed) {
125
+ throw new Error("Queue is closed");
126
+ }
127
+ if (this.tryPutNow(element)) {
128
+ return;
129
+ }
130
+
131
+ // Queue is full: wait with the element. (Before, a waiting putter kept only its resolve
132
+ // function, so its element was dropped when space came: BUGS-2026-07 C11.)
133
+ return new Promise<void>((resolve, reject) => {
134
+ const putter: Putter<T> = { element, resolve, reject };
135
+ const timeoutMs = timeout ?? this.defaultTimeout;
136
+ if (timeoutMs !== undefined) {
137
+ putter.timeoutId = setTimeout(() => {
138
+ const index = this.putters.indexOf(putter);
139
+ if (index !== -1) {
140
+ this.putters.splice(index, 1);
141
+ }
142
+ reject(new Error(`Put timeout after ${timeoutMs}ms`));
143
+ }, timeoutMs);
144
+ }
145
+ this.putters.push(putter);
146
+ });
147
+ }
148
+
149
+ /**
150
+ * Removes and returns an element from the queue.
151
+ * If the queue is empty, waits until an element is available.
152
+ *
153
+ * @throws Error if queue is closed and empty
154
+ * @throws Error if timeout expires
155
+ */
156
+ async take(timeout?: number): Promise<T> {
157
+ const next = this.takeNow();
158
+ if (next.found) {
159
+ return next.element;
160
+ }
161
+
162
+ // If closed and empty, throw
163
+ if (this._isClosed) {
164
+ throw new Error("Queue is closed and empty");
165
+ }
166
+
167
+ // Wait for an element
168
+ return new Promise<T>((resolve, reject) => {
169
+ const taker: Resolver<T> = { resolve, reject };
170
+ const timeoutMs = timeout ?? this.defaultTimeout;
171
+ if (timeoutMs !== undefined) {
172
+ taker.timeoutId = setTimeout(() => {
173
+ const index = this.takers.indexOf(taker);
174
+ if (index !== -1) {
175
+ this.takers.splice(index, 1);
176
+ }
177
+ reject(new Error(`Take timeout after ${timeoutMs}ms`));
178
+ }, timeoutMs);
179
+ }
180
+ this.takers.push(taker);
181
+ });
182
+ }
183
+
184
+ // ========================================================================
185
+ // Non-blocking operations
186
+ // ========================================================================
187
+
188
+ /**
189
+ * Attempts to add an element without waiting.
190
+ * Returns false if queue is full (with a capacity of 0: if no taker waits).
191
+ */
192
+ tryPut(element: T): boolean {
193
+ if (this._isClosed) {
194
+ return false;
195
+ }
196
+ return this.tryPutNow(element);
197
+ }
198
+
199
+ /**
200
+ * Attempts to remove an element without waiting.
201
+ * Returns undefined if queue is empty.
202
+ */
203
+ tryTake(): T | undefined {
204
+ const next = this.takeNow();
205
+ return next.found ? next.element : undefined;
206
+ }
207
+
208
+ /** Gives the element to a waiting taker, or puts it in the buffer when there is space. */
209
+ private tryPutNow(element: T): boolean {
210
+ // A waiting taker gets the element directly (the buffer is empty when a taker waits)
211
+ const taker = this.takers.shift();
212
+ if (taker) {
213
+ this.clearTimeout(taker);
214
+ taker.resolve(element);
215
+ return true;
216
+ }
217
+ if (this.buffer.length < this.capacity) {
218
+ this.buffer.push(element);
219
+ return true;
220
+ }
221
+ return false;
222
+ }
223
+
224
+ /**
225
+ * Takes the next element: from the buffer (then a waiting putter moves its element into the
226
+ * buffer), or directly from a waiting putter (a capacity of 0). (Before, the direct path
227
+ * released the putter but never gave its element to the taker, so the taker waited forever:
228
+ * BUGS-2026-07 C11.)
229
+ */
230
+ private takeNow(): { found: true; element: T } | { found: false } {
231
+ if (this.buffer.length > 0) {
232
+ const element = this.buffer.shift()!;
233
+ this.admitPutter();
234
+ return { found: true, element };
235
+ }
236
+ const putter = this.putters.shift();
237
+ if (putter) {
238
+ this.clearTimeout(putter);
239
+ putter.resolve();
240
+ return { found: true, element: putter.element };
241
+ }
242
+ return { found: false };
243
+ }
244
+
245
+ // ========================================================================
246
+ // Peeking
247
+ // ========================================================================
248
+
249
+ /**
250
+ * Returns the next element without removing it.
251
+ * Waits if queue is empty.
252
+ */
253
+ async peek(): Promise<T> {
254
+ if (this.buffer.length > 0) {
255
+ return this.buffer[0]!;
256
+ }
257
+ if (this.putters.length > 0) {
258
+ return this.putters[0]!.element;
259
+ }
260
+
261
+ if (this._isClosed) {
262
+ throw new Error("Queue is closed and empty");
263
+ }
264
+
265
+ // Wait for an element, then put it back at the front
266
+ const element = await this.take();
267
+ this.buffer.unshift(element);
268
+ return element;
269
+ }
270
+
271
+ /**
272
+ * Returns the next element without waiting.
273
+ * Returns undefined if queue is empty.
274
+ */
275
+ tryPeek(): T | undefined {
276
+ return this.buffer.length > 0 ? this.buffer[0] : this.putters[0]?.element;
277
+ }
278
+
279
+ // ========================================================================
280
+ // Closing and draining
281
+ // ========================================================================
282
+
283
+ /**
284
+ * Closes the queue. No more elements can be added.
285
+ * Existing elements can still be consumed.
286
+ */
287
+ close(): void {
288
+ this._isClosed = true;
289
+
290
+ // Reject all waiting putters
291
+ for (const putter of this.putters) {
292
+ this.clearTimeout(putter);
293
+ putter.reject(new Error("Queue closed"));
294
+ }
295
+ this.putters = [];
296
+
297
+ // Wake up takers if queue is empty
298
+ if (this.buffer.length === 0) {
299
+ for (const taker of this.takers) {
300
+ this.clearTimeout(taker);
301
+ taker.reject(new Error("Queue closed and empty"));
302
+ }
303
+ this.takers = [];
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Drains all elements into an array.
309
+ * Returns immediately with current elements.
310
+ */
311
+ drain(): T[] {
312
+ // The buffer, then the elements of the waiting putters, in order. (Before, the waiting
313
+ // putters were released but their elements were dropped.)
314
+ const elements = this.buffer.slice();
315
+ this.buffer = [];
316
+ for (const putter of this.putters.splice(0)) {
317
+ this.clearTimeout(putter);
318
+ putter.resolve();
319
+ elements.push(putter.element);
320
+ }
321
+ return elements;
322
+ }
323
+
324
+ // ========================================================================
325
+ // Async iteration
326
+ // ========================================================================
327
+
328
+ /**
329
+ * Async iterator that yields elements as they become available.
330
+ * Stops when queue is closed and empty.
331
+ */
332
+ async *[Symbol.asyncIterator](): AsyncIterator<T> {
333
+ while (true) {
334
+ const next = this.takeNow();
335
+ if (next.found) {
336
+ yield next.element;
337
+ } else if (this._isClosed) {
338
+ break;
339
+ } else {
340
+ let element: T;
341
+ try {
342
+ element = await this.take();
343
+ } catch (error) {
344
+ // The queue was closed while the iterator waited
345
+ if (this._isClosed) break;
346
+ throw error;
347
+ }
348
+ yield element;
349
+ }
350
+ }
351
+ }
352
+
353
+ // ========================================================================
354
+ // Private helpers
355
+ // ========================================================================
356
+
357
+ /** When the buffer has space, the first waiting putter moves its element into it. */
358
+ private admitPutter(): void {
359
+ if (this.putters.length > 0 && this.buffer.length < this.capacity) {
360
+ const putter = this.putters.shift()!;
361
+ this.clearTimeout(putter);
362
+ this.buffer.push(putter.element);
363
+ putter.resolve();
364
+ }
365
+ }
366
+
367
+ private clearTimeout(resolver: Resolver<any>): void {
368
+ if (resolver.timeoutId) {
369
+ clearTimeout(resolver.timeoutId);
370
+ }
371
+ }
372
+
373
+ // ========================================================================
374
+ // Utility methods
375
+ // ========================================================================
376
+
377
+ /**
378
+ * Returns statistics about the queue.
379
+ */
380
+ getStats() : {
381
+ size: number;
382
+ capacity: number;
383
+ isEmpty: boolean;
384
+ isFull: boolean;
385
+ isClosed: boolean;
386
+ waitingPutters: number;
387
+ waitingTakers: number;
388
+ remainingCapacity: number;
389
+ } {
390
+ return {
391
+ size: this.size,
392
+ capacity: this.capacity,
393
+ isEmpty: this.isEmpty,
394
+ isFull: this.isFull,
395
+ isClosed: this._isClosed,
396
+ waitingPutters: this.putters.length,
397
+ waitingTakers: this.takers.length,
398
+ remainingCapacity: this.remainingCapacity,
399
+ };
400
+ }
401
+
402
+ toString(): string {
403
+ return `AsyncQueue[size=${this.size}, capacity=${this.capacity}, closed=${this._isClosed}]`;
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Factory function to create an AsyncQueue.
409
+ *
410
+ * @example
411
+ * const queue = asyncQueue<number>({ capacity: 100 })
412
+ * await queue.put(42)
413
+ * const value = await queue.take()
414
+ */
415
+ export function asyncQueue<T>(options?: AsyncQueueOptions): AsyncQueue<T> {
416
+ return new AsyncQueue<T>(options);
417
+ }