@tanstack/pacer 0.21.1 → 0.23.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 (101) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher.d.ts +11 -14
  3. package/dist/async-batcher.js +186 -132
  4. package/dist/async-debouncer.d.ts +10 -13
  5. package/dist/async-debouncer.js +187 -146
  6. package/dist/async-queuer.d.ts +12 -14
  7. package/dist/async-queuer.js +384 -259
  8. package/dist/async-rate-limiter.d.ts +9 -12
  9. package/dist/async-rate-limiter.js +198 -147
  10. package/dist/async-retryer.d.ts +10 -10
  11. package/dist/async-retryer.js +209 -188
  12. package/dist/async-throttler.d.ts +10 -13
  13. package/dist/async-throttler.js +215 -161
  14. package/dist/batcher.d.ts +5 -8
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -9
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -11
  19. package/dist/event-client.js +1 -2
  20. package/dist/index.js +1 -1
  21. package/dist/queuer.d.ts +8 -10
  22. package/dist/queuer.js +277 -207
  23. package/dist/rate-limiter.d.ts +6 -9
  24. package/dist/rate-limiter.js +127 -109
  25. package/dist/throttler.d.ts +6 -9
  26. package/dist/throttler.js +127 -90
  27. package/dist/types.d.ts +4 -6
  28. package/dist/utils.d.ts +3 -6
  29. package/dist/utils.js +1 -2
  30. package/package.json +23 -70
  31. package/dist/async-batcher.cjs +0 -337
  32. package/dist/async-batcher.cjs.map +0 -1
  33. package/dist/async-batcher.d.cts +0 -344
  34. package/dist/async-batcher.js.map +0 -1
  35. package/dist/async-debouncer.cjs +0 -330
  36. package/dist/async-debouncer.cjs.map +0 -1
  37. package/dist/async-debouncer.d.cts +0 -300
  38. package/dist/async-debouncer.js.map +0 -1
  39. package/dist/async-queuer.cjs +0 -484
  40. package/dist/async-queuer.cjs.map +0 -1
  41. package/dist/async-queuer.d.cts +0 -440
  42. package/dist/async-queuer.js.map +0 -1
  43. package/dist/async-rate-limiter.cjs +0 -373
  44. package/dist/async-rate-limiter.cjs.map +0 -1
  45. package/dist/async-rate-limiter.d.cts +0 -357
  46. package/dist/async-rate-limiter.js.map +0 -1
  47. package/dist/async-retryer.cjs +0 -374
  48. package/dist/async-retryer.cjs.map +0 -1
  49. package/dist/async-retryer.d.cts +0 -319
  50. package/dist/async-retryer.js.map +0 -1
  51. package/dist/async-throttler.cjs +0 -347
  52. package/dist/async-throttler.cjs.map +0 -1
  53. package/dist/async-throttler.d.cts +0 -320
  54. package/dist/async-throttler.js.map +0 -1
  55. package/dist/batcher.cjs +0 -200
  56. package/dist/batcher.cjs.map +0 -1
  57. package/dist/batcher.d.cts +0 -180
  58. package/dist/batcher.js.map +0 -1
  59. package/dist/debouncer.cjs +0 -203
  60. package/dist/debouncer.cjs.map +0 -1
  61. package/dist/debouncer.d.cts +0 -167
  62. package/dist/debouncer.js.map +0 -1
  63. package/dist/event-client.cjs +0 -64
  64. package/dist/event-client.cjs.map +0 -1
  65. package/dist/event-client.d.cts +0 -66
  66. package/dist/event-client.js.map +0 -1
  67. package/dist/index.cjs +0 -52
  68. package/dist/index.d.cts +0 -15
  69. package/dist/queuer.cjs +0 -401
  70. package/dist/queuer.cjs.map +0 -1
  71. package/dist/queuer.d.cts +0 -345
  72. package/dist/queuer.js.map +0 -1
  73. package/dist/rate-limiter.cjs +0 -263
  74. package/dist/rate-limiter.cjs.map +0 -1
  75. package/dist/rate-limiter.d.cts +0 -215
  76. package/dist/rate-limiter.js.map +0 -1
  77. package/dist/throttler.cjs +0 -215
  78. package/dist/throttler.cjs.map +0 -1
  79. package/dist/throttler.d.cts +0 -207
  80. package/dist/throttler.js.map +0 -1
  81. package/dist/types.cjs +0 -0
  82. package/dist/types.d.cts +0 -13
  83. package/dist/utils.cjs +0 -14
  84. package/dist/utils.cjs.map +0 -1
  85. package/dist/utils.d.cts +0 -8
  86. package/dist/utils.js.map +0 -1
  87. package/src/async-batcher.ts +0 -594
  88. package/src/async-debouncer.ts +0 -565
  89. package/src/async-queuer.ts +0 -925
  90. package/src/async-rate-limiter.ts +0 -647
  91. package/src/async-retryer.ts +0 -684
  92. package/src/async-throttler.ts +0 -633
  93. package/src/batcher.ts +0 -329
  94. package/src/debouncer.ts +0 -334
  95. package/src/event-client.ts +0 -129
  96. package/src/index.ts +0 -24
  97. package/src/queuer.ts +0 -740
  98. package/src/rate-limiter.ts +0 -429
  99. package/src/throttler.ts +0 -380
  100. package/src/types.ts +0 -12
  101. package/src/utils.ts +0 -12
@@ -1,344 +0,0 @@
1
- import { OptionalKeys } from "./types.cjs";
2
- import { AsyncRetryer, AsyncRetryerOptions } from "./async-retryer.cjs";
3
- import { Store } from "@tanstack/store";
4
-
5
- //#region src/async-batcher.d.ts
6
- interface AsyncBatcherState<TValue> {
7
- /**
8
- * Number of batch executions that have resulted in errors
9
- */
10
- errorCount: number;
11
- /**
12
- * Number of batch executions that have been executed
13
- */
14
- executeCount: number;
15
- /**
16
- * Array of items that failed during batch processing
17
- */
18
- failedItems: Array<TValue>;
19
- /**
20
- * Whether the batcher has no items to process (items array is empty)
21
- */
22
- isEmpty: boolean;
23
- /**
24
- * Whether a batch is currently being processed asynchronously
25
- */
26
- isExecuting: boolean;
27
- /**
28
- * Whether the batcher is waiting for the timeout to trigger batch processing
29
- */
30
- isPending: boolean;
31
- /**
32
- * Array of items currently queued for batch processing
33
- */
34
- items: Array<TValue>;
35
- /**
36
- * The result from the most recent batch execution
37
- */
38
- lastResult: any;
39
- /**
40
- * Number of batch executions that have completed (either successfully or with errors)
41
- */
42
- settleCount: number;
43
- /**
44
- * Number of items currently in the batch queue
45
- */
46
- size: number;
47
- /**
48
- * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout, 'executing' when processing, 'populated' when items are present, but no wait is configured
49
- */
50
- status: 'idle' | 'pending' | 'executing' | 'populated';
51
- /**
52
- * Number of batch executions that have completed successfully
53
- */
54
- successCount: number;
55
- /**
56
- * Total number of items that have failed processing across all batches
57
- */
58
- totalItemsFailed: number;
59
- /**
60
- * Total number of items that have been processed across all batches
61
- */
62
- totalItemsProcessed: number;
63
- }
64
- /**
65
- * Options for configuring an AsyncBatcher instance
66
- */
67
- interface AsyncBatcherOptions<TValue> {
68
- /**
69
- * Options for configuring the underlying async retryer
70
- */
71
- asyncRetryerOptions?: AsyncRetryerOptions<(items: Array<TValue>) => Promise<any>>;
72
- /**
73
- * Custom function to determine if a batch should be processed
74
- * Return true to process the batch immediately
75
- */
76
- getShouldExecute?: (items: Array<TValue>, batcher: AsyncBatcher<TValue>) => boolean;
77
- /**
78
- * Initial state for the async batcher
79
- */
80
- initialState?: Partial<AsyncBatcherState<TValue>>;
81
- /**
82
- * Optional key to identify this async batcher instance.
83
- * If provided, the async batcher will be identified by this key in the devtools and PacerProvider if applicable.
84
- */
85
- key?: string;
86
- /**
87
- * Maximum number of items in a batch
88
- * @default Infinity
89
- */
90
- maxSize?: number;
91
- /**
92
- * Optional error handler for when the batch function throws.
93
- * If provided, the handler will be called with the error, the batch of items that failed, and batcher instance.
94
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
95
- */
96
- onError?: (error: Error, batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void;
97
- /**
98
- * Callback fired after items are added to the batcher
99
- */
100
- onItemsChange?: (batcher: AsyncBatcher<TValue>) => void;
101
- /**
102
- * Optional callback to call when a batch is settled (completed or failed)
103
- */
104
- onSettled?: (batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void;
105
- /**
106
- * Optional callback to call when a batch succeeds
107
- */
108
- onSuccess?: (result: any, batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void;
109
- /**
110
- * Whether the batcher should start processing immediately
111
- * @default true
112
- */
113
- started?: boolean;
114
- /**
115
- * Whether to throw errors when they occur.
116
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
117
- * Can be explicitly set to override these defaults.
118
- */
119
- throwOnError?: boolean;
120
- /**
121
- * Maximum time in milliseconds to wait before processing a batch.
122
- * If the wait duration has elapsed, the batch will be processed.
123
- * If not provided, the batch will not be triggered by a timeout.
124
- * @default Infinity
125
- */
126
- wait?: number | ((asyncBatcher: AsyncBatcher<TValue>) => number);
127
- }
128
- /**
129
- * Utility function for sharing common `AsyncBatcherOptions` options between different `AsyncBatcher` instances.
130
- *
131
- */
132
- declare function asyncBatcherOptions<TValue = any, TOptions extends Partial<AsyncBatcherOptions<TValue>> = Partial<AsyncBatcherOptions<TValue>>>(options: TOptions): TOptions;
133
- type AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<Required<AsyncBatcherOptions<TValue>>, 'initialState' | 'onError' | 'onItemsChange' | 'onSettled' | 'onSuccess' | 'key'>;
134
- /**
135
- * A class that collects items and processes them in batches asynchronously.
136
- *
137
- * Async vs Sync Versions:
138
- * The async version provides advanced features over the sync Batcher:
139
- * - Returns promises that can be awaited for batch results
140
- * - Built-in retry support via AsyncRetryer integration
141
- * - Abort support to cancel in-flight batch executions
142
- * - Cancel support to prevent pending batches from starting
143
- * - Comprehensive error handling with onError callbacks and throwOnError control
144
- * - Detailed execution tracking (success/error/settle counts)
145
- *
146
- * The sync Batcher is lighter weight and simpler when you don't need async features,
147
- * return values, or execution control.
148
- *
149
- * What is Batching?
150
- * Batching is a technique for grouping multiple operations together to be processed as a single unit.
151
- *
152
- * The AsyncBatcher provides a flexible way to implement async batching with configurable:
153
- * - Maximum batch size (number of items per batch)
154
- * - Time-based batching (process after X milliseconds)
155
- * - Custom batch processing logic via getShouldExecute
156
- * - Event callbacks for monitoring batch operations
157
- * - Error handling for failed batch operations
158
- *
159
- * Error Handling:
160
- * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
161
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
162
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
163
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
164
- * - The error state can be checked using the AsyncBatcher instance
165
- *
166
- * State Management:
167
- * - Uses TanStack Store for reactive state management
168
- * - Use `initialState` to provide initial state values when creating the async batcher
169
- * - Use `onSuccess` callback to react to successful batch execution and implement custom logic
170
- * - Use `onError` callback to react to batch execution errors and implement custom error handling
171
- * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic
172
- * - Use `onExecute` callback to react to batch execution and implement custom logic
173
- * - Use `onItemsChange` callback to react to items being added or removed from the batcher
174
- * - The state includes total items processed, success/error counts, and execution status
175
- * - State can be accessed via `asyncBatcher.store.state` when using the class directly
176
- * - When using framework adapters (React/Solid), state is accessed from `asyncBatcher.state`
177
- *
178
- * @example
179
- * ```ts
180
- * const batcher = new AsyncBatcher<number>(
181
- * async (items) => {
182
- * const result = await processItems(items);
183
- * console.log('Processing batch:', items);
184
- * return result;
185
- * },
186
- * {
187
- * maxSize: 5,
188
- * wait: 2000,
189
- * onSuccess: (result) => console.log('Batch succeeded:', result),
190
- * onError: (error) => console.error('Batch failed:', error)
191
- * }
192
- * );
193
- *
194
- * batcher.addItem(1);
195
- * batcher.addItem(2);
196
- * // After 2 seconds or when 5 items are added, whichever comes first,
197
- * // the batch will be processed and the result will be available
198
- * // batcher.execute() // manually trigger a batch
199
- * ```
200
- */
201
- declare class AsyncBatcher<TValue> {
202
- #private;
203
- fn: (items: Array<TValue>) => Promise<any>;
204
- readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;
205
- key: string | undefined;
206
- options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>;
207
- asyncRetryers: Map<number, AsyncRetryer<(items: Array<TValue>) => Promise<any>>>;
208
- constructor(fn: (items: Array<TValue>) => Promise<any>, initialOptions: AsyncBatcherOptions<TValue>);
209
- /**
210
- * Updates the async batcher options
211
- */
212
- setOptions: (newOptions: Partial<AsyncBatcherOptions<TValue>>) => void;
213
- /**
214
- * Adds an item to the async batcher
215
- * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
216
- *
217
- * @returns The result from the batch function, or undefined if an error occurred and was handled by onError
218
- *
219
- * @throws The error from the batch function if no onError handler is configured or throwOnError is true
220
- */
221
- addItem: (item: TValue) => Promise<any>;
222
- /**
223
- * Processes the current batch of items immediately
224
- */
225
- flush: () => Promise<any>;
226
- /**
227
- * Returns a copy of all items in the async batcher
228
- */
229
- peekAllItems: () => Array<TValue>;
230
- peekFailedItems: () => Array<TValue>;
231
- /**
232
- * Removes all items from the async batcher
233
- */
234
- clear: () => void;
235
- /**
236
- * Returns the AbortSignal for a specific execution.
237
- * If no executeCount is provided, returns the signal for the most recent execution.
238
- * Returns null if no execution is found or not currently executing.
239
- *
240
- * @param executeCount - Optional specific execution to get signal for
241
- * @example
242
- * ```typescript
243
- * const batcher = new AsyncBatcher(
244
- * async (items: string[]) => {
245
- * const signal = batcher.getAbortSignal()
246
- * if (signal) {
247
- * const response = await fetch('/api/batch', {
248
- * method: 'POST',
249
- * body: JSON.stringify(items),
250
- * signal
251
- * })
252
- * return response.json()
253
- * }
254
- * },
255
- * { maxSize: 10, wait: 100 }
256
- * )
257
- * ```
258
- */
259
- getAbortSignal: (executeCount?: number) => AbortSignal | null;
260
- /**
261
- * Aborts all ongoing executions with the internal abort controllers.
262
- * Does NOT cancel any pending execution that have not started yet.
263
- * Does NOT clear out the items.
264
- */
265
- abort: () => void;
266
- /**
267
- * Cancels any pending execution that have not started yet.
268
- * Does NOT abort any execution already in progress.
269
- * Does NOT clear out the items.
270
- */
271
- cancel: () => void;
272
- /**
273
- * Resets the async batcher state to its default values
274
- */
275
- reset: () => void;
276
- }
277
- /**
278
- * Creates an async batcher that processes items in batches.
279
- *
280
- * Async vs Sync Versions:
281
- * The async version provides advanced features over the sync batch function:
282
- * - Returns promises that can be awaited for batch results
283
- * - Built-in retry support via AsyncRetryer integration
284
- * - Abort support to cancel in-flight batch executions
285
- * - Cancel support to prevent pending batches from starting
286
- * - Comprehensive error handling with onError callbacks and throwOnError control
287
- * - Detailed execution tracking (success/error/settle counts)
288
- *
289
- * The sync batch function is lighter weight and simpler when you don't need async features,
290
- * return values, or execution control.
291
- *
292
- * What is Batching?
293
- * Batching is a technique for grouping multiple operations together to be processed as a single unit.
294
- *
295
- * Configuration Options:
296
- * - `maxSize`: Maximum number of items per batch (default: Infinity)
297
- * - `wait`: Time to wait before processing batch (default: Infinity)
298
- * - `getShouldExecute`: Custom logic to trigger batch processing
299
- * - `asyncRetryerOptions`: Configure retry behavior for batch executions
300
- * - `started`: Whether to start processing immediately (default: true)
301
- *
302
- * Error Handling:
303
- * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
304
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
305
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
306
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
307
- * - The error state can be checked using the underlying AsyncBatcher instance
308
- *
309
- * State Management:
310
- * - Uses TanStack Store for reactive state management
311
- * - Use `initialState` to provide initial state values when creating the async batcher
312
- * - Use `onSuccess` callback to react to successful batch execution and implement custom logic
313
- * - Use `onError` callback to react to batch execution errors and implement custom error handling
314
- * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic
315
- * - Use `onItemsChange` callback to react to items being added or removed from the batcher
316
- * - The state includes total items processed, success/error counts, and execution status
317
- * - State can be accessed via the underlying AsyncBatcher instance's `store.state` property
318
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
319
- *
320
- * @example
321
- * ```ts
322
- * const batchItems = asyncBatch<number>(
323
- * async (items) => {
324
- * const result = await processApiCall(items);
325
- * console.log('Processing:', items);
326
- * return result;
327
- * },
328
- * {
329
- * maxSize: 3,
330
- * wait: 1000,
331
- * onSuccess: (result) => console.log('Batch succeeded:', result),
332
- * onError: (error) => console.error('Batch failed:', error)
333
- * }
334
- * );
335
- *
336
- * batchItems(1);
337
- * batchItems(2);
338
- * batchItems(3); // Triggers batch processing
339
- * ```
340
- */
341
- declare function asyncBatch<TValue>(fn: (items: Array<TValue>) => Promise<any>, options: AsyncBatcherOptions<TValue>): (item: TValue) => Promise<any>;
342
- //#endregion
343
- export { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState, asyncBatch, asyncBatcherOptions };
344
- //# sourceMappingURL=async-batcher.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-batcher.js","names":["#setState","#execute","#clearTimeout","#timeoutId","#getWait"],"sources":["../src/async-batcher.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'\n\nexport interface AsyncBatcherState<TValue> {\n /**\n * Number of batch executions that have resulted in errors\n */\n errorCount: number\n /**\n * Number of batch executions that have been executed\n */\n executeCount: number\n /**\n * Array of items that failed during batch processing\n */\n failedItems: Array<TValue>\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether a batch is currently being processed asynchronously\n */\n isExecuting: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * The result from the most recent batch execution\n */\n lastResult: any\n /**\n * Number of batch executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout, 'executing' when processing, 'populated' when items are present, but no wait is configured\n */\n status: 'idle' | 'pending' | 'executing' | 'populated'\n /**\n * Number of batch executions that have completed successfully\n */\n successCount: number\n /**\n * Total number of items that have failed processing across all batches\n */\n totalItemsFailed: number\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultAsyncBatcherState<TValue>(): AsyncBatcherState<TValue> {\n return {\n errorCount: 0,\n executeCount: 0,\n failedItems: [],\n isEmpty: true,\n isExecuting: false,\n isPending: false,\n items: [],\n lastResult: undefined,\n settleCount: 0,\n size: 0,\n status: 'idle',\n successCount: 0,\n totalItemsProcessed: 0,\n totalItemsFailed: 0,\n }\n}\n\n/**\n * Options for configuring an AsyncBatcher instance\n */\nexport interface AsyncBatcherOptions<TValue> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<\n (items: Array<TValue>) => Promise<any>\n >\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (\n items: Array<TValue>,\n batcher: AsyncBatcher<TValue>,\n ) => boolean\n /**\n * Initial state for the async batcher\n */\n initialState?: Partial<AsyncBatcherState<TValue>>\n /**\n * Optional key to identify this async batcher instance.\n * If provided, the async batcher will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Optional error handler for when the batch function throws.\n * If provided, the handler will be called with the error, the batch of items that failed, and batcher instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (\n error: Error,\n batch: Array<TValue>,\n batcher: AsyncBatcher<TValue>,\n ) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: AsyncBatcher<TValue>) => void\n /**\n * Optional callback to call when a batch is settled (completed or failed)\n */\n onSettled?: (batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void\n /**\n * Optional callback to call when a batch succeeds\n */\n onSuccess?: (\n result: any,\n batch: Array<TValue>,\n batcher: AsyncBatcher<TValue>,\n ) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\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 * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((asyncBatcher: AsyncBatcher<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncBatcherOptions` options between different `AsyncBatcher` instances.\n *\n */\nexport function asyncBatcherOptions<\n TValue = any,\n TOptions extends Partial<AsyncBatcherOptions<TValue>> = Partial<\n AsyncBatcherOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<AsyncBatcherOptions<TValue>>,\n | 'initialState'\n | 'onError'\n | 'onItemsChange'\n | 'onSettled'\n | 'onSuccess'\n | 'key'\n>\n\nconst defaultOptions: AsyncBatcherOptionsWithOptionalCallbacks<any> = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n throwOnError: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches asynchronously.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Batcher:\n * - Returns promises that can be awaited for batch results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight batch executions\n * - Cancel support to prevent pending batches from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync Batcher is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Batching?\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * The AsyncBatcher provides a flexible way to implement async batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher 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 AsyncBatcher 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 batcher\n * - Use `onSuccess` callback to react to successful batch execution and implement custom logic\n * - Use `onError` callback to react to batch execution errors and implement custom error handling\n * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes total items processed, success/error counts, and execution status\n * - State can be accessed via `asyncBatcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncBatcher.state`\n *\n * @example\n * ```ts\n * const batcher = new AsyncBatcher<number>(\n * async (items) => {\n * const result = await processItems(items);\n * console.log('Processing batch:', items);\n * return result;\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onSuccess: (result) => console.log('Batch succeeded:', result),\n * onError: (error) => console.error('Batch failed:', error)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed and the result will be available\n * // batcher.execute() // manually trigger a batch\n * ```\n */\nexport class AsyncBatcher<TValue> {\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>> = new Store(\n getDefaultAsyncBatcherState<TValue>(),\n )\n key: string | undefined\n options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>\n asyncRetryers = new Map<\n number,\n AsyncRetryer<(items: Array<TValue>) => Promise<any>>\n >()\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => Promise<any>,\n initialOptions: AsyncBatcherOptions<TValue>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-AsyncBatcher', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<AsyncBatcherState<TValue>>,\n )\n this.setOptions(\n event.payload.options as Partial<AsyncBatcherOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the async batcher options\n */\n setOptions = (newOptions: Partial<AsyncBatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncBatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isExecuting, isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isExecuting\n ? 'executing'\n : isPending\n ? 'pending'\n : isEmpty\n ? 'idle'\n : 'populated',\n }\n })\n emitChange('AsyncBatcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the async batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n *\n * @returns The result from the batch function, or undefined if an error occurred and was handled by onError\n *\n * @throws The error from the batch function if no onError handler is configured or throwOnError is true\n */\n addItem = async (item: TValue): Promise<any> => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n return await this.#execute()\n } else if (this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n await new Promise((resolve) => setTimeout(resolve, this.#getWait()))\n }\n }\n\n /**\n * Processes the current batch of items asynchronously.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches maxSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n *\n * @returns A promise that resolves with the result of the batch function, or undefined if an error occurred and was handled by onError\n * @throws The error from the batch function if no onError handler is configured or throwOnError is true\n */\n #execute = async (): Promise<any> => {\n if (this.store.state.items.length === 0) {\n return undefined\n }\n\n const currentExecuteCount = this.store.state.executeCount + 1\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this)\n\n this.#setState({ isExecuting: true, executeCount: currentExecuteCount })\n\n try {\n const currentAsyncRetryer = new AsyncRetryer(\n this.fn,\n this.options.asyncRetryerOptions,\n )\n this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer)\n const result = await currentAsyncRetryer.execute(batch) // EXECUTE\n this.#setState({\n totalItemsProcessed:\n this.store.state.totalItemsProcessed + batch.length,\n lastResult: result,\n successCount: this.store.state.successCount + 1,\n })\n this.options.onSuccess?.(result, batch, this)\n return result\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n failedItems: [...this.store.state.failedItems, ...batch],\n totalItemsFailed: this.store.state.totalItemsFailed + batch.length,\n })\n this.options.onError?.(error as Error, batch, this)\n if (this.options.throwOnError) {\n throw error\n }\n return undefined\n } finally {\n this.asyncRetryers.delete(currentExecuteCount) // dispose retryer\n this.#setState({\n isExecuting: false,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(batch, this)\n }\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = async (): Promise<any> => {\n this.#clearTimeout() // clear any pending timeout\n return await this.#execute()\n }\n\n /**\n * Returns a copy of all items in the async batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n peekFailedItems = (): Array<TValue> => {\n return [...this.store.state.failedItems]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the async batcher\n */\n clear = (): void => {\n this.#setState({ items: [], failedItems: [], isPending: false })\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 batcher = new AsyncBatcher(\n * async (items: string[]) => {\n * const signal = batcher.getAbortSignal()\n * if (signal) {\n * const response = await fetch('/api/batch', {\n * method: 'POST',\n * body: JSON.stringify(items),\n * signal\n * })\n * return response.json()\n * }\n * },\n * { maxSize: 10, wait: 100 }\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 cancel any pending execution that have not started yet.\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 * Cancels any pending execution that have not started yet.\n * Does NOT abort any execution already in progress.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n isPending: false,\n })\n }\n\n /**\n * Resets the async batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates an async batcher that processes items in batches.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync batch function:\n * - Returns promises that can be awaited for batch results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight batch executions\n * - Cancel support to prevent pending batches from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync batch function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Batching?\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * Configuration Options:\n * - `maxSize`: Maximum number of items per batch (default: Infinity)\n * - `wait`: Time to wait before processing batch (default: Infinity)\n * - `getShouldExecute`: Custom logic to trigger batch processing\n * - `asyncRetryerOptions`: Configure retry behavior for batch executions\n * - `started`: Whether to start processing immediately (default: true)\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher 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 AsyncBatcher 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 batcher\n * - Use `onSuccess` callback to react to successful batch execution and implement custom logic\n * - Use `onError` callback to react to batch execution errors and implement custom error handling\n * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes total items processed, success/error counts, and execution status\n * - State can be accessed via the underlying AsyncBatcher 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 batchItems = asyncBatch<number>(\n * async (items) => {\n * const result = await processApiCall(items);\n * console.log('Processing:', items);\n * return result;\n * },\n * {\n * maxSize: 3,\n * wait: 1000,\n * onSuccess: (result) => console.log('Batch succeeded:', result),\n * onError: (error) => console.error('Batch failed:', error)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function asyncBatch<TValue>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: AsyncBatcherOptions<TValue>,\n) {\n const batcher = new AsyncBatcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;;AAkEA,SAAS,8BAAiE;CACxE,OAAO;EACL,YAAY;EACZ,cAAc;EACd,aAAa,EAAE;EACf,SAAS;EACT,aAAa;EACb,WAAW;EACX,OAAO,EAAE;EACT,YAAY;EACZ,aAAa;EACb,MAAM;EACN,QAAQ;EACR,cAAc;EACd,qBAAqB;EACrB,kBAAkB;EACnB;;;;;;AAqFH,SAAgB,oBAKd,SAA6B;CAC7B,OAAO;;AAaT,MAAM,iBAAg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