@tanstack/pacer 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/cjs/async-batcher.cjs +163 -0
  2. package/dist/cjs/async-batcher.cjs.map +1 -0
  3. package/dist/cjs/async-batcher.d.cts +273 -0
  4. package/dist/cjs/async-debouncer.cjs +149 -162
  5. package/dist/cjs/async-debouncer.cjs.map +1 -1
  6. package/dist/cjs/async-debouncer.d.cts +76 -57
  7. package/dist/cjs/async-queuer.cjs +282 -343
  8. package/dist/cjs/async-queuer.cjs.map +1 -1
  9. package/dist/cjs/async-queuer.d.cts +121 -100
  10. package/dist/cjs/async-rate-limiter.cjs +128 -185
  11. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  12. package/dist/cjs/async-rate-limiter.d.cts +72 -61
  13. package/dist/cjs/async-throttler.cjs +168 -178
  14. package/dist/cjs/async-throttler.cjs.map +1 -1
  15. package/dist/cjs/async-throttler.d.cts +97 -69
  16. package/dist/cjs/batcher.cjs +110 -119
  17. package/dist/cjs/batcher.cjs.map +1 -1
  18. package/dist/cjs/batcher.d.cts +76 -51
  19. package/dist/cjs/debouncer.cjs +97 -85
  20. package/dist/cjs/debouncer.cjs.map +1 -1
  21. package/dist/cjs/debouncer.d.cts +54 -26
  22. package/dist/cjs/index.cjs +3 -6
  23. package/dist/cjs/index.cjs.map +1 -1
  24. package/dist/cjs/index.d.cts +1 -1
  25. package/dist/cjs/queuer.cjs +246 -294
  26. package/dist/cjs/queuer.cjs.map +1 -1
  27. package/dist/cjs/queuer.d.cts +102 -81
  28. package/dist/cjs/rate-limiter.cjs +97 -130
  29. package/dist/cjs/rate-limiter.cjs.map +1 -1
  30. package/dist/cjs/rate-limiter.d.cts +50 -37
  31. package/dist/cjs/throttler.cjs +107 -123
  32. package/dist/cjs/throttler.cjs.map +1 -1
  33. package/dist/cjs/throttler.d.cts +59 -35
  34. package/dist/cjs/utils.cjs +0 -13
  35. package/dist/cjs/utils.cjs.map +1 -1
  36. package/dist/cjs/utils.d.cts +0 -1
  37. package/dist/esm/async-batcher.d.ts +273 -0
  38. package/dist/esm/async-batcher.js +163 -0
  39. package/dist/esm/async-batcher.js.map +1 -0
  40. package/dist/esm/async-debouncer.d.ts +76 -57
  41. package/dist/esm/async-debouncer.js +149 -162
  42. package/dist/esm/async-debouncer.js.map +1 -1
  43. package/dist/esm/async-queuer.d.ts +121 -100
  44. package/dist/esm/async-queuer.js +282 -343
  45. package/dist/esm/async-queuer.js.map +1 -1
  46. package/dist/esm/async-rate-limiter.d.ts +72 -61
  47. package/dist/esm/async-rate-limiter.js +128 -185
  48. package/dist/esm/async-rate-limiter.js.map +1 -1
  49. package/dist/esm/async-throttler.d.ts +97 -69
  50. package/dist/esm/async-throttler.js +168 -178
  51. package/dist/esm/async-throttler.js.map +1 -1
  52. package/dist/esm/batcher.d.ts +76 -51
  53. package/dist/esm/batcher.js +110 -119
  54. package/dist/esm/batcher.js.map +1 -1
  55. package/dist/esm/debouncer.d.ts +54 -26
  56. package/dist/esm/debouncer.js +97 -85
  57. package/dist/esm/debouncer.js.map +1 -1
  58. package/dist/esm/index.d.ts +1 -1
  59. package/dist/esm/index.js +4 -7
  60. package/dist/esm/queuer.d.ts +102 -81
  61. package/dist/esm/queuer.js +246 -294
  62. package/dist/esm/queuer.js.map +1 -1
  63. package/dist/esm/rate-limiter.d.ts +50 -37
  64. package/dist/esm/rate-limiter.js +97 -130
  65. package/dist/esm/rate-limiter.js.map +1 -1
  66. package/dist/esm/throttler.d.ts +59 -35
  67. package/dist/esm/throttler.js +107 -123
  68. package/dist/esm/throttler.js.map +1 -1
  69. package/dist/esm/utils.d.ts +0 -1
  70. package/dist/esm/utils.js +0 -13
  71. package/dist/esm/utils.js.map +1 -1
  72. package/package.json +14 -11
  73. package/src/async-batcher.ts +475 -0
  74. package/src/async-debouncer.ts +201 -121
  75. package/src/async-queuer.ts +337 -216
  76. package/src/async-rate-limiter.ts +176 -136
  77. package/src/async-throttler.ts +233 -139
  78. package/src/batcher.ts +158 -92
  79. package/src/debouncer.ts +135 -52
  80. package/src/index.ts +1 -1
  81. package/src/queuer.ts +348 -226
  82. package/src/rate-limiter.ts +125 -80
  83. package/src/throttler.ts +152 -78
  84. package/src/utils.ts +0 -15
  85. package/dist/cjs/compare.cjs +0 -72
  86. package/dist/cjs/compare.cjs.map +0 -1
  87. package/dist/cjs/compare.d.cts +0 -12
  88. package/dist/esm/compare.d.ts +0 -12
  89. package/dist/esm/compare.js +0 -72
  90. package/dist/esm/compare.js.map +0 -1
  91. package/src/compare.ts +0 -105
