@tanstack/pacer 0.22.0 → 0.23.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 (100) hide show
  1. package/README.md +4 -4
  2. package/dist/async-batcher.d.ts +11 -13
  3. package/dist/async-batcher.js +185 -131
  4. package/dist/async-debouncer.d.ts +6 -8
  5. package/dist/async-debouncer.js +186 -142
  6. package/dist/async-queuer.d.ts +11 -13
  7. package/dist/async-queuer.js +383 -290
  8. package/dist/async-rate-limiter.d.ts +6 -8
  9. package/dist/async-rate-limiter.js +197 -143
  10. package/dist/async-retryer.d.ts +6 -8
  11. package/dist/async-retryer.js +209 -179
  12. package/dist/async-throttler.d.ts +6 -8
  13. package/dist/async-throttler.js +214 -157
  14. package/dist/batcher.d.ts +5 -7
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -8
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -10
  19. package/dist/event-client.js +1 -2
  20. package/dist/queuer.d.ts +7 -9
  21. package/dist/queuer.js +277 -212
  22. package/dist/rate-limiter.d.ts +6 -8
  23. package/dist/rate-limiter.js +127 -109
  24. package/dist/throttler.d.ts +6 -8
  25. package/dist/throttler.js +127 -90
  26. package/dist/types.d.ts +4 -6
  27. package/dist/utils.d.ts +3 -5
  28. package/dist/utils.js +1 -2
  29. package/package.json +21 -68
  30. package/dist/async-batcher.cjs +0 -337
  31. package/dist/async-batcher.cjs.map +0 -1
  32. package/dist/async-batcher.d.cts +0 -343
  33. package/dist/async-batcher.js.map +0 -1
  34. package/dist/async-debouncer.cjs +0 -327
  35. package/dist/async-debouncer.cjs.map +0 -1
  36. package/dist/async-debouncer.d.cts +0 -299
  37. package/dist/async-debouncer.js.map +0 -1
  38. package/dist/async-queuer.cjs +0 -516
  39. package/dist/async-queuer.cjs.map +0 -1
  40. package/dist/async-queuer.d.cts +0 -440
  41. package/dist/async-queuer.js.map +0 -1
  42. package/dist/async-rate-limiter.cjs +0 -370
  43. package/dist/async-rate-limiter.cjs.map +0 -1
  44. package/dist/async-rate-limiter.d.cts +0 -356
  45. package/dist/async-rate-limiter.js.map +0 -1
  46. package/dist/async-retryer.cjs +0 -365
  47. package/dist/async-retryer.cjs.map +0 -1
  48. package/dist/async-retryer.d.cts +0 -321
  49. package/dist/async-retryer.js.map +0 -1
  50. package/dist/async-throttler.cjs +0 -344
  51. package/dist/async-throttler.cjs.map +0 -1
  52. package/dist/async-throttler.d.cts +0 -319
  53. package/dist/async-throttler.js.map +0 -1
  54. package/dist/batcher.cjs +0 -200
  55. package/dist/batcher.cjs.map +0 -1
  56. package/dist/batcher.d.cts +0 -179
  57. package/dist/batcher.js.map +0 -1
  58. package/dist/debouncer.cjs +0 -203
  59. package/dist/debouncer.cjs.map +0 -1
  60. package/dist/debouncer.d.cts +0 -166
  61. package/dist/debouncer.js.map +0 -1
  62. package/dist/event-client.cjs +0 -64
  63. package/dist/event-client.cjs.map +0 -1
  64. package/dist/event-client.d.cts +0 -65
  65. package/dist/event-client.js.map +0 -1
  66. package/dist/index.cjs +0 -52
  67. package/dist/index.d.cts +0 -15
  68. package/dist/queuer.cjs +0 -406
  69. package/dist/queuer.cjs.map +0 -1
  70. package/dist/queuer.d.cts +0 -345
  71. package/dist/queuer.js.map +0 -1
  72. package/dist/rate-limiter.cjs +0 -263
  73. package/dist/rate-limiter.cjs.map +0 -1
  74. package/dist/rate-limiter.d.cts +0 -214
  75. package/dist/rate-limiter.js.map +0 -1
  76. package/dist/throttler.cjs +0 -215
  77. package/dist/throttler.cjs.map +0 -1
  78. package/dist/throttler.d.cts +0 -206
  79. package/dist/throttler.js.map +0 -1
  80. package/dist/types.cjs +0 -0
  81. package/dist/types.d.cts +0 -13
  82. package/dist/utils.cjs +0 -13
  83. package/dist/utils.cjs.map +0 -1
  84. package/dist/utils.d.cts +0 -7
  85. package/dist/utils.js.map +0 -1
  86. package/src/async-batcher.ts +0 -594
  87. package/src/async-debouncer.ts +0 -566
  88. package/src/async-queuer.ts +0 -988
  89. package/src/async-rate-limiter.ts +0 -648
  90. package/src/async-retryer.ts +0 -673
  91. package/src/async-throttler.ts +0 -634
  92. package/src/batcher.ts +0 -329
  93. package/src/debouncer.ts +0 -334
  94. package/src/event-client.ts +0 -129
  95. package/src/index.ts +0 -24
  96. package/src/queuer.ts +0 -751
  97. package/src/rate-limiter.ts +0 -429
  98. package/src/throttler.ts +0 -380
  99. package/src/types.ts +0 -12
  100. package/src/utils.ts +0 -12
