@tanstack/pacer 0.2.0 → 0.4.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 (65) hide show
  1. package/dist/cjs/async-debouncer.cjs +78 -45
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +60 -24
  4. package/dist/cjs/async-queuer.cjs +53 -3
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +28 -3
  7. package/dist/cjs/async-rate-limiter.cjs +75 -38
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +76 -24
  10. package/dist/cjs/async-throttler.cjs +85 -57
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +66 -25
  13. package/dist/cjs/debouncer.cjs +12 -14
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +10 -9
  16. package/dist/cjs/queuer.cjs +51 -1
  17. package/dist/cjs/queuer.cjs.map +1 -1
  18. package/dist/cjs/queuer.d.cts +30 -1
  19. package/dist/cjs/rate-limiter.cjs +19 -9
  20. package/dist/cjs/rate-limiter.cjs.map +1 -1
  21. package/dist/cjs/rate-limiter.d.cts +31 -11
  22. package/dist/cjs/throttler.cjs +29 -36
  23. package/dist/cjs/throttler.cjs.map +1 -1
  24. package/dist/cjs/throttler.d.cts +16 -17
  25. package/dist/cjs/types.d.cts +2 -6
  26. package/dist/cjs/utils.cjs.map +1 -1
  27. package/dist/cjs/utils.d.cts +1 -1
  28. package/dist/esm/async-debouncer.d.ts +60 -24
  29. package/dist/esm/async-debouncer.js +78 -45
  30. package/dist/esm/async-debouncer.js.map +1 -1
  31. package/dist/esm/async-queuer.d.ts +28 -3
  32. package/dist/esm/async-queuer.js +53 -3
  33. package/dist/esm/async-queuer.js.map +1 -1
  34. package/dist/esm/async-rate-limiter.d.ts +76 -24
  35. package/dist/esm/async-rate-limiter.js +75 -38
  36. package/dist/esm/async-rate-limiter.js.map +1 -1
  37. package/dist/esm/async-throttler.d.ts +66 -25
  38. package/dist/esm/async-throttler.js +85 -57
  39. package/dist/esm/async-throttler.js.map +1 -1
  40. package/dist/esm/debouncer.d.ts +10 -9
  41. package/dist/esm/debouncer.js +12 -14
  42. package/dist/esm/debouncer.js.map +1 -1
  43. package/dist/esm/queuer.d.ts +30 -1
  44. package/dist/esm/queuer.js +51 -1
  45. package/dist/esm/queuer.js.map +1 -1
  46. package/dist/esm/rate-limiter.d.ts +31 -11
  47. package/dist/esm/rate-limiter.js +19 -9
  48. package/dist/esm/rate-limiter.js.map +1 -1
  49. package/dist/esm/throttler.d.ts +16 -17
  50. package/dist/esm/throttler.js +29 -36
  51. package/dist/esm/throttler.js.map +1 -1
  52. package/dist/esm/types.d.ts +2 -6
  53. package/dist/esm/utils.d.ts +1 -1
  54. package/dist/esm/utils.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/async-debouncer.ts +130 -81
  57. package/src/async-queuer.ts +93 -8
  58. package/src/async-rate-limiter.ts +141 -67
  59. package/src/async-throttler.ts +152 -94
  60. package/src/debouncer.ts +26 -33
  61. package/src/queuer.ts +92 -4
  62. package/src/rate-limiter.ts +56 -32
  63. package/src/throttler.ts +45 -53
  64. package/src/types.ts +2 -10
  65. package/src/utils.ts +1 -1
@@ -9,6 +9,16 @@ export interface AsyncQueuerOptions<TValue> {
9
9
  * Maximum number of concurrent tasks to process
10
10
  */
11
11
  concurrency?: number;
12
+ /**
13
+ * Maximum time in milliseconds that an item can stay in the queue
14
+ * If not provided, items will never expire
15
+ */
16
+ expirationDuration?: number;
17
+ /**
18
+ * Function to determine if an item has expired
19
+ * If provided, this overrides the expirationDuration behavior
20
+ */
21
+ getIsExpired?: (item: () => Promise<TValue>, addedAt: number) => boolean;
12
22
  /**
13
23
  * Default position to get items from during processing
14
24
  * @default 'front'
@@ -47,7 +57,11 @@ export interface AsyncQueuerOptions<TValue> {
47
57
  */
48
58
  onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
49
59
  /**
50
- * Whether the queuer should start processing tasks immediately
60
+ * Callback fired whenever an item expires in the queuer
61
+ */
62
+ onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
63
+ /**
64
+ * Whether the queuer should start processing tasks immediately or not.
51
65
  */
52
66
  started?: boolean;
53
67
  /**
@@ -65,6 +79,7 @@ export interface AsyncQueuerOptions<TValue> {
65
79
  * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
66
80
  * - Pause/resume task processing
67
81
  * - Task cancellation
82
+ * - Item expiration to clear stale items from the queue
68
83
  *
69
84
  * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
70
85
  * the next pending task is processed if below the concurrency limit.
@@ -89,7 +104,9 @@ export declare class AsyncQueuer<TValue> {
89
104
  private _activeItems;
90
105
  private _executionCount;
91
106
  private _rejectionCount;
107
+ private _expirationCount;
92
108
  private _items;
109
+ private _itemTimestamps;
93
110
  private _onErrorCallbacks;
94
111
  private _onSettledCallbacks;
95
112
  private _onSuccessCallbacks;
@@ -100,7 +117,7 @@ export declare class AsyncQueuer<TValue> {
100
117
  * Updates the queuer options
101
118
  * Returns the new options state
102
119
  */
103
- setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): AsyncQueuerOptions<TValue>;
120
+ setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void;
104
121
  /**
105
122
  * Returns the current queuer options
106
123
  */
@@ -109,6 +126,10 @@ export declare class AsyncQueuer<TValue> {
109
126
  * Processes items in the queuer
110
127
  */
111
128
  private tick;
129
+ /**
130
+ * Checks for and removes expired items from the queuer
131
+ */
132
+ private checkExpiredItems;
112
133
  /**
113
134
  * Starts the queuer and processes items
114
135
  */
@@ -191,6 +212,10 @@ export declare class AsyncQueuer<TValue> {
191
212
  * Adds a callback to be called when a task is settled
192
213
  */
193
214
  onSettled(cb: (result: TValue | Error) => void): () => void;
215
+ /**
216
+ * Returns the number of items that have expired from the queuer
217
+ */
218
+ getExpirationCount(): number;
194
219
  }
195
220
  /**
196
221
  * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
@@ -209,6 +234,6 @@ export declare class AsyncQueuer<TValue> {
209
234
  * @param options - Configuration options for the AsyncQueuer
210
235
  * @returns A bound addItem function that can be used to add tasks to the queuer
211
236
  */
212
- export declare function asyncQueue<TValue>(options?: AsyncQueuerOptions<TValue>): (fn: (() => Promise<TValue>) & {
237
+ export declare function asyncQueue<TValue>(options?: Omit<AsyncQueuerOptions<TValue>, 'started'>): (fn: (() => Promise<TValue>) & {
213
238
  priority?: number;
214
239
  }, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
@@ -2,19 +2,25 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const defaultOptions = {
4
4
  enabled: true,
5
+ onError: () => {
6
+ },
5
7
  onReject: () => {
6
8
  },
7
- onError: () => {
9
+ onSettled: () => {
8
10
  },
9
- onExecute: () => {
10
- }
11
+ onSuccess: () => {
12
+ },
13
+ windowType: "fixed"
11
14
  };
12
15
  class AsyncRateLimiter {
13
16
  constructor(fn, initialOptions) {
14
17
  this.fn = fn;
15
- this._executionCount = 0;
18
+ this._errorCount = 0;
16
19
  this._executionTimes = [];
17
20
  this._rejectionCount = 0;
21
+ this._settleCount = 0;
22
+ this._successCount = 0;
23
+ this._isExecuting = false;
18
24
  this._options = {
19
25
  ...defaultOptions,
20
26
  ...initialOptions
@@ -25,11 +31,7 @@ class AsyncRateLimiter {
25
31
  * Returns the new options state
26
32
  */
27
33
  setOptions(newOptions) {
28
- this._options = {
29
- ...this._options,
30
- ...newOptions
31
- };
32
- return this._options;
34
+ this._options = { ...this._options, ...newOptions };
33
35
  }
34
36
  /**
35
37
  * Returns the current rate limiter options
@@ -55,33 +57,42 @@ class AsyncRateLimiter {
55
57
  */
56
58
  async maybeExecute(...args) {
57
59
  this.cleanupOldExecutions();
58
- if (this._executionTimes.length < this._options.limit) {
59
- await this.executeFunction(...args);
60
- return true;
60
+ if (this._options.windowType === "sliding") {
61
+ if (this._executionTimes.length < this._options.limit) {
62
+ await this.executeFunction(...args);
63
+ return this._lastResult;
64
+ }
65
+ } else {
66
+ const now = Date.now();
67
+ const oldestExecution = Math.min(...this._executionTimes);
68
+ const isNewWindow = oldestExecution + this._options.window <= now;
69
+ if (isNewWindow || this._executionTimes.length < this._options.limit) {
70
+ await this.executeFunction(...args);
71
+ return this._lastResult;
72
+ }
61
73
  }
62
74
  this.rejectFunction();
63
- return false;
75
+ return void 0;
64
76
  }
65
77
  async executeFunction(...args) {
66
- var _a, _b;
78
+ var _a, _b, _c, _d, _e, _f;
67
79
  if (!this._options.enabled) return;
80
+ this._isExecuting = true;
68
81
  const now = Date.now();
69
- this._executionCount++;
70
82
  this._executionTimes.push(now);
71
83
  try {
72
- await this.fn(...args);
84
+ this._lastResult = await this.fn(...args);
85
+ this._successCount++;
86
+ (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
73
87
  } catch (error) {
74
- if (this._options.onError) {
75
- try {
76
- this._options.onError(error);
77
- } catch (error2) {
78
- console.error("Error in onError handler", error2);
79
- }
80
- }
81
- throw error;
88
+ this._errorCount++;
89
+ (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
82
90
  } finally {
83
- (_b = (_a = this._options).onExecute) == null ? void 0 : _b.call(_a, this);
91
+ this._isExecuting = false;
92
+ this._settleCount++;
93
+ (_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
84
94
  }
95
+ return this._lastResult;
85
96
  }
86
97
  rejectFunction() {
87
98
  this._rejectionCount++;
@@ -96,38 +107,64 @@ class AsyncRateLimiter {
96
107
  (time) => time > windowStart
97
108
  );
98
109
  }
110
+ /**
111
+ * Returns the number of remaining executions allowed in the current window
112
+ */
113
+ getRemainingInWindow() {
114
+ this.cleanupOldExecutions();
115
+ return Math.max(0, this._options.limit - this._executionTimes.length);
116
+ }
117
+ /**
118
+ * Returns the number of milliseconds until the next execution will be possible
119
+ * For fixed windows, this is the time until the current window resets
120
+ * For sliding windows, this is the time until the oldest execution expires
121
+ */
122
+ getMsUntilNextWindow() {
123
+ if (this.getRemainingInWindow() > 0) {
124
+ return 0;
125
+ }
126
+ const oldestExecution = Math.min(...this._executionTimes);
127
+ return oldestExecution + this._options.window - Date.now();
128
+ }
99
129
  /**
100
130
  * Returns the number of times the function has been executed
101
131
  */
102
- getExecutionCount() {
103
- return this._executionCount;
132
+ getSuccessCount() {
133
+ return this._successCount;
104
134
  }
105
135
  /**
106
- * Returns the number of times the function has been rejected
136
+ * Returns the number of times the function has been settled
107
137
  */
108
- getRejectionCount() {
109
- return this._rejectionCount;
138
+ getSettleCount() {
139
+ return this._settleCount;
110
140
  }
111
141
  /**
112
- * Returns the number of remaining executions allowed in the current window
142
+ * Returns the number of times the function has errored
113
143
  */
114
- getRemainingInWindow() {
115
- this.cleanupOldExecutions();
116
- return Math.max(0, this._options.limit - this._executionTimes.length);
144
+ getErrorCount() {
145
+ return this._errorCount;
117
146
  }
118
147
  /**
119
- * Returns the number of milliseconds until the next execution will be possible
148
+ * Returns the number of times the function has been rejected
120
149
  */
121
- getMsUntilNextWindow() {
122
- return this.getRemainingInWindow() * this._options.window;
150
+ getRejectionCount() {
151
+ return this._rejectionCount;
152
+ }
153
+ /**
154
+ * Returns whether the function is currently executing
155
+ */
156
+ getIsExecuting() {
157
+ return this._isExecuting;
123
158
  }
124
159
  /**
125
160
  * Resets the rate limiter state
126
161
  */
127
162
  reset() {
128
163
  this._executionTimes = [];
129
- this._executionCount = 0;
164
+ this._successCount = 0;
165
+ this._errorCount = 0;
130
166
  this._rejectionCount = 0;
167
+ this._settleCount = 0;
131
168
  }
132
169
  }
133
170
  function asyncRateLimit(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onExecute?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any, any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onReject: () => {},\n onError: () => {},\n onExecute: () => {},\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 * 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 * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _executionCount = 0\n private _executionTimes: Array<number> = []\n private _options: AsyncRateLimiterOptions<TFn, TArgs>\n private _rejectionCount = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn, TArgs>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncRateLimiterOptions<TFn, TArgs>>,\n ): AsyncRateLimiterOptions<TFn, TArgs> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn, TArgs>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn, TArgs>>\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 * @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(...args: TArgs): Promise<boolean> {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n return false\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n\n try {\n await this.fn(...args)\n } catch (error) {\n if (this._options.onError) {\n try {\n this._options.onError(error)\n } catch (error) {\n console.error('Error in onError handler', error)\n }\n }\n throw error\n } finally {\n this._options.onExecute?.(this)\n }\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._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\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 the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n return this.getRemainingInWindow() * this._options.window\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 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 * 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 * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\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 * 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<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn, TArgs>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateL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,QAAO;AACN,kBAAA,MAAM,4BAA4BA,MAAK;AAAA,QAAA;AAAA,MACjD;AAEI,YAAA;AAAA,IAAA,UACN;AACK,uBAAA,UAAS,cAAT,4BAAqB;AAAA,IAAI;AAAA,EAChC;AAAA,EAGM,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,SAAS,UAAU;AACrB,WAAA,SAAS,SAAS,IAAI;AAAA,IAAA;AAAA,EAC7B;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,SAAS;AACnC,SAAA,kBAAkB,KAAK,gBAAgB;AAAA,MAC1C,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,SAAK,qBAAqB;AACnB,WAAA,KAAK,IAAI,GAAG,KAAK,SAAS,QAAQ,KAAK,gBAAgB,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtE,uBAA+B;AAC7B,WAAO,KAAK,qBAAA,IAAyB,KAAK,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMrD,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAgCgB,SAAA,eAId,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
1
+ {"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { AnyAsyncFunction } 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 * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Optional error handler for when the rate-limited function throws\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 * Time window in milliseconds within which the limit applies\n */\n window: 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: Required<\n Omit<AsyncRateLimiterOptions<any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\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 * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\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: AsyncRateLimiterOptions<TFn>\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 }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\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(): Required<AsyncRateLimiterOptions<TFn>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn>>\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 * @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 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 < this._options.limit) {\n await this.executeFunction(...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 + this._options.window <= now\n\n if (isNewWindow || this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) 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 } 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._options.window\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._options.limit - 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._options.window - 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 * @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 * 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: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,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AK,SAAS,SAAS,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;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;AA4CgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
@@ -2,7 +2,7 @@ import { AnyAsyncFunction } from './types.cjs';
2
2
  /**
3
3
  * Options for configuring an async rate-limited function
4
4
  */
5
- export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
5
+ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
6
6
  /**
7
7
  * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
8
8
  * Defaults to true.
@@ -15,19 +15,30 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TArgs ext
15
15
  /**
16
16
  * Optional error handler for when the rate-limited function throws
17
17
  */
18
- onError?: (error: unknown) => void;
18
+ onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void;
19
+ /**
20
+ * Optional callback function that is called when an execution is rejected due to rate limiting
21
+ */
22
+ onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void;
19
23
  /**
20
24
  * Optional function to call when the rate-limited function is executed
21
25
  */
22
- onExecute?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void;
26
+ onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void;
23
27
  /**
24
- * Optional callback function that is called when an execution is rejected due to rate limiting
28
+ * Optional function to call when the rate-limited function is executed
25
29
  */
26
- onReject?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void;
30
+ onSuccess?: (result: ReturnType<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
27
31
  /**
28
32
  * Time window in milliseconds within which the limit applies
29
33
  */
30
34
  window: number;
35
+ /**
36
+ * Type of window to use for rate limiting
37
+ * - 'fixed': Uses a fixed window that resets after the window period
38
+ * - 'sliding': Uses a sliding window that allows executions as old ones expire
39
+ * Defaults to 'fixed'
40
+ */
41
+ windowType?: 'fixed' | 'sliding';
31
42
  }
32
43
  /**
33
44
  * A class that creates an async rate-limited function.
@@ -36,6 +47,16 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TArgs ext
36
47
  * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
37
48
  * all executions happen immediately, followed by a complete block.
38
49
  *
50
+ * The rate limiter supports two types of windows:
51
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
52
+ * towards the limit, and the window resets completely after the period.
53
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
54
+ * consistent rate of execution over time.
55
+ *
56
+ * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
57
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
58
+ * instead of setting the result on a state variable from within the rate-limited function.
59
+ *
39
60
  * For smoother execution patterns, consider using:
40
61
  * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
41
62
  * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
@@ -47,29 +68,34 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TArgs ext
47
68
  * ```ts
48
69
  * const rateLimiter = new AsyncRateLimiter(
49
70
  * async (id: string) => await api.getData(id),
50
- * { limit: 5, window: 1000 } // 5 calls per second
71
+ * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window
51
72
  * );
52
73
  *
53
74
  * // Will execute immediately until limit reached, then block
54
- * await rateLimiter.maybeExecute('123');
75
+ * // Returns the API response directly
76
+ * const data = await rateLimiter.maybeExecute('123');
55
77
  * ```
56
78
  */
57
- export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
79
+ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
58
80
  private fn;
59
- private _executionCount;
60
- private _executionTimes;
61
81
  private _options;
82
+ private _errorCount;
83
+ private _executionTimes;
84
+ private _lastResult;
62
85
  private _rejectionCount;
63
- constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn, TArgs>);
86
+ private _settleCount;
87
+ private _successCount;
88
+ private _isExecuting;
89
+ constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>);
64
90
  /**
65
91
  * Updates the rate limiter options
66
92
  * Returns the new options state
67
93
  */
68
- setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn, TArgs>>): AsyncRateLimiterOptions<TFn, TArgs>;
94
+ setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void;
69
95
  /**
70
96
  * Returns the current rate limiter options
71
97
  */
72
- getOptions(): Required<AsyncRateLimiterOptions<TFn, TArgs>>;
98
+ getOptions(): Required<AsyncRateLimiterOptions<TFn>>;
73
99
  /**
74
100
  * Attempts to execute the rate-limited function if within the configured limits.
75
101
  * Will reject execution if the number of calls in the current window exceeds the limit.
@@ -86,26 +112,40 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction, TArgs extend
86
112
  * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
87
113
  * ```
88
114
  */
89
- maybeExecute(...args: TArgs): Promise<boolean>;
115
+ maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
90
116
  private executeFunction;
91
117
  private rejectFunction;
92
118
  private cleanupOldExecutions;
119
+ /**
120
+ * Returns the number of remaining executions allowed in the current window
121
+ */
122
+ getRemainingInWindow(): number;
123
+ /**
124
+ * Returns the number of milliseconds until the next execution will be possible
125
+ * For fixed windows, this is the time until the current window resets
126
+ * For sliding windows, this is the time until the oldest execution expires
127
+ */
128
+ getMsUntilNextWindow(): number;
93
129
  /**
94
130
  * Returns the number of times the function has been executed
95
131
  */
96
- getExecutionCount(): number;
132
+ getSuccessCount(): number;
97
133
  /**
98
- * Returns the number of times the function has been rejected
134
+ * Returns the number of times the function has been settled
99
135
  */
100
- getRejectionCount(): number;
136
+ getSettleCount(): number;
101
137
  /**
102
- * Returns the number of remaining executions allowed in the current window
138
+ * Returns the number of times the function has errored
103
139
  */
104
- getRemainingInWindow(): number;
140
+ getErrorCount(): number;
105
141
  /**
106
- * Returns the number of milliseconds until the next execution will be possible
142
+ * Returns the number of times the function has been rejected
107
143
  */
108
- getMsUntilNextWindow(): number;
144
+ getRejectionCount(): number;
145
+ /**
146
+ * Returns whether the function is currently executing
147
+ */
148
+ getIsExecuting(): boolean;
109
149
  /**
110
150
  * Resets the rate limiter state
111
151
  */
@@ -114,6 +154,16 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction, TArgs extend
114
154
  /**
115
155
  * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
116
156
  *
157
+ * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,
158
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
159
+ * instead of setting the result on a state variable from within the rate-limited function.
160
+ *
161
+ * The rate limiter supports two types of windows:
162
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
163
+ * towards the limit, and the window resets completely after the period.
164
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
165
+ * consistent rate of execution over time.
166
+ *
117
167
  * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
118
168
  * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
119
169
  * - A throttler ensures even spacing between executions, which can be better for consistent performance
@@ -124,10 +174,11 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction, TArgs extend
124
174
  *
125
175
  * @example
126
176
  * ```ts
127
- * // Rate limit to 5 calls per minute
177
+ * // Rate limit to 5 calls per minute with a sliding window
128
178
  * const rateLimited = asyncRateLimit(makeApiCall, {
129
179
  * limit: 5,
130
180
  * window: 60000,
181
+ * windowType: 'sliding',
131
182
  * onReject: (rateLimiter) => {
132
183
  * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
133
184
  * }
@@ -135,10 +186,11 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction, TArgs extend
135
186
  *
136
187
  * // First 5 calls will execute immediately
137
188
  * // Additional calls will be rejected until the minute window resets
138
- * await rateLimited();
189
+ * // Returns the API response directly
190
+ * const result = await rateLimited();
139
191
  *
140
192
  * // For more even execution, consider using throttle instead:
141
193
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
142
194
  * ```
143
195
  */
144
- export declare function asyncRateLimit<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions<TFn, TArgs>, 'enabled'>): (...args: TArgs) => Promise<boolean>;
196
+ export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;