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