@@ -1,204 +1,147 @@
1
+ import { Store } from "@tanstack/store";
1
2
  import { parseFunctionOrValue } from "./utils.js";
3
+ function getDefaultAsyncRateLimiterState() {
4
+ return {
5
+ errorCount: 0,
6
+ executionTimes: [],
7
+ isExecuting: false,
8
+ lastResult: void 0,
9
+ rejectionCount: 0,
10
+ settleCount: 0,
11
+ successCount: 0
12
+ };
13
+ }
2
14
  const defaultOptions = {
3
15
  enabled: true,
4
- windowType: "fixed"
16
+ limit: 1,
17
+ window: 0,
18
+ windowType: "fixed",
19
+ throwOnError: true
5
20
  };
6
21
  class AsyncRateLimiter {
7
22
  constructor(fn, initialOptions) {
8
23
  this.fn = fn;
9
- this._errorCount = 0;
10
- this._executionTimes = [];
11
- this._rejectionCount = 0;
12
- this._settleCount = 0;
13
- this._successCount = 0;
14
- this._isExecuting = false;
15
- this._options = {
16
- ...defaultOptions,
17
- ...initialOptions,
18
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
24
+ this.store = new Store(getDefaultAsyncRateLimiterState());
25
+ this.setOptions = (newOptions) => {
26
+ this.options = { ...this.options, ...newOptions };
19
27
  };
20
- }
21
- /**
22
- * Updates the rate limiter options
23
- */
24
- setOptions(newOptions) {
25
- this._options = { ...this._options, ...newOptions };
26
- }
27
- /**
28
- * Returns the current rate limiter options
29
- */
30
- getOptions() {
31
- return this._options;
32
- }
33
- /**
34
- * Returns the current enabled state of the rate limiter
35
- */
36
- getEnabled() {
37
- return !!parseFunctionOrValue(this._options.enabled, this);
38
- }
39
- /**
40
- * Returns the current limit of executions allowed within the time window
41
- */
42
- getLimit() {
43
- return parseFunctionOrValue(this._options.limit, this);
44
- }
45
- /**
46
- * Returns the current time window in milliseconds
47
- */
48
- getWindow() {
49
- return parseFunctionOrValue(this._options.window, this);
50
- }
51
- /**
52
- * Attempts to execute the rate-limited function if within the configured limits.
53
- * Will reject execution if the number of calls in the current window exceeds the limit.
54
- * If execution is allowed, waits for any previous execution to complete before proceeding.
55
- *
56
- * Error Handling:
57
- * - If the rate-limited function throws and no `onError` handler is configured,
58
- * the error will be thrown from this method.
59
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
60
- * and this method will return undefined.
61
- * - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler
62
- * will be called if configured.
63
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
64
- * - Rate limit rejections can be tracked using `getRejectionCount()`.
65
- *
66
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
67
- * @throws The error from the rate-limited function if no onError handler is configured
68
- *
69
- * @example
70
- * ```ts
71
- * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
72
- *
73
- * // First 5 calls will execute
74
- * await rateLimiter.maybeExecute('arg1', 'arg2');
75
- *
76
- * // Additional calls within the window will be rejected
77
- * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
78
- * ```
79
- */
80
- async maybeExecute(...args) {
81
- this.cleanupOldExecutions();
82
- const limit = this.getLimit();
83
- const window = this.getWindow();
84
- if (this._options.windowType === "sliding") {
85
- if (this._executionTimes.length < limit) {
86
- await this.execute(...args);
87
- return this._lastResult;
28
+ this.#setState = (newState) => {
29
+ this.store.setState((state) => {
30
+ const combinedState = {
31
+ ...state,
32
+ ...newState
33
+ };
34
+ return combinedState;
35
+ });
36
+ };
37
+ this.#getEnabled = () => {
38
+ return !!parseFunctionOrValue(this.options.enabled, this);
39
+ };
40
+ this.#getLimit = () => {
41
+ return parseFunctionOrValue(this.options.limit, this);
42
+ };
43
+ this.#getWindow = () => {
44
+ return parseFunctionOrValue(this.options.window, this);
45
+ };
46
+ this.maybeExecute = async (...args) => {
47
+ this.#cleanupOldExecutions();
48
+ const relevantExecutionTimes = this.#getRelevantExecutionTimes();
49
+ if (relevantExecutionTimes.length < this.#getLimit()) {
50
+ await this.#execute(...args);
51
+ return this.store.state.lastResult;
88
52
  }
89
- } else {
53
+ this.#setState({
54
+ rejectionCount: this.store.state.rejectionCount + 1
55
+ });
56
+ this.options.onReject?.(this);
57
+ return void 0;
58
+ };
59
+ this.#execute = async (...args) => {
60
+ if (!this.#getEnabled()) return;
90
61
  const now = Date.now();
91
- const oldestExecution = Math.min(...this._executionTimes);
92
- const isNewWindow = oldestExecution + window <= now;
93
- if (isNewWindow || this._executionTimes.length < limit) {
94
- await this.execute(...args);
95
- return this._lastResult;
62
+ const executionTimes = [...this.store.state.executionTimes, now];
63
+ this.#setState({
64
+ isExecuting: true,
65
+ executionTimes
66
+ });
67
+ try {
68
+ const result = await this.fn(...args);
69
+ this.#setState({
70
+ successCount: this.store.state.successCount + 1,
71
+ lastResult: result
72
+ });
73
+ this.options.onSuccess?.(result, this);
74
+ } catch (error) {
75
+ this.#setState({
76
+ errorCount: this.store.state.errorCount + 1
77
+ });
78
+ this.options.onError?.(error, this);
79
+ if (this.options.throwOnError) {
80
+ throw error;
81
+ }
82
+ } finally {
83
+ this.#setState({
84
+ isExecuting: false,
85
+ settleCount: this.store.state.settleCount + 1
86
+ });
87
+ this.options.onSettled?.(this);
96
88
  }
