@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
@@ -0,0 +1,338 @@
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-debouncer.ts
7
+ function getDefaultAsyncDebouncerState() {
8
+ return {
9
+ canLeadingExecute: true,
10
+ errorCount: 0,
11
+ isExecuting: false,
12
+ isPending: false,
13
+ lastArgs: void 0,
14
+ lastResult: void 0,
15
+ maybeExecuteCount: 0,
16
+ settleCount: 0,
17
+ status: "idle",
18
+ successCount: 0
19
+ };
20
+ }
21
+ /**
22
+ * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.
23
+ */
24
+ function asyncDebouncerOptions(options) {
25
+ return options;
26
+ }
27
+ const defaultOptions = {
28
+ asyncRetryerOptions: { maxAttempts: 1 },
29
+ enabled: true,
30
+ leading: false,
31
+ trailing: true,
32
+ wait: 0
33
+ };
34
+ /**
35
+ * A class that creates an async debounced function.
36
+ *
37
+ * Async vs Sync Versions:
38
+ * The async version provides advanced features over the sync Debouncer:
39
+ * - Returns promises that can be awaited for debounced function results
40
+ * - Built-in retry support via AsyncRetryer integration
41
+ * - Abort support to cancel in-flight executions
42
+ * - Cancel support to prevent pending executions from starting
43
+ * - Comprehensive error handling with onError callbacks and throwOnError control
44
+ * - Detailed execution tracking (success/error/settle counts)
45
+ *
46
+ * The sync Debouncer is lighter weight and simpler when you don't need async features,
47
+ * return values, or execution control.
48
+ *
49
+ * What is Debouncing?
50
+ * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
51
+ * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
52
+ * or input changes where you only want to execute the handler after the events have stopped occurring.
53
+ *
54
+ * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
55
+ * the function stops being called for the specified delay period.
56
+ *
57
+ * Error Handling:
58
+ * - If an `onError` handler is provided, it will be called with the error and debouncer instance
59
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
60
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
61
+ * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
62
+ * - The error state can be checked using the underlying store
63
+ *
64
+ * State Management:
65
+ * - The debouncer uses a reactive store for state management
66
+ * - Use `initialState` to provide initial state values when creating the async debouncer
67
+ * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
68
+ * - State can be accessed via the `store` property and its `state` getter
69
+ * - The store is reactive and will notify subscribers of state changes
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
74
+ * const results = await searchAPI(value);
75
+ * return results; // Return value is preserved
76
+ * }, {
77
+ * wait: 500,
78
+ * onError: (error) => {
79
+ * console.error('Search failed:', error);
80
+ * }
81
+ * });
82
+ *
83
+ * // Called on each keystroke but only executes after 500ms of no typing
84
+ * // Returns the API response directly
85
+ * const results = await asyncDebouncer.maybeExecute(inputElement.value);
86
+ * ```
87
+ */
88
+ var AsyncDebouncer = class {
89
+ #timeoutId = null;
90
+ #resolvePreviousPromise = null;
91
+ constructor(fn, initialOptions) {
92
+ this.fn = fn;
93
+ this.store = new Store(getDefaultAsyncDebouncerState());
94
+ this.asyncRetryers = /* @__PURE__ */ new Map();
95
+ this.setOptions = (newOptions) => {
96
+ this.options = {
97
+ ...this.options,
98
+ ...newOptions
99
+ };
100
+ if (!this.#getEnabled()) this.cancel();
101
+ };
102
+ this.maybeExecute = async (...args) => {
103
+ if (!this.#getEnabled()) return void 0;
104
+ this.#cancelPendingExecution();
105
+ this.#setState({
106
+ lastArgs: args,
107
+ maybeExecuteCount: this.store.state.maybeExecuteCount + 1
108
+ });
109
+ if (this.options.leading && this.store.state.canLeadingExecute) {
110
+ this.#setState({ canLeadingExecute: false });
111
+ await this.#execute(...args);
112
+ return this.store.state.lastResult;
113
+ }
114
+ if (this.options.trailing && this.#getEnabled()) this.#setState({ isPending: true });
115
+ return new Promise((resolve, reject) => {
116
+ this.#resolvePreviousPromise = resolve;
117
+ this.#timeoutId = setTimeout(async () => {
118
+ if (this.options.trailing && this.store.state.lastArgs) try {
119
+ await this.#execute(...this.store.state.lastArgs);
120
+ } catch (error) {
121
+ reject(error);
122
+ }
123
+ this.#setState({ canLeadingExecute: true });
124
+ this.#resolvePreviousPromise = null;
125
+ resolve(this.store.state.lastResult);
126
+ }, this.#getWait());
127
+ });
128
+ };
129
+ this.flush = async () => {
130
+ if (this.store.state.isPending && this.store.state.lastArgs) {
131
+ const { lastArgs } = this.store.state;
132
+ this.#cancelPendingExecution();
133
+ return await this.#execute(...lastArgs);
134
+ }
135
+ };
136
+ this.abort = () => {
137
+ this.asyncRetryers.forEach((retryer) => retryer.abort());
138
+ this.asyncRetryers.clear();
139
+ this.#setState({ isExecuting: false });
140
+ };
141
+ this.cancel = () => {
142
+ this.#cancelPendingExecution();
143
+ this.#setState({ canLeadingExecute: true });
144
+ };
145
+ this.reset = () => {
146
+ this.#setState(getDefaultAsyncDebouncerState());
147
+ this.asyncRetryers.forEach((retryer) => retryer.reset());
148
+ };
149
+ this.key = initialOptions.key;
150
+ this.options = {
151
+ ...defaultOptions,
152
+ ...initialOptions,
153
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
154
+ };
155
+ this.#setState(this.options.initialState ?? {});
156
+ if (this.key) pacerEventClient.on("d-AsyncDebouncer", (event) => {
157
+ if (event.payload.key !== this.key) return;
158
+ this.#setState(event.payload.store.state);
159
+ this.setOptions(event.payload.options);
160
+ });
161
+ }
162
+ #setState = (newState) => {
163
+ this.store.setState((state) => {
164
+ const combinedState = {
165
+ ...state,
166
+ ...newState
167
+ };
168
+ const { isPending, isExecuting, settleCount } = combinedState;
169
+ return {
170
+ ...combinedState,
171
+ status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : isExecuting ? "executing" : settleCount > 0 ? "settled" : "idle"
172
+ };
173
+ });
174
+ emitChange("AsyncDebouncer", this);
175
+ };
176
+ /**
177
+ * Returns the current debouncer enabled state
178
+ */
179
+ #getEnabled = () => {
180
+ return !!parseFunctionOrValue(this.options.enabled, this);
181
+ };
182
+ /**
183
+ * Returns the current debouncer wait state
184
+ */
185
+ #getWait = () => {
186
+ return parseFunctionOrValue(this.options.wait, this);
187
+ };
188
+ #execute = async (...args) => {
189
+ if (!this.#getEnabled()) return void 0;
190
+ const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1;
191
+ try {
192
+ this.#setState({ isExecuting: true });
193
+ const currentAsyncRetryer = new AsyncRetryer(this.fn, {
194
+ ...this.options.asyncRetryerOptions,
195
+ key: `${this.key}-retryer-${currentMaybeExecuteCount}`
196
+ });
197
+ this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer);
198
+ const result = await currentAsyncRetryer.execute(...args);
199
+ this.#setState({
200
+ lastResult: result,
201
+ successCount: this.store.state.successCount + 1
202
+ });
203
+ this.options.onSuccess?.(result, args, this);
204
+ } catch (error) {
205
+ this.#setState({ errorCount: this.store.state.errorCount + 1 });
206
+ this.options.onError?.(error, args, this);
207
+ if (this.options.throwOnError) throw error;
208
+ } finally {
209
+ this.asyncRetryers.delete(currentMaybeExecuteCount);
210
+ this.#setState({
211
+ isExecuting: false,
212
+ isPending: false,
213
+ lastArgs: void 0,
214
+ settleCount: this.store.state.settleCount + 1
215
+ });
216
+ this.options.onSettled?.(args, this);
217
+ }
218
+ return this.store.state.lastResult;
219
+ };
220
+ #resolvePreviousPromiseInternal = () => {
221
+ if (this.#resolvePreviousPromise) {
222
+ this.#resolvePreviousPromise(this.store.state.lastResult);
223
+ this.#resolvePreviousPromise = null;
224
+ }
225
+ };
226
+ #clearTimeout = () => {
227
+ if (this.#timeoutId) {
228
+ clearTimeout(this.#timeoutId);
229
+ this.#timeoutId = null;
230
+ }
231
+ };
232
+ /**
233
+ * Internal cancel without resetting the leading execute state
234
+ */
235
+ #cancelPendingExecution = () => {
236
+ this.#clearTimeout();
237
+ this.#resolvePreviousPromiseInternal();
238
+ this.#setState({
239
+ isPending: false,
240
+ lastArgs: void 0
241
+ });
242
+ };
243
+ /**
244
+ * Returns the AbortSignal for a specific execution.
245
+ * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
246
+ * Returns null if no execution is found or not currently executing.
247
+ *
248
+ * @param maybeExecuteCount - Optional specific execution to get signal for
249
+ * @example
250
+ * ```typescript
251
+ * const debouncer = new AsyncDebouncer(
252
+ * async (searchTerm: string) => {
253
+ * const signal = debouncer.getAbortSignal()
254
+ * if (signal) {
255
+ * const response = await fetch(`/api/search?q=${searchTerm}`, { signal })
256
+ * return response.json()
257
+ * }
258
+ * },
259
+ * { wait: 300 }
260
+ * )
261
+ * ```
262
+ */
263
+ getAbortSignal(maybeExecuteCount) {
264
+ const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount;
265
+ return this.asyncRetryers.get(count)?.getAbortSignal() ?? null;
266
+ }
267
+ };
268
+ /**
269
+ * Creates an async debounced function that delays execution until after a specified wait time.
270
+ * The debounced function will only execute once the wait period has elapsed without any new calls.
271
+ * If called again during the wait period, the timer resets and a new wait period begins.
272
+ *
273
+ * Async vs Sync Versions:
274
+ * The async version provides advanced features over the sync debounce function:
275
+ * - Returns promises that can be awaited for debounced function results
276
+ * - Built-in retry support via AsyncRetryer integration
277
+ * - Abort support to cancel in-flight executions
278
+ * - Cancel support to prevent pending executions from starting
279
+ * - Comprehensive error handling with onError callbacks and throwOnError control
280
+ * - Detailed execution tracking (success/error/settle counts)
281
+ *
282
+ * The sync debounce function is lighter weight and simpler when you don't need async features,
283
+ * return values, or execution control.
284
+ *
285
+ * What is Debouncing?
286
+ * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
287
+ * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
288
+ * or input changes where you only want to execute the handler after the events have stopped occurring.
289
+ *
290
+ * Configuration Options:
291
+ * - `wait`: Delay in milliseconds to wait after the last call (required)
292
+ * - `leading`: Execute on the leading edge of the timeout (default: false)
293
+ * - `trailing`: Execute on the trailing edge of the timeout (default: true)
294
+ * - `enabled`: Whether the debouncer is enabled (default: true)
295
+ * - `asyncRetryerOptions`: Configure retry behavior for executions
296
+ *
297
+ * Error Handling:
298
+ * - If an `onError` handler is provided, it will be called with the error and debouncer instance
299
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
300
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
301
+ * - The error state can be checked using the underlying AsyncDebouncer instance
302
+ * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
303
+ *
304
+ * State Management:
305
+ * - Uses TanStack Store for reactive state management
306
+ * - Use `initialState` to provide initial state values when creating the async debouncer
307
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
308
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
309
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
310
+ * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
311
+ * - State can be accessed via `asyncDebouncer.store.state` when using the class directly
312
+ * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * const debounced = asyncDebounce(async (value: string) => {
317
+ * const result = await saveToAPI(value);
318
+ * return result; // Return value is preserved
319
+ * }, {
320
+ * wait: 1000,
321
+ * onError: (error) => {
322
+ * console.error('API call failed:', error);
323
+ * },
324
+ * throwOnError: true // Will both log the error and throw it
325
+ * });
326
+ *
327
+ * // Will only execute once, 1 second after the last call
328
+ * // Returns the API response directly
329
+ * const result = await debounced("third");
330
+ * ```
331
+ */
332
+ function asyncDebounce(fn, initialOptions) {
333
+ return new AsyncDebouncer(fn, initialOptions).maybeExecute;
334
+ }
335
+
336
+ //#endregion
337
+ export { AsyncDebouncer, asyncDebounce, asyncDebouncerOptions };
338
+ //# sourceMappingURL=async-debouncer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-debouncer.js","names":["defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks","fn: TFn","#getEnabled","#cancelPendingExecution","#setState","#execute","#resolvePreviousPromise","#timeoutId","#getWait","#clearTimeout","#resolvePreviousPromiseInternal"],"sources":["../src/async-debouncer.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 AsyncDebouncerState<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have resulted in errors\n */\n errorCount: number\n /**\n * Whether the debounced function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * Whether the debouncer 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 * 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 * 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 getDefaultAsyncDebouncerState<\n TFn extends AnyAsyncFunction,\n>(): AsyncDebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n errorCount: 0,\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n lastResult: undefined,\n maybeExecuteCount: 0,\n settleCount: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<TFn>\n /**\n * Whether the debouncer 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 | ((debouncer: AsyncDebouncer<TFn>) => boolean)\n /**\n * Initial state for the async debouncer\n */\n initialState?: Partial<AsyncDebouncerState<TFn>>\n /**\n * Optional key to identify this async debouncer instance.\n * If provided, the async debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws.\n * If provided, the handler will be called with the error and debouncer 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 debouncer: AsyncDebouncer<TFn>,\n ) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n args: Parameters<TFn>,\n debouncer: AsyncDebouncer<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 on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.\n */\nexport function asyncDebouncerOptions<\n TFn extends AnyAsyncFunction = AnyAsyncFunction,\n TOptions extends Partial<AsyncDebouncerOptions<TFn>> = Partial<\n AsyncDebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncDebouncerOptions<any>,\n 'initialState' | 'onError' | 'onSettled' | 'onSuccess' | 'key'\n>\n\nconst defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Debouncer:\n * - Returns promises that can be awaited for debounced 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 *\n * The sync Debouncer is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Debouncing?\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 store\n *\n * State Management:\n * - The debouncer uses a reactive store for state management\n * - Use `initialState` to provide initial state values when creating the async debouncer\n * - The state includes canLeadingExecute, error count, execution status, and success/settle counts\n * - State can be accessed via the `store` property and its `state` getter\n * - The store is reactive and will notify subscribers of state changes\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, {\n * wait: 500,\n * onError: (error) => {\n * console.error('Search failed:', error);\n * }\n * });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n readonly store: Store<Readonly<AsyncDebouncerState<TFn>>> = new Store<\n AsyncDebouncerState<TFn>\n >(getDefaultAsyncDebouncerState<TFn>())\n key: string | undefined\n options: AsyncDebouncerOptions<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: AsyncDebouncerOptions<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-AsyncDebouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as AsyncDebouncerState<TFn>)\n this.setOptions(event.payload.options)\n })\n }\n }\n\n /**\n * Updates the async debouncer options\n */\n setOptions = (newOptions: Partial<AsyncDebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<AsyncDebouncerState<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('AsyncDebouncer', this)\n }\n\n /**\n * Returns the current debouncer enabled state\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function.\n * If a call is already in progress, it will be queued.\n *\n * Error Handling:\n * - If the debounced function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the debounced function if no onError handler is configured\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return undefined\n this.#cancelPendingExecution()\n this.#setState({\n lastArgs: args,\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n await this.#execute(...args)\n return this.store.state.lastResult\n }\n\n // Handle trailing execution\n if (this.options.trailing && this.#getEnabled()) {\n this.#setState({ isPending: true })\n }\n\n return new Promise((resolve, reject) => {\n this.#resolvePreviousPromise = resolve\n // this.#rejectPreviousPromise = reject\n this.#timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this.options.trailing && this.store.state.lastArgs) {\n try {\n await this.#execute(...this.store.state.lastArgs)\n } catch (error) {\n reject(error)\n }\n }\n\n // Reset state and resolve\n this.#setState({ canLeadingExecute: true })\n this.#resolvePreviousPromise = null\n resolve(this.store.state.lastResult)\n }, this.#getWait())\n })\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return undefined\n const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1\n\n try {\n this.#setState({ isExecuting: true })\n const currentAsyncRetryer = new AsyncRetryer(this.fn, {\n ...this.options.asyncRetryerOptions,\n key: `${this.key}-retryer-${currentMaybeExecuteCount}`,\n })\n this.asyncRetryers.set(currentMaybeExecuteCount, 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(currentMaybeExecuteCount) // dispose retryer\n this.#setState({\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(args, this)\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 const { lastArgs } = this.store.state\n this.#cancelPendingExecution()\n return await this.#execute(...lastArgs)\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 * Internal cancel without resetting the leading execute state\n */\n #cancelPendingExecution = (): void => {\n this.#clearTimeout()\n this.#resolvePreviousPromiseInternal()\n this.#setState({\n isPending: false,\n lastArgs: undefined,\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 debouncer = new AsyncDebouncer(\n * async (searchTerm: string) => {\n * const signal = debouncer.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/search?q=${searchTerm}`, { signal })\n * return response.json()\n * }\n * },\n * { wait: 300 }\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({\n isExecuting: false,\n })\n }\n\n /**\n * Cancels any pending execution that have not started yet.\n * Does NOT abort any execution already in progress.\n */\n cancel = (): void => {\n this.#cancelPendingExecution()\n this.#setState({ canLeadingExecute: true })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncDebouncerState<TFn>())\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync debounce function:\n * - Returns promises that can be awaited for debounced 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 *\n * The sync debounce function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Debouncing?\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Configuration Options:\n * - `wait`: Delay in milliseconds to wait after the last call (required)\n * - `leading`: Execute on the leading edge of the timeout (default: false)\n * - `trailing`: Execute on the trailing edge of the timeout (default: true)\n * - `enabled`: Whether the debouncer 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 debouncer 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 * - The error state can be checked using the underlying AsyncDebouncer instance\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async debouncer\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 canLeadingExecute, error count, execution status, and success/settle counts\n * - State can be accessed via `asyncDebouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(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 * throwOnError: true // Will both log the error and throw it\n * });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute\n}\n"],"mappings":";;;;;;AAkDA,SAAS,gCAEqB;AAC5B,QAAO;EACL,mBAAmB;EACnB,YAAY;EACZ,aAAa;EACb,WAAW;EACX,UAAU;EACV,YAAY;EACZ,mBAAmB;EACnB,aAAa;EACb,QAAQ;EACR,cAAc;EACf;;;;;AA2EH,SAAgB,sBAKd,SAA6B;AAC7B,QAAO;;AAQT,MAAMA,iBAA6D;CACjE,qBAAqB,EACnB,aAAa,GACd;CACD,SAAS;CACT,SAAS;CACT,UAA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