@tanstack/pacer 0.1.0 → 0.3.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 (74) hide show
  1. package/dist/cjs/async-debouncer.cjs +112 -63
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +66 -25
  4. package/dist/cjs/async-queuer.cjs +198 -124
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +91 -49
  7. package/dist/cjs/async-rate-limiter.cjs +83 -55
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +55 -28
  10. package/dist/cjs/async-throttler.cjs +121 -70
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +75 -25
  13. package/dist/cjs/debouncer.cjs +45 -23
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +27 -12
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/index.d.cts +2 -0
  19. package/dist/cjs/queuer.cjs +161 -101
  20. package/dist/cjs/queuer.cjs.map +1 -1
  21. package/dist/cjs/queuer.d.cts +80 -38
  22. package/dist/cjs/rate-limiter.cjs +52 -44
  23. package/dist/cjs/rate-limiter.cjs.map +1 -1
  24. package/dist/cjs/rate-limiter.d.cts +38 -46
  25. package/dist/cjs/throttler.cjs +57 -44
  26. package/dist/cjs/throttler.cjs.map +1 -1
  27. package/dist/cjs/throttler.d.cts +35 -23
  28. package/dist/cjs/types.d.cts +8 -0
  29. package/dist/cjs/utils.cjs +13 -0
  30. package/dist/cjs/utils.cjs.map +1 -0
  31. package/dist/cjs/utils.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +66 -25
  33. package/dist/esm/async-debouncer.js +112 -63
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +91 -49
  36. package/dist/esm/async-queuer.js +198 -124
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +55 -28
  39. package/dist/esm/async-rate-limiter.js +83 -55
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +75 -25
  42. package/dist/esm/async-throttler.js +121 -70
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/debouncer.d.ts +27 -12
  45. package/dist/esm/debouncer.js +45 -23
  46. package/dist/esm/debouncer.js.map +1 -1
  47. package/dist/esm/index.d.ts +2 -0
  48. package/dist/esm/index.js +2 -0
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/queuer.d.ts +80 -38
  51. package/dist/esm/queuer.js +161 -101
  52. package/dist/esm/queuer.js.map +1 -1
  53. package/dist/esm/rate-limiter.d.ts +38 -46
  54. package/dist/esm/rate-limiter.js +52 -44
  55. package/dist/esm/rate-limiter.js.map +1 -1
  56. package/dist/esm/throttler.d.ts +35 -23
  57. package/dist/esm/throttler.js +57 -44
  58. package/dist/esm/throttler.js.map +1 -1
  59. package/dist/esm/types.d.ts +8 -0
  60. package/dist/esm/utils.d.ts +1 -0
  61. package/dist/esm/utils.js +13 -0
  62. package/dist/esm/utils.js.map +1 -0
  63. package/package.json +8 -1
  64. package/src/async-debouncer.ts +157 -88
  65. package/src/async-queuer.ts +266 -148
  66. package/src/async-rate-limiter.ts +123 -83
  67. package/src/async-throttler.ts +173 -89
  68. package/src/debouncer.ts +71 -42
  69. package/src/index.ts +2 -0
  70. package/src/queuer.ts +219 -114
  71. package/src/rate-limiter.ts +74 -88
  72. package/src/throttler.ts +83 -65
  73. package/src/types.ts +9 -0
  74. package/src/utils.ts +13 -0
@@ -1,8 +1,8 @@
1
- import { RateLimitRejectionInfo } from './rate-limiter.js';
1
+ import { AnyAsyncFunction } from './types.js';
2
2
  /**
3
3
  * Options for configuring an async rate-limited function
4
4
  */
5
- export interface AsyncRateLimiterOptions {
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.
@@ -13,17 +13,25 @@ export interface AsyncRateLimiterOptions {
13
13
  */
14
14
  limit: number;
15
15
  /**
16
- * Time window in milliseconds within which the limit applies
16
+ * Optional error handler for when the rate-limited function throws
17
17
  */
18
- window: number;
18
+ onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void;
19
+ /**
20
+ * Optional function to call when the rate-limited function is executed
21
+ */
22
+ onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void;
23
+ /**
24
+ * Optional function to call when the rate-limited function is executed
25
+ */
26
+ onSuccess?: (result: ReturnType<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
19
27
  /**
20
28
  * Optional callback function that is called when an execution is rejected due to rate limiting
21
29
  */
22
- onReject?: (info: RateLimitRejectionInfo) => void;
30
+ onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void;
23
31
  /**
24
- * Optional error handler for when the rate-limited function throws
32
+ * Time window in milliseconds within which the limit applies
25
33
  */
26
- onError?: (error: unknown) => void;
34
+ window: number;
27
35
  }
28
36
  /**
29
37
  * A class that creates an async rate-limited function.
@@ -50,30 +58,25 @@ export interface AsyncRateLimiterOptions {
50
58
  * await rateLimiter.maybeExecute('123');
51
59
  * ```
52
60
  */
53
- export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
61
+ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
54
62
  private fn;
55
- private executionCount;
56
- private rejectionCount;
57
- private executionTimes;
58
- private options;
59
- constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions);
63
+ private _options;
64
+ private _errorCount;
65
+ private _executionTimes;
66
+ private _lastResult;
67
+ private _rejectionCount;
68
+ private _settleCount;
69
+ private _successCount;
70
+ constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>);
60
71
  /**
61
72
  * Updates the rate limiter options
62
73
  * Returns the new options state
63
74
  */
64
- setOptions(newOptions: Partial<AsyncRateLimiterOptions>): AsyncRateLimiterOptions;
75
+ setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void;
65
76
  /**
66
- * Returns the number of times the function has been executed
67
- */
68
- getExecutionCount(): number;
69
- /**
70
- * Returns the number of times the function has been rejected
71
- */
72
- getRejectionCount(): number;
73
- /**
74
- * Returns the number of remaining executions allowed in the current window
77
+ * Returns the current rate limiter options
75
78
  */
76
- getRemainingInWindow(): number;
79
+ getOptions(): Required<AsyncRateLimiterOptions<TFn>>;
77
80
  /**
78
81
  * Attempts to execute the rate-limited function if within the configured limits.
79
82
  * Will reject execution if the number of calls in the current window exceeds the limit.
@@ -90,10 +93,34 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
90
93
  * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
91
94
  * ```
92
95
  */
93
- maybeExecute(...args: TArgs): Promise<boolean>;
96
+ maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
94
97
  private executeFunction;
95
98
  private rejectFunction;
96
99
  private cleanupOldExecutions;
100
+ /**
101
+ * Returns the number of remaining executions allowed in the current window
102
+ */
103
+ getRemainingInWindow(): number;
104
+ /**
105
+ * Returns the number of milliseconds until the next execution will be possible
106
+ */
107
+ getMsUntilNextWindow(): number;
108
+ /**
109
+ * Returns the number of times the function has been executed
110
+ */
111
+ getSuccessCount(): number;
112
+ /**
113
+ * Returns the number of times the function has been settled
114
+ */
115
+ getSettleCount(): number;
116
+ /**
117
+ * Returns the number of times the function has errored
118
+ */
119
+ getErrorCount(): number;
120
+ /**
121
+ * Returns the number of times the function has been rejected
122
+ */
123
+ getRejectionCount(): number;
97
124
  /**
98
125
  * Resets the rate limiter state
99
126
  */
@@ -116,8 +143,8 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
116
143
  * const rateLimited = asyncRateLimit(makeApiCall, {
117
144
  * limit: 5,
118
145
  * window: 60000,
119
- * onReject: ({ msUntilNextWindow }) => {
120
- * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
146
+ * onReject: (rateLimiter) => {
147
+ * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
121
148
  * }
122
149
  * });
123
150
  *
@@ -129,4 +156,4 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
129
156
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
130
157
  * ```
131
158
  */
132
- export declare function asyncRateLimit<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<boolean>;
159
+ export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
@@ -1,11 +1,24 @@
1
+ const defaultOptions = {
2
+ enabled: true,
3
+ onError: () => {
4
+ },
5
+ onReject: () => {
6
+ },
7
+ onSettled: () => {
8
+ },
9
+ onSuccess: () => {
10
+ }
11
+ };
1
12
  class AsyncRateLimiter {
2
13
  constructor(fn, initialOptions) {
3
14
  this.fn = fn;
4
- this.executionCount = 0;
5
- this.rejectionCount = 0;
6
- this.executionTimes = [];
7
- this.options = {
8
- enabled: true,
15
+ this._errorCount = 0;
16
+ this._executionTimes = [];
17
+ this._rejectionCount = 0;
18
+ this._settleCount = 0;
19
+ this._successCount = 0;
20
+ this._options = {
21
+ ...defaultOptions,
9
22
  ...initialOptions
10
23
  };
11
24
  }
@@ -14,30 +27,13 @@ class AsyncRateLimiter {
14
27
  * Returns the new options state
15
28
  */
16
29
  setOptions(newOptions) {
17
- this.options = {
18
- ...this.options,
19
- ...newOptions
20
- };
21
- return this.options;
22
- }
23
- /**
24
- * Returns the number of times the function has been executed
25
- */
26
- getExecutionCount() {
27
- return this.executionCount;
28
- }
29
- /**
30
- * Returns the number of times the function has been rejected
31
- */
32
- getRejectionCount() {
33
- return this.rejectionCount;
30
+ this._options = { ...this._options, ...newOptions };
34
31
  }
35
32
  /**
36
- * Returns the number of remaining executions allowed in the current window
33
+ * Returns the current rate limiter options
37
34
  */
38
- getRemainingInWindow() {
39
- this.cleanupOldExecutions();
40
- return Math.max(0, this.options.limit - this.executionTimes.length);
35
+ getOptions() {
36
+ return this._options;
41
37
  }
42
38
  /**
43
39
  * Attempts to execute the rate-limited function if within the configured limits.
@@ -57,58 +53,90 @@ class AsyncRateLimiter {
57
53
  */
58
54
  async maybeExecute(...args) {
59
55
  this.cleanupOldExecutions();
60
- if (this.executionTimes.length < this.options.limit) {
56
+ if (this._executionTimes.length < this._options.limit) {
61
57
  await this.executeFunction(...args);
62
- return true;
58
+ return this._lastResult;
63
59
  }
64
60
  this.rejectFunction();
65
- return false;
61
+ return void 0;
66
62
  }
67
63
  async executeFunction(...args) {
68
- if (!this.options.enabled) return;
64
+ var _a, _b, _c, _d, _e, _f;
65
+ if (!this._options.enabled) return;
69
66
  const now = Date.now();
70
- this.executionCount++;
71
- this.executionTimes.push(now);
67
+ this._executionTimes.push(now);
72
68
  try {
73
- await this.fn(...args);
69
+ this._lastResult = await this.fn(...args);
70
+ this._successCount++;
71
+ (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
74
72
  } catch (error) {
75
- if (this.options.onError) {
76
- try {
77
- this.options.onError(error);
78
- } catch {
79
- }
80
- }
81
- throw error;
73
+ this._errorCount++;
74
+ (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
82
75
  } finally {
76
+ this._settleCount++;
77
+ (_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
83
78
  }
79
+ return this._lastResult;
84
80
  }
85
81
  rejectFunction() {
86
- this.rejectionCount++;
87
- if (this.options.onReject) {
88
- const oldestExecution = Math.min(...this.executionTimes);
89
- const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
90
- this.options.onReject({
91
- msUntilNextWindow,
92
- currentExecutions: this.executionTimes.length,
93
- limit: this.options.limit,
94
- rejectionCount: this.rejectionCount
95
- });
82
+ this._rejectionCount++;
83
+ if (this._options.onReject) {
84
+ this._options.onReject(this);
96
85
  }
97
86
  }
98
87
  cleanupOldExecutions() {
99
88
  const now = Date.now();
100
- const windowStart = now - this.options.window;
101
- this.executionTimes = this.executionTimes.filter(
89
+ const windowStart = now - this._options.window;
90
+ this._executionTimes = this._executionTimes.filter(
102
91
  (time) => time > windowStart
103
92
  );
104
93
  }
94
+ /**
95
+ * Returns the number of remaining executions allowed in the current window
96
+ */
97
+ getRemainingInWindow() {
98
+ this.cleanupOldExecutions();
99
+ return Math.max(0, this._options.limit - this._executionTimes.length);
100
+ }
101
+ /**
102
+ * Returns the number of milliseconds until the next execution will be possible
103
+ */
104
+ getMsUntilNextWindow() {
105
+ return this.getRemainingInWindow() * this._options.window;
106
+ }
107
+ /**
108
+ * Returns the number of times the function has been executed
109
+ */
110
+ getSuccessCount() {
111
+ return this._successCount;
112
+ }
113
+ /**
114
+ * Returns the number of times the function has been settled
115
+ */
116
+ getSettleCount() {
117
+ return this._settleCount;
118
+ }
119
+ /**
120
+ * Returns the number of times the function has errored
121
+ */
122
+ getErrorCount() {
123
+ return this._errorCount;
124
+ }
125
+ /**
126
+ * Returns the number of times the function has been rejected
127
+ */
128
+ getRejectionCount() {
129
+ return this._rejectionCount;
130
+ }
105
131
  /**
106
132
  * Resets the rate limiter state
107
133
  */
108
134
  reset() {
109
- this.executionTimes = [];
110
- this.executionCount = 0;
111
- this.rejectionCount = 0;
135
+ this._executionTimes = [];
136
+ this._successCount = 0;
137
+ this._errorCount = 0;
138
+ this._rejectionCount = 0;
139
+ this._settleCount = 0;
112
140
  }
113
141
  }
114
142
  function asyncRateLimit(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"async-rate-limiter.js","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { RateLimitRejectionInfo } from './rate-limiter'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions {\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 * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (info: RateLimitRejectionInfo) => void\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown) => void\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 (...args: Array<any>) => Promise<any>,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private rejectionCount = 0\n private executionTimes: Array<number> = []\n private options: AsyncRateLimiterOptions\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions,\n ) {\n this.options = {\n enabled: true,\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>,\n ): AsyncRateLimiterOptions {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\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 * 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 {\n // Ignore errors from error handler\n }\n }\n throw error\n } finally {\n }\n }\n\n private rejectFunction(): void {\n this.rejectionCount++\n if (this.options.onReject) {\n const oldestExecution = Math.min(...this.executionTimes)\n const msUntilNextWindow =\n oldestExecution + this.options.window - Date.now()\n\n this.options.onReject({\n msUntilNextWindow,\n currentExecutions: this.executionTimes.length,\n limit: this.options.limit,\n rejectionCount: this.rejectionCount,\n })\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 * 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: ({ msUntilNextWindow }) => {\n * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}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 (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions, 'enabled'>) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AAsDO,MAAM,iBAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,iBAAiB;AACzB,SAAQ,iBAAiB;AACzB,SAAQ,iBAAgC,CAAC;AAOvC,SAAK,UAAU;AAAA,MACb,SAAS;AAAA,MACT,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACyB;AACzB,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AA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QACA,mBAAmB,KAAK,eAAe;AAAA,QACvC,OAAO,KAAK,QAAQ;AAAA,QACpB,gBAAgB,KAAK;AAAA,MAAA,CACtB;AAAA,IAAA;AAAA,EACH;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,QAAQ;AAClC,SAAA,iBAAiB,KAAK,eAAe;AAAA,MACxC,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAc;AACZ,SAAK,iBAAiB,CAAC;AACvB,SAAK,iBAAiB;AACtB,SAAK,iBAAiB;AAAA,EAAA;AAE1B;AAgCgB,SAAA,eAEd,IAAS,gBAA0D;AACnE,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 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 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 * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => 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>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\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<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\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._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\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 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._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 */\n getMsUntilNextWindow(): number {\n return this.getRemainingInWindow() * this._options.window\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 * 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 * 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<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AAwCA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAA;AACnB;AA2BO,MAAM,iBAA+C;AAAA,EAS1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AARV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;A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B;AAAA,MAC1C,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,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,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,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,gBAAgB;AACrB,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AAgCgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
@@ -1,21 +1,40 @@
1
+ import { AnyAsyncFunction } from './types.js';
1
2
  /**
2
3
  * Options for configuring an async throttled function
3
4
  */
4
- export interface AsyncThrottlerOptions {
5
+ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
5
6
  /**
6
7
  * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
7
8
  * Defaults to true.
8
9
  */
9
10
  enabled?: boolean;
10
11
  /**
11
- * Time window in milliseconds during which the function can only be executed once
12
- * Defaults to 0ms
12
+ * Whether to execute the function immediately when called
13
+ * Defaults to true
13
14
  */
14
- wait: number;
15
+ leading?: boolean;
15
16
  /**
16
17
  * Optional error handler for when the throttled function throws
17
18
  */
18
- onError?: (error: unknown) => void;
19
+ onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void;
20
+ /**
21
+ * Optional function to call when the throttled function is executed
22
+ */
23
+ onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void;
24
+ /**
25
+ * Optional function to call when the throttled function is executed
26
+ */
27
+ onSuccess?: (result: ReturnType<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
28
+ /**
29
+ * Whether to execute the function on the trailing edge of the wait period
30
+ * Defaults to true
31
+ */
32
+ trailing?: boolean;
33
+ /**
34
+ * Time window in milliseconds during which the function can only be executed once
35
+ * Defaults to 0ms
36
+ */
37
+ wait: number;
19
38
  }
20
39
  /**
21
40
  * A class that creates an async throttled function.
@@ -39,40 +58,71 @@ export interface AsyncThrottlerOptions {
39
58
  * });
40
59
  * ```
41
60
  */
42
- export declare class AsyncThrottler<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
61
+ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
43
62
  private fn;
44
- private abortController;
45
- private executionCount;
46
- private isExecuting;
47
- private isScheduled;
48
- private lastArgs;
49
- private nextExecutionTime;
50
- private options;
51
- constructor(fn: TFn, initialOptions: AsyncThrottlerOptions);
63
+ private _options;
64
+ private _abortController;
65
+ private _errorCount;
66
+ private _isExecuting;
67
+ private _lastArgs;
68
+ private _lastExecutionTime;
69
+ private _lastResult;
70
+ private _nextExecutionTime;
71
+ private _settleCount;
72
+ private _successCount;
73
+ private _timeoutId;
74
+ constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>);
52
75
  /**
53
76
  * Updates the throttler options
54
77
  * Returns the new options state
55
78
  */
56
- setOptions(newOptions: Partial<AsyncThrottlerOptions>): Required<AsyncThrottlerOptions>;
79
+ setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void;
80
+ /**
81
+ * Returns the current options
82
+ */
83
+ getOptions(): Required<AsyncThrottlerOptions<TFn>>;
84
+ /**
85
+ * Attempts to execute the throttled function
86
+ * If a call is already in progress, it may be blocked or queued depending on the `wait` option
87
+ */
88
+ maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
89
+ private executeFunction;
57
90
  /**
58
- * Returns the number of times the function has been executed
91
+ * Cancels any pending execution or aborts any execution in progress
59
92
  */
60
- getExecutionCount(): number;
93
+ cancel(): void;
94
+ /**
95
+ * Returns the last execution time
96
+ */
97
+ getLastExecutionTime(): number;
61
98
  /**
62
99
  * Returns the next execution time
63
100
  */
64
101
  getNextExecutionTime(): number;
65
102
  /**
66
- * Cancels any pending execution
103
+ * Returns the last result of the debounced function
67
104
  */
68
- cancel(): void;
105
+ getLastResult(): ReturnType<TFn> | undefined;
69
106
  /**
70
- * Attempts to execute the throttled function
71
- * If a call is already in progress, it may be blocked or queued depending on the `wait` option
107
+ * Returns the number of times the function has been executed successfully
72
108
  */
73
- maybeExecute(...args: TArgs): Promise<void>;
74
- private delay;
75
- private executeFunction;
109
+ getSuccessCount(): number;
110
+ /**
111
+ * Returns the number of times the function has settled (completed or errored)
112
+ */
113
+ getSettleCount(): number;
114
+ /**
115
+ * Returns the number of times the function has errored
116
+ */
117
+ getErrorCount(): number;
118
+ /**
119
+ * Returns the current pending state
120
+ */
121
+ getIsPending(): boolean;
122
+ /**
123
+ * Returns the current executing state
124
+ */
125
+ getIsExecuting(): boolean;
76
126
  }
77
127
  /**
78
128
  * Creates an async throttled function that limits how often the function can execute.
@@ -90,4 +140,4 @@ export declare class AsyncThrottler<TFn extends (...args: Array<any>) => Promise
90
140
  * await throttled(); // Waits 1 second before executing
91
141
  * ```
92
142
  */
93
- export declare function asyncThrottle<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<void>;
143
+ export declare function asyncThrottle<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;