@tanstack/pacer 0.16.3 → 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 (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 +38 -122
  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,315 +0,0 @@
1
- import { Store } from '@tanstack/store';
2
- import { AsyncRetryer, AsyncRetryerOptions } from './async-retryer.cjs';
3
- import { AnyAsyncFunction } from './types.cjs';
4
- export interface AsyncThrottlerState<TFn extends AnyAsyncFunction> {
5
- /**
6
- * Number of function executions that have resulted in errors
7
- */
8
- errorCount: number;
9
- /**
10
- * Whether the throttled function is currently executing asynchronously
11
- */
12
- isExecuting: boolean;
13
- /**
14
- * Whether the throttler is waiting for the timeout to trigger execution
15
- */
16
- isPending: boolean;
17
- /**
18
- * The arguments from the most recent call to maybeExecute
19
- */
20
- lastArgs: Parameters<TFn> | undefined;
21
- /**
22
- * Timestamp of the last function execution in milliseconds
23
- */
24
- lastExecutionTime: number;
25
- /**
26
- * The result from the most recent successful function execution
27
- */
28
- lastResult: ReturnType<TFn> | undefined;
29
- /**
30
- * Number of times maybeExecute has been called (for reduction calculations)
31
- */
32
- maybeExecuteCount: number;
33
- /**
34
- * Timestamp when the next execution can occur in milliseconds
35
- */
36
- nextExecutionTime: number | undefined;
37
- /**
38
- * Number of function executions that have completed (either successfully or with errors)
39
- */
40
- settleCount: number;
41
- /**
42
- * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed
43
- */
44
- status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled';
45
- /**
46
- * Number of function executions that have completed successfully
47
- */
48
- successCount: number;
49
- }
50
- /**
51
- * Options for configuring an async throttled function
52
- */
53
- export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
54
- /**
55
- * Options for configuring the underlying async retryer
56
- */
57
- asyncRetryerOptions?: AsyncRetryerOptions<TFn>;
58
- /**
59
- * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
60
- * Can be a boolean or a function that returns a boolean.
61
- * Defaults to true.
62
- */
63
- enabled?: boolean | ((throttler: AsyncThrottler<TFn>) => boolean);
64
- /**
65
- * Initial state for the async throttler
66
- */
67
- initialState?: Partial<AsyncThrottlerState<TFn>>;
68
- /**
69
- * Optional key to identify this async throttler instance.
70
- * If provided, the async throttler will be identified by this key in the devtools and PacerProvider if applicable.
71
- */
72
- key?: string;
73
- /**
74
- * Whether to execute the function immediately when called
75
- * Defaults to true
76
- */
77
- leading?: boolean;
78
- /**
79
- * Optional error handler for when the throttled function throws.
80
- * If provided, the handler will be called with the error and throttler instance.
81
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
82
- */
83
- onError?: (error: Error, args: Parameters<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
84
- /**
85
- * Optional function to call when the throttled function is executed
86
- */
87
- onSettled?: (args: Parameters<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
88
- /**
89
- * Optional function to call when the throttled function is executed
90
- */
91
- onSuccess?: (result: ReturnType<TFn>, args: Parameters<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
92
- /**
93
- * Whether to throw errors when they occur.
94
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
95
- * Can be explicitly set to override these defaults.
96
- */
97
- throwOnError?: boolean;
98
- /**
99
- * Whether to execute the function on the trailing edge of the wait period
100
- * Defaults to true
101
- */
102
- trailing?: boolean;
103
- /**
104
- * Time window in milliseconds during which the function can only be executed once.
105
- * Can be a number or a function that returns a number.
106
- * Defaults to 0ms
107
- */
108
- wait: number | ((throttler: AsyncThrottler<TFn>) => number);
109
- }
110
- /**
111
- * Utility function for sharing common `AsyncThrottlerOptions` options between different `AsyncThrottler` instances.
112
- */
113
- export declare function asyncThrottlerOptions<TFn extends AnyAsyncFunction = AnyAsyncFunction, TOptions extends Partial<AsyncThrottlerOptions<TFn>> = Partial<AsyncThrottlerOptions<TFn>>>(options: TOptions): TOptions;
114
- /**
115
- * A class that creates an async throttled function.
116
- *
117
- * Async vs Sync Versions:
118
- * The async version provides advanced features over the sync Throttler:
119
- * - Returns promises that can be awaited for throttled function results
120
- * - Built-in retry support via AsyncRetryer integration
121
- * - Abort support to cancel in-flight executions
122
- * - Cancel support to prevent pending executions from starting
123
- * - Comprehensive error handling with onError callbacks and throwOnError control
124
- * - Detailed execution tracking (success/error/settle counts)
125
- * - Waits for ongoing executions to complete before scheduling the next one
126
- *
127
- * The sync Throttler is lighter weight and simpler when you don't need async features,
128
- * return values, or execution control.
129
- *
130
- * What is Throttling?
131
- * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
132
- * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
133
- * regular interval regardless of how often it's called.
134
- *
135
- * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
136
- * ensure a maximum execution frequency.
137
- *
138
- * Error Handling:
139
- * - If an `onError` handler is provided, it will be called with the error and throttler instance
140
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
141
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
142
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
143
- * - The error state can be checked using the underlying AsyncThrottler instance
144
- *
145
- * State Management:
146
- * - Uses TanStack Store for reactive state management
147
- * - Use `initialState` to provide initial state values when creating the async throttler
148
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
149
- * - Use `onError` callback to react to function execution errors and implement custom error handling
150
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
151
- * - The state includes error count, execution status, last execution time, and success/settle counts
152
- * - State can be accessed via `asyncThrottler.store.state` when using the class directly
153
- * - When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`
154
- *
155
- * @example
156
- * ```ts
157
- * const throttler = new AsyncThrottler(async (value: string) => {
158
- * const result = await saveToAPI(value);
159
- * return result; // Return value is preserved
160
- * }, {
161
- * wait: 1000,
162
- * onError: (error) => {
163
- * console.error('API call failed:', error);
164
- * }
165
- * });
166
- *
167
- * // Will only execute once per second no matter how often called
168
- * // Returns the API response directly
169
- * const result = await throttler.maybeExecute(inputElement.value);
170
- * ```
171
- */
172
- export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
173
- #private;
174
- fn: TFn;
175
- readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
176
- key: string | undefined;
177
- options: AsyncThrottlerOptions<TFn>;
178
- asyncRetryers: Map<number, AsyncRetryer<TFn>>;
179
- constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>);
180
- /**
181
- * Updates the async throttler options
182
- */
183
- setOptions: (newOptions: Partial<AsyncThrottlerOptions<TFn>>) => void;
184
- /**
185
- * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
186
- *
187
- * - If enough time has passed since the last execution (>= wait period):
188
- * - With leading=true: Executes immediately
189
- * - With leading=false: Waits for the next trailing execution
190
- *
191
- * - If within the wait period:
192
- * - With trailing=true: Schedules execution for end of wait period
193
- * - With trailing=false: Drops the execution
194
- *
195
- * @example
196
- * ```ts
197
- * const throttled = new AsyncThrottler(fn, { wait: 1000 });
198
- *
199
- * // First call executes immediately
200
- * await throttled.maybeExecute('a', 'b');
201
- *
202
- * // Call during wait period - gets throttled
203
- * await throttled.maybeExecute('c', 'd');
204
- * ```
205
- */
206
- maybeExecute: (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
207
- /**
208
- * Processes the current pending execution immediately
209
- */
210
- flush: () => Promise<ReturnType<TFn> | undefined>;
211
- /**
212
- * Returns the AbortSignal for a specific execution.
213
- * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
214
- * Returns null if no execution is found or not currently executing.
215
- *
216
- * @param maybeExecuteCount - Optional specific execution to get signal for
217
- * @example
218
- * ```typescript
219
- * const throttler = new AsyncThrottler(
220
- * async (data: string) => {
221
- * const signal = throttler.getAbortSignal()
222
- * if (signal) {
223
- * const response = await fetch('/api/save', {
224
- * method: 'POST',
225
- * body: data,
226
- * signal
227
- * })
228
- * return response.json()
229
- * }
230
- * },
231
- * { wait: 1000 }
232
- * )
233
- * ```
234
- */
235
- getAbortSignal(maybeExecuteCount?: number): AbortSignal | null;
236
- /**
237
- * Aborts all ongoing executions with the internal abort controllers.
238
- * Does NOT cancel any pending execution that have not started yet.
239
- */
240
- abort: () => void;
241
- /**
242
- * Cancels any pending execution that have not started yet.
243
- * Does NOT abort any execution already in progress.
244
- */
245
- cancel: () => void;
246
- /**
247
- * Resets the debouncer state to its default values
248
- */
249
- reset: () => void;
250
- }
251
- /**
252
- * Creates an async throttled function that limits how often the function can execute.
253
- * The throttled function will execute at most once per wait period, even if called multiple times.
254
- * If called while executing, it will wait until execution completes before scheduling the next call.
255
- *
256
- * Async vs Sync Versions:
257
- * The async version provides advanced features over the sync throttle function:
258
- * - Returns promises that can be awaited for throttled function results
259
- * - Built-in retry support via AsyncRetryer integration
260
- * - Abort support to cancel in-flight executions
261
- * - Cancel support to prevent pending executions from starting
262
- * - Comprehensive error handling with onError callbacks and throwOnError control
263
- * - Detailed execution tracking (success/error/settle counts)
264
- * - Waits for ongoing executions to complete before scheduling the next one
265
- *
266
- * The sync throttle function is lighter weight and simpler when you don't need async features,
267
- * return values, or execution control.
268
- *
269
- * What is Throttling?
270
- * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
271
- * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
272
- * regular interval regardless of how often it's called.
273
- *
274
- * Configuration Options:
275
- * - `wait`: Time window in milliseconds during which the function can only execute once (required)
276
- * - `leading`: Execute immediately when called (default: true)
277
- * - `trailing`: Execute on the trailing edge of the wait period (default: true)
278
- * - `enabled`: Whether the throttler is enabled (default: true)
279
- * - `asyncRetryerOptions`: Configure retry behavior for executions
280
- *
281
- * Error Handling:
282
- * - If an `onError` handler is provided, it will be called with the error and throttler instance
283
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
284
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
285
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
286
- * - The error state can be checked using the underlying AsyncThrottler instance
287
- *
288
- * State Management:
289
- * - Uses TanStack Store for reactive state management
290
- * - Use `initialState` to provide initial state values when creating the async throttler
291
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
292
- * - Use `onError` callback to react to function execution errors and implement custom error handling
293
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
294
- * - The state includes error count, execution status, last execution time, and success/settle counts
295
- * - State can be accessed via the underlying AsyncThrottler instance's `store.state` property
296
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
297
- *
298
- * @example
299
- * ```ts
300
- * const throttled = asyncThrottle(async (value: string) => {
301
- * const result = await saveToAPI(value);
302
- * return result; // Return value is preserved
303
- * }, {
304
- * wait: 1000,
305
- * onError: (error) => {
306
- * console.error('API call failed:', error);
307
- * }
308
- * });
309
- *
310
- * // This will execute at most once per second
311
- * // Returns the API response directly
312
- * const result = await throttled(inputElement.value);
313
- * ```
314
- */
315
- export declare function asyncThrottle<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
@@ -1,132 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const store = require("@tanstack/store");
4
- const utils = require("./utils.cjs");
5
- const eventClient = require("./event-client.cjs");
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
- class Batcher {
24
- constructor(fn, initialOptions) {
25
- this.fn = fn;
26
- this.store = new store.Store(
27
- getDefaultBatcherState()
28
- );
29
- this.#timeoutId = null;
30
- this.setOptions = (newOptions) => {
31
- this.options = { ...this.options, ...newOptions };
32
- };
33
- this.#setState = (newState) => {
34
- this.store.setState((state) => {
35
- const combinedState = {
36
- ...state,
37
- ...newState
38
- };
39
- const { isPending, items } = combinedState;
40
- const size = items.length;
41
- const isEmpty = size === 0;
42
- return {
43
- ...combinedState,
44
- isEmpty,
45
- size,
46
- status: isPending ? "pending" : "idle"
47
- };
48
- });
49
- eventClient.emitChange("Batcher", this);
50
- };
51
- this.#getWait = () => {
52
- return utils.parseFunctionOrValue(this.options.wait, this);
53
- };
54
- this.addItem = (item) => {
55
- this.#setState({
56
- items: [...this.store.state.items, item],
57
- isPending: this.options.wait !== Infinity
58
- });
59
- this.options.onItemsChange?.(this);
60
- const shouldProcess = this.store.state.items.length >= this.options.maxSize || this.options.getShouldExecute(this.store.state.items, this);
61
- if (shouldProcess) {
62
- this.#execute();
63
- } else if (this.options.wait !== Infinity) {
64
- this.#clearTimeout();
65
- this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait());
66
- }
67
- };
68
- this.#execute = () => {
69
- if (this.store.state.items.length === 0) {
70
- return;
71
- }
72
- const batch2 = this.peekAllItems();
73
- this.clear();
74
- this.options.onItemsChange?.(this);
75
- this.fn(batch2);
76
- this.#setState({
77
- executionCount: this.store.state.executionCount + 1,
78
- totalItemsProcessed: this.store.state.totalItemsProcessed + batch2.length
79
- });
80
- this.options.onExecute?.(batch2, this);
81
- };
82
- this.flush = () => {
83
- this.#clearTimeout();
84
- this.#execute();
85
- };
86
- this.peekAllItems = () => {
87
- return [...this.store.state.items];
88
- };
89
- this.#clearTimeout = () => {
90
- if (this.#timeoutId) {
91
- clearTimeout(this.#timeoutId);
92
- this.#timeoutId = null;
93
- }
94
- };
95
- this.clear = () => {
96
- this.#setState({ items: [], isPending: false });
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) {
113
- eventClient.pacerEventClient.on("d-Batcher", (event) => {
114
- if (event.payload.key !== this.key) return;
115
- this.#setState(event.payload.store.state);
116
- this.setOptions(event.payload.options);
117
- });
118
- }
119
- }
120
- #timeoutId;
121
- #setState;
122
- #getWait;
123
- #execute;
124
- #clearTimeout;
125
- }
126
- function batch(fn, options) {
127
- const batcher = new Batcher(fn, options);
128
- return batcher.addItem;
129
- }
130
- exports.Batcher = Batcher;
131
- exports.batch = batch;
132
- //# sourceMappingURL=batcher.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"batcher.cjs","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"],"names":["Store","emitChange","parseFunctionOrValue","batch","pacerEventClient"],"mappings":"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"}
@@ -1,176 +0,0 @@
1
- import { Store } from '@tanstack/store';
2
- import { OptionalKeys } from './types.cjs';
3
- export interface BatcherState<TValue> {
4
- /**
5
- * Number of batch executions that have been completed
6
- */
7
- executionCount: number;
8
- /**
9
- * Whether the batcher has no items to process (items array is empty)
10
- */
11
- isEmpty: boolean;
12
- /**
13
- * Whether the batcher is waiting for the timeout to trigger batch processing
14
- */
15
- isPending: boolean;
16
- /**
17
- * Array of items currently queued for batch processing
18
- */
19
- items: Array<TValue>;
20
- /**
21
- * Number of items currently in the batch queue
22
- */
23
- size: number;
24
- /**
25
- * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout
26
- */
27
- status: 'idle' | 'pending';
28
- /**
29
- * Total number of items that have been processed across all batches
30
- */
31
- totalItemsProcessed: number;
32
- }
33
- /**
34
- * Options for configuring a Batcher instance
35
- */
36
- export interface BatcherOptions<TValue> {
37
- /**
38
- * Custom function to determine if a batch should be processed
39
- * Return true to process the batch immediately
40
- */
41
- getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean;
42
- /**
43
- * Initial state for the batcher
44
- */
45
- initialState?: Partial<BatcherState<TValue>>;
46
- /**
47
- * Optional key to identify this batcher instance.
48
- * If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.
49
- */
50
- key?: string;
51
- /**
52
- * Maximum number of items in a batch
53
- * @default Infinity
54
- */
55
- maxSize?: number;
56
- /**
57
- * Callback fired after a batch is processed
58
- */
59
- onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void;
60
- /**
61
- * Callback fired after items are added to the batcher
62
- */
63
- onItemsChange?: (batcher: Batcher<TValue>) => void;
64
- /**
65
- * Whether the batcher should start processing immediately
66
- * @default true
67
- */
68
- started?: boolean;
69
- /**
70
- * Maximum time in milliseconds to wait before processing a batch.
71
- * If the wait duration has elapsed, the batch will be processed.
72
- * If not provided, the batch will not be triggered by a timeout.
73
- * @default Infinity
74
- */
75
- wait?: number | ((batcher: Batcher<TValue>) => number);
76
- }
77
- type BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<Required<BatcherOptions<TValue>>, 'initialState' | 'onExecute' | 'onItemsChange' | 'key'>;
78
- /**
79
- * A class that collects items and processes them in batches.
80
- *
81
- * Batching is a technique for grouping multiple operations together to be processed as a single unit.
82
- * 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.
83
- *
84
- * The Batcher provides a flexible way to implement batching with configurable:
85
- * - Maximum batch size (number of items per batch)
86
- * - Time-based batching (process after X milliseconds)
87
- * - Custom batch processing logic via getShouldExecute
88
- * - Event callbacks for monitoring batch operations
89
- *
90
- * State Management:
91
- * - Uses TanStack Store for reactive state management
92
- * - Use `initialState` to provide initial state values when creating the batcher
93
- * - Use `onExecute` callback to react to batch execution and implement custom logic
94
- * - Use `onItemsChange` callback to react to items being added or removed from the batcher
95
- * - The state includes batch execution count, total items processed, items, and running status
96
- * - State can be accessed via `batcher.store.state` when using the class directly
97
- * - When using framework adapters (React/Solid), state is accessed from `batcher.state`
98
- *
99
- * @example
100
- * ```ts
101
- * const batcher = new Batcher<number>(
102
- * (items) => console.log('Processing batch:', items),
103
- * {
104
- * maxSize: 5,
105
- * wait: 2000,
106
- * onExecute: (batch, batcher) => console.log('Batch executed:', batch)
107
- * }
108
- * );
109
- *
110
- * batcher.addItem(1);
111
- * batcher.addItem(2);
112
- * // After 2 seconds or when 5 items are added, whichever comes first,
113
- * // the batch will be processed
114
- * // batcher.flush() // manually trigger a batch
115
- * ```
116
- */
117
- export declare class Batcher<TValue> {
118
- #private;
119
- fn: (items: Array<TValue>) => void;
120
- readonly store: Store<Readonly<BatcherState<TValue>>>;
121
- key: string | undefined;
122
- options: BatcherOptionsWithOptionalCallbacks<TValue>;
123
- constructor(fn: (items: Array<TValue>) => void, initialOptions: BatcherOptions<TValue>);
124
- /**
125
- * Updates the batcher options
126
- */
127
- setOptions: (newOptions: Partial<BatcherOptions<TValue>>) => void;
128
- /**
129
- * Adds an item to the batcher
130
- * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
131
- */
132
- addItem: (item: TValue) => void;
133
- /**
134
- * Processes the current batch of items immediately
135
- */
136
- flush: () => void;
137
- /**
138
- * Returns a copy of all items in the batcher
139
- */
140
- peekAllItems: () => Array<TValue>;
141
- /**
142
- * Removes all items from the batcher
143
- */
144
- clear: () => void;
145
- /**
146
- * Cancels any pending execution that was scheduled.
147
- * Does NOT clear out the items.
148
- */
149
- cancel: () => void;
150
- /**
151
- * Resets the batcher state to its default values
152
- */
153
- reset: () => void;
154
- }
155
- /**
156
- * Creates a batcher that processes items in batches.
157
- *
158
- * 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.
159
- *
160
- * @example
161
- * ```ts
162
- * const batchItems = batch<number>(
163
- * (items) => console.log('Processing:', items),
164
- * {
165
- * maxSize: 3,
166
- * onExecute: (batch, batcher) => console.log('Batch executed:', batch)
167
- * }
168
- * );
169
- *
170
- * batchItems(1);
171
- * batchItems(2);
172
- * batchItems(3); // Triggers batch processing
173
- * ```
174
- */
175
- export declare function batch<TValue>(fn: (items: Array<TValue>) => void, options: BatcherOptions<TValue>): (item: TValue) => void;
176
- export {};