97
- }
98
- this.rejectFunction();
99
- return void 0;
100
- }
101
- async execute(...args) {
102
- var _a, _b, _c, _d, _e, _f;
103
- if (!this.getEnabled()) return;
104
- this._isExecuting = true;
105
- const now = Date.now();
106
- this._executionTimes.push(now);
107
- try {
108
- this._lastResult = await this.fn(...args);
109
- this._successCount++;
110
- (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
111
- } catch (error) {
112
- this._errorCount++;
113
- (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
114
- if (this._options.throwOnError) {
115
- throw error;
89
+ return this.store.state.lastResult;
90
+ };
91
+ this.#getRelevantExecutionTimes = () => {
92
+ if (this.options.windowType === "sliding") {
93
+ return this.store.state.executionTimes.filter(
94
+ (time) => time > Date.now() - this.#getWindow()
95
+ );
116
96
  } else {
117
- console.error(error);
97
+ const oldestExecution = Math.min(...this.store.state.executionTimes);
98
+ const windowStart = oldestExecution;
99
+ return this.store.state.executionTimes.filter(
100
+ (time) => time >= windowStart && time <= windowStart + this.#getWindow()
101
+ );
118
102
  }
119
- } finally {
120
- this._isExecuting = false;
121
- this._settleCount++;
122
- (_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
123
- }
124
- return this._lastResult;
125
- }
126
- rejectFunction() {
127
- this._rejectionCount++;
128
- if (this._options.onReject) {
129
- this._options.onReject(this);
130
- }
131
- }
132
- cleanupOldExecutions() {
133
- const now = Date.now();
134
- const windowStart = now - this.getWindow();
135
- this._executionTimes = this._executionTimes.filter(
136
- (time) => time > windowStart
137
- );
138
- }
139
- /**
140
- * Returns the number of remaining executions allowed in the current window
141
- */
142
- getRemainingInWindow() {
143
- this.cleanupOldExecutions();
144
- return Math.max(0, this.getLimit() - this._executionTimes.length);
145
- }
146
- /**
147
- * Returns the number of milliseconds until the next execution will be possible
148
- * For fixed windows, this is the time until the current window resets
149
- * For sliding windows, this is the time until the oldest execution expires
150
- */
151
- getMsUntilNextWindow() {
152
- if (this.getRemainingInWindow() > 0) {
153
- return 0;
154
- }
155
- const oldestExecution = Math.min(...this._executionTimes);
156
- return oldestExecution + this.getWindow() - Date.now();
157
- }
158
- /**
159
- * Returns the number of times the function has been executed
160
- */
161
- getSuccessCount() {
162
- return this._successCount;
163
- }
164
- /**
165
- * Returns the number of times the function has been settled
166
- */
167
- getSettleCount() {
168
- return this._settleCount;
169
- }
170
- /**
171
- * Returns the number of times the function has errored
172
- */
173
- getErrorCount() {
174
- return this._errorCount;
175
- }
176
- /**
177
- * Returns the number of times the function has been rejected
178
- */
179
- getRejectionCount() {
180
- return this._rejectionCount;
181
- }
182
- /**
183
- * Returns whether the function is currently executing
184
- */
185
- getIsExecuting() {
186
- return this._isExecuting;
187
- }
188
- /**
189
- * Resets the rate limiter state
190
- */
191
- reset() {
192
- this._executionTimes = [];
193
- this._successCount = 0;
194
- this._errorCount = 0;
195
- this._rejectionCount = 0;
196
- this._settleCount = 0;
197
- }
103
+ };
104
+ this.#cleanupOldExecutions = () => {
105
+ const now = Date.now();
106
+ const windowStart = now - this.#getWindow();
107
+ this.#setState({
108
+ executionTimes: this.store.state.executionTimes.filter(
109
+ (time) => time > windowStart
110
+ )
111
+ });
112
+ };
113
+ this.getRemainingInWindow = () => {
114
+ const relevantExecutionTimes = this.#getRelevantExecutionTimes();
115
+ return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
116
+ };
117
+ this.getMsUntilNextWindow = () => {
118
+ if (this.getRemainingInWindow() > 0) {
119
+ return 0;
120
+ }
121
+ const oldestExecution = this.store.state.executionTimes[0] ?? Infinity;
122
+ return oldestExecution + this.#getWindow() - Date.now();
123
+ };
124
+ this.reset = () => {
125
+ this.#setState(getDefaultAsyncRateLimiterState());
126
+ };
127
+ this.options = {
128
+ ...defaultOptions,
129
+ ...initialOptions,
130
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
131
+ };
132
+ this.#setState(this.options.initialState ?? {});
133
+ }
134
+ #setState;
135
+ #getEnabled;
136
+ #getLimit;
137
+ #getWindow;
138
+ #execute;
139
+ #getRelevantExecutionTimes;
140
+ #cleanupOldExecutions;
198
141
  }
