@tanstack/pacer 0.16.2 → 0.16.4

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 (180) 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 +38 -122
  89. package/src/async-batcher.ts +7 -5
  90. package/src/async-debouncer.ts +7 -5
  91. package/src/async-queuer.ts +7 -5
  92. package/src/async-rate-limiter.ts +7 -5
  93. package/src/async-retryer.ts +7 -5
  94. package/src/async-throttler.ts +7 -5
  95. package/src/batcher.ts +7 -5
  96. package/src/debouncer.ts +7 -5
  97. package/src/queuer.ts +7 -5
  98. package/src/rate-limiter.ts +7 -5
  99. package/src/throttler.ts +7 -5
  100. package/dist/cjs/async-batcher.cjs +0 -220
  101. package/dist/cjs/async-batcher.cjs.map +0 -1
  102. package/dist/cjs/async-batcher.d.cts +0 -340
  103. package/dist/cjs/async-debouncer.cjs +0 -231
  104. package/dist/cjs/async-debouncer.cjs.map +0 -1
  105. package/dist/cjs/async-debouncer.d.cts +0 -295
  106. package/dist/cjs/async-queuer.cjs +0 -397
  107. package/dist/cjs/async-queuer.cjs.map +0 -1
  108. package/dist/cjs/async-queuer.d.cts +0 -435
  109. package/dist/cjs/async-rate-limiter.cjs +0 -252
  110. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  111. package/dist/cjs/async-retryer.cjs +0 -285
  112. package/dist/cjs/async-retryer.cjs.map +0 -1
  113. package/dist/cjs/async-retryer.d.cts +0 -308
  114. package/dist/cjs/async-throttler.cjs +0 -261
  115. package/dist/cjs/async-throttler.cjs.map +0 -1
  116. package/dist/cjs/async-throttler.d.cts +0 -315
  117. package/dist/cjs/batcher.cjs +0 -130
  118. package/dist/cjs/batcher.cjs.map +0 -1
  119. package/dist/cjs/batcher.d.cts +0 -176
  120. package/dist/cjs/debouncer.cjs +0 -137
  121. package/dist/cjs/debouncer.cjs.map +0 -1
  122. package/dist/cjs/debouncer.d.cts +0 -162
  123. package/dist/cjs/event-client.cjs +0 -20
  124. package/dist/cjs/event-client.cjs.map +0 -1
  125. package/dist/cjs/event-client.d.cts +0 -45
  126. package/dist/cjs/index.cjs +0 -51
  127. package/dist/cjs/index.cjs.map +0 -1
  128. package/dist/cjs/index.d.cts +0 -15
  129. package/dist/cjs/queuer.cjs +0 -306
  130. package/dist/cjs/queuer.cjs.map +0 -1
  131. package/dist/cjs/queuer.d.cts +0 -340
  132. package/dist/cjs/rate-limiter.cjs +0 -179
  133. package/dist/cjs/rate-limiter.cjs.map +0 -1
  134. package/dist/cjs/throttler.cjs +0 -151
  135. package/dist/cjs/throttler.cjs.map +0 -1
  136. package/dist/cjs/throttler.d.cts +0 -202
  137. package/dist/cjs/types.d.cts +0 -9
  138. package/dist/cjs/utils.cjs +0 -11
  139. package/dist/cjs/utils.cjs.map +0 -1
  140. package/dist/cjs/utils.d.cts +0 -3
  141. package/dist/esm/async-batcher.d.ts +0 -340
  142. package/dist/esm/async-batcher.js +0 -220
  143. package/dist/esm/async-batcher.js.map +0 -1
  144. package/dist/esm/async-debouncer.d.ts +0 -295
  145. package/dist/esm/async-debouncer.js +0 -231
  146. package/dist/esm/async-debouncer.js.map +0 -1
  147. package/dist/esm/async-queuer.d.ts +0 -435
  148. package/dist/esm/async-queuer.js +0 -397
  149. package/dist/esm/async-queuer.js.map +0 -1
  150. package/dist/esm/async-rate-limiter.js +0 -252
  151. package/dist/esm/async-rate-limiter.js.map +0 -1
  152. package/dist/esm/async-retryer.d.ts +0 -308
  153. package/dist/esm/async-retryer.js +0 -285
  154. package/dist/esm/async-retryer.js.map +0 -1
  155. package/dist/esm/async-throttler.d.ts +0 -315
  156. package/dist/esm/async-throttler.js +0 -261
  157. package/dist/esm/async-throttler.js.map +0 -1
  158. package/dist/esm/batcher.d.ts +0 -176
  159. package/dist/esm/batcher.js +0 -130
  160. package/dist/esm/batcher.js.map +0 -1
  161. package/dist/esm/debouncer.d.ts +0 -162
  162. package/dist/esm/debouncer.js +0 -137
  163. package/dist/esm/debouncer.js.map +0 -1
  164. package/dist/esm/event-client.d.ts +0 -45
  165. package/dist/esm/event-client.js +0 -20
  166. package/dist/esm/event-client.js.map +0 -1
  167. package/dist/esm/index.d.ts +0 -15
  168. package/dist/esm/index.js.map +0 -1
  169. package/dist/esm/queuer.d.ts +0 -340
  170. package/dist/esm/queuer.js +0 -306
  171. package/dist/esm/queuer.js.map +0 -1
  172. package/dist/esm/rate-limiter.js +0 -179
  173. package/dist/esm/rate-limiter.js.map +0 -1
  174. package/dist/esm/throttler.d.ts +0 -202
  175. package/dist/esm/throttler.js +0 -151
  176. package/dist/esm/throttler.js.map +0 -1
  177. package/dist/esm/types.d.ts +0 -9
  178. package/dist/esm/utils.d.ts +0 -3
  179. package/dist/esm/utils.js +0 -11
  180. package/dist/esm/utils.js.map +0 -1
@@ -0,0 +1,360 @@
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-throttler.ts
7
+ function getDefaultAsyncThrottlerState() {
8
+ return {
9
+ errorCount: 0,
10
+ isExecuting: false,
11
+ isPending: false,
12
+ lastArgs: void 0,
13
+ lastExecutionTime: 0,
14
+ lastResult: void 0,
15
+ maybeExecuteCount: 0,
16
+ nextExecutionTime: void 0,
17
+ settleCount: 0,
18
+ status: "idle",
19
+ successCount: 0
20
+ };
21
+ }
22
+ /**
23
+ * Utility function for sharing common `AsyncThrottlerOptions` options between different `AsyncThrottler` instances.
24
+ */
25
+ function asyncThrottlerOptions(options) {
26
+ return options;
27
+ }
28
+ const defaultOptions = {
29
+ asyncRetryerOptions: { maxAttempts: 1 },
30
+ enabled: true,
31
+ leading: true,
32
+ trailing: true,
33
+ wait: 0
34
+ };
35
+ /**
36
+ * A class that creates an async throttled function.
37
+ *
38
+ * Async vs Sync Versions:
39
+ * The async version provides advanced features over the sync Throttler:
40
+ * - Returns promises that can be awaited for throttled function results
41
+ * - Built-in retry support via AsyncRetryer integration
42
+ * - Abort support to cancel in-flight executions
43
+ * - Cancel support to prevent pending executions from starting
44
+ * - Comprehensive error handling with onError callbacks and throwOnError control
45
+ * - Detailed execution tracking (success/error/settle counts)
46
+ * - Waits for ongoing executions to complete before scheduling the next one
47
+ *
48
+ * The sync Throttler is lighter weight and simpler when you don't need async features,
49
+ * return values, or execution control.
50
+ *
51
+ * What is Throttling?
52
+ * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
53
+ * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
54
+ * regular interval regardless of how often it's called.
55
+ *
56
+ * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
57
+ * ensure a maximum execution frequency.
58
+ *
59
+ * Error Handling:
60
+ * - If an `onError` handler is provided, it will be called with the error and throttler instance
61
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
62
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
63
+ * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
64
+ * - The error state can be checked using the underlying AsyncThrottler instance
65
+ *
66
+ * State Management:
67
+ * - Uses TanStack Store for reactive state management
68
+ * - Use `initialState` to provide initial state values when creating the async throttler
69
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
70
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
71
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
72
+ * - The state includes error count, execution status, last execution time, and success/settle counts
73
+ * - State can be accessed via `asyncThrottler.store.state` when using the class directly
74
+ * - When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const throttler = new AsyncThrottler(async (value: string) => {
79
+ * const result = await saveToAPI(value);
80
+ * return result; // Return value is preserved
81
+ * }, {
82
+ * wait: 1000,
83
+ * onError: (error) => {
84
+ * console.error('API call failed:', error);
85
+ * }
86
+ * });
87
+ *
88
+ * // Will only execute once per second no matter how often called
89
+ * // Returns the API response directly
90
+ * const result = await throttler.maybeExecute(inputElement.value);
91
+ * ```
92
+ */
93
+ var AsyncThrottler = class {
94
+ #timeoutId = null;
95
+ #resolvePreviousPromise = null;
96
+ constructor(fn, initialOptions) {
97
+ this.fn = fn;
98
+ this.store = new Store(getDefaultAsyncThrottlerState());
99
+ this.asyncRetryers = /* @__PURE__ */ new Map();
100
+ this.setOptions = (newOptions) => {
101
+ this.options = {
102
+ ...this.options,
103
+ ...newOptions
104
+ };
105
+ if (!this.#getEnabled()) this.cancel();
106
+ };
107
+ this.maybeExecute = async (...args) => {
108
+ if (!this.#getEnabled()) return void 0;
109
+ this.#resolvePreviousPromiseInternal();
110
+ this.#setState({
111
+ maybeExecuteCount: this.store.state.maybeExecuteCount + 1,
112
+ lastArgs: args
113
+ });
114
+ const wait = this.#getWait();
115
+ const thisMaybeExecuteNumber = this.store.state.maybeExecuteCount;
116
+ for (let maxNumIterations = wait / 10; this.store.state.isExecuting && maxNumIterations > 0; maxNumIterations--) {
117
+ await new Promise((resolve) => setTimeout(resolve, 10));
118
+ if (this.store.state.maybeExecuteCount !== thisMaybeExecuteNumber) return this.store.state.lastResult;
119
+ }
120
+ const now = Date.now();
121
+ const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
122
+ if (this.options.leading && !this.store.state.isPending && timeSinceLastExecution >= wait) await this.#execute(...args);
123
+ else if (this.options.trailing) {
124
+ this.cancel();
125
+ this.#setState({ isPending: true });
126
+ return new Promise((resolve, reject) => {
127
+ this.#resolvePreviousPromise = resolve;
128
+ const newTimeSinceLastExecution = this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0;
129
+ const timeoutDuration = Math.max(0, wait - newTimeSinceLastExecution);
130
+ this.#timeoutId = setTimeout(async () => {
131
+ this.#clearTimeout();
132
+ if (this.store.state.lastArgs !== void 0) try {
133
+ await this.#execute(...this.store.state.lastArgs);
134
+ } catch (error) {
135
+ reject(error);
136
+ }
137
+ this.#resolvePreviousPromise = null;
138
+ resolve(this.store.state.lastResult);
139
+ }, timeoutDuration);
140
+ });
141
+ }
142
+ return this.store.state.lastResult;
143
+ };
144
+ this.flush = async () => {
145
+ if (this.store.state.isPending && this.store.state.lastArgs) {
146
+ const resolvePromise = this.#resolvePreviousPromise;
147
+ this.#clearTimeout();
148
+ this.#setState({ isPending: false });
149
+ const result = await this.#execute(...this.store.state.lastArgs);
150
+ if (resolvePromise) resolvePromise(result);
151
+ return result;
152
+ }
153
+ };
154
+ this.abort = () => {
155
+ this.asyncRetryers.forEach((retryer) => retryer.abort());
156
+ this.asyncRetryers.clear();
157
+ this.#setState({ isExecuting: false });
158
+ };
159
+ this.cancel = () => {
160
+ this.#clearTimeout();
161
+ if (this.#resolvePreviousPromise) {
162
+ this.#resolvePreviousPromiseInternal();
163
+ this.#resolvePreviousPromise = null;
164
+ }
165
+ this.#setState({ isPending: false });
166
+ };
167
+ this.reset = () => {
168
+ this.#setState(getDefaultAsyncThrottlerState());
169
+ this.asyncRetryers.forEach((retryer) => retryer.reset());
170
+ };
171
+ this.key = initialOptions.key;
172
+ this.options = {
173
+ ...defaultOptions,
174
+ ...initialOptions,
175
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
176
+ };
177
+ this.#setState(this.options.initialState ?? {});
178
+ if (this.key) pacerEventClient.on("d-AsyncThrottler", (event) => {
179
+ if (event.payload.key !== this.key) return;
180
+ this.#setState(event.payload.store.state);
181
+ this.setOptions(event.payload.options);
182
+ });
183
+ }
184
+ #setState = (newState) => {
185
+ this.store.setState((state) => {
186
+ const combinedState = {
187
+ ...state,
188
+ ...newState
189
+ };
190
+ const { isPending, isExecuting, settleCount } = combinedState;
191
+ return {
192
+ ...combinedState,
193
+ status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : isExecuting ? "executing" : settleCount > 0 ? "settled" : "idle"
194
+ };
195
+ });
196
+ emitChange("AsyncThrottler", this);
197
+ };
198
+ /**
199
+ * Returns the current enabled state of the async throttler
200
+ */
201
+ #getEnabled = () => {
202
+ return !!parseFunctionOrValue(this.options.enabled, this);
203
+ };
204
+ /**
205
+ * Returns the current wait time in milliseconds
206
+ */
207
+ #getWait = () => {
208
+ return parseFunctionOrValue(this.options.wait, this);
209
+ };
210
+ #execute = async (...args) => {
211
+ if (!this.#getEnabled()) return void 0;
212
+ const currentMaybeExecute = this.store.state.maybeExecuteCount;
213
+ try {
214
+ this.#setState({ isExecuting: true });
215
+ const currentAsyncRetryer = new AsyncRetryer(this.fn, {
216
+ ...this.options.asyncRetryerOptions,
217
+ key: `${this.key}-retryer-${currentMaybeExecute}`
218
+ });
219
+ this.asyncRetryers.set(currentMaybeExecute, currentAsyncRetryer);
220
+ const result = await currentAsyncRetryer.execute(...args);
221
+ this.#setState({
222
+ lastResult: result,
223
+ successCount: this.store.state.successCount + 1
224
+ });
225
+ this.options.onSuccess?.(result, args, this);
226
+ } catch (error) {
227
+ this.#setState({ errorCount: this.store.state.errorCount + 1 });
228
+ this.options.onError?.(error, args, this);
229
+ if (this.options.throwOnError) throw error;
230
+ } finally {
231
+ this.asyncRetryers.delete(currentMaybeExecute);
232
+ const lastExecutionTime = Date.now();
233
+ const wait = this.#getWait();
234
+ const nextExecutionTime = lastExecutionTime + wait;
235
+ this.#setState({
236
+ isExecuting: false,
237
+ isPending: !!this.#timeoutId,
238
+ settleCount: this.store.state.settleCount + 1,
239
+ lastExecutionTime,
240
+ nextExecutionTime
241
+ });
242
+ this.options.onSettled?.(args, this);
243
+ setTimeout(() => {
244
+ if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
245
+ }, wait);
246
+ }
247
+ return this.store.state.lastResult;
248
+ };
249
+ #resolvePreviousPromiseInternal = () => {
250
+ if (this.#resolvePreviousPromise) {
251
+ this.#resolvePreviousPromise(this.store.state.lastResult);
252
+ this.#resolvePreviousPromise = null;
253
+ }
254
+ };
255
+ #clearTimeout = () => {
256
+ if (this.#timeoutId) {
257
+ clearTimeout(this.#timeoutId);
258
+ this.#timeoutId = null;
259
+ }
260
+ };
261
+ /**
262
+ * Returns the AbortSignal for a specific execution.
263
+ * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
264
+ * Returns null if no execution is found or not currently executing.
265
+ *
266
+ * @param maybeExecuteCount - Optional specific execution to get signal for
267
+ * @example
268
+ * ```typescript
269
+ * const throttler = new AsyncThrottler(
270
+ * async (data: string) => {
271
+ * const signal = throttler.getAbortSignal()
272
+ * if (signal) {
273
+ * const response = await fetch('/api/save', {
274
+ * method: 'POST',
275
+ * body: data,
276
+ * signal
277
+ * })
278
+ * return response.json()
279
+ * }
280
+ * },
281
+ * { wait: 1000 }
282
+ * )
283
+ * ```
284
+ */
285
+ getAbortSignal(maybeExecuteCount) {
286
+ const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount;
287
+ return this.asyncRetryers.get(count)?.getAbortSignal() ?? null;
288
+ }
289
+ };
290
+ /**
291
+ * Creates an async throttled function that limits how often the function can execute.
292
+ * The throttled function will execute at most once per wait period, even if called multiple times.
293
+ * If called while executing, it will wait until execution completes before scheduling the next call.
294
+ *
295
+ * Async vs Sync Versions:
296
+ * The async version provides advanced features over the sync throttle function:
297
+ * - Returns promises that can be awaited for throttled function results
298
+ * - Built-in retry support via AsyncRetryer integration
299
+ * - Abort support to cancel in-flight executions
300
+ * - Cancel support to prevent pending executions from starting
301
+ * - Comprehensive error handling with onError callbacks and throwOnError control
302
+ * - Detailed execution tracking (success/error/settle counts)
303
+ * - Waits for ongoing executions to complete before scheduling the next one
304
+ *
305
+ * The sync throttle function is lighter weight and simpler when you don't need async features,
306
+ * return values, or execution control.
307
+ *
308
+ * What is Throttling?
309
+ * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
310
+ * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
311
+ * regular interval regardless of how often it's called.
312
+ *
313
+ * Configuration Options:
314
+ * - `wait`: Time window in milliseconds during which the function can only execute once (required)
315
+ * - `leading`: Execute immediately when called (default: true)
316
+ * - `trailing`: Execute on the trailing edge of the wait period (default: true)
317
+ * - `enabled`: Whether the throttler is enabled (default: true)
318
+ * - `asyncRetryerOptions`: Configure retry behavior for executions
319
+ *
320
+ * Error Handling:
321
+ * - If an `onError` handler is provided, it will be called with the error and throttler instance
322
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
323
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
324
+ * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
325
+ * - The error state can be checked using the underlying AsyncThrottler instance
326
+ *
327
+ * State Management:
328
+ * - Uses TanStack Store for reactive state management
329
+ * - Use `initialState` to provide initial state values when creating the async throttler
330
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
331
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
332
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
333
+ * - The state includes error count, execution status, last execution time, and success/settle counts
334
+ * - State can be accessed via the underlying AsyncThrottler instance's `store.state` property
335
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
336
+ *
337
+ * @example
338
+ * ```ts
339
+ * const throttled = asyncThrottle(async (value: string) => {
340
+ * const result = await saveToAPI(value);
341
+ * return result; // Return value is preserved
342
+ * }, {
343
+ * wait: 1000,
344
+ * onError: (error) => {
345
+ * console.error('API call failed:', error);
346
+ * }
347
+ * });
348
+ *
349
+ * // This will execute at most once per second
350
+ * // Returns the API response directly
351
+ * const result = await throttled(inputElement.value);
352
+ * ```
353
+ */
354
+ function asyncThrottle(fn, initialOptions) {
355
+ return new AsyncThrottler(fn, initialOptions).maybeExecute;
356
+ }
357
+
358
+ //#endregion
359
+ export { AsyncThrottler, asyncThrottle, asyncThrottlerOptions };
360
+ //# sourceMappingURL=async-throttler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-throttler.js","names":["defaultOptions: AsyncThrottlerOptionsWithOptionalCallbacks","fn: TFn","#getEnabled","#resolvePreviousPromiseInternal","#setState","#getWait","#execute","#resolvePreviousPromise","#timeoutId","#clearTimeout"],"sources":["../src/async-throttler.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 { AnyAsyncFunction, OptionalKeys } from './types'\n\nexport interface AsyncThrottlerState<TFn extends AnyAsyncFunction> {\n /**\n * Number of function executions that have resulted in errors\n */\n errorCount: number\n /**\n * Whether the throttled function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * The result from the most recent successful function execution\n */\n lastResult: ReturnType<TFn> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Number of function executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed\n */\n status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled'\n /**\n * Number of function executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncThrottlerState<\n TFn extends AnyAsyncFunction,\n>(): AsyncThrottlerState<TFn> {\n return {\n errorCount: 0,\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n lastResult: undefined,\n maybeExecuteCount: 0,\n nextExecutionTime: undefined,\n settleCount: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\n/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<TFn>\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: AsyncThrottler<TFn>) => boolean)\n /**\n * Initial state for the async throttler\n */\n initialState?: Partial<AsyncThrottlerState<TFn>>\n /**\n * Optional key to identify this async throttler instance.\n * If provided, the async throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute the function immediately when called\n * Defaults to true\n */\n leading?: boolean\n /**\n * Optional error handler for when the throttled function throws.\n * If provided, the handler will be called with the error and throttler 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 args: Parameters<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSettled?: (\n args: Parameters<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n args: Parameters<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\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 * Whether to execute the function on the trailing edge of the wait period\n * Defaults to true\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: AsyncThrottler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncThrottlerOptions` options between different `AsyncThrottler` instances.\n */\nexport function asyncThrottlerOptions<\n TFn extends AnyAsyncFunction = AnyAsyncFunction,\n TOptions extends Partial<AsyncThrottlerOptions<TFn>> = Partial<\n AsyncThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncThrottlerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncThrottlerOptions<any>,\n 'initialState' | 'onError' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: AsyncThrottlerOptionsWithOptionalCallbacks = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Throttler:\n * - Returns promises that can be awaited for throttled function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Cancel support to prevent pending executions from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Waits for ongoing executions to complete before scheduling the next one\n *\n * The sync Throttler is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Throttling?\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler 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 throttler\n * - Use `onSuccess` callback to react to successful function execution and implement custom logic\n * - Use `onError` callback to react to function execution errors and implement custom error handling\n * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic\n * - The state includes error count, execution status, last execution time, and success/settle counts\n * - State can be accessed via `asyncThrottler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * });\n *\n * // Will only execute once per second no matter how often called\n * // Returns the API response directly\n * const result = await throttler.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncThrottler<TFn extends AnyAsyncFunction> {\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>> = new Store<\n AsyncThrottlerState<TFn>\n >(getDefaultAsyncThrottlerState<TFn>())\n key: string | undefined\n options: AsyncThrottlerOptions<TFn>\n asyncRetryers = new Map<number, AsyncRetryer<TFn>>()\n #timeoutId: NodeJS.Timeout | null = null\n #resolvePreviousPromise:\n | ((value?: ReturnType<TFn> | undefined) => void)\n | null = null\n\n constructor(\n public fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\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-AsyncThrottler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as AsyncThrottlerState<TFn>)\n this.setOptions(event.payload.options)\n })\n }\n }\n\n /**\n * Updates the async throttler options\n */\n setOptions = (newOptions: Partial<AsyncThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // End the pending state if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<AsyncThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, isExecuting, settleCount } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : isExecuting\n ? 'executing'\n : settleCount > 0\n ? 'settled'\n : 'idle',\n }\n })\n emitChange('AsyncThrottler', this)\n }\n\n /**\n * Returns the current enabled state of the async throttler\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new AsyncThrottler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * await throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * await throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return undefined\n\n this.#resolvePreviousPromiseInternal()\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n lastArgs: args, // store the arguments for potential trailing execution\n })\n\n const wait = this.#getWait()\n const thisMaybeExecuteNumber = this.store.state.maybeExecuteCount\n\n // Wait for the wait period for the previous execution to complete if it's still running\n for (\n let maxNumIterations = wait / 10;\n this.store.state.isExecuting && maxNumIterations > 0;\n maxNumIterations--\n ) {\n await new Promise((resolve) => setTimeout(resolve, 10))\n if (this.store.state.maybeExecuteCount !== thisMaybeExecuteNumber) {\n // cancel the current maybeExecute loop because a new maybeExecute call was made\n return this.store.state.lastResult\n }\n }\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n\n if (\n this.options.leading &&\n !this.store.state.isPending &&\n timeSinceLastExecution >= wait\n ) {\n await this.#execute(...args) // Leading EXECUTE!\n } else if (this.options.trailing) {\n // replace old pending execution with a new one\n this.cancel()\n this.#setState({\n isPending: true,\n })\n\n // Set up new trailing execution\n return new Promise((resolve, reject) => {\n this.#resolvePreviousPromise = resolve\n\n const newTimeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = Math.max(0, wait - newTimeSinceLastExecution)\n\n this.#timeoutId = setTimeout(async () => {\n this.#clearTimeout()\n if (this.store.state.lastArgs !== undefined) {\n try {\n await this.#execute(...this.store.state.lastArgs) // Trailing EXECUTE!\n } catch (error) {\n reject(error)\n }\n }\n this.#resolvePreviousPromise = null\n resolve(this.store.state.lastResult)\n }, timeoutDuration)\n })\n }\n return this.store.state.lastResult\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return undefined\n\n const currentMaybeExecute = this.store.state.maybeExecuteCount\n\n try {\n this.#setState({ isExecuting: true })\n const currentAsyncRetryer = new AsyncRetryer(this.fn, {\n ...this.options.asyncRetryerOptions,\n key: `${this.key}-retryer-${currentMaybeExecute}`,\n })\n this.asyncRetryers.set(currentMaybeExecute, currentAsyncRetryer)\n const result = await currentAsyncRetryer.execute(...args) // EXECUTE!\n this.#setState({\n lastResult: result,\n successCount: this.store.state.successCount + 1,\n })\n this.options.onSuccess?.(result as ReturnType<TFn>, args, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, args, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentMaybeExecute) // dispose retryer\n const lastExecutionTime = Date.now()\n const wait = this.#getWait()\n const nextExecutionTime = lastExecutionTime + wait\n this.#setState({\n isExecuting: false,\n isPending: !!this.#timeoutId,\n settleCount: this.store.state.settleCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n })\n this.options.onSettled?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n // clear nextExecutionTime if there is no pending execution\n this.#setState({ nextExecutionTime: undefined })\n }\n }, wait)\n }\n return this.store.state.lastResult\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = async (): Promise<ReturnType<TFn> | undefined> => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n // Store the pending promise resolver before clearing timeout\n const resolvePromise = this.#resolvePreviousPromise\n\n // Clear timeout and state without resolving the promise\n this.#clearTimeout()\n this.#setState({\n isPending: false,\n })\n\n const result = await this.#execute(...this.store.state.lastArgs)\n\n // Resolve the pending promise with the result\n if (resolvePromise) {\n resolvePromise(result)\n }\n\n return result\n }\n return undefined\n }\n\n #resolvePreviousPromiseInternal = (): void => {\n if (this.#resolvePreviousPromise) {\n this.#resolvePreviousPromise(this.store.state.lastResult)\n this.#resolvePreviousPromise = null\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no maybeExecuteCount 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 maybeExecuteCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const throttler = new AsyncThrottler(\n * async (data: string) => {\n * const signal = throttler.getAbortSignal()\n * if (signal) {\n * const response = await fetch('/api/save', {\n * method: 'POST',\n * body: data,\n * signal\n * })\n * return response.json()\n * }\n * },\n * { wait: 1000 }\n * )\n * ```\n */\n getAbortSignal(maybeExecuteCount?: number): AbortSignal | null {\n const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount\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 */\n abort = (): void => {\n this.asyncRetryers.forEach((retryer) => retryer.abort())\n this.asyncRetryers.clear()\n this.#setState({ isExecuting: false })\n }\n\n /**\n * Cancels any pending execution that have not started yet.\n * Does NOT abort any execution already in progress.\n */\n cancel = (): void => {\n this.#clearTimeout()\n if (this.#resolvePreviousPromise) {\n this.#resolvePreviousPromiseInternal()\n this.#resolvePreviousPromise = null\n }\n this.#setState({\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncThrottlerState<TFn>())\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync throttle function:\n * - Returns promises that can be awaited for throttled function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Cancel support to prevent pending executions from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Waits for ongoing executions to complete before scheduling the next one\n *\n * The sync throttle function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Throttling?\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * Configuration Options:\n * - `wait`: Time window in milliseconds during which the function can only execute once (required)\n * - `leading`: Execute immediately when called (default: true)\n * - `trailing`: Execute on the trailing edge of the wait period (default: true)\n * - `enabled`: Whether the throttler is enabled (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for executions\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler 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 throttler\n * - Use `onSuccess` callback to react to successful function execution and implement custom logic\n * - Use `onError` callback to react to function execution errors and implement custom error handling\n * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic\n * - The state includes error count, execution status, last execution time, and success/settle counts\n * - State can be accessed via the underlying AsyncThrottler 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 throttled = asyncThrottle(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * });\n *\n * // This will execute at most once per second\n * // Returns the API response directly\n * const result = await throttled(inputElement.value);\n * ```\n */\nexport function asyncThrottle<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute\n}\n"],"mappings":";;;;;;AAsDA,SAAS,gCAEqB;AAC5B,QAAO;EACL,YAAY;EACZ,aAAa;EACb,WAAW;EACX,UAAU;EACV,mBAAmB;EACnB,YAAY;EACZ,mBAAmB;EACnB,mBAAmB;EACnB,aAAa;EACb,QAAQ;EACR,cAAc;EACf;;;;;AA8EH,SAAgB,sBAKd,SAA6B;AAC7B,QAAO;;AAQT,MAAMA,iBAA6D;CACjE,qBAAqB,EACnB,aAAa,GACd;CACD,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DD,IAAa,iBAAb,MAA0D;CAOxD,aAAoC;CACpC,0BAEW;CAEX,YACE,AAAOC,IACP,gBACA;EAFO;eAZmD,IAAI,MAE9D,+BAAoC,CAAC;uCAGvB,IAAI,KAAgC;qBA8BtC,eAA0D;AACtE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;AAGjD,OAAI,CAAC,MAAKC,YAAa,CACrB,MAAK,QAAQ;;sBA+DF,OACb,GAAG,SACsC;AACzC,OAAI,CAAC,MAAKA,YAAa,CAAE,QAAO;AAEhC,SAAKC,gCAAiC;AAEtC,SAAKC,SAAU;IACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB;IACxD,UAAU;IACX,CAAC;GAEF,MAAM,OAAO,MAAKC,SAAU;GAC5B,MAAM,yBAAyB,KAAK,MAAM,MAAM;AAGhD,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;;;;;;;;;;CA4BtB,eAAe,mBAAgD;EAC7D,MAAM,QAAQ,qBAAqB,KAAK,MAAM,MAAM;AAEpD,SADgB,KAAK,cAAc,IAAI,MAAM,EAC7B,gBAAgB,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGxC,SAAgB,cACd,IACA,gBACA;AAEA,QADuB,IAAI,eAAe,IAAI,eAAe,CACvC"}
@@ -0,0 +1,194 @@
1
+ const require_utils = require('./utils.cjs');
2
+ const require_event_client = require('./event-client.cjs');
3
+ let __tanstack_store = require("@tanstack/store");
4
+
5
+ //#region src/batcher.ts
6
+ function getDefaultBatcherState() {
7
+ return {
8
+ executionCount: 0,
9
+ isEmpty: true,
10
+ isPending: false,
11
+ totalItemsProcessed: 0,
12
+ items: [],
13
+ size: 0,
14
+ status: "idle"
15
+ };
16
+ }
17
+ const defaultOptions = {
18
+ getShouldExecute: () => false,
19
+ maxSize: Infinity,
20
+ started: true,
21
+ wait: Infinity
22
+ };
23
+ /**
24
+ * A class that collects items and processes them in batches.
25
+ *
26
+ * Batching is a technique for grouping multiple operations together to be processed as a single unit.
27
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
28
+ *
29
+ * The Batcher provides a flexible way to implement batching with configurable:
30
+ * - Maximum batch size (number of items per batch)
31
+ * - Time-based batching (process after X milliseconds)
32
+ * - Custom batch processing logic via getShouldExecute
33
+ * - Event callbacks for monitoring batch operations
34
+ *
35
+ * State Management:
36
+ * - Uses TanStack Store for reactive state management
37
+ * - Use `initialState` to provide initial state values when creating the batcher
38
+ * - Use `onExecute` callback to react to batch execution and implement custom logic
39
+ * - Use `onItemsChange` callback to react to items being added or removed from the batcher
40
+ * - The state includes batch execution count, total items processed, items, and running status
41
+ * - State can be accessed via `batcher.store.state` when using the class directly
42
+ * - When using framework adapters (React/Solid), state is accessed from `batcher.state`
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const batcher = new Batcher<number>(
47
+ * (items) => console.log('Processing batch:', items),
48
+ * {
49
+ * maxSize: 5,
50
+ * wait: 2000,
51
+ * onExecute: (batch, batcher) => console.log('Batch executed:', batch)
52
+ * }
53
+ * );
54
+ *
55
+ * batcher.addItem(1);
56
+ * batcher.addItem(2);
57
+ * // After 2 seconds or when 5 items are added, whichever comes first,
58
+ * // the batch will be processed
59
+ * // batcher.flush() // manually trigger a batch
60
+ * ```
61
+ */
62
+ var Batcher = class {
63
+ #timeoutId = null;
64
+ constructor(fn, initialOptions) {
65
+ this.fn = fn;
66
+ this.store = new __tanstack_store.Store(getDefaultBatcherState());
67
+ this.setOptions = (newOptions) => {
68
+ this.options = {
69
+ ...this.options,
70
+ ...newOptions
71
+ };
72
+ };
73
+ this.addItem = (item) => {
74
+ this.#setState({
75
+ items: [...this.store.state.items, item],
76
+ isPending: this.options.wait !== Infinity
77
+ });
78
+ this.options.onItemsChange?.(this);
79
+ if (this.store.state.items.length >= this.options.maxSize || this.options.getShouldExecute(this.store.state.items, this)) this.#execute();
80
+ else if (this.options.wait !== Infinity) {
81
+ this.#clearTimeout();
82
+ this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait());
83
+ }
84
+ };
85
+ this.flush = () => {
86
+ this.#clearTimeout();
87
+ this.#execute();
88
+ };
89
+ this.peekAllItems = () => {
90
+ return [...this.store.state.items];
91
+ };
92
+ this.clear = () => {
93
+ this.#setState({
94
+ items: [],
95
+ isPending: false
96
+ });
97
+ };
98
+ this.cancel = () => {
99
+ this.#clearTimeout();
100
+ this.#setState({ isPending: false });
101
+ };
102
+ this.reset = () => {
103
+ this.#setState(getDefaultBatcherState());
104
+ this.options.onItemsChange?.(this);
105
+ };
106
+ this.key = initialOptions.key;
107
+ this.options = {
108
+ ...defaultOptions,
109
+ ...initialOptions
110
+ };
111
+ this.#setState(this.options.initialState ?? {});
112
+ if (this.key) require_event_client.pacerEventClient.on("d-Batcher", (event) => {
113
+ if (event.payload.key !== this.key) return;
114
+ this.#setState(event.payload.store.state);
115
+ this.setOptions(event.payload.options);
116
+ });
117
+ }
118
+ #setState = (newState) => {
119
+ this.store.setState((state) => {
120
+ const combinedState = {
121
+ ...state,
122
+ ...newState
123
+ };
124
+ const { isPending, items } = combinedState;
125
+ const size = items.length;
126
+ const isEmpty = size === 0;
127
+ return {
128
+ ...combinedState,
129
+ isEmpty,
130
+ size,
131
+ status: isPending ? "pending" : "idle"
132
+ };
133
+ });
134
+ require_event_client.emitChange("Batcher", this);
135
+ };
136
+ #getWait = () => {
137
+ return require_utils.parseFunctionOrValue(this.options.wait, this);
138
+ };
139
+ /**
140
+ * Processes the current batch of items.
141
+ * This method will automatically be triggered if the batcher is running and any of these conditions are met:
142
+ * - The number of items reaches batchSize
143
+ * - The wait duration has elapsed
144
+ * - The getShouldExecute function returns true upon adding an item
145
+ *
146
+ * You can also call this method manually to process the current batch at any time.
147
+ */
148
+ #execute = () => {
149
+ if (this.store.state.items.length === 0) return;
150
+ const batch$1 = this.peekAllItems();
151
+ this.clear();
152
+ this.options.onItemsChange?.(this);
153
+ this.fn(batch$1);
154
+ this.#setState({
155
+ executionCount: this.store.state.executionCount + 1,
156
+ totalItemsProcessed: this.store.state.totalItemsProcessed + batch$1.length
157
+ });
158
+ this.options.onExecute?.(batch$1, this);
159
+ };
160
+ #clearTimeout = () => {
161
+ if (this.#timeoutId) {
162
+ clearTimeout(this.#timeoutId);
163
+ this.#timeoutId = null;
164
+ }
165
+ };
166
+ };
167
+ /**
168
+ * Creates a batcher that processes items in batches.
169
+ *
170
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * const batchItems = batch<number>(
175
+ * (items) => console.log('Processing:', items),
176
+ * {
177
+ * maxSize: 3,
178
+ * onExecute: (batch, batcher) => console.log('Batch executed:', batch)
179
+ * }
180
+ * );
181
+ *
182
+ * batchItems(1);
183
+ * batchItems(2);
184
+ * batchItems(3); // Triggers batch processing
185
+ * ```
186
+ */
187
+ function batch(fn, options) {
188
+ return new Batcher(fn, options).addItem;
189
+ }
190
+
191
+ //#endregion
192
+ exports.Batcher = Batcher;
193
+ exports.batch = batch;
194
+ //# sourceMappingURL=batcher.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batcher.cjs","names":["defaultOptions: BatcherOptionsWithOptionalCallbacks<any>","fn: (items: Array<TValue>) => void","Store","#setState","#execute","#clearTimeout","#timeoutId","#getWait","parseFunctionOrValue","batch"],"sources":["../src/batcher.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: 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 * 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\n */\n status: 'idle' | 'pending'\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Optional key to identify this batcher instance.\n * If provided, the 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 * Callback fired after a batch is processed\n */\n onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: 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 | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange' | 'key'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The Batcher provides a flexible way to implement 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 *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\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 batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\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\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n key: string | undefined\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Batcher', (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 batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n emitChange('Batcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\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 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 }\n }\n\n /**\n * Processes the current batch of items.\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 batchSize\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 #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\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) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(batch, this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\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 batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Cancels any pending execution that was scheduled.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({ isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;AAoCA,SAAS,yBAAuD;AAC9D,QAAO;EACL,gBAAgB;EAChB,SAAS;EACT,WAAW;EACX,qBAAqB;EACrB,OAAO,EAAE;EACT,MAAM;EACN,QAAQ;EACT;;AAqDH,MAAMA,iBAA2D;CAC/D,wBAAwB;CACxB,SAAS;CACT,SAAS;CACT,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCD,IAAa,UAAb,MAA6B;CAM3B,aAAoC;CAEpC,YACE,AAAOC,IACP,gBACA;EAFO;eAR+C,IAAIC,uBAC1D,wBAAgC,CACjC;qBA4Ba,eAAsD;AAClE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;kBA8BxC,SAAuB;AAChC,SAAKC,SAAU;IACb,OAAO,CAAC,GAAG,KAAK,MAAM,MAAM,OAAO,KAAK;IACxC,WAAW,KAAK,QAAQ,SAAS;IAClC,CAAC;AACF,QAAK,QAAQ,gBAAgB,KAAK;AAMlC,OAHE,KAAK,MAAM,MAAM,MAAM,UAAU,KAAK,QAAQ,WAC9C,KAAK,QAAQ,iBAAiB,KAAK,MAAM,MAAM,OAAO,KAAK,CAG3D,OAAKC,SAAU;YACN,KAAK,QAAQ,SAAS,UAAU;AACzC,UAAKC,cAAe;AACpB,UAAKC,YAAa,iBAAiB,MAAKF,SAAU,EAAE,MAAKG,SAAU,CAAC;;;qBAiCpD;AAClB,SAAKF,cAAe;AACpB,SAAKD,SAAU;;4BAMmB;AAClC,UAAO,CAAC,GAAG,KAAK,MAAM,MAAM,MAAM;;qBAahB;AAClB,SAAKD,SAAU;IAAE,OAAO,EAAE;IAAE,WAAW;IAAO,CAAC;;sBAO5B;AACnB,SAAKE,cAAe;AACpB,SAAKF,SAAU,EAAE,WAAW,OA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