@tanstack/pacer 0.16.3 → 0.17.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 (169) hide show
  1. package/README.md +165 -0
  2. package/dist/async-batcher.cjs +355 -0
  3. package/dist/async-batcher.cjs.map +1 -0
  4. package/dist/async-batcher.d.cts +344 -0
  5. package/dist/async-batcher.d.ts +344 -0
  6. package/dist/async-batcher.js +353 -0
  7. package/dist/async-batcher.js.map +1 -0
  8. package/dist/async-debouncer.cjs +340 -0
  9. package/dist/async-debouncer.cjs.map +1 -0
  10. package/dist/async-debouncer.d.cts +300 -0
  11. package/dist/async-debouncer.d.ts +300 -0
  12. package/dist/async-debouncer.js +338 -0
  13. package/dist/async-debouncer.js.map +1 -0
  14. package/dist/async-queuer.cjs +496 -0
  15. package/dist/async-queuer.cjs.map +1 -0
  16. package/dist/async-queuer.d.cts +440 -0
  17. package/dist/async-queuer.d.ts +440 -0
  18. package/dist/async-queuer.js +494 -0
  19. package/dist/async-queuer.js.map +1 -0
  20. package/dist/async-rate-limiter.cjs +381 -0
  21. package/dist/async-rate-limiter.cjs.map +1 -0
  22. package/dist/{cjs/async-rate-limiter.d.cts → async-rate-limiter.d.cts} +190 -185
  23. package/dist/{esm/async-rate-limiter.d.ts → async-rate-limiter.d.ts} +190 -185
  24. package/dist/async-rate-limiter.js +379 -0
  25. package/dist/async-rate-limiter.js.map +1 -0
  26. package/dist/async-retryer.cjs +378 -0
  27. package/dist/async-retryer.cjs.map +1 -0
  28. package/dist/async-retryer.d.cts +312 -0
  29. package/dist/async-retryer.d.ts +312 -0
  30. package/dist/async-retryer.js +376 -0
  31. package/dist/async-retryer.js.map +1 -0
  32. package/dist/async-throttler.cjs +362 -0
  33. package/dist/async-throttler.cjs.map +1 -0
  34. package/dist/async-throttler.d.cts +320 -0
  35. package/dist/async-throttler.d.ts +320 -0
  36. package/dist/async-throttler.js +360 -0
  37. package/dist/async-throttler.js.map +1 -0
  38. package/dist/batcher.cjs +194 -0
  39. package/dist/batcher.cjs.map +1 -0
  40. package/dist/batcher.d.cts +180 -0
  41. package/dist/batcher.d.ts +180 -0
  42. package/dist/batcher.js +193 -0
  43. package/dist/batcher.js.map +1 -0
  44. package/dist/debouncer.cjs +197 -0
  45. package/dist/debouncer.cjs.map +1 -0
  46. package/dist/debouncer.d.cts +167 -0
  47. package/dist/debouncer.d.ts +167 -0
  48. package/dist/debouncer.js +195 -0
  49. package/dist/debouncer.js.map +1 -0
  50. package/dist/event-client.cjs +20 -0
  51. package/dist/event-client.cjs.map +1 -0
  52. package/dist/event-client.d.cts +49 -0
  53. package/dist/event-client.d.ts +49 -0
  54. package/dist/event-client.js +19 -0
  55. package/dist/event-client.js.map +1 -0
  56. package/dist/index.cjs +49 -0
  57. package/dist/index.d.cts +15 -0
  58. package/dist/index.d.ts +15 -0
  59. package/dist/{esm/index.js → index.js} +5 -41
  60. package/dist/queuer.cjs +393 -0
  61. package/dist/queuer.cjs.map +1 -0
  62. package/dist/queuer.d.cts +345 -0
  63. package/dist/queuer.d.ts +345 -0
  64. package/dist/queuer.js +391 -0
  65. package/dist/queuer.js.map +1 -0
  66. package/dist/rate-limiter.cjs +251 -0
  67. package/dist/rate-limiter.cjs.map +1 -0
  68. package/dist/{cjs/rate-limiter.d.cts → rate-limiter.d.cts} +113 -108
  69. package/dist/{esm/rate-limiter.d.ts → rate-limiter.d.ts} +113 -108
  70. package/dist/rate-limiter.js +249 -0
  71. package/dist/rate-limiter.js.map +1 -0
  72. package/dist/throttler.cjs +209 -0
  73. package/dist/throttler.cjs.map +1 -0
  74. package/dist/throttler.d.cts +207 -0
  75. package/dist/throttler.d.ts +207 -0
  76. package/dist/throttler.js +207 -0
  77. package/dist/throttler.js.map +1 -0
  78. package/dist/types.cjs +0 -0
  79. package/dist/types.d.cts +13 -0
  80. package/dist/types.d.ts +13 -0
  81. package/dist/types.js +1 -0
  82. package/dist/utils.cjs +13 -0
  83. package/dist/utils.cjs.map +1 -0
  84. package/dist/utils.d.cts +8 -0
  85. package/dist/utils.d.ts +8 -0
  86. package/dist/utils.js +11 -0
  87. package/dist/utils.js.map +1 -0
  88. package/package.json +39 -123
  89. package/dist/cjs/async-batcher.cjs +0 -222
  90. package/dist/cjs/async-batcher.cjs.map +0 -1
  91. package/dist/cjs/async-batcher.d.cts +0 -340
  92. package/dist/cjs/async-debouncer.cjs +0 -233
  93. package/dist/cjs/async-debouncer.cjs.map +0 -1
  94. package/dist/cjs/async-debouncer.d.cts +0 -295
  95. package/dist/cjs/async-queuer.cjs +0 -399
  96. package/dist/cjs/async-queuer.cjs.map +0 -1
  97. package/dist/cjs/async-queuer.d.cts +0 -435
  98. package/dist/cjs/async-rate-limiter.cjs +0 -254
  99. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  100. package/dist/cjs/async-retryer.cjs +0 -287
  101. package/dist/cjs/async-retryer.cjs.map +0 -1
  102. package/dist/cjs/async-retryer.d.cts +0 -308
  103. package/dist/cjs/async-throttler.cjs +0 -263
  104. package/dist/cjs/async-throttler.cjs.map +0 -1
  105. package/dist/cjs/async-throttler.d.cts +0 -315
  106. package/dist/cjs/batcher.cjs +0 -132
  107. package/dist/cjs/batcher.cjs.map +0 -1
  108. package/dist/cjs/batcher.d.cts +0 -176
  109. package/dist/cjs/debouncer.cjs +0 -139
  110. package/dist/cjs/debouncer.cjs.map +0 -1
  111. package/dist/cjs/debouncer.d.cts +0 -162
  112. package/dist/cjs/event-client.cjs +0 -20
  113. package/dist/cjs/event-client.cjs.map +0 -1
  114. package/dist/cjs/event-client.d.cts +0 -45
  115. package/dist/cjs/index.cjs +0 -51
  116. package/dist/cjs/index.cjs.map +0 -1
  117. package/dist/cjs/index.d.cts +0 -15
  118. package/dist/cjs/queuer.cjs +0 -308
  119. package/dist/cjs/queuer.cjs.map +0 -1
  120. package/dist/cjs/queuer.d.cts +0 -340
  121. package/dist/cjs/rate-limiter.cjs +0 -181
  122. package/dist/cjs/rate-limiter.cjs.map +0 -1
  123. package/dist/cjs/throttler.cjs +0 -153
  124. package/dist/cjs/throttler.cjs.map +0 -1
  125. package/dist/cjs/throttler.d.cts +0 -202
  126. package/dist/cjs/types.d.cts +0 -9
  127. package/dist/cjs/utils.cjs +0 -11
  128. package/dist/cjs/utils.cjs.map +0 -1
  129. package/dist/cjs/utils.d.cts +0 -3
  130. package/dist/esm/async-batcher.d.ts +0 -340
  131. package/dist/esm/async-batcher.js +0 -222
  132. package/dist/esm/async-batcher.js.map +0 -1
  133. package/dist/esm/async-debouncer.d.ts +0 -295
  134. package/dist/esm/async-debouncer.js +0 -233
  135. package/dist/esm/async-debouncer.js.map +0 -1
  136. package/dist/esm/async-queuer.d.ts +0 -435
  137. package/dist/esm/async-queuer.js +0 -399
  138. package/dist/esm/async-queuer.js.map +0 -1
  139. package/dist/esm/async-rate-limiter.js +0 -254
  140. package/dist/esm/async-rate-limiter.js.map +0 -1
  141. package/dist/esm/async-retryer.d.ts +0 -308
  142. package/dist/esm/async-retryer.js +0 -287
  143. package/dist/esm/async-retryer.js.map +0 -1
  144. package/dist/esm/async-throttler.d.ts +0 -315
  145. package/dist/esm/async-throttler.js +0 -263
  146. package/dist/esm/async-throttler.js.map +0 -1
  147. package/dist/esm/batcher.d.ts +0 -176
  148. package/dist/esm/batcher.js +0 -132
  149. package/dist/esm/batcher.js.map +0 -1
  150. package/dist/esm/debouncer.d.ts +0 -162
  151. package/dist/esm/debouncer.js +0 -139
  152. package/dist/esm/debouncer.js.map +0 -1
  153. package/dist/esm/event-client.d.ts +0 -45
  154. package/dist/esm/event-client.js +0 -20
  155. package/dist/esm/event-client.js.map +0 -1
  156. package/dist/esm/index.d.ts +0 -15
  157. package/dist/esm/index.js.map +0 -1
  158. package/dist/esm/queuer.d.ts +0 -340
  159. package/dist/esm/queuer.js +0 -308
  160. package/dist/esm/queuer.js.map +0 -1
  161. package/dist/esm/rate-limiter.js +0 -181
  162. package/dist/esm/rate-limiter.js.map +0 -1
  163. package/dist/esm/throttler.d.ts +0 -202
  164. package/dist/esm/throttler.js +0 -153
  165. package/dist/esm/throttler.js.map +0 -1
  166. package/dist/esm/types.d.ts +0 -9
  167. package/dist/esm/utils.d.ts +0 -3
  168. package/dist/esm/utils.js +0 -11
  169. package/dist/esm/utils.js.map +0 -1
@@ -0,0 +1,494 @@
1
+ import { parseFunctionOrValue } from "./utils.js";
2
+ import { emitChange, pacerEventClient } from "./event-client.js";
3
+ import { AsyncRetryer } from "./async-retryer.js";
4
+ import { Store } from "@tanstack/store";
5
+
6
+ //#region src/async-queuer.ts
7
+ function getDefaultAsyncQueuerState() {
8
+ return {
9
+ activeItems: [],
10
+ addItemCount: 0,
11
+ errorCount: 0,
12
+ executeCount: 0,
13
+ expirationCount: 0,
14
+ isEmpty: true,
15
+ isExecuting: false,
16
+ isFull: false,
17
+ isIdle: true,
18
+ isRunning: true,
19
+ itemTimestamps: [],
20
+ items: [],
21
+ lastResult: null,
22
+ pendingTick: false,
23
+ rejectionCount: 0,
24
+ settledCount: 0,
25
+ size: 0,
26
+ status: "idle",
27
+ successCount: 0
28
+ };
29
+ }
30
+ /**
31
+ * Utility function for sharing common `AsyncQueuerOptions` options between different `AsyncQueuer` instances.
32
+ */
33
+ function asyncQueuerOptions(options) {
34
+ return options;
35
+ }
36
+ const defaultOptions = {
37
+ addItemsTo: "back",
38
+ asyncRetryerOptions: { maxAttempts: 1 },
39
+ concurrency: 1,
40
+ expirationDuration: Infinity,
41
+ getIsExpired: () => false,
42
+ getItemsFrom: "front",
43
+ getPriority: (item) => item?.priority ?? 0,
44
+ initialItems: [],
45
+ maxSize: Infinity,
46
+ started: true,
47
+ wait: 0
48
+ };
49
+ /**
50
+ * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.
51
+ *
52
+ * Async vs Sync Versions:
53
+ * The async version provides advanced features over the sync Queuer:
54
+ * - Returns promises that can be awaited for task results
55
+ * - Built-in retry support via AsyncRetryer integration for each queued task
56
+ * - Abort support to cancel in-flight task executions
57
+ * - Comprehensive error handling with onError callbacks and throwOnError control
58
+ * - Detailed execution tracking (success/error/settle counts)
59
+ * - Concurrent execution support (process multiple items simultaneously)
60
+ *
61
+ * The sync Queuer is lighter weight and simpler when you don't need async features,
62
+ * return values, or execution control.
63
+ *
64
+ * What is Queuing?
65
+ * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
66
+ * Tasks are processed up to the configured concurrency limit. When a task completes,
67
+ * the next pending task is processed if the concurrency limit allows.
68
+ *
69
+ * Key Features:
70
+ * - Priority queue support via the getPriority option
71
+ * - Configurable concurrency limit
72
+ * - Callbacks for task success, error, completion, and queue state changes
73
+ * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
74
+ * - Pause and resume processing
75
+ * - Item expiration to remove stale items from the queue
76
+ *
77
+ * Error Handling:
78
+ * - If an `onError` handler is provided, it will be called with the error and queuer instance
79
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
80
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
81
+ * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
82
+ * - The error state can be checked using the AsyncQueuer instance
83
+ *
84
+ * State Management:
85
+ * - Uses TanStack Store for reactive state management
86
+ * - Use `initialState` to provide initial state values when creating the async queuer
87
+ * - Use `onSuccess` callback to react to successful task execution and implement custom logic
88
+ * - Use `onError` callback to react to task execution errors and implement custom error handling
89
+ * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
90
+ * - Use `onItemsChange` callback to react to items being added or removed from the queue
91
+ * - Use `onExpire` callback to react to items expiring and implement custom logic
92
+ * - Use `onReject` callback to react to items being rejected when the queue is full
93
+ * - The state includes error count, expiration count, rejection count, running status, and success/settle counts
94
+ * - State can be accessed via `asyncQueuer.store.state` when using the class directly
95
+ * - When using framework adapters (React/Solid), state is accessed from `asyncQueuer.state`
96
+ *
97
+ * Example usage:
98
+ * ```ts
99
+ * const asyncQueuer = new AsyncQueuer<string>(async (item) => {
100
+ * // process item
101
+ * return item.toUpperCase();
102
+ * }, {
103
+ * concurrency: 2,
104
+ * onSuccess: (result) => {
105
+ * console.log(result);
106
+ * }
107
+ * });
108
+ *
109
+ * asyncQueuer.addItem('hello');
110
+ * asyncQueuer.start();
111
+ * ```
112
+ */
113
+ var AsyncQueuer = class {
114
+ #timeoutIds = /* @__PURE__ */ new Set();
115
+ constructor(fn, initialOptions = {}) {
116
+ this.fn = fn;
117
+ this.store = new Store(getDefaultAsyncQueuerState());
118
+ this.asyncRetryers = /* @__PURE__ */ new Map();
119
+ this.setOptions = (newOptions) => {
120
+ this.options = {
121
+ ...this.options,
122
+ ...newOptions
123
+ };
124
+ };
125
+ this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
126
+ this.#setState({ addItemCount: this.store.state.addItemCount + 1 });
127
+ if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
128
+ this.#setState({ rejectionCount: this.store.state.rejectionCount + 1 });
129
+ this.options.onReject?.(item, this);
130
+ return false;
131
+ }
132
+ const priority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(item) : item.priority;
133
+ const items = this.store.state.items;
134
+ const itemTimestamps = this.store.state.itemTimestamps;
135
+ if (priority !== void 0) {
136
+ const insertIndex = items.findIndex((existing) => {
137
+ return (this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(existing) : existing.priority) < priority;
138
+ });
139
+ if (insertIndex === -1) {
140
+ items.push(item);
141
+ itemTimestamps.push(Date.now());
142
+ } else {
143
+ items.splice(insertIndex, 0, item);
144
+ itemTimestamps.splice(insertIndex, 0, Date.now());
145
+ }
146
+ } else if (position === "front") {
147
+ items.unshift(item);
148
+ itemTimestamps.unshift(Date.now());
149
+ } else {
150
+ items.push(item);
151
+ itemTimestamps.push(Date.now());
152
+ }
153
+ this.#setState({
154
+ items,
155
+ itemTimestamps
156
+ });
157
+ if (runOnItemsChange) this.options.onItemsChange?.(this);
158
+ if (this.store.state.isRunning && !this.store.state.pendingTick) this.#tick();
159
+ return true;
160
+ };
161
+ this.getNextItem = (position = this.options.getItemsFrom ?? "front") => {
162
+ const { items, itemTimestamps } = this.store.state;
163
+ let item;
164
+ if (this.options.getPriority !== defaultOptions.getPriority || position === "front") {
165
+ item = items[0];
166
+ if (item !== void 0) this.#setState({
167
+ items: items.slice(1),
168
+ itemTimestamps: itemTimestamps.slice(1)
169
+ });
170
+ } else {
171
+ item = items[items.length - 1];
172
+ if (item !== void 0) this.#setState({
173
+ items: items.slice(0, -1),
174
+ itemTimestamps: itemTimestamps.slice(0, -1)
175
+ });
176
+ }
177
+ if (item !== void 0) this.options.onItemsChange?.(this);
178
+ return item;
179
+ };
180
+ this.execute = async (position) => {
181
+ const item = this.getNextItem(position);
182
+ if (item !== void 0) {
183
+ const currentExecuteCount = this.store.state.executeCount + 1;
184
+ this.#setState({
185
+ executeCount: currentExecuteCount,
186
+ isExecuting: true
187
+ });
188
+ try {
189
+ const currentAsyncRetryer = new AsyncRetryer(this.fn, {
190
+ ...this.options.asyncRetryerOptions,
191
+ key: `${this.key}-retryer-${currentExecuteCount}`
192
+ });
193
+ this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer);
194
+ const lastResult = await currentAsyncRetryer.execute(item);
195
+ this.#setState({
196
+ successCount: this.store.state.successCount + 1,
197
+ lastResult
198
+ });
199
+ this.options.onSuccess?.(lastResult, item, this);
200
+ } catch (error) {
201
+ this.#setState({ errorCount: this.store.state.errorCount + 1 });
202
+ this.options.onError?.(error, item, this);
203
+ if (this.options.throwOnError) throw error;
204
+ } finally {
205
+ this.asyncRetryers.delete(currentExecuteCount);
206
+ this.#setState({
207
+ activeItems: this.store.state.activeItems.filter((activeItem) => activeItem !== item),
208
+ isExecuting: false,
209
+ settledCount: this.store.state.settledCount + 1
210
+ });
211
+ this.options.onSettled?.(item, this);
212
+ }
213
+ }
214
+ return item;
215
+ };
216
+ this.flush = async (numberOfItems = this.store.state.items.length, position) => {
217
+ this.#clearTimeouts();
218
+ await Promise.all(Array.from({ length: numberOfItems }, () => this.execute(position)));
219
+ };
220
+ this.flushAsBatch = async (batchFunction) => {
221
+ this.#clearTimeouts();
222
+ await batchFunction(this.#getAllItems());
223
+ };
224
+ this.peekNextItem = (position = "front") => {
225
+ if (position === "front") return this.store.state.items[0];
226
+ return this.store.state.items[this.store.state.items.length - 1];
227
+ };
228
+ this.peekAllItems = () => {
229
+ return [...this.peekActiveItems(), ...this.peekPendingItems()];
230
+ };
231
+ this.peekActiveItems = () => {
232
+ return [...this.store.state.activeItems];
233
+ };
234
+ this.peekPendingItems = () => {
235
+ return [...this.store.state.items];
236
+ };
237
+ this.start = () => {
238
+ this.#setState({ isRunning: true });
239
+ if (!this.store.state.pendingTick && this.store.state.items.length > 0) this.#tick();
240
+ };
241
+ this.stop = () => {
242
+ this.#clearTimeouts();
243
+ this.#setState({
244
+ isRunning: false,
245
+ pendingTick: false
246
+ });
247
+ };
248
+ this.clear = () => {
249
+ this.#setState({
250
+ items: [],
251
+ itemTimestamps: []
252
+ });
253
+ this.options.onItemsChange?.(this);
254
+ };
255
+ this.abort = () => {
256
+ this.asyncRetryers.forEach((retryer) => retryer.abort());
257
+ this.asyncRetryers.clear();
258
+ this.#setState({ isExecuting: false });
259
+ };
260
+ this.reset = () => {
261
+ this.#setState(getDefaultAsyncQueuerState());
262
+ this.options.onItemsChange?.(this);
263
+ this.asyncRetryers.forEach((retryer) => retryer.reset());
264
+ };
265
+ this.key = initialOptions.key;
266
+ this.options = {
267
+ ...defaultOptions,
268
+ ...initialOptions,
269
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
270
+ };
271
+ const isInitiallyRunning = this.options.initialState?.isRunning ?? this.options.started ?? true;
272
+ this.#setState({
273
+ ...this.options.initialState,
274
+ isRunning: isInitiallyRunning
275
+ });
276
+ if (this.options.initialState?.items) {
277
+ if (this.store.state.isRunning) this.#tick();
278
+ } else for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {
279
+ const item = this.options.initialItems[i];
280
+ const isLast = i === (this.options.initialItems?.length ?? 0) - 1;
281
+ this.addItem(item, this.options.addItemsTo ?? "back", isLast);
282
+ }
283
+ if (this.key) pacerEventClient.on("d-AsyncQueuer", (e) => {
284
+ if (e.payload.key !== this.key) return;
285
+ this.#setState(e.payload.store.state);
286
+ this.setOptions(e.payload.options);
287
+ });
288
+ }
289
+ #setState = (newState) => {
290
+ this.store.setState((state) => {
291
+ const combinedState = {
292
+ ...state,
293
+ ...newState
294
+ };
295
+ const { activeItems, items, isRunning } = combinedState;
296
+ const size = items.length;
297
+ const isFull = size >= (this.options.maxSize ?? Infinity);
298
+ const isEmpty = size === 0;
299
+ const isIdle = isRunning && isEmpty && activeItems.length === 0;
300
+ const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
301
+ return {
302
+ ...combinedState,
303
+ isEmpty,
304
+ isFull,
305
+ isIdle,
306
+ size,
307
+ status
308
+ };
309
+ });
310
+ emitChange("AsyncQueuer", this);
311
+ };
312
+ /**
313
+ * Returns the current wait time (in milliseconds) between processing items.
314
+ * If a function is provided, it is called with the queuer instance.
315
+ */
316
+ #getWait = () => {
317
+ return parseFunctionOrValue(this.options.wait ?? 0, this);
318
+ };
319
+ /**
320
+ * Returns the current concurrency limit for processing items.
321
+ * If a function is provided, it is called with the queuer instance.
322
+ */
323
+ #getConcurrency = () => {
324
+ return parseFunctionOrValue(this.options.concurrency ?? 1, this);
325
+ };
326
+ /**
327
+ * Processes items in the queue up to the concurrency limit. Internal use only.
328
+ */
329
+ #tick = () => {
330
+ if (!this.store.state.isRunning) {
331
+ this.#setState({ pendingTick: false });
332
+ return;
333
+ }
334
+ this.#setState({ pendingTick: true });
335
+ this.#checkExpiredItems();
336
+ const activeItems = this.store.state.activeItems;
337
+ while (activeItems.length < this.#getConcurrency() && this.store.state.items.length > 0) {
338
+ const nextItem = this.peekNextItem();
339
+ if (!nextItem) break;
340
+ activeItems.push(nextItem);
341
+ this.#setState({ activeItems });
342
+ (async () => {
343
+ const result = await this.execute();
344
+ this.#setState({ lastResult: result });
345
+ const wait = this.#getWait();
346
+ if (wait > 0) {
347
+ const timeoutId = setTimeout(() => this.#tick(), wait);
348
+ this.#timeoutIds.add(timeoutId);
349
+ return;
350
+ }
351
+ this.#tick();
352
+ })();
353
+ }
354
+ this.#setState({ pendingTick: false });
355
+ };
356
+ #getAllItems = () => {
357
+ const items = this.peekAllItems();
358
+ this.clear();
359
+ return items;
360
+ };
361
+ /**
362
+ * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
363
+ * Internal use only.
364
+ */
365
+ #checkExpiredItems = () => {
366
+ if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
367
+ const now = Date.now();
368
+ const expiredIndices = [];
369
+ for (let i = 0; i < this.store.state.items.length; i++) {
370
+ const timestamp = this.store.state.itemTimestamps[i];
371
+ if (timestamp === void 0) continue;
372
+ const item = this.store.state.items[i];
373
+ if (item === void 0) continue;
374
+ if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
375
+ }
376
+ for (let i = expiredIndices.length - 1; i >= 0; i--) {
377
+ const index = expiredIndices[i];
378
+ if (index === void 0) continue;
379
+ const expiredItem = this.store.state.items[index];
380
+ if (expiredItem === void 0) continue;
381
+ const newItems = [...this.store.state.items];
382
+ const newTimestamps = [...this.store.state.itemTimestamps];
383
+ newItems.splice(index, 1);
384
+ newTimestamps.splice(index, 1);
385
+ this.#setState({
386
+ items: newItems,
387
+ itemTimestamps: newTimestamps,
388
+ expirationCount: this.store.state.expirationCount + 1
389
+ });
390
+ this.options.onExpire?.(expiredItem, this);
391
+ }
392
+ if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
393
+ };
394
+ #clearTimeouts = () => {
395
+ this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
396
+ this.#timeoutIds.clear();
397
+ };
398
+ /**
399
+ * Returns the AbortSignal for a specific execution.
400
+ * If no executeCount is provided, returns the signal for the most recent execution.
401
+ * Returns null if no execution is found or not currently executing.
402
+ *
403
+ * @param executeCount - Optional specific execution to get signal for
404
+ * @example
405
+ * ```typescript
406
+ * const queuer = new AsyncQueuer(
407
+ * async (item: string) => {
408
+ * const signal = queuer.getAbortSignal()
409
+ * if (signal) {
410
+ * const response = await fetch(`/api/process/${item}`, { signal })
411
+ * return response.json()
412
+ * }
413
+ * },
414
+ * { concurrency: 2 }
415
+ * )
416
+ * ```
417
+ */
418
+ getAbortSignal(executeCount) {
419
+ const count = executeCount ?? this.store.state.executeCount;
420
+ return this.asyncRetryers.get(count)?.getAbortSignal() ?? null;
421
+ }
422
+ };
423
+ /**
424
+ * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.
425
+ * The queuer is started automatically and ready to process items.
426
+ *
427
+ * Async vs Sync Versions:
428
+ * The async version provides advanced features over the sync queue function:
429
+ * - Returns promises that can be awaited for task results
430
+ * - Built-in retry support via AsyncRetryer integration for each queued task
431
+ * - Abort support to cancel in-flight task executions
432
+ * - Comprehensive error handling with onError callbacks and throwOnError control
433
+ * - Detailed execution tracking (success/error/settle counts)
434
+ * - Concurrent execution support (process multiple items simultaneously)
435
+ *
436
+ * The sync queue function is lighter weight and simpler when you don't need async features,
437
+ * return values, or execution control.
438
+ *
439
+ * What is Queuing?
440
+ * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
441
+ * Tasks are processed up to the configured concurrency limit. When a task completes,
442
+ * the next pending task is processed if the concurrency limit allows.
443
+ *
444
+ * Configuration Options:
445
+ * - `concurrency`: Maximum number of concurrent tasks (default: 1)
446
+ * - `wait`: Time to wait between processing items (default: 0)
447
+ * - `maxSize`: Maximum number of items allowed in the queue (default: Infinity)
448
+ * - `getPriority`: Function to determine item priority
449
+ * - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')
450
+ * - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')
451
+ * - `expirationDuration`: Maximum time items can stay in queue
452
+ * - `started`: Whether to start processing immediately (default: true)
453
+ * - `asyncRetryerOptions`: Configure retry behavior for task executions
454
+ *
455
+ * Error Handling:
456
+ * - If an `onError` handler is provided, it will be called with the error and queuer instance
457
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
458
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
459
+ * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
460
+ * - The error state can be checked using the underlying AsyncQueuer instance
461
+ *
462
+ * State Management:
463
+ * - Uses TanStack Store for reactive state management
464
+ * - Use `initialState` to provide initial state values when creating the async queuer
465
+ * - Use `onSuccess` callback to react to successful task execution and implement custom logic
466
+ * - Use `onError` callback to react to task execution errors and implement custom error handling
467
+ * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
468
+ * - Use `onItemsChange` callback to react to items being added or removed from the queue
469
+ * - Use `onExpire` callback to react to items expiring and implement custom logic
470
+ * - Use `onReject` callback to react to items being rejected when the queue is full
471
+ * - The state includes error count, expiration count, rejection count, running status, and success/settle counts
472
+ * - State can be accessed via the underlying AsyncQueuer instance's `store.state` property
473
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
474
+ *
475
+ * @example
476
+ * ```ts
477
+ * const enqueue = asyncQueue<string>(async (item) => {
478
+ * return item.toUpperCase();
479
+ * }, {
480
+ * concurrency: 2,
481
+ * wait: 100,
482
+ * onSuccess: (result) => console.log('Processed:', result)
483
+ * });
484
+ *
485
+ * enqueue('hello');
486
+ * ```
487
+ */
488
+ function asyncQueue(fn, initialOptions) {
489
+ return new AsyncQueuer(fn, initialOptions).addItem;
490
+ }
491
+
492
+ //#endregion
493
+ export { AsyncQueuer, asyncQueue, asyncQueuerOptions };
494
+ //# sourceMappingURL=async-queuer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-queuer.js","names":["defaultOptions: AsyncQueuerOptionsWithOptionalCallbacks","fn: (item: TValue) => Promise<any>","#setState","#tick","item: TValue | undefined","#clearTimeouts","#getAllItems","#checkExpiredItems","#getConcurrency","#getWait","#timeoutIds","expiredIndices: Array<number>"],"sources":["../src/async-queuer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { AsyncRetryer } from './async-retryer'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AsyncRetryerOptions } from './async-retryer'\nimport type { OptionalKeys } from './types'\nimport type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerState<TValue> {\n /**\n * Items currently being processed by the queuer\n */\n activeItems: Array<TValue>\n /**\n * Number of times addItem has been called (for reduction calculations)\n */\n addItemCount: number\n /**\n * Number of task executions that have resulted in errors\n */\n errorCount: number\n /**\n * Number of times execute has been called\n */\n executeCount: number\n /**\n * Number of items that have been removed from the queue due to expiration\n */\n expirationCount: number\n /**\n * Whether the queuer has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the queuer is currently executing\n */\n isExecuting: boolean\n /**\n * Whether the queuer has reached its maximum capacity\n */\n isFull: boolean\n /**\n * Whether the queuer is not currently processing any items\n */\n isIdle: boolean\n /**\n * Whether the queuer is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Array of items currently waiting to be processed\n */\n items: Array<TValue>\n /**\n * Timestamps when items were added to the queue for expiration tracking\n */\n itemTimestamps: Array<number>\n /**\n * The result from the most recent task execution\n */\n lastResult: any\n /**\n * Whether the queuer has a pending timeout for processing the next item\n */\n pendingTick: boolean\n /**\n * Number of items that have been rejected from being added to the queue\n */\n rejectionCount: number\n /**\n * Number of task executions that have completed (either successfully or with errors)\n */\n settledCount: number\n /**\n * Number of items currently in the queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused\n */\n status: 'idle' | 'running' | 'stopped'\n /**\n * Number of task executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncQueuerState<TValue>(): AsyncQueuerState<TValue> {\n return {\n activeItems: [],\n addItemCount: 0,\n errorCount: 0,\n executeCount: 0,\n expirationCount: 0,\n isEmpty: true,\n isExecuting: false,\n isFull: false,\n isIdle: true,\n isRunning: true,\n itemTimestamps: [],\n items: [],\n lastResult: null,\n pendingTick: false,\n rejectionCount: 0,\n settledCount: 0,\n size: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\nexport interface AsyncQueuerOptions<TValue> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<(item: TValue) => Promise<any>>\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum number of concurrent tasks to process.\n * Can be a number or a function that returns a number.\n * @default 1\n */\n concurrency?: number | ((queuer: AsyncQueuer<TValue>) => number)\n /**\n * Maximum time in milliseconds that an item can stay in the queue\n * If not provided, items will never expire\n */\n expirationDuration?: number\n /**\n * Function to determine if an item has expired\n * If provided, this overrides the expirationDuration behavior\n */\n getIsExpired?: (item: TValue, addedAt: number) => boolean\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n * If not provided, will use static priority values attached to tasks\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Initial state for the async queuer\n */\n initialState?: Partial<AsyncQueuerState<TValue>>\n /**\n * Optional key to identify this async queuer instance.\n * If provided, the async queuer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Optional error handler for when a task throws.\n * If provided, the handler will be called with the error and queuer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: Error, item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task is settled\n */\n onSettled?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task succeeds\n */\n onSuccess?: (result: any, item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately or not.\n */\n started?: boolean\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Time in milliseconds to wait between processing items.\n * Can be a number or a function that returns a number.\n * @default 0\n */\n wait?: number | ((queuer: AsyncQueuer<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncQueuerOptions` options between different `AsyncQueuer` instances.\n */\nexport function asyncQueuerOptions<\n TValue = any,\n TOptions extends Partial<AsyncQueuerOptions<TValue>> = Partial<\n AsyncQueuerOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncQueuerOptionsWithOptionalCallbacks = OptionalKeys<\n Required<AsyncQueuerOptions<any>>,\n | 'initialState'\n | 'throwOnError'\n | 'onSuccess'\n | 'onSettled'\n | 'onReject'\n | 'onItemsChange'\n | 'onExpire'\n | 'onError'\n | 'key'\n>\n\nconst defaultOptions: AsyncQueuerOptionsWithOptionalCallbacks = {\n addItemsTo: 'back',\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n concurrency: 1,\n expirationDuration: Infinity,\n getIsExpired: () => false,\n getItemsFrom: 'front',\n getPriority: (item: any) => item?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n started: true,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Queuer:\n * - Returns promises that can be awaited for task results\n * - Built-in retry support via AsyncRetryer integration for each queued task\n * - Abort support to cancel in-flight task executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Concurrent execution support (process multiple items simultaneously)\n *\n * The sync Queuer is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Queuing?\n * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.\n * Tasks are processed up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Key Features:\n * - Priority queue support via the getPriority option\n * - Configurable concurrency limit\n * - Callbacks for task success, error, completion, and queue state changes\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause and resume processing\n * - Item expiration to remove stale items from the queue\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown\n * - The error state can be checked using the AsyncQueuer instance\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async queuer\n * - Use `onSuccess` callback to react to successful task execution and implement custom logic\n * - Use `onError` callback to react to task execution errors and implement custom error handling\n * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes error count, expiration count, rejection count, running status, and success/settle counts\n * - State can be accessed via `asyncQueuer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncQueuer.state`\n *\n * Example usage:\n * ```ts\n * const asyncQueuer = new AsyncQueuer<string>(async (item) => {\n * // process item\n * return item.toUpperCase();\n * }, {\n * concurrency: 2,\n * onSuccess: (result) => {\n * console.log(result);\n * }\n * });\n *\n * asyncQueuer.addItem('hello');\n * asyncQueuer.start();\n * ```\n */\nexport class AsyncQueuer<TValue> {\n readonly store: Store<Readonly<AsyncQueuerState<TValue>>> = new Store<\n AsyncQueuerState<TValue>\n >(getDefaultAsyncQueuerState<TValue>())\n key: string | undefined\n options: AsyncQueuerOptions<TValue>\n asyncRetryers = new Map<\n number,\n AsyncRetryer<(item: TValue) => Promise<any>>\n >()\n #timeoutIds: Set<NodeJS.Timeout> = new Set()\n\n constructor(\n public fn: (item: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue> = {},\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n const isInitiallyRunning =\n this.options.initialState?.isRunning ?? this.options.started ?? true\n this.#setState({\n ...this.options.initialState,\n isRunning: isInitiallyRunning,\n })\n\n if (this.options.initialState?.items) {\n if (this.store.state.isRunning) {\n this.#tick()\n }\n } else {\n for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {\n const item = this.options.initialItems![i]!\n const isLast = i === (this.options.initialItems?.length ?? 0) - 1\n this.addItem(item, this.options.addItemsTo ?? 'back', isLast)\n }\n }\n\n if (this.key) {\n pacerEventClient.on('d-AsyncQueuer', (e) => {\n if (e.payload.key !== this.key) return\n this.#setState(e.payload.store.state)\n this.setOptions(e.payload.options)\n })\n }\n }\n\n /**\n * Updates the queuer options. New options are merged with existing options.\n */\n setOptions = (newOptions: Partial<AsyncQueuerOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncQueuerState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n\n const { activeItems, items, isRunning } = combinedState\n\n const size = items.length\n const isFull = size >= (this.options.maxSize ?? Infinity)\n const isEmpty = size === 0\n const isIdle = isRunning && isEmpty && activeItems.length === 0\n\n const status = isIdle ? 'idle' : isRunning ? 'running' : 'stopped'\n\n return {\n ...combinedState,\n isEmpty,\n isFull,\n isIdle,\n size,\n status,\n }\n })\n emitChange('AsyncQueuer', this)\n }\n\n /**\n * Returns the current wait time (in milliseconds) between processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait ?? 0, this)\n }\n\n /**\n * Returns the current concurrency limit for processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getConcurrency = (): number => {\n return parseFunctionOrValue(this.options.concurrency ?? 1, this)\n }\n\n /**\n * Processes items in the queue up to the concurrency limit. Internal use only.\n */\n #tick = () => {\n if (!this.store.state.isRunning) {\n this.#setState({ pendingTick: false })\n return\n }\n this.#setState({ pendingTick: true })\n\n // Check for expired items\n this.#checkExpiredItems()\n\n // Process items concurrently up to the concurrency limit\n const activeItems = this.store.state.activeItems\n while (\n activeItems.length < this.#getConcurrency() &&\n this.store.state.items.length > 0\n ) {\n const nextItem = this.peekNextItem()\n if (!nextItem) {\n break\n }\n activeItems.push(nextItem)\n this.#setState({\n activeItems,\n })\n ;(async () => {\n const result = await this.execute()\n this.#setState({ lastResult: result })\n\n const wait = this.#getWait()\n if (wait > 0) {\n const timeoutId = setTimeout(() => this.#tick(), wait)\n this.#timeoutIds.add(timeoutId)\n return\n }\n\n this.#tick()\n })()\n }\n\n this.#setState({ pendingTick: false })\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.\n * Items can be inserted based on priority or at the front/back depending on configuration.\n *\n * @example\n * ```ts\n * queuer.addItem({ value: 'task', priority: 10 });\n * queuer.addItem('task2', 'front');\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo ?? 'back',\n runOnItemsChange: boolean = true,\n ): boolean => {\n this.#setState({\n addItemCount: this.store.state.addItemCount + 1,\n })\n\n if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n // Get priority either from the function or from getPriority option\n const priority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(item)\n : (item as any).priority\n\n const items = this.store.state.items\n const itemTimestamps = this.store.state.itemTimestamps\n\n if (priority !== undefined) {\n // Insert based on priority - higher priority items go to front\n const insertIndex = items.findIndex((existing) => {\n const existingPriority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(existing)\n : (existing as any).priority\n return existingPriority < priority\n })\n\n if (insertIndex === -1) {\n items.push(item)\n itemTimestamps.push(Date.now())\n } else {\n items.splice(insertIndex, 0, item)\n itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n if (position === 'front') {\n // Default FIFO/LIFO behavior\n items.unshift(item)\n itemTimestamps.unshift(Date.now())\n } else {\n // LIFO\n items.push(item)\n itemTimestamps.push(Date.now())\n }\n }\n\n this.#setState({\n items,\n itemTimestamps,\n })\n\n if (runOnItemsChange) {\n this.options.onItemsChange?.(this)\n }\n\n if (this.store.state.isRunning && !this.store.state.pendingTick) {\n this.#tick()\n }\n\n return true\n }\n\n /**\n * Removes and returns the next item from the queue without executing the task function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * @example\n * ```ts\n * // FIFO\n * queuer.getNextItem();\n * // LIFO\n * queuer.getNextItem('back');\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom ?? 'front',\n ): TValue | undefined => {\n const { items, itemTimestamps } = this.store.state\n let item: TValue | undefined\n\n // When priority function is provided or position is 'front', always get from front (highest priority)\n // Priority takes precedence over FIFO/LIFO behavior\n if (\n this.options.getPriority !== defaultOptions.getPriority ||\n position === 'front'\n ) {\n item = items[0]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(1),\n itemTimestamps: itemTimestamps.slice(1),\n })\n }\n } else {\n item = items[items.length - 1]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(0, -1),\n itemTimestamps: itemTimestamps.slice(0, -1),\n })\n }\n }\n\n if (item !== undefined) {\n this.options.onItemsChange?.(this)\n }\n\n return item\n }\n\n #getAllItems = (): Array<TValue> => {\n const items = this.peekAllItems()\n this.clear()\n return items\n }\n\n /**\n * Removes and returns the next item from the queue and executes the task function with it.\n *\n * @example\n * ```ts\n * queuer.execute();\n * // LIFO\n * queuer.execute('back');\n * ```\n */\n execute = async (position?: QueuePosition): Promise<any> => {\n const item = this.getNextItem(position)\n\n if (item !== undefined) {\n const currentExecuteCount = this.store.state.executeCount + 1\n this.#setState({\n executeCount: currentExecuteCount,\n isExecuting: true,\n })\n try {\n const currentAsyncRetryer = new AsyncRetryer(this.fn, {\n ...this.options.asyncRetryerOptions,\n key: `${this.key}-retryer-${currentExecuteCount}`,\n })\n this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer)\n const lastResult = await currentAsyncRetryer.execute(item) // EXECUTE!\n this.#setState({\n successCount: this.store.state.successCount + 1,\n lastResult,\n })\n this.options.onSuccess?.(lastResult, item, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, item, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentExecuteCount) // dispose retryer\n this.#setState({\n activeItems: this.store.state.activeItems.filter(\n (activeItem) => activeItem !== item,\n ),\n isExecuting: false,\n settledCount: this.store.state.settledCount + 1,\n })\n this.options.onSettled?.(item, this)\n }\n }\n return item\n }\n\n /**\n * Processes a specified number of items to execute immediately with no wait time\n * If no numberOfItems is provided, all items will be processed\n */\n flush = async (\n numberOfItems: number = this.store.state.items.length,\n position?: QueuePosition,\n ): Promise<void> => {\n this.#clearTimeouts() // clear any pending timeouts\n await Promise.all(\n Array.from({ length: numberOfItems }, () => this.execute(position)),\n )\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function as an argument\n * The queue is cleared after processing\n */\n flushAsBatch = async (\n batchFunction: (items: Array<TValue>) => Promise<any>,\n ): Promise<void> => {\n this.#clearTimeouts() // clear any pending timeouts\n const items = this.#getAllItems()\n await batchFunction(items)\n }\n\n /**\n * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.\n * Internal use only.\n */\n #checkExpiredItems = (): void => {\n if (\n (this.options.expirationDuration ?? Infinity) === Infinity &&\n this.options.getIsExpired === defaultOptions.getIsExpired\n ) {\n return\n }\n\n const now = Date.now()\n const expiredIndices: Array<number> = []\n\n // Find indices of expired items\n for (let i = 0; i < this.store.state.items.length; i++) {\n const timestamp = this.store.state.itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this.store.state.items[i]\n if (item === undefined) continue\n\n const isExpired =\n this.options.getIsExpired !== defaultOptions.getIsExpired\n ? this.options.getIsExpired!(item, timestamp)\n : now - timestamp > (this.options.expirationDuration ?? Infinity)\n\n if (isExpired) {\n expiredIndices.push(i)\n }\n }\n\n // Remove expired items from back to front to maintain indices\n for (let i = expiredIndices.length - 1; i >= 0; i--) {\n const index = expiredIndices[i]\n if (index === undefined) continue\n\n const expiredItem = this.store.state.items[index]\n if (expiredItem === undefined) continue\n\n const newItems = [...this.store.state.items]\n const newTimestamps = [...this.store.state.itemTimestamps]\n newItems.splice(index, 1)\n newTimestamps.splice(index, 1)\n this.#setState({\n items: newItems,\n itemTimestamps: newTimestamps,\n expirationCount: this.store.state.expirationCount + 1,\n })\n this.options.onExpire?.(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this.options.onItemsChange?.(this)\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * @example\n * ```ts\n * queuer.peekNextItem(); // front\n * queuer.peekNextItem('back'); // back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (position === 'front') {\n return this.store.state.items[0]\n }\n return this.store.state.items[this.store.state.items.length - 1]\n }\n\n /**\n * Returns a copy of all items in the queue, including active and pending items.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.peekActiveItems(), ...this.peekPendingItems()]\n }\n\n /**\n * Returns the items currently being processed (active tasks).\n */\n peekActiveItems = (): Array<TValue> => {\n return [...this.store.state.activeItems]\n }\n\n /**\n * Returns the items waiting to be processed (pending tasks).\n */\n peekPendingItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start = (): void => {\n this.#setState({ isRunning: true })\n if (!this.store.state.pendingTick && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = (): void => {\n this.#clearTimeouts()\n this.#setState({ isRunning: false, pendingTick: false })\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n /**\n * Removes all pending items from the queue.\n * Does NOT affect active tasks.\n */\n clear = (): void => {\n this.#setState({ items: [], itemTimestamps: [] })\n this.options.onItemsChange?.(this)\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no executeCount is provided, returns the signal for the most recent execution.\n * Returns null if no execution is found or not currently executing.\n *\n * @param executeCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const queuer = new AsyncQueuer(\n * async (item: string) => {\n * const signal = queuer.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/process/${item}`, { signal })\n * return response.json()\n * }\n * },\n * { concurrency: 2 }\n * )\n * ```\n */\n getAbortSignal(executeCount?: number): AbortSignal | null {\n const count = executeCount ?? this.store.state.executeCount\n const retryer = this.asyncRetryers.get(count)\n return retryer?.getAbortSignal() ?? null\n }\n\n /**\n * Aborts all ongoing executions with the internal abort controllers.\n * Does NOT clear out the items.\n */\n abort = (): void => {\n this.asyncRetryers.forEach((retryer) => retryer.abort())\n this.asyncRetryers.clear()\n this.#setState({\n isExecuting: false,\n })\n }\n\n /**\n * Resets the queuer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncQueuerState<TValue>())\n this.options.onItemsChange?.(this)\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.\n * The queuer is started automatically and ready to process items.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync queue function:\n * - Returns promises that can be awaited for task results\n * - Built-in retry support via AsyncRetryer integration for each queued task\n * - Abort support to cancel in-flight task executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Concurrent execution support (process multiple items simultaneously)\n *\n * The sync queue function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Queuing?\n * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.\n * Tasks are processed up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Configuration Options:\n * - `concurrency`: Maximum number of concurrent tasks (default: 1)\n * - `wait`: Time to wait between processing items (default: 0)\n * - `maxSize`: Maximum number of items allowed in the queue (default: Infinity)\n * - `getPriority`: Function to determine item priority\n * - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')\n * - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')\n * - `expirationDuration`: Maximum time items can stay in queue\n * - `started`: Whether to start processing immediately (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for task executions\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncQueuer instance\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async queuer\n * - Use `onSuccess` callback to react to successful task execution and implement custom logic\n * - Use `onError` callback to react to task execution errors and implement custom error handling\n * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes error count, expiration count, rejection count, running status, and success/settle counts\n * - State can be accessed via the underlying AsyncQueuer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const enqueue = asyncQueue<string>(async (item) => {\n * return item.toUpperCase();\n * }, {\n * concurrency: 2,\n * wait: 100,\n * onSuccess: (result) => console.log('Processed:', result)\n * });\n *\n * enqueue('hello');\n * ```\n */\nexport function asyncQueue<TValue>(\n fn: (value: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue>,\n) {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n return asyncQueuer.addItem\n}\n"],"mappings":";;;;;;AAuFA,SAAS,6BAA+D;AACtE,QAAO;EACL,aAAa,EAAE;EACf,cAAc;EACd,YAAY;EACZ,cAAc;EACd,iBAAiB;EACjB,SAAS;EACT,aAAa;EACb,QAAQ;EACR,QAAQ;EACR,WAAW;EACX,gBAAgB,EAAE;EAClB,OAAO,EAAE;EACT,YAAY;EACZ,aAAa;EACb,gBAAgB;EAChB,cAAc;EACd,MAAM;EACN,QAAQ;EACR,cAAc;EACf;;;;;AAwGH,SAAgB,mBAKd,SAA6B;AAC7B,QAAO;;AAgBT,MAAMA,iBAA0D;CAC9D,YAAY;CACZ,qBAAqB,EACnB,aAAa,GACd;CACD,aAAa;CACb,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,cAAc,SAAc,MAAM,YAAY;CAC9C,cAAc,EAAE;CAChB,SAAS;CACT,SAAS;CACT,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkED,IAAa,cAAb,MAAiC;CAU/B,8BAAmC,IAAI,KAAK;CAE5C,YACE,AAAOC,IACP,iBAA6C,EAAE,EAC/C;EAFO;eAZmD,IAAI,MAE9D,4BAAoC,CAAC;uCAGvB,IAAI,KAGjB;qBA4CW,eAA0D;AACtE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;kBAuGjD,MACA,WAA0B,KAAK,QAAQ,cAAc,Q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