199
142
  function asyncRateLimit(fn, initialOptions) {
200
143
  const rateLimiter = new AsyncRateLimiter(fn, initialOptions);
201
- return rateLimiter.maybeExecute.bind(rateLimiter);
144
+ return rateLimiter.maybeExecute;
202
145
  }
203
146
  export {
204
147
  AsyncRateLimiter,
@@ -1 +1 @@
1
- {"version":3,"file":"async-rate-limiter.js","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter 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 | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean)\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a function that returns a number.\n */\n limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Optional error handler for when the rate-limited function throws.\n * If provided, the handler will be called with the error and rate limiter instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<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 * Time window in milliseconds within which the limit applies.\n * Can be a number or a function that returns a number.\n */\n window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\ntype AsyncRateLimiterOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncRateLimiterOptions<any>,\n 'onError' | 'onReject' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: Omit<\n AsyncRateLimiterOptionsWithOptionalCallbacks,\n 'limit' | 'window'\n> = {\n enabled: true,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (limiter) => {\n * console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);\n * }\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptionsWithOptionalCallbacks\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n private _isExecuting = false\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): AsyncRateLimiterOptions<TFn> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n getEnabled(): boolean {\n return !!parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n getLimit(): number {\n return parseFunctionOrValue(this._options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n getWindow(): number {\n return parseFunctionOrValue(this._options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * Error Handling:\n * - If the rate-limited 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 * - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler\n * will be called if configured.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n * - Rate limit rejections can be tracked using `getRejectionCount()`.\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 rate-limited function if no onError handler is configured\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n const limit = this.getLimit()\n const window = this.getWindow()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < limit) {\n await this.execute(...args)\n return this._lastResult\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + window <= now\n\n if (isNewWindow || this._executionTimes.length < limit) {\n await this.execute(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async execute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return\n this._isExecuting = true\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\n this._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.getWindow()\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.getLimit() - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns whether the function is currently executing\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 0\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";AAgEA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,YAAY;AACd;AAwDO,MAAM,iBAA+C;AAAA,EAU1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,eAAe;AAMrB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,MACH,cAAc,eAAe,gBAAgB,CAAC,eAAe;AAAA,IAC/D;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,WAAW,YAAyD;AAClE,SAAK,WAAW,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AK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,gBAAgB;AACrB,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AAuDgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
1
+ {"version":3,"file":"async-rate-limiter.js","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\n\nexport interface AsyncRateLimiterState<TFn extends AnyAsyncFunction> {\n /**\n * Number of function executions that have resulted in errors\n */\n errorCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate-limited function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * The result from the most recent successful function execution\n */\n lastResult: ReturnType<TFn> | undefined\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Number of function executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Number of function executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncRateLimiterState<\n TFn extends AnyAsyncFunction,\n>(): AsyncRateLimiterState<TFn> {\n return {\n errorCount: 0,\n executionTimes: [],\n isExecuting: false,\n lastResult: undefined,\n rejectionCount: 0,\n settleCount: 0,\n successCount: 0,\n }\n}\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter 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 | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<AsyncRateLimiterState<TFn>>\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a function that returns a number.\n */\n limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Optional error handler for when the rate-limited function throws.\n * If provided, the handler will be called with the error and rate limiter instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<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 * Time window in milliseconds within which the limit applies.\n * Can be a number or a function that returns a number.\n */\n window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Omit<\n Required<AsyncRateLimiterOptions<any>>,\n 'initialState' | 'onError' | 'onReject' | 'onSettled' | 'onSuccess'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n throwOnError: true,\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - `initialState` can be a partial state object\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 * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution times, success/error counts, and current execution status\n * - State can be accessed via `asyncRateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncRateLimiter.state`\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (limiter) => {\n * console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);\n * }\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>> = new Store<\n AsyncRateLimiterState<TFn>\n >(getDefaultAsyncRateLimiterState<TFn>())\n options: AsyncRateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the async rate limiter options\n */\n setOptions = (newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncRateLimiterState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n return combinedState\n })\n }\n\n /**\n * Returns the current enabled state of the async rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * Error Handling:\n * - If the rate-limited 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 rate-limited function if no onError handler is configured\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return a promise that resolves with the result\n * const result = await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will return undefined\n * const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined\n * ```\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getRelevantExecutionTimes()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n await this.#execute(...args)\n return this.store.state.lastResult\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return undefined\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return\n\n const now = Date.now()\n const executionTimes = [...this.store.state.executionTimes, now]\n this.#setState({\n isExecuting: true,\n executionTimes,\n })\n\n try {\n const result = await this.fn(...args)\n this.#setState({\n successCount: this.store.state.successCount + 1,\n lastResult: result,\n })\n this.options.onSuccess?.(result, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.#setState({\n isExecuting: false,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(this)\n }\n\n return this.store.state.lastResult\n }\n\n #getRelevantExecutionTimes = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n return this.store.state.executionTimes.filter(\n (time) =>\n time >= windowStart && time <= windowStart + this.#getWindow(),\n )\n }\n }\n\n #cleanupOldExecutions = (): void => {\n const now = Date.now()\n const windowStart = now - this.#getWindow()\n this.#setState({\n executionTimes: this.store.state.executionTimes.filter(\n (time) => time > windowStart,\n ),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getRelevantExecutionTimes()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncRateLimiterState())\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - `initialState` can be a partial state object\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 * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution times, success/error counts, and current execution status\n * - State can be accessed via the underlying AsyncRateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"names":[],"mappings":";;AAmCA,SAAS,kCAEuB;AAC9B,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,gBAAgB,CAAA;AAAA,IAChB,aAAa;AAAA,IACb,YAAY;AAAA,IACZ,gBAAgB;AAAA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AAC/B,WAAK,UAAU;AAAA,QACb,gBAAgB,KAAK,MAAM,MAAM,eAAe;AAAA,UAC9C,CAAC,SAAS,OAAO;AAAA,QAAA;AAAA,MACnB,CACD;AAAA,IAAA;AAMH,SAAA,uBAAuB,MAAc;AACnC,YAAM,yBAAyB,KAAK,2BAAA;AACpC,aAAO,KAAK,IAAI,GAAG,KAAK,UAAA,IAAc,uBAAuB,MAAM;AAAA,IAAA;AAQrE,SAAA,uBAAuB,MAAc;AACnC,UAAI,KAAK,qBAAA,IAAyB,GAAG;AACnC,eAAO;AAAA,MAAA;AAET,YAAM,kBAAkB,KAAK,MAAM,MAAM,eAAe,CAAC,KAAK;AAC9D,aAAO,kBAAkB,KAAK,WAAA,IAAe,KAAK,IAAA;AAAA,IAAI;AAMxD,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,iCAAiC;AAAA,IAAA;AArLhD,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,MACH,cAAc,eAAe,gBAAgB,CAAC,eAAe;AAAA,IAAA;AAE/D,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAAA,EAAA;AAAA,EAUhD;AAAA,EAaA;AAAA,EAOA;AAAA,EAOA;AAAA,EAgDA;AAAA,EAsCA;AAAA,EAkBA;AAqCF;AAmEO,SAAS,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AAC3D,SAAO,YAAY;AACrB;"}
@@ -1,4 +1,47 @@
1
+ import { Store } from '@tanstack/store';
1
2
  import { AnyAsyncFunction } from './types.js';
3
+ export interface AsyncThrottlerState<TFn extends AnyAsyncFunction> {
4
+ /**
5
+ * Number of function executions that have resulted in errors
6
+ */
7
+ errorCount: number;
8
+ /**
9
+ * Whether the throttled function is currently executing asynchronously
10
+ */
11
+ isExecuting: boolean;
12
+ /**
13
+ * Whether the throttler is waiting for the timeout to trigger execution
14
+ */
15
+ isPending: boolean;
16
+ /**
17
+ * The arguments from the most recent call to maybeExecute
18
+ */
19
+ lastArgs: Parameters<TFn> | undefined;
20
+ /**
21
+ * Timestamp of the last function execution in milliseconds
22
+ */
23
+ lastExecutionTime: number;
24
+ /**
25
+ * The result from the most recent successful function execution
26
+ */
27
+ lastResult: ReturnType<TFn> | undefined;
28
+ /**
29
+ * Timestamp when the next execution can occur in milliseconds
30
+ */
31
+ nextExecutionTime: number;
32
+ /**
33
+ * Number of function executions that have completed (either successfully or with errors)
34
+ */
35
+ settleCount: number;
36
+ /**
37
+ * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed
38
+ */
39
+ status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled';
40
+ /**
41
+ * Number of function executions that have completed successfully
42
+ */
43
+ successCount: number;
44
+ }
2
45
  /**
3
46
  * Options for configuring an async throttled function
4
47
  */
@@ -9,6 +52,10 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
9
52
  * Defaults to true.
10
53
  */
11
54
  enabled?: boolean | ((throttler: AsyncThrottler<TFn>) => boolean);
55
+ /**
56
+ * Initial state for the async throttler
57
+ */
58
+ initialState?: Partial<AsyncThrottlerState<TFn>>;
12
59
  /**
13
60
  * Whether to execute the function immediately when called
14
61
  * Defaults to true
@@ -67,6 +114,16 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
67
114
  * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
68
115
  * - The error state can be checked using the underlying AsyncThrottler instance
69
116
  *
117
+ * State Management:
118
+ * - Uses TanStack Store for reactive state management
119
+ * - Use `initialState` to provide initial state values when creating the async throttler
120
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
121
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
122
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
123
+ * - The state includes error count, execution status, last execution time, and success/settle counts
124
+ * - State can be accessed via `asyncThrottler.store.state` when using the class directly
125
+ * - When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`
126
+ *
70
127
  * @example
71
128
  * ```ts
72
129
  * const throttler = new AsyncThrottler(async (value: string) => {
@@ -85,89 +142,50 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
85
142
  * ```
86
143
  */
87
144
  export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
145
+ #private;
88
146
  private fn;
89
- private _options;
90
- private _abortController;
91
- private _errorCount;
92
- private _isExecuting;
93
- private _lastArgs;
94
- private _lastExecutionTime;
95
- private _lastResult;
96
- private _nextExecutionTime;
97
- private _settleCount;
98
- private _successCount;
99
- private _timeoutId;
100
- private _resolvePreviousPromise;
147
+ readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
148
+ options: AsyncThrottlerOptions<TFn>;
101
149
  constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>);
102
150
  /**
103
- * Updates the throttler options
151
+ * Updates the async throttler options
104
152
  */
105
- setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void;
153
+ setOptions: (newOptions: Partial<AsyncThrottlerOptions<TFn>>) => void;
106
154
  /**
107
- * Returns the current options
108
- */
109
- getOptions(): AsyncThrottlerOptions<TFn>;
110
- /**
111
- * Returns the current enabled state of the throttler
112
- */
113
- getEnabled(): boolean;
114
- /**
115
- * Returns the current wait time in milliseconds
116
- */
117
- getWait(): number;
118
- /**
119
- * Attempts to execute the throttled function.
120
- * If a call is already in progress, it may be blocked or queued depending on the `wait` option.
155
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
121
156
  *
122
- * Error Handling:
123
- * - If the throttled function throws and no `onError` handler is configured,
124
- * the error will be thrown from this method.
125
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
126
- * and this method will return undefined.
127
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
157
+ * - If enough time has passed since the last execution (>= wait period):
158
+ * - With leading=true: Executes immediately
159
+ * - With leading=false: Waits for the next trailing execution
128
160
  *
129
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
130
- * @throws The error from the throttled function if no onError handler is configured
131
- */
132
- maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
133
- private execute;
134
- private resolvePreviousPromise;
135
- /**
136
- * Cancels any pending execution or aborts any execution in progress
137
- */
138
- cancel(): void;
139
- /**
140
- * Returns the last execution time
141
- */
142
- getLastExecutionTime(): number;
143
- /**
144
- * Returns the next execution time
145
- */
146
- getNextExecutionTime(): number;
147
- /**
148
- * Returns the last result of the debounced function
149
- */
150
- getLastResult(): ReturnType<TFn> | undefined;
151
- /**
152
- * Returns the number of times the function has been executed successfully
153
- */
154
- getSuccessCount(): number;
155
- /**
156
- * Returns the number of times the function has settled (completed or errored)
161
+ * - If within the wait period:
162
+ * - With trailing=true: Schedules execution for end of wait period
163
+ * - With trailing=false: Drops the execution
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * const throttled = new AsyncThrottler(fn, { wait: 1000 });
168
+ *
169
+ * // First call executes immediately
170
+ * await throttled.maybeExecute('a', 'b');
171
+ *
172
+ * // Call during wait period - gets throttled
173
+ * await throttled.maybeExecute('c', 'd');
174
+ * ```
157
175
  */
158
- getSettleCount(): number;
176
+ maybeExecute: (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
159
177
  /**
160
- * Returns the number of times the function has errored
178
+ * Processes the current pending execution immediately
161
179
  */
162
- getErrorCount(): number;
180
+ flush: () => void;
163
181
  /**
164
- * Returns the current pending state
182
+ * Cancels any pending execution or aborts any execution in progress
165
183
  */
166
- getIsPending(): boolean;
184
+ cancel: () => void;
167
185
  /**
168
- * Returns the current executing state
186
+ * Resets the debouncer state to its default values
169
187
  */
170
- getIsExecuting(): boolean;
188
+ reset: () => void;
171
189
  }
172
190
  /**
173
191
  * Creates an async throttled function that limits how often the function can execute.
@@ -185,6 +203,16 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
185
203
  * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
186
204
  * - The error state can be checked using the underlying AsyncThrottler instance
187
205
  *
206
+ * State Management:
207
+ * - Uses TanStack Store for reactive state management
208
+ * - Use `initialState` to provide initial state values when creating the async throttler
209
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
210
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
211
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
212
+ * - The state includes error count, execution status, last execution time, and success/settle counts
213
+ * - State can be accessed via the underlying AsyncThrottler instance's `store.state` property
214
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
215
+ *
188
216
  * @example
189
217
  * ```ts
190
218
  * const throttled = asyncThrottle(async (value: string) => {