@tanstack/pacer 0.1.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 (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
@@ -0,0 +1,197 @@
1
+ import { QueuePosition } from './queuer.cjs';
2
+ export interface AsyncQueuerOptions<TValue> {
3
+ /**
4
+ * Default position to add items to the queuer
5
+ * @default 'back'
6
+ */
7
+ addItemsTo?: QueuePosition;
8
+ /**
9
+ * Maximum number of concurrent tasks to process
10
+ */
11
+ concurrency?: number;
12
+ /**
13
+ * Default position to get items from during processing
14
+ * @default 'front'
15
+ */
16
+ getItemsFrom?: QueuePosition;
17
+ /**
18
+ * Function to determine priority of items in the queuer
19
+ * Higher priority items will be processed first
20
+ * If not provided, will use static priority values attached to tasks
21
+ */
22
+ getPriority?: (item: () => Promise<TValue>) => number;
23
+ /**
24
+ * Initial items to populate the queuer with
25
+ */
26
+ initialItems?: Array<(() => Promise<TValue>) & {
27
+ priority?: number;
28
+ }>;
29
+ /**
30
+ * Maximum number of items allowed in the queuer
31
+ */
32
+ maxSize?: number;
33
+ /**
34
+ * Callback fired whenever an item is removed from the queuer
35
+ */
36
+ onGetNextItem?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
37
+ /**
38
+ * Callback fired whenever an item is added or removed from the queuer
39
+ */
40
+ onUpdate?: (queuer: AsyncQueuer<TValue>) => void;
41
+ /**
42
+ * Whether the queuer should start processing tasks immediately
43
+ */
44
+ started?: boolean;
45
+ /**
46
+ * Time in milliseconds to wait between processing items
47
+ */
48
+ wait?: number;
49
+ }
50
+ /**
51
+ * A flexible asynchronous queuer that processes tasks with configurable concurrency control.
52
+ *
53
+ * Features:
54
+ * - Priority queuer support via getPriority option
55
+ * - Configurable concurrency limit
56
+ * - Task success/error/completion callbacks
57
+ * - FIFO (First In First Out) or LIFO (Last In First Out) queuer behavior
58
+ * - Pause/resume task processing
59
+ * - Task cancellation
60
+ *
61
+ * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
62
+ * the next pending task is processed if below the concurrency limit.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const queuer = new AsyncQueuer<string>({ concurrency: 2 });
67
+ *
68
+ * queuer.addItem(async () => {
69
+ * return 'Hello';
70
+ * });
71
+ *
72
+ * queuer.start();
73
+ *
74
+ * queuer.onSuccess((result) => {
75
+ * console.log(result); // 'Hello'
76
+ * });
77
+ * ```
78
+ */
79
+ export declare class AsyncQueuer<TValue> {
80
+ protected options: Required<AsyncQueuerOptions<TValue>>;
81
+ private items;
82
+ private activeItems;
83
+ private onSuccessCallbacks;
84
+ private onErrorCallbacks;
85
+ private onSettledCallbacks;
86
+ private running;
87
+ private pendingTick;
88
+ private executionCount;
89
+ constructor(initialOptions?: AsyncQueuerOptions<TValue>);
90
+ /**
91
+ * Updates the queuer options
92
+ * Returns the new options state
93
+ */
94
+ setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): AsyncQueuerOptions<TValue>;
95
+ /**
96
+ * Processes items in the queuer
97
+ */
98
+ protected tick(): void;
99
+ /**
100
+ * Adds a task to the queuer
101
+ */
102
+ addItem(fn: (() => Promise<TValue>) & {
103
+ priority?: number;
104
+ }, position?: QueuePosition, runOnUpdate?: boolean): Promise<TValue>;
105
+ /**
106
+ * Removes and returns an item from the queuer
107
+ */
108
+ getNextItem(position?: QueuePosition): (() => Promise<TValue>) | undefined;
109
+ /**
110
+ * Returns an item without removing it
111
+ */
112
+ peek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
113
+ /**
114
+ * Returns true if the queuer is empty
115
+ */
116
+ isEmpty(): boolean;
117
+ /**
118
+ * Returns true if the queuer is full
119
+ */
120
+ isFull(): boolean;
121
+ /**
122
+ * Returns the current size of the queuer
123
+ */
124
+ size(): number;
125
+ /**
126
+ * Removes all items from the queuer
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Resets the queuer to its initial state
131
+ */
132
+ reset(withInitialItems?: boolean): void;
133
+ /**
134
+ * Returns a copy of all items in the queuer
135
+ */
136
+ getAllItems(): Array<() => Promise<TValue>>;
137
+ /**
138
+ * Returns the number of items that have been removed from the queuer
139
+ */
140
+ getExecutionCount(): number;
141
+ /**
142
+ * Returns the active items
143
+ */
144
+ getActiveItems(): Array<() => Promise<TValue>>;
145
+ /**
146
+ * Returns the pending items
147
+ */
148
+ getPendingItems(): Array<() => Promise<TValue>>;
149
+ /**
150
+ * Adds a callback to be called when a task succeeds
151
+ */
152
+ onSuccess(cb: (result: TValue) => void): () => void;
153
+ /**
154
+ * Adds a callback to be called when a task errors
155
+ */
156
+ onError(cb: (error: Error) => void): () => void;
157
+ /**
158
+ * Adds a callback to be called when a task is settled
159
+ */
160
+ onSettled(cb: (result: TValue | Error) => void): () => void;
161
+ /**
162
+ * Starts the queuer and processes items
163
+ */
164
+ start(): Promise<void>;
165
+ /**
166
+ * Stops the queuer from processing items
167
+ */
168
+ stop(): void;
169
+ /**
170
+ * Returns true if the queuer is running
171
+ */
172
+ isRunning(): boolean;
173
+ /**
174
+ * Returns true if the queuer is running but has no items to process
175
+ */
176
+ isIdle(): boolean;
177
+ }
178
+ /**
179
+ * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
180
+ * The queuer is automatically started and ready to process items.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const enqueue = asyncQueue<string>();
185
+ *
186
+ * // Add items to be processed
187
+ * enqueue(async () => {
188
+ * return 'Hello';
189
+ * });
190
+ * ```
191
+ *
192
+ * @param options - Configuration options for the AsyncQueuer
193
+ * @returns A bound addItem function that can be used to add tasks to the queuer
194
+ */
195
+ export declare function asyncQueue<TValue>(options?: AsyncQueuerOptions<TValue>): (fn: (() => Promise<TValue>) & {
196
+ priority?: number;
197
+ }, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ class AsyncRateLimiter {
4
+ constructor(fn, initialOptions) {
5
+ this.fn = fn;
6
+ this.executionCount = 0;
7
+ this.rejectionCount = 0;
8
+ this.executionTimes = [];
9
+ this.options = {
10
+ enabled: true,
11
+ ...initialOptions
12
+ };
13
+ }
14
+ /**
15
+ * Updates the rate limiter options
16
+ * Returns the new options state
17
+ */
18
+ setOptions(newOptions) {
19
+ this.options = {
20
+ ...this.options,
21
+ ...newOptions
22
+ };
23
+ return this.options;
24
+ }
25
+ /**
26
+ * Returns the number of times the function has been executed
27
+ */
28
+ getExecutionCount() {
29
+ return this.executionCount;
30
+ }
31
+ /**
32
+ * Returns the number of times the function has been rejected
33
+ */
34
+ getRejectionCount() {
35
+ return this.rejectionCount;
36
+ }
37
+ /**
38
+ * Returns the number of remaining executions allowed in the current window
39
+ */
40
+ getRemainingInWindow() {
41
+ this.cleanupOldExecutions();
42
+ return Math.max(0, this.options.limit - this.executionTimes.length);
43
+ }
44
+ /**
45
+ * Attempts to execute the rate-limited function if within the configured limits.
46
+ * Will reject execution if the number of calls in the current window exceeds the limit.
47
+ * If execution is allowed, waits for any previous execution to complete before proceeding.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
52
+ *
53
+ * // First 5 calls will execute
54
+ * await rateLimiter.maybeExecute('arg1', 'arg2');
55
+ *
56
+ * // Additional calls within the window will be rejected
57
+ * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
58
+ * ```
59
+ */
60
+ async maybeExecute(...args) {
61
+ this.cleanupOldExecutions();
62
+ if (this.executionTimes.length < this.options.limit) {
63
+ await this.executeFunction(...args);
64
+ return true;
65
+ }
66
+ this.rejectFunction();
67
+ return false;
68
+ }
69
+ async executeFunction(...args) {
70
+ if (!this.options.enabled) return;
71
+ const now = Date.now();
72
+ this.executionCount++;
73
+ this.executionTimes.push(now);
74
+ try {
75
+ await this.fn(...args);
76
+ } catch (error) {
77
+ if (this.options.onError) {
78
+ try {
79
+ this.options.onError(error);
80
+ } catch {
81
+ }
82
+ }
83
+ throw error;
84
+ } finally {
85
+ }
86
+ }
87
+ rejectFunction() {
88
+ this.rejectionCount++;
89
+ if (this.options.onReject) {
90
+ const oldestExecution = Math.min(...this.executionTimes);
91
+ const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
92
+ this.options.onReject({
93
+ msUntilNextWindow,
94
+ currentExecutions: this.executionTimes.length,
95
+ limit: this.options.limit,
96
+ rejectionCount: this.rejectionCount
97
+ });
98
+ }
99
+ }
100
+ cleanupOldExecutions() {
101
+ const now = Date.now();
102
+ const windowStart = now - this.options.window;
103
+ this.executionTimes = this.executionTimes.filter(
104
+ (time) => time > windowStart
105
+ );
106
+ }
107
+ /**
108
+ * Resets the rate limiter state
109
+ */
110
+ reset() {
111
+ this.executionTimes = [];
112
+ this.executionCount = 0;
113
+ this.rejectionCount = 0;
114
+ }
115
+ }
116
+ function asyncRateLimit(fn, initialOptions) {
117
+ const rateLimiter = new AsyncRateLimiter(fn, initialOptions);
118
+ return rateLimiter.maybeExecute.bind(rateLimiter);
119
+ }
120
+ exports.AsyncRateLimiter = AsyncRateLimiter;
121
+ exports.asyncRateLimit = asyncRateLimit;
122
+ //# sourceMappingURL=async-rate-limiter.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-rate-limiter.cjs","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;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,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,QAAQ,QAAQ,KAAK,eAAe,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBpE,MAAM,gBAAgB,MAA+B;AACnD,SAAK,qBAAqB;AAE1B,QAAI,KAAK,eAAe,SAAS,KAAK,QAAQ,OAAO;AAC7C,YAAA,KAAK,gBAAgB,GAAG,IAAI;AAC3B,aAAA;AAAA,IAAA;AAGT,SAAK,eAAe;AACb,WAAA;AAAA,EAAA;AAAA,EAGT,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,QAAQ,QAAS;AACrB,UAAA,MAAM,KAAK,IAAI;AAChB,SAAA;AACA,SAAA,eAAe,KAAK,GAAG;AAExB,QAAA;AACI,YAAA,KAAK,GAAG,GAAG,IAAI;AAAA,aACd,OAAO;AACV,UAAA,KAAK,QAAQ,SAAS;AACpB,YAAA;AACG,eAAA,QAAQ,QAAQ,KAAK;AAAA,QAAA,QACpB;AAAA,QAAA;AAAA,MAER;AAEI,YAAA;AAAA,IAAA,UACN;AAAA,IAAA;AAAA,EACF;AAAA,EAGM,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,QAAQ,UAAU;AACzB,YAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,cAAc;AACvD,YAAM,oBACJ,kBAAkB,KAAK,QAAQ,SAAS,KAAK,IAAI;AAEnD,WAAK,QAAQ,SAAS;AAAA,QACpB;AAAA,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;;;"}
@@ -0,0 +1,132 @@
1
+ import { RateLimitRejectionInfo } from './rate-limiter.cjs';
2
+ /**
3
+ * Options for configuring an async rate-limited function
4
+ */
5
+ export interface AsyncRateLimiterOptions {
6
+ /**
7
+ * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
8
+ * Defaults to true.
9
+ */
10
+ enabled?: boolean;
11
+ /**
12
+ * Maximum number of executions allowed within the time window
13
+ */
14
+ limit: number;
15
+ /**
16
+ * Time window in milliseconds within which the limit applies
17
+ */
18
+ window: number;
19
+ /**
20
+ * Optional callback function that is called when an execution is rejected due to rate limiting
21
+ */
22
+ onReject?: (info: RateLimitRejectionInfo) => void;
23
+ /**
24
+ * Optional error handler for when the rate-limited function throws
25
+ */
26
+ onError?: (error: unknown) => void;
27
+ }
28
+ /**
29
+ * A class that creates an async rate-limited function.
30
+ *
31
+ * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
32
+ * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
33
+ * all executions happen immediately, followed by a complete block.
34
+ *
35
+ * For smoother execution patterns, consider using:
36
+ * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
37
+ * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
38
+ *
39
+ * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
40
+ * smoothing out frequent events, throttling or debouncing usually provide better user experience.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const rateLimiter = new AsyncRateLimiter(
45
+ * async (id: string) => await api.getData(id),
46
+ * { limit: 5, window: 1000 } // 5 calls per second
47
+ * );
48
+ *
49
+ * // Will execute immediately until limit reached, then block
50
+ * await rateLimiter.maybeExecute('123');
51
+ * ```
52
+ */
53
+ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
54
+ private fn;
55
+ private executionCount;
56
+ private rejectionCount;
57
+ private executionTimes;
58
+ private options;
59
+ constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions);
60
+ /**
61
+ * Updates the rate limiter options
62
+ * Returns the new options state
63
+ */
64
+ setOptions(newOptions: Partial<AsyncRateLimiterOptions>): AsyncRateLimiterOptions;
65
+ /**
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
75
+ */
76
+ getRemainingInWindow(): number;
77
+ /**
78
+ * Attempts to execute the rate-limited function if within the configured limits.
79
+ * Will reject execution if the number of calls in the current window exceeds the limit.
80
+ * If execution is allowed, waits for any previous execution to complete before proceeding.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
85
+ *
86
+ * // First 5 calls will execute
87
+ * await rateLimiter.maybeExecute('arg1', 'arg2');
88
+ *
89
+ * // Additional calls within the window will be rejected
90
+ * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
91
+ * ```
92
+ */
93
+ maybeExecute(...args: TArgs): Promise<boolean>;
94
+ private executeFunction;
95
+ private rejectFunction;
96
+ private cleanupOldExecutions;
97
+ /**
98
+ * Resets the rate limiter state
99
+ */
100
+ reset(): void;
101
+ }
102
+ /**
103
+ * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
104
+ *
105
+ * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
106
+ * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
107
+ * - A throttler ensures even spacing between executions, which can be better for consistent performance
108
+ * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
109
+ *
110
+ * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
111
+ * need to enforce a hard limit on the number of executions within a time period.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * // Rate limit to 5 calls per minute
116
+ * const rateLimited = asyncRateLimit(makeApiCall, {
117
+ * limit: 5,
118
+ * window: 60000,
119
+ * onReject: ({ msUntilNextWindow }) => {
120
+ * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
121
+ * }
122
+ * });
123
+ *
124
+ * // First 5 calls will execute immediately
125
+ * // Additional calls will be rejected until the minute window resets
126
+ * await rateLimited();
127
+ *
128
+ * // For more even execution, consider using throttle instead:
129
+ * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
130
+ * ```
131
+ */
132
+ export declare function asyncRateLimit<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<boolean>;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const defaultOptions = {
4
+ enabled: true,
5
+ onError: () => {
6
+ },
7
+ wait: 0
8
+ };
9
+ class AsyncThrottler {
10
+ constructor(fn, initialOptions) {
11
+ this.fn = fn;
12
+ this.abortController = null;
13
+ this.executionCount = 0;
14
+ this.isExecuting = false;
15
+ this.isScheduled = false;
16
+ this.nextExecutionTime = 0;
17
+ this.options = {
18
+ ...defaultOptions,
19
+ ...initialOptions
20
+ };
21
+ }
22
+ /**
23
+ * Updates the throttler options
24
+ * Returns the new options state
25
+ */
26
+ setOptions(newOptions) {
27
+ this.options = {
28
+ ...this.options,
29
+ ...newOptions
30
+ };
31
+ return this.options;
32
+ }
33
+ /**
34
+ * Returns the number of times the function has been executed
35
+ */
36
+ getExecutionCount() {
37
+ return this.executionCount;
38
+ }
39
+ /**
40
+ * Returns the next execution time
41
+ */
42
+ getNextExecutionTime() {
43
+ return this.nextExecutionTime;
44
+ }
45
+ /**
46
+ * Cancels any pending execution
47
+ */
48
+ cancel() {
49
+ if (this.abortController) {
50
+ this.abortController.abort();
51
+ this.abortController = null;
52
+ }
53
+ this.isScheduled = false;
54
+ this.lastArgs = void 0;
55
+ }
56
+ /**
57
+ * Attempts to execute the throttled function
58
+ * If a call is already in progress, it may be blocked or queued depending on the `wait` option
59
+ */
60
+ async maybeExecute(...args) {
61
+ this.lastArgs = args;
62
+ if (this.isScheduled) return;
63
+ this.isScheduled = true;
64
+ this.abortController = new AbortController();
65
+ const signal = this.abortController.signal;
66
+ try {
67
+ while (this.isExecuting) {
68
+ await this.delay(this.options.wait, signal);
69
+ }
70
+ while (Date.now() < this.nextExecutionTime) {
71
+ await this.delay(this.nextExecutionTime - Date.now(), signal);
72
+ }
73
+ this.isScheduled = false;
74
+ this.isExecuting = true;
75
+ await this.executeFunction(...this.lastArgs);
76
+ } catch (error) {
77
+ if (error instanceof Error && error.name === "AbortError") {
78
+ return;
79
+ }
80
+ try {
81
+ this.options.onError(error);
82
+ } catch {
83
+ }
84
+ } finally {
85
+ this.nextExecutionTime = Date.now() + this.options.wait;
86
+ this.isExecuting = false;
87
+ this.abortController = null;
88
+ }
89
+ }
90
+ delay(ms, signal) {
91
+ return new Promise((resolve, reject) => {
92
+ const timeout = setTimeout(resolve, ms);
93
+ signal.addEventListener(
94
+ "abort",
95
+ () => {
96
+ clearTimeout(timeout);
97
+ reject(new Error("AbortError"));
98
+ },
99
+ { once: true }
100
+ );
101
+ });
102
+ }
103
+ async executeFunction(...args) {
104
+ if (!this.options.enabled) return;
105
+ this.executionCount++;
106
+ await this.fn(...args);
107
+ }
108
+ }
109
+ function asyncThrottle(fn, initialOptions) {
110
+ const asyncThrottler = new AsyncThrottler(fn, initialOptions);
111
+ return asyncThrottler.maybeExecute.bind(asyncThrottler);
112
+ }
113
+ exports.AsyncThrottler = AsyncThrottler;
114
+ exports.asyncThrottle = asyncThrottle;
115
+ //# sourceMappingURL=async-throttler.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-throttler.cjs","sources":["../../src/async-throttler.ts"],"sourcesContent":["/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once\n * Defaults to 0ms\n */\n wait: number\n /**\n * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown) => void\n}\n\nconst defaultOptions: Required<AsyncThrottlerOptions> = {\n enabled: true,\n onError: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once per second no matter how often called\n * inputElement.addEventListener('input', () => {\n * throttler.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncThrottler<\n TFn extends (...args: Array<any>) => Promise<any>,\n TArgs extends Parameters<TFn>,\n> {\n private abortController: AbortController | null = null\n private executionCount = 0\n private isExecuting = false\n private isScheduled = false\n private lastArgs: TArgs | undefined\n private nextExecutionTime = 0\n private options: Required<AsyncThrottlerOptions>\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncThrottlerOptions>,\n ): Required<AsyncThrottlerOptions> {\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 next execution time\n */\n getNextExecutionTime(): number {\n return this.nextExecutionTime\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.isScheduled = false\n this.lastArgs = undefined\n }\n\n /**\n * Attempts to execute the throttled function\n * If a call is already in progress, it may be blocked or queued depending on the `wait` option\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this.lastArgs = args\n if (this.isScheduled) return\n this.isScheduled = true\n\n this.abortController = new AbortController()\n const signal = this.abortController.signal\n\n try {\n while (this.isExecuting) {\n await this.delay(this.options.wait, signal)\n }\n\n while (Date.now() < this.nextExecutionTime) {\n await this.delay(this.nextExecutionTime - Date.now(), signal)\n }\n\n this.isScheduled = false\n this.isExecuting = true\n\n await this.executeFunction(...this.lastArgs)\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n return // Silent return on cancellation\n }\n try {\n this.options.onError(error)\n } catch {\n // Ignore errors from error handler\n }\n } finally {\n this.nextExecutionTime = Date.now() + this.options.wait\n this.isExecuting = false\n this.abortController = null\n }\n }\n\n private delay(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, ms)\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timeout)\n reject(new Error('AbortError'))\n },\n { once: true },\n )\n })\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this.options.enabled) return\n this.executionCount++\n await this.fn(...args)\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * @example\n * ```ts\n * const throttled = asyncThrottle(async () => {\n * await someAsyncOperation();\n * }, { wait: 1000 });\n *\n * // This will execute at most once per second\n * await throttled();\n * await throttled(); // Waits 1 second before executing\n * ```\n */\nexport function asyncThrottle<\n TFn extends (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions, 'enabled'>) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":[],"mappings":";;AAoBA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,MAAM;AACR;AAwBO,MAAM,eAGX;AAAA,EASA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,kBAA0C;AAClD,SAAQ,iBAAiB;AACzB,SAAQ,cAAc;AACtB,SAAQ,cAAc;AAEtB,SAAQ,oBAAoB;AAO1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACiC;AACjC,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAe;AACb,QAAI,KAAK,iBAAiB;AACxB,WAAK,gBAAgB,MAAM;AAC3B,WAAK,kBAAkB;AAAA,IAAA;AAEzB,SAAK,cAAc;AACnB,SAAK,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlB,MAAM,gBAAgB,MAA4B;AAChD,SAAK,WAAW;AAChB,QAAI,KAAK,YAAa;AACtB,SAAK,cAAc;AAEd,SAAA,kBAAkB,IAAI,gBAAgB;AACrC,UAAA,SAAS,KAAK,gBAAgB;AAEhC,QAAA;AACF,aAAO,KAAK,aAAa;AACvB,cAAM,KAAK,MAAM,KAAK,QAAQ,MAAM,MAAM;AAAA,MAAA;AAG5C,aAAO,KAAK,QAAQ,KAAK,mBAAmB;AAC1C,cAAM,KAAK,MAAM,KAAK,oBAAoB,KAAK,OAAO,MAAM;AAAA,MAAA;AAG9D,WAAK,cAAc;AACnB,WAAK,cAAc;AAEnB,YAAM,KAAK,gBAAgB,GAAG,KAAK,QAAQ;AAAA,aACpC,OAAO;AACd,UAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc;AACzD;AAAA,MAAA;AAEE,UAAA;AACG,aAAA,QAAQ,QAAQ,KAAK;AAAA,MAAA,QACpB;AAAA,MAAA;AAAA,IAER,UACA;AACA,WAAK,oBAAoB,KAAK,IAAI,IAAI,KAAK,QAAQ;AACnD,WAAK,cAAc;AACnB,WAAK,kBAAkB;AAAA,IAAA;AAAA,EACzB;AAAA,EAGM,MAAM,IAAY,QAAoC;AAC5D,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AAChC,YAAA,UAAU,WAAW,SAAS,EAAE;AAC/B,aAAA;AAAA,QACL;AAAA,QACA,MAAM;AACJ,uBAAa,OAAO;AACb,iBAAA,IAAI,MAAM,YAAY,CAAC;AAAA,QAChC;AAAA,QACA,EAAE,MAAM,KAAK;AAAA,MACf;AAAA,IAAA,CACD;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,QAAQ,QAAS;AACtB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAAA,EAAA;AAEzB;AAkBgB,SAAA,cAEd,IAAS,gBAAwD;AACjE,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}