@@ -1,263 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils.cjs');
3
- const require_event_client = require('./event-client.cjs');
4
- let _tanstack_store = require("@tanstack/store");
5
-
6
- //#region src/rate-limiter.ts
7
- function getDefaultRateLimiterState() {
8
- return {
9
- executionCount: 0,
10
- executionTimes: [],
11
- isExceeded: false,
12
- rejectionCount: 0,
13
- status: "idle",
14
- maybeExecuteCount: 0
15
- };
16
- }
17
- /**
18
- * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
19
- */
20
- function rateLimiterOptions(options) {
21
- return options;
22
- }
23
- const defaultOptions = {
24
- enabled: true,
25
- limit: 1,
26
- window: 0,
27
- windowType: "fixed"
28
- };
29
- /**
30
- * A class that creates a rate-limited function.
31
- *
32
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
33
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
34
- * all executions happen immediately, followed by a complete block.
35
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.
36
- *
37
- * The rate limiter supports two types of windows:
38
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
39
- * towards the limit, and the window resets completely after the period.
40
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
41
- * consistent rate of execution over time.
42
- *
43
- * For smoother execution patterns, consider using:
44
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
45
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
46
- *
47
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
48
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
49
- *
50
- * State Management:
51
- * - Uses TanStack Store for reactive state management
52
- * - Use `initialState` to provide initial state values when creating the rate limiter
53
- * - Use `onExecute` callback to react to function execution and implement custom logic
54
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
55
- * - The state includes execution count, execution times, and rejection count
56
- * - State can be accessed via `rateLimiter.store.state` when using the class directly
57
- * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
58
- *
59
- * @example
60
- * ```ts
61
- * const rateLimiter = new RateLimiter(
62
- * (id: string) => api.getData(id),
63
- * {
64
- * limit: 5,
65
- * window: 1000,
66
- * windowType: 'sliding',
67
- * }
68
- * );
69
- *
70
- * // Will execute immediately until limit reached, then block
71
- * rateLimiter.maybeExecute('123');
72
- * ```
73
- */
74
- var RateLimiter = class {
75
- #timeoutIds;
76
- constructor(fn, initialOptions) {
77
- this.fn = fn;
78
- this.store = new _tanstack_store.Store(getDefaultRateLimiterState());
79
- this.#timeoutIds = /* @__PURE__ */ new Set();
80
- this.setOptions = (newOptions) => {
81
- this.options = {
82
- ...this.options,
83
- ...newOptions
84
- };
85
- };
86
- this.#setState = (newState) => {
87
- this.store.setState((state) => {
88
- const combinedState = {
89
- ...state,
90
- ...newState
91
- };
92
- const isExceeded = combinedState.executionTimes.length >= this.#getLimit();
93
- const status = !this.#getEnabled() ? "disabled" : isExceeded ? "exceeded" : "idle";
94
- return {
95
- ...combinedState,
96
- isExceeded,
97
- status
98
- };
99
- });
100
- require_event_client.emitChange("RateLimiter", this);
101
- };
102
- this.#getEnabled = () => {
103
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
104
- };
105
- this.#getLimit = () => {
106
- return require_utils.parseFunctionOrValue(this.options.limit, this);
107
- };
108
- this.#getWindow = () => {
109
- return require_utils.parseFunctionOrValue(this.options.window, this);
110
- };
111
- this.maybeExecute = (...args) => {
112
- this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
113
- this.#cleanupOldExecutions();
114
- if (this.#getExecutionTimesInWindow().length < this.#getLimit()) {
115
- this.#execute(...args);
116
- return true;
117
- }
118
- this.#setState({ rejectionCount: this.store.state.rejectionCount + 1 });
119
- this.options.onReject?.(this);
120
- return false;
121
- };
122
- this.#execute = (...args) => {
123
- if (!this.#getEnabled()) return;
124
- const now = Date.now();
125
- this.fn(...args);
126
- this.store.state.executionTimes.push(now);
127
- this.#setCleanupTimeout(now);
128
- this.#setState({ executionCount: this.store.state.executionCount + 1 });
129
- this.options.onExecute?.(args, this);
130
- };
131
- this.#getExecutionTimesInWindow = () => {
132
- if (this.options.windowType === "sliding") return this.store.state.executionTimes.filter((time) => time > Date.now() - this.#getWindow());
133
- else {
134
- if (this.store.state.executionTimes.length === 0) return [];
135
- const windowStart = Math.min(...this.store.state.executionTimes);
136
- const windowEnd = windowStart + this.#getWindow();
137
- if (Date.now() > windowEnd) return [];
138
- return this.store.state.executionTimes.filter((time) => time >= windowStart && time <= windowEnd);
139
- }
140
- };
141
- this.#setCleanupTimeout = (executionTime) => {
142
- if (this.options.windowType === "sliding" || this.#timeoutIds.size === 0) {
143
- const timeUntilExpiration = executionTime - Date.now() + this.#getWindow() + 1;
144
- const timeoutId = setTimeout(() => {
145
- this.#cleanupOldExecutions();
146
- this.#clearTimeout(timeoutId);
147
- }, timeUntilExpiration);
148
- this.#timeoutIds.add(timeoutId);
149
- }
150
- };
151
- this.#clearTimeout = (timeoutId) => {
152
- clearTimeout(timeoutId);
153
- this.#timeoutIds.delete(timeoutId);
154
- };
155
- this.#clearTimeouts = () => {
156
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
157
- this.#timeoutIds.clear();
158
- };
159
- this.#cleanupOldExecutions = () => {
160
- this.#setState({ executionTimes: this.#getExecutionTimesInWindow() });
161
- };
162
- this.getRemainingInWindow = () => {
163
- const relevantExecutionTimes = this.#getExecutionTimesInWindow();
164
- return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
165
- };
166
- this.getMsUntilNextWindow = () => {
167
- if (this.getRemainingInWindow() > 0) return 0;
168
- return (this.store.state.executionTimes[0] ?? Infinity) + this.#getWindow() - Date.now();
169
- };
170
- this.reset = () => {
171
- this.#setState(getDefaultRateLimiterState());
172
- this.#clearTimeouts();
173
- };
174
- this.key = initialOptions.key;
175
- this.options = {
176
- ...defaultOptions,
177
- ...initialOptions
178
- };
179
- this.#setState(this.options.initialState ?? {});
180
- for (const executionTime of this.#getExecutionTimesInWindow()) this.#setCleanupTimeout(executionTime);
181
- if (this.key) require_event_client.pacerEventClient.on("d-RateLimiter", (event) => {
182
- if (event.payload.key !== this.key) return;
183
- this.#setState(event.payload.store.state);
184
- this.setOptions(event.payload.options);
185
- });
186
- }
187
- #setState;
188
- /**
189
- * Returns the current enabled state of the rate limiter
190
- */
191
- #getEnabled;
192
- /**
193
- * Returns the current limit of executions allowed within the time window
194
- */
195
- #getLimit;
196
- /**
197
- * Returns the current time window in milliseconds
198
- */
199
- #getWindow;
200
- #execute;
201
- #getExecutionTimesInWindow;
202
- #setCleanupTimeout;
203
- #clearTimeout;
204
- #clearTimeouts;
205
- #cleanupOldExecutions;
206
- };
207
- /**
208
- * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
209
- *
210
- * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.
211
- *
212
- * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
213
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
214
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
215
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
216
- *
217
- * The rate limiter supports two types of windows:
218
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
219
- * towards the limit, and the window resets completely after the period.
220
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
221
- * consistent rate of execution over time.
222
- *
223
- * State Management:
224
- * - Uses TanStack Store for reactive state management
225
- * - Use `initialState` to provide initial state values when creating the rate limiter
226
- * - Use `onExecute` callback to react to function execution and implement custom logic
227
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
228
- * - The state includes execution count, execution times, and rejection count
229
- * - State can be accessed via the underlying RateLimiter instance's `store.state` property
230
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
231
- *
232
- * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
233
- * need to enforce a hard limit on the number of executions within a time period.
234
- *
235
- * @example
236
- * ```ts
237
- * // Rate limit to 5 calls per minute with a sliding window
238
- * const rateLimited = rateLimit(makeApiCall, {
239
- * limit: 5,
240
- * window: 60000,
241
- * windowType: 'sliding',
242
- * onReject: (rateLimiter) => {
243
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
244
- * }
245
- * });
246
- *
247
- * // First 5 calls will execute immediately
248
- * // Additional calls will be rejected until the minute window resets
249
- * rateLimited();
250
- *
251
- * // For more even execution, consider using throttle instead:
252
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
253
- * ```
254
- */
255
- function rateLimit(fn, initialOptions) {
256
- return new RateLimiter(fn, initialOptions).maybeExecute;
257
- }
258
-
259
- //#endregion
260
- exports.RateLimiter = RateLimiter;
261
- exports.rateLimit = rateLimit;
262
- exports.rateLimiterOptions = rateLimiterOptions;
263
- //# sourceMappingURL=rate-limiter.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rate-limiter.cjs","names":["Store","#getLimit","#getEnabled","parseFunctionOrValue","#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#execute","#setCleanupTimeout","#getWindow","#timeoutIds","#clearTimeout","#clearTimeouts"],"sources":["../src/rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'exceeded' | 'idle'\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return {\n executionCount: 0,\n executionTimes: [],\n isExceeded: false,\n rejectionCount: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Optional key to identify this rate limiter instance.\n * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\n/**\n * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.\n */\nexport function rateLimiterOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<\n RateLimiterOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject' | 'key'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a 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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.\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 * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n key: string | undefined\n options: RateLimiterOptions<TFn>\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n\n if (this.key) {\n pacerEventClient.on('d-RateLimiter', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as Partial<RateLimiterState>)\n this.setOptions(\n event.payload.options as Partial<RateLimiterOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n emitChange('RateLimiter', this)\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n\n this.#setCleanupTimeout(now)\n\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(args, this)\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultRateLimiterState())\n this.#clearTimeouts()\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.\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 * 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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(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 * 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 rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"mappings":";;;;;;AAgCA,SAAS,6BAA+C;CACtD,OAAO;EACL,gBAAgB;EAChB,gBAAgB,CAAC;EACjB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;CACrB;AACF;;;;AAkDA,SAAgB,mBAKd,SAA6B;CAC7B,OAAO;AACT;AAEA,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAa,cAAb,MAAkD;CAKhD;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eANP,IAAIA,sBAAwB,2BAA2B,CAAC;qCAGR,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C;GAC3C,KAAKQ,eAAe;EACtB;EA7ME,KAAK,MAAM,eAAe;EAC1B,KAAK,UAAU;GACb,GAAG;GACH,GAAG;EACL;EACA,KAAKR,UAAU,KAAK,QAAQ,gBAAgB,CAAC,CAAC;EAC9C,KAAK,MAAM,iBAAiB,KAAKE,2BAA2B,GAC1D,KAAKE,mBAAmB,aAAa;EAGvC,IAAI,KAAK,KACP,sCAAiB,GAAG,kBAAkB,UAAU;GAC9C,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKJ,UAAU,MAAM,QAAQ,MAAM,KAAkC;GACrE,KAAK,WACH,MAAM,QAAQ,OAChB;EACF,CAAC;CAEL;CASA;;;;CAwBA;;;;CAOA;;;;CAOA;CAwCA;CAcA;CA6BA;CAeA;CAKA;CAKA;AAgCF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,UACd,IACA,gBACA;CAEA,OAAO,IADiB,YAAY,IAAI,cACvB,CAAC,CAAC;AACrB"}
@@ -1,214 +0,0 @@
1
- import { AnyFunction } from "./types.cjs";
2
- import { Store } from "@tanstack/store";
3
- //#region src/rate-limiter.d.ts
4
- interface RateLimiterState {
5
- /**
6
- * Number of function executions that have been completed
7
- */
8
- executionCount: number;
9
- /**
10
- * Array of timestamps when executions occurred for rate limiting calculations
11
- */
12
- executionTimes: Array<number>;
13
- /**
14
- * Whether the rate limiter has exceeded the limit
15
- */
16
- isExceeded: boolean;
17
- /**
18
- * Number of times maybeExecute has been called (for reduction calculations)
19
- */
20
- maybeExecuteCount: number;
21
- /**
22
- * Number of function executions that have been rejected due to rate limiting
23
- */
24
- rejectionCount: number;
25
- /**
26
- * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded
27
- */
28
- status: 'disabled' | 'exceeded' | 'idle';
29
- }
30
- /**
31
- * Options for configuring a rate-limited function
32
- */
33
- interface RateLimiterOptions<TFn extends AnyFunction> {
34
- /**
35
- * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
36
- * Defaults to true.
37
- */
38
- enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean);
39
- /**
40
- * Initial state for the rate limiter
41
- */
42
- initialState?: Partial<RateLimiterState>;
43
- /**
44
- * Optional key to identify this rate limiter instance.
45
- * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.
46
- */
47
- key?: string;
48
- /**
49
- * Maximum number of executions allowed within the time window.
50
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
51
- */
52
- limit: number | ((rateLimiter: RateLimiter<TFn>) => number);
53
- /**
54
- * Callback function that is called after the function is executed
55
- */
56
- onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void;
57
- /**
58
- * Optional callback function that is called when an execution is rejected due to rate limiting
59
- */
60
- onReject?: (rateLimiter: RateLimiter<TFn>) => void;
61
- /**
62
- * Time window in milliseconds within which the limit applies.
63
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
64
- */
65
- window: number | ((rateLimiter: RateLimiter<TFn>) => number);
66
- /**
67
- * Type of window to use for rate limiting
68
- * - 'fixed': Uses a fixed window that resets after the window period
69
- * - 'sliding': Uses a sliding window that allows executions as old ones expire
70
- * Defaults to 'fixed'
71
- */
72
- windowType?: 'fixed' | 'sliding';
73
- }
74
- /**
75
- * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
76
- */
77
- declare function rateLimiterOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<RateLimiterOptions<TFn>>>(options: TOptions): TOptions;
78
- /**
79
- * A class that creates a rate-limited function.
80
- *
81
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
82
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
83
- * all executions happen immediately, followed by a complete block.
84
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.
85
- *
86
- * The rate limiter supports two types of windows:
87
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
88
- * towards the limit, and the window resets completely after the period.
89
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
90
- * consistent rate of execution over time.
91
- *
92
- * For smoother execution patterns, consider using:
93
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
94
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
95
- *
96
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
97
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
98
- *
99
- * State Management:
100
- * - Uses TanStack Store for reactive state management
101
- * - Use `initialState` to provide initial state values when creating the rate limiter
102
- * - Use `onExecute` callback to react to function execution and implement custom logic
103
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
104
- * - The state includes execution count, execution times, and rejection count
105
- * - State can be accessed via `rateLimiter.store.state` when using the class directly
106
- * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
107
- *
108
- * @example
109
- * ```ts
110
- * const rateLimiter = new RateLimiter(
111
- * (id: string) => api.getData(id),
112
- * {
113
- * limit: 5,
114
- * window: 1000,
115
- * windowType: 'sliding',
116
- * }
117
- * );
118
- *
119
- * // Will execute immediately until limit reached, then block
120
- * rateLimiter.maybeExecute('123');
121
- * ```
122
- */
123
- declare class RateLimiter<TFn extends AnyFunction> {
124
- #private;
125
- fn: TFn;
126
- readonly store: Store<Readonly<RateLimiterState>>;
127
- key: string | undefined;
128
- options: RateLimiterOptions<TFn>;
129
- constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn>);
130
- /**
131
- * Updates the rate limiter options
132
- */
133
- setOptions: (newOptions: Partial<RateLimiterOptions<TFn>>) => void;
134
- /**
135
- * Attempts to execute the rate-limited function if within the configured limits.
136
- * Will reject execution if the number of calls in the current window exceeds the limit.
137
- *
138
- * @example
139
- * ```ts
140
- * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
141
- *
142
- * // First 5 calls will return true
143
- * rateLimiter.maybeExecute('arg1', 'arg2'); // true
144
- *
145
- * // Additional calls within the window will return false
146
- * rateLimiter.maybeExecute('arg1', 'arg2'); // false
147
- * ```
148
- */
149
- maybeExecute: (...args: Parameters<TFn>) => boolean;
150
- /**
151
- * Returns the number of remaining executions allowed in the current window
152
- */
153
- getRemainingInWindow: () => number;
154
- /**
155
- * Returns the number of milliseconds until the next execution will be possible
156
- */
157
- getMsUntilNextWindow: () => number;
158
- /**
159
- * Resets the rate limiter state
160
- */
161
- reset: () => void;
162
- }
163
- /**
164
- * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
165
- *
166
- * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.
167
- *
168
- * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
169
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
170
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
171
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
172
- *
173
- * The rate limiter supports two types of windows:
174
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
175
- * towards the limit, and the window resets completely after the period.
176
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
177
- * consistent rate of execution over time.
178
- *
179
- * State Management:
180
- * - Uses TanStack Store for reactive state management
181
- * - Use `initialState` to provide initial state values when creating the rate limiter
182
- * - Use `onExecute` callback to react to function execution and implement custom logic
183
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
184
- * - The state includes execution count, execution times, and rejection count
185
- * - State can be accessed via the underlying RateLimiter instance's `store.state` property
186
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
187
- *
188
- * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
189
- * need to enforce a hard limit on the number of executions within a time period.
190
- *
191
- * @example
192
- * ```ts
193
- * // Rate limit to 5 calls per minute with a sliding window
194
- * const rateLimited = rateLimit(makeApiCall, {
195
- * limit: 5,
196
- * window: 60000,
197
- * windowType: 'sliding',
198
- * onReject: (rateLimiter) => {
199
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
200
- * }
201
- * });
202
- *
203
- * // First 5 calls will execute immediately
204
- * // Additional calls will be rejected until the minute window resets
205
- * rateLimited();
206
- *
207
- * // For more even execution, consider using throttle instead:
208
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
209
- * ```
210
- */
211
- declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: RateLimiterOptions<TFn>): (...args: Parameters<TFn>) => boolean;
212
- //#endregion
213
- export { RateLimiter, RateLimiterOptions, RateLimiterState, rateLimit, rateLimiterOptions };
214
- //# sourceMappingURL=rate-limiter.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rate-limiter.js","names":["#getLimit","#getEnabled","#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#execute","#setCleanupTimeout","#getWindow","#timeoutIds","#clearTimeout","#clearTimeouts"],"sources":["../src/rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'exceeded' | 'idle'\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return {\n executionCount: 0,\n executionTimes: [],\n isExceeded: false,\n rejectionCount: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Optional key to identify this rate limiter instance.\n * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\n/**\n * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.\n */\nexport function rateLimiterOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<\n RateLimiterOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject' | 'key'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a 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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.\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 * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n key: string | undefined\n options: RateLimiterOptions<TFn>\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n\n if (this.key) {\n pacerEventClient.on('d-RateLimiter', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as Partial<RateLimiterState>)\n this.setOptions(\n event.payload.options as Partial<RateLimiterOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n emitChange('RateLimiter', this)\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n\n this.#setCleanupTimeout(now)\n\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(args, this)\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultRateLimiterState())\n this.#clearTimeouts()\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.\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 * 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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(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 * 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 rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"mappings":";;;;;AAgCA,SAAS,6BAA+C;CACtD,OAAO;EACL,gBAAgB;EAChB,gBAAgB,CAAC;EACjB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;CACrB;AACF;;;;AAkDA,SAAgB,mBAKd,SAA6B;CAC7B,OAAO;AACT;AAEA,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAa,cAAb,MAAkD;CAKhD;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eANP,IAAI,MAAwB,2BAA2B,CAAC;qCAGR,IAAI,IAAI;qBA8B5C,eAAuD;GACnE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;GAAW;EAClD;oBAEa,aAA8C;GACzD,KAAK,MAAM,UAAU,UAAU;IAC7B,MAAM,gBAAgB;KACpB,GAAG;KACH,GAAG;IACL;IACA,MAAM,aAAa,cAAc,eAAe,UAAU,KAAKA,UAAU;IACzE,MAAM,SAAS,CAAC,KAAKC,YAAY,IAC7B,aACA,aACE,aACA;IACN,OAAO;KACL,GAAG;KACH;KACA;IACF;GACF,CAAC;GACD,WAAW,eAAe,IAAI;EAChC;2BAK6B;GAC3B,OAAO,CAAC,CAAC,qBAAqB,KAAK,QAAQ,SAAS,IAAI;EAC1D;yBAK0B;GACxB,OAAO,qBAAqB,KAAK,QAAQ,OA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