@tanstack/pacer 0.16.2 → 0.16.4

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 (180) hide show
  1. package/README.md +165 -0
  2. package/dist/async-batcher.cjs +355 -0
  3. package/dist/async-batcher.cjs.map +1 -0
  4. package/dist/async-batcher.d.cts +344 -0
  5. package/dist/async-batcher.d.ts +344 -0
  6. package/dist/async-batcher.js +353 -0
  7. package/dist/async-batcher.js.map +1 -0
  8. package/dist/async-debouncer.cjs +340 -0
  9. package/dist/async-debouncer.cjs.map +1 -0
  10. package/dist/async-debouncer.d.cts +300 -0
  11. package/dist/async-debouncer.d.ts +300 -0
  12. package/dist/async-debouncer.js +338 -0
  13. package/dist/async-debouncer.js.map +1 -0
  14. package/dist/async-queuer.cjs +496 -0
  15. package/dist/async-queuer.cjs.map +1 -0
  16. package/dist/async-queuer.d.cts +440 -0
  17. package/dist/async-queuer.d.ts +440 -0
  18. package/dist/async-queuer.js +494 -0
  19. package/dist/async-queuer.js.map +1 -0
  20. package/dist/async-rate-limiter.cjs +381 -0
  21. package/dist/async-rate-limiter.cjs.map +1 -0
  22. package/dist/{cjs/async-rate-limiter.d.cts → async-rate-limiter.d.cts} +190 -185
  23. package/dist/{esm/async-rate-limiter.d.ts → async-rate-limiter.d.ts} +190 -185
  24. package/dist/async-rate-limiter.js +379 -0
  25. package/dist/async-rate-limiter.js.map +1 -0
  26. package/dist/async-retryer.cjs +378 -0
  27. package/dist/async-retryer.cjs.map +1 -0
  28. package/dist/async-retryer.d.cts +312 -0
  29. package/dist/async-retryer.d.ts +312 -0
  30. package/dist/async-retryer.js +376 -0
  31. package/dist/async-retryer.js.map +1 -0
  32. package/dist/async-throttler.cjs +362 -0
  33. package/dist/async-throttler.cjs.map +1 -0
  34. package/dist/async-throttler.d.cts +320 -0
  35. package/dist/async-throttler.d.ts +320 -0
  36. package/dist/async-throttler.js +360 -0
  37. package/dist/async-throttler.js.map +1 -0
  38. package/dist/batcher.cjs +194 -0
  39. package/dist/batcher.cjs.map +1 -0
  40. package/dist/batcher.d.cts +180 -0
  41. package/dist/batcher.d.ts +180 -0
  42. package/dist/batcher.js +193 -0
  43. package/dist/batcher.js.map +1 -0
  44. package/dist/debouncer.cjs +197 -0
  45. package/dist/debouncer.cjs.map +1 -0
  46. package/dist/debouncer.d.cts +167 -0
  47. package/dist/debouncer.d.ts +167 -0
  48. package/dist/debouncer.js +195 -0
  49. package/dist/debouncer.js.map +1 -0
  50. package/dist/event-client.cjs +20 -0
  51. package/dist/event-client.cjs.map +1 -0
  52. package/dist/event-client.d.cts +49 -0
  53. package/dist/event-client.d.ts +49 -0
  54. package/dist/event-client.js +19 -0
  55. package/dist/event-client.js.map +1 -0
  56. package/dist/index.cjs +49 -0
  57. package/dist/index.d.cts +15 -0
  58. package/dist/index.d.ts +15 -0
  59. package/dist/{esm/index.js → index.js} +5 -41
  60. package/dist/queuer.cjs +393 -0
  61. package/dist/queuer.cjs.map +1 -0
  62. package/dist/queuer.d.cts +345 -0
  63. package/dist/queuer.d.ts +345 -0
  64. package/dist/queuer.js +391 -0
  65. package/dist/queuer.js.map +1 -0
  66. package/dist/rate-limiter.cjs +251 -0
  67. package/dist/rate-limiter.cjs.map +1 -0
  68. package/dist/{cjs/rate-limiter.d.cts → rate-limiter.d.cts} +113 -108
  69. package/dist/{esm/rate-limiter.d.ts → rate-limiter.d.ts} +113 -108
  70. package/dist/rate-limiter.js +249 -0
  71. package/dist/rate-limiter.js.map +1 -0
  72. package/dist/throttler.cjs +209 -0
  73. package/dist/throttler.cjs.map +1 -0
  74. package/dist/throttler.d.cts +207 -0
  75. package/dist/throttler.d.ts +207 -0
  76. package/dist/throttler.js +207 -0
  77. package/dist/throttler.js.map +1 -0
  78. package/dist/types.cjs +0 -0
  79. package/dist/types.d.cts +13 -0
  80. package/dist/types.d.ts +13 -0
  81. package/dist/types.js +1 -0
  82. package/dist/utils.cjs +13 -0
  83. package/dist/utils.cjs.map +1 -0
  84. package/dist/utils.d.cts +8 -0
  85. package/dist/utils.d.ts +8 -0
  86. package/dist/utils.js +11 -0
  87. package/dist/utils.js.map +1 -0
  88. package/package.json +38 -122
  89. package/src/async-batcher.ts +7 -5
  90. package/src/async-debouncer.ts +7 -5
  91. package/src/async-queuer.ts +7 -5
  92. package/src/async-rate-limiter.ts +7 -5
  93. package/src/async-retryer.ts +7 -5
  94. package/src/async-throttler.ts +7 -5
  95. package/src/batcher.ts +7 -5
  96. package/src/debouncer.ts +7 -5
  97. package/src/queuer.ts +7 -5
  98. package/src/rate-limiter.ts +7 -5
  99. package/src/throttler.ts +7 -5
  100. package/dist/cjs/async-batcher.cjs +0 -220
  101. package/dist/cjs/async-batcher.cjs.map +0 -1
  102. package/dist/cjs/async-batcher.d.cts +0 -340
  103. package/dist/cjs/async-debouncer.cjs +0 -231
  104. package/dist/cjs/async-debouncer.cjs.map +0 -1
  105. package/dist/cjs/async-debouncer.d.cts +0 -295
  106. package/dist/cjs/async-queuer.cjs +0 -397
  107. package/dist/cjs/async-queuer.cjs.map +0 -1
  108. package/dist/cjs/async-queuer.d.cts +0 -435
  109. package/dist/cjs/async-rate-limiter.cjs +0 -252
  110. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  111. package/dist/cjs/async-retryer.cjs +0 -285
  112. package/dist/cjs/async-retryer.cjs.map +0 -1
  113. package/dist/cjs/async-retryer.d.cts +0 -308
  114. package/dist/cjs/async-throttler.cjs +0 -261
  115. package/dist/cjs/async-throttler.cjs.map +0 -1
  116. package/dist/cjs/async-throttler.d.cts +0 -315
  117. package/dist/cjs/batcher.cjs +0 -130
  118. package/dist/cjs/batcher.cjs.map +0 -1
  119. package/dist/cjs/batcher.d.cts +0 -176
  120. package/dist/cjs/debouncer.cjs +0 -137
  121. package/dist/cjs/debouncer.cjs.map +0 -1
  122. package/dist/cjs/debouncer.d.cts +0 -162
  123. package/dist/cjs/event-client.cjs +0 -20
  124. package/dist/cjs/event-client.cjs.map +0 -1
  125. package/dist/cjs/event-client.d.cts +0 -45
  126. package/dist/cjs/index.cjs +0 -51
  127. package/dist/cjs/index.cjs.map +0 -1
  128. package/dist/cjs/index.d.cts +0 -15
  129. package/dist/cjs/queuer.cjs +0 -306
  130. package/dist/cjs/queuer.cjs.map +0 -1
  131. package/dist/cjs/queuer.d.cts +0 -340
  132. package/dist/cjs/rate-limiter.cjs +0 -179
  133. package/dist/cjs/rate-limiter.cjs.map +0 -1
  134. package/dist/cjs/throttler.cjs +0 -151
  135. package/dist/cjs/throttler.cjs.map +0 -1
  136. package/dist/cjs/throttler.d.cts +0 -202
  137. package/dist/cjs/types.d.cts +0 -9
  138. package/dist/cjs/utils.cjs +0 -11
  139. package/dist/cjs/utils.cjs.map +0 -1
  140. package/dist/cjs/utils.d.cts +0 -3
  141. package/dist/esm/async-batcher.d.ts +0 -340
  142. package/dist/esm/async-batcher.js +0 -220
  143. package/dist/esm/async-batcher.js.map +0 -1
  144. package/dist/esm/async-debouncer.d.ts +0 -295
  145. package/dist/esm/async-debouncer.js +0 -231
  146. package/dist/esm/async-debouncer.js.map +0 -1
  147. package/dist/esm/async-queuer.d.ts +0 -435
  148. package/dist/esm/async-queuer.js +0 -397
  149. package/dist/esm/async-queuer.js.map +0 -1
  150. package/dist/esm/async-rate-limiter.js +0 -252
  151. package/dist/esm/async-rate-limiter.js.map +0 -1
  152. package/dist/esm/async-retryer.d.ts +0 -308
  153. package/dist/esm/async-retryer.js +0 -285
  154. package/dist/esm/async-retryer.js.map +0 -1
  155. package/dist/esm/async-throttler.d.ts +0 -315
  156. package/dist/esm/async-throttler.js +0 -261
  157. package/dist/esm/async-throttler.js.map +0 -1
  158. package/dist/esm/batcher.d.ts +0 -176
  159. package/dist/esm/batcher.js +0 -130
  160. package/dist/esm/batcher.js.map +0 -1
  161. package/dist/esm/debouncer.d.ts +0 -162
  162. package/dist/esm/debouncer.js +0 -137
  163. package/dist/esm/debouncer.js.map +0 -1
  164. package/dist/esm/event-client.d.ts +0 -45
  165. package/dist/esm/event-client.js +0 -20
  166. package/dist/esm/event-client.js.map +0 -1
  167. package/dist/esm/index.d.ts +0 -15
  168. package/dist/esm/index.js.map +0 -1
  169. package/dist/esm/queuer.d.ts +0 -340
  170. package/dist/esm/queuer.js +0 -306
  171. package/dist/esm/queuer.js.map +0 -1
  172. package/dist/esm/rate-limiter.js +0 -179
  173. package/dist/esm/rate-limiter.js.map +0 -1
  174. package/dist/esm/throttler.d.ts +0 -202
  175. package/dist/esm/throttler.js +0 -151
  176. package/dist/esm/throttler.js.map +0 -1
  177. package/dist/esm/types.d.ts +0 -9
  178. package/dist/esm/utils.d.ts +0 -3
  179. package/dist/esm/utils.js +0 -11
  180. package/dist/esm/utils.js.map +0 -1
@@ -0,0 +1,209 @@
1
+ const require_utils = require('./utils.cjs');
2
+ const require_event_client = require('./event-client.cjs');
3
+ let __tanstack_store = require("@tanstack/store");
4
+
5
+ //#region src/throttler.ts
6
+ function getDefaultThrottlerState() {
7
+ return {
8
+ executionCount: 0,
9
+ isPending: false,
10
+ lastArgs: void 0,
11
+ lastExecutionTime: 0,
12
+ nextExecutionTime: 0,
13
+ status: "idle",
14
+ maybeExecuteCount: 0
15
+ };
16
+ }
17
+ /**
18
+ * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
19
+ */
20
+ function throttlerOptions(options) {
21
+ return options;
22
+ }
23
+ const defaultOptions = {
24
+ enabled: true,
25
+ leading: true,
26
+ trailing: true,
27
+ wait: 0
28
+ };
29
+ /**
30
+ * A class that creates a throttled function.
31
+ *
32
+ * Throttling ensures a function is called at most once within a specified time window.
33
+ * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
34
+ * execution timing regardless of call frequency.
35
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
36
+ *
37
+ * Supports both leading and trailing edge execution:
38
+ * - Leading: Execute immediately on first call (default: true)
39
+ * - Trailing: Execute after wait period if called during throttle (default: true)
40
+ *
41
+ * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
42
+ *
43
+ * State Management:
44
+ * - Uses TanStack Store for reactive state management
45
+ * - Use `initialState` to provide initial state values when creating the throttler
46
+ * - Use `onExecute` callback to react to function execution and implement custom logic
47
+ * - The state includes execution count, last execution time, pending status, and more
48
+ * - State can be accessed via `throttler.store.state` when using the class directly
49
+ * - When using framework adapters (React/Solid), state is accessed from `throttler.state`
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const throttler = new Throttler(
54
+ * (id: string) => api.getData(id),
55
+ * { wait: 1000 } // Execute at most once per second
56
+ * );
57
+ *
58
+ * // First call executes immediately
59
+ * throttler.maybeExecute('123');
60
+ *
61
+ * // Subsequent calls within 1000ms are throttled
62
+ * throttler.maybeExecute('123'); // Throttled
63
+ * ```
64
+ */
65
+ var Throttler = class {
66
+ #timeoutId;
67
+ constructor(fn, initialOptions) {
68
+ this.fn = fn;
69
+ this.store = new __tanstack_store.Store(getDefaultThrottlerState());
70
+ this.setOptions = (newOptions) => {
71
+ this.options = {
72
+ ...this.options,
73
+ ...newOptions
74
+ };
75
+ if (!this.#getEnabled()) this.cancel();
76
+ };
77
+ this.maybeExecute = (...args) => {
78
+ this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
79
+ const now = Date.now();
80
+ const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
81
+ const wait = this.#getWait();
82
+ if (this.options.leading && timeSinceLastExecution >= wait) this.#execute(...args);
83
+ else {
84
+ this.#setState({ lastArgs: args });
85
+ if (!this.#timeoutId && this.options.trailing) {
86
+ const timeoutDuration = wait - (this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0);
87
+ this.#setState({ isPending: true });
88
+ this.#timeoutId = setTimeout(() => {
89
+ const { lastArgs } = this.store.state;
90
+ if (lastArgs !== void 0) this.#execute(...lastArgs);
91
+ }, timeoutDuration);
92
+ }
93
+ }
94
+ };
95
+ this.flush = () => {
96
+ if (this.store.state.isPending && this.store.state.lastArgs) this.#execute(...this.store.state.lastArgs);
97
+ };
98
+ this.cancel = () => {
99
+ this.#clearTimeout();
100
+ this.#setState({
101
+ lastArgs: void 0,
102
+ isPending: false
103
+ });
104
+ };
105
+ this.reset = () => {
106
+ this.#setState(getDefaultThrottlerState());
107
+ };
108
+ this.key = initialOptions.key;
109
+ this.options = {
110
+ ...defaultOptions,
111
+ ...initialOptions
112
+ };
113
+ this.#setState(this.options.initialState ?? {});
114
+ if (this.key) require_event_client.pacerEventClient.on("d-Throttler", (event) => {
115
+ if (event.payload.key !== this.key) return;
116
+ this.#setState(event.payload.store.state);
117
+ this.setOptions(event.payload.options);
118
+ });
119
+ }
120
+ #setState = (newState) => {
121
+ this.store.setState((state) => {
122
+ const combinedState = {
123
+ ...state,
124
+ ...newState
125
+ };
126
+ const { isPending } = combinedState;
127
+ return {
128
+ ...combinedState,
129
+ status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
130
+ };
131
+ });
132
+ require_event_client.emitChange("Throttler", this);
133
+ };
134
+ #getEnabled = () => {
135
+ return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
136
+ };
137
+ #getWait = () => {
138
+ return require_utils.parseFunctionOrValue(this.options.wait, this);
139
+ };
140
+ #execute = (...args) => {
141
+ if (!this.#getEnabled()) return;
142
+ this.fn(...args);
143
+ const lastExecutionTime = Date.now();
144
+ const nextExecutionTime = lastExecutionTime + this.#getWait();
145
+ this.#clearTimeout();
146
+ this.#setState({
147
+ executionCount: this.store.state.executionCount + 1,
148
+ lastExecutionTime,
149
+ nextExecutionTime,
150
+ isPending: false,
151
+ lastArgs: void 0
152
+ });
153
+ this.options.onExecute?.(args, this);
154
+ setTimeout(() => {
155
+ if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
156
+ }, this.#getWait());
157
+ };
158
+ #clearTimeout = () => {
159
+ if (this.#timeoutId) {
160
+ clearTimeout(this.#timeoutId);
161
+ this.#timeoutId = void 0;
162
+ }
163
+ };
164
+ };
165
+ /**
166
+ * Creates a throttled function that limits how often the provided function can execute.
167
+ *
168
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
169
+ *
170
+ * Throttling ensures a function executes at most once within a specified time window,
171
+ * regardless of how many times it is called. This is useful for rate-limiting
172
+ * expensive operations or UI updates.
173
+ *
174
+ * The throttled function can be configured to execute on the leading and/or trailing
175
+ * edge of the throttle window via options.
176
+ *
177
+ * For handling bursts of events, consider using debounce() instead. For hard execution
178
+ * limits, consider using rateLimit().
179
+ *
180
+ * State Management:
181
+ * - Uses TanStack Store for reactive state management
182
+ * - Use `initialState` to provide initial state values when creating the throttler
183
+ * - Use `onExecute` callback to react to function execution and implement custom logic
184
+ * - The state includes execution count, last execution time, pending status, and more
185
+ * - State can be accessed via the underlying Throttler instance's `store.state` property
186
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * // Basic throttling - max once per second
191
+ * const throttled = throttle(updateUI, { wait: 1000 });
192
+ *
193
+ * // Configure leading/trailing execution
194
+ * const throttled = throttle(saveData, {
195
+ * wait: 2000,
196
+ * leading: true, // Execute immediately on first call
197
+ * trailing: true // Execute again after delay if called during wait
198
+ * });
199
+ * ```
200
+ */
201
+ function throttle(fn, initialOptions) {
202
+ return new Throttler(fn, initialOptions).maybeExecute;
203
+ }
204
+
205
+ //#endregion
206
+ exports.Throttler = Throttler;
207
+ exports.throttle = throttle;
208
+ exports.throttlerOptions = throttlerOptions;
209
+ //# sourceMappingURL=throttler.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttler.cjs","names":["defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n>","fn: TFn","Store","#getEnabled","#setState","#getWait","#execute","#timeoutId","#clearTimeout","parseFunctionOrValue"],"sources":["../src/throttler.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 ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as ThrottlerState<TFn>)\n this.setOptions(event.payload.options)\n })\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#execute(...this.store.state.lastArgs)\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"mappings":"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"}
@@ -0,0 +1,207 @@
1
+ import { AnyFunction } from "./types.cjs";
2
+ import { Store } from "@tanstack/store";
3
+
4
+ //#region src/throttler.d.ts
5
+ interface ThrottlerState<TFn extends AnyFunction> {
6
+ /**
7
+ * Number of function executions that have been completed
8
+ */
9
+ executionCount: number;
10
+ /**
11
+ * Whether the throttler is waiting for the timeout to trigger execution
12
+ */
13
+ isPending: boolean;
14
+ /**
15
+ * The arguments from the most recent call to maybeExecute
16
+ */
17
+ lastArgs: Parameters<TFn> | undefined;
18
+ /**
19
+ * Timestamp of the last function execution in milliseconds
20
+ */
21
+ lastExecutionTime: number;
22
+ /**
23
+ * Number of times maybeExecute has been called (for reduction calculations)
24
+ */
25
+ maybeExecuteCount: number;
26
+ /**
27
+ * Timestamp when the next execution can occur in milliseconds
28
+ */
29
+ nextExecutionTime: number | undefined;
30
+ /**
31
+ * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
32
+ */
33
+ status: 'disabled' | 'idle' | 'pending';
34
+ }
35
+ /**
36
+ * Options for configuring a throttled function
37
+ */
38
+ interface ThrottlerOptions<TFn extends AnyFunction> {
39
+ /**
40
+ * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
41
+ * Can be a boolean or a function that returns a boolean.
42
+ * Defaults to true.
43
+ */
44
+ enabled?: boolean | ((throttler: Throttler<TFn>) => boolean);
45
+ /**
46
+ * Initial state for the throttler
47
+ */
48
+ initialState?: Partial<ThrottlerState<TFn>>;
49
+ /**
50
+ * A key to identify the throttler.
51
+ * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.
52
+ */
53
+ key?: string;
54
+ /**
55
+ * Whether to execute on the leading edge of the timeout.
56
+ * Defaults to true.
57
+ */
58
+ leading?: boolean;
59
+ /**
60
+ * Callback function that is called after the function is executed
61
+ */
62
+ onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void;
63
+ /**
64
+ * Whether to execute on the trailing edge of the timeout.
65
+ * Defaults to true.
66
+ */
67
+ trailing?: boolean;
68
+ /**
69
+ * Time window in milliseconds during which the function can only be executed once.
70
+ * Can be a number or a function that returns a number.
71
+ * Defaults to 0ms
72
+ */
73
+ wait: number | ((throttler: Throttler<TFn>) => number);
74
+ }
75
+ /**
76
+ * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
77
+ */
78
+ declare function throttlerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<ThrottlerOptions<TFn>>>(options: TOptions): TOptions;
79
+ /**
80
+ * A class that creates a throttled function.
81
+ *
82
+ * Throttling ensures a function is called at most once within a specified time window.
83
+ * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
84
+ * execution timing regardless of call frequency.
85
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
86
+ *
87
+ * Supports both leading and trailing edge execution:
88
+ * - Leading: Execute immediately on first call (default: true)
89
+ * - Trailing: Execute after wait period if called during throttle (default: true)
90
+ *
91
+ * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
92
+ *
93
+ * State Management:
94
+ * - Uses TanStack Store for reactive state management
95
+ * - Use `initialState` to provide initial state values when creating the throttler
96
+ * - Use `onExecute` callback to react to function execution and implement custom logic
97
+ * - The state includes execution count, last execution time, pending status, and more
98
+ * - State can be accessed via `throttler.store.state` when using the class directly
99
+ * - When using framework adapters (React/Solid), state is accessed from `throttler.state`
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * const throttler = new Throttler(
104
+ * (id: string) => api.getData(id),
105
+ * { wait: 1000 } // Execute at most once per second
106
+ * );
107
+ *
108
+ * // First call executes immediately
109
+ * throttler.maybeExecute('123');
110
+ *
111
+ * // Subsequent calls within 1000ms are throttled
112
+ * throttler.maybeExecute('123'); // Throttled
113
+ * ```
114
+ */
115
+ declare class Throttler<TFn extends AnyFunction> {
116
+ #private;
117
+ fn: TFn;
118
+ readonly store: Store<Readonly<ThrottlerState<TFn>>>;
119
+ key: string | undefined;
120
+ options: ThrottlerOptions<TFn>;
121
+ constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
122
+ /**
123
+ * Updates the throttler options
124
+ */
125
+ setOptions: (newOptions: Partial<ThrottlerOptions<TFn>>) => void;
126
+ /**
127
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
128
+ *
129
+ * - If enough time has passed since the last execution (>= wait period):
130
+ * - With leading=true: Executes immediately
131
+ * - With leading=false: Waits for the next trailing execution
132
+ *
133
+ * - If within the wait period:
134
+ * - With trailing=true: Schedules execution for end of wait period
135
+ * - With trailing=false: Drops the execution
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * const throttled = new Throttler(fn, { wait: 1000 });
140
+ *
141
+ * // First call executes immediately
142
+ * throttled.maybeExecute('a', 'b');
143
+ *
144
+ * // Call during wait period - gets throttled
145
+ * throttled.maybeExecute('c', 'd');
146
+ * ```
147
+ */
148
+ maybeExecute: (...args: Parameters<TFn>) => void;
149
+ /**
150
+ * Processes the current pending execution immediately
151
+ */
152
+ flush: () => void;
153
+ /**
154
+ * Cancels any pending trailing execution and clears internal state.
155
+ *
156
+ * If a trailing execution is scheduled (due to throttling with trailing=true),
157
+ * this will prevent that execution from occurring. The internal timeout and
158
+ * stored arguments will be cleared.
159
+ *
160
+ * Has no effect if there is no pending execution.
161
+ */
162
+ cancel: () => void;
163
+ /**
164
+ * Resets the throttler state to its default values
165
+ */
166
+ reset: () => void;
167
+ }
168
+ /**
169
+ * Creates a throttled function that limits how often the provided function can execute.
170
+ *
171
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
172
+ *
173
+ * Throttling ensures a function executes at most once within a specified time window,
174
+ * regardless of how many times it is called. This is useful for rate-limiting
175
+ * expensive operations or UI updates.
176
+ *
177
+ * The throttled function can be configured to execute on the leading and/or trailing
178
+ * edge of the throttle window via options.
179
+ *
180
+ * For handling bursts of events, consider using debounce() instead. For hard execution
181
+ * limits, consider using rateLimit().
182
+ *
183
+ * State Management:
184
+ * - Uses TanStack Store for reactive state management
185
+ * - Use `initialState` to provide initial state values when creating the throttler
186
+ * - Use `onExecute` callback to react to function execution and implement custom logic
187
+ * - The state includes execution count, last execution time, pending status, and more
188
+ * - State can be accessed via the underlying Throttler instance's `store.state` property
189
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * // Basic throttling - max once per second
194
+ * const throttled = throttle(updateUI, { wait: 1000 });
195
+ *
196
+ * // Configure leading/trailing execution
197
+ * const throttled = throttle(saveData, {
198
+ * wait: 2000,
199
+ * leading: true, // Execute immediately on first call
200
+ * trailing: true // Execute again after delay if called during wait
201
+ * });
202
+ * ```
203
+ */
204
+ declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: ThrottlerOptions<TFn>): (...args: Parameters<TFn>) => void;
205
+ //#endregion
206
+ export { Throttler, ThrottlerOptions, ThrottlerState, throttle, throttlerOptions };
207
+ //# sourceMappingURL=throttler.d.cts.map
@@ -0,0 +1,207 @@
1
+ import { AnyFunction } from "./types.js";
2
+ import { Store } from "@tanstack/store";
3
+
4
+ //#region src/throttler.d.ts
5
+ interface ThrottlerState<TFn extends AnyFunction> {
6
+ /**
7
+ * Number of function executions that have been completed
8
+ */
9
+ executionCount: number;
10
+ /**
11
+ * Whether the throttler is waiting for the timeout to trigger execution
12
+ */
13
+ isPending: boolean;
14
+ /**
15
+ * The arguments from the most recent call to maybeExecute
16
+ */
17
+ lastArgs: Parameters<TFn> | undefined;
18
+ /**
19
+ * Timestamp of the last function execution in milliseconds
20
+ */
21
+ lastExecutionTime: number;
22
+ /**
23
+ * Number of times maybeExecute has been called (for reduction calculations)
24
+ */
25
+ maybeExecuteCount: number;
26
+ /**
27
+ * Timestamp when the next execution can occur in milliseconds
28
+ */
29
+ nextExecutionTime: number | undefined;
30
+ /**
31
+ * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
32
+ */
33
+ status: 'disabled' | 'idle' | 'pending';
34
+ }
35
+ /**
36
+ * Options for configuring a throttled function
37
+ */
38
+ interface ThrottlerOptions<TFn extends AnyFunction> {
39
+ /**
40
+ * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
41
+ * Can be a boolean or a function that returns a boolean.
42
+ * Defaults to true.
43
+ */
44
+ enabled?: boolean | ((throttler: Throttler<TFn>) => boolean);
45
+ /**
46
+ * Initial state for the throttler
47
+ */
48
+ initialState?: Partial<ThrottlerState<TFn>>;
49
+ /**
50
+ * A key to identify the throttler.
51
+ * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.
52
+ */
53
+ key?: string;
54
+ /**
55
+ * Whether to execute on the leading edge of the timeout.
56
+ * Defaults to true.
57
+ */
58
+ leading?: boolean;
59
+ /**
60
+ * Callback function that is called after the function is executed
61
+ */
62
+ onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void;
63
+ /**
64
+ * Whether to execute on the trailing edge of the timeout.
65
+ * Defaults to true.
66
+ */
67
+ trailing?: boolean;
68
+ /**
69
+ * Time window in milliseconds during which the function can only be executed once.
70
+ * Can be a number or a function that returns a number.
71
+ * Defaults to 0ms
72
+ */
73
+ wait: number | ((throttler: Throttler<TFn>) => number);
74
+ }
75
+ /**
76
+ * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
77
+ */
78
+ declare function throttlerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<ThrottlerOptions<TFn>>>(options: TOptions): TOptions;
79
+ /**
80
+ * A class that creates a throttled function.
81
+ *
82
+ * Throttling ensures a function is called at most once within a specified time window.
83
+ * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
84
+ * execution timing regardless of call frequency.
85
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
86
+ *
87
+ * Supports both leading and trailing edge execution:
88
+ * - Leading: Execute immediately on first call (default: true)
89
+ * - Trailing: Execute after wait period if called during throttle (default: true)
90
+ *
91
+ * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
92
+ *
93
+ * State Management:
94
+ * - Uses TanStack Store for reactive state management
95
+ * - Use `initialState` to provide initial state values when creating the throttler
96
+ * - Use `onExecute` callback to react to function execution and implement custom logic
97
+ * - The state includes execution count, last execution time, pending status, and more
98
+ * - State can be accessed via `throttler.store.state` when using the class directly
99
+ * - When using framework adapters (React/Solid), state is accessed from `throttler.state`
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * const throttler = new Throttler(
104
+ * (id: string) => api.getData(id),
105
+ * { wait: 1000 } // Execute at most once per second
106
+ * );
107
+ *
108
+ * // First call executes immediately
109
+ * throttler.maybeExecute('123');
110
+ *
111
+ * // Subsequent calls within 1000ms are throttled
112
+ * throttler.maybeExecute('123'); // Throttled
113
+ * ```
114
+ */
115
+ declare class Throttler<TFn extends AnyFunction> {
116
+ #private;
117
+ fn: TFn;
118
+ readonly store: Store<Readonly<ThrottlerState<TFn>>>;
119
+ key: string | undefined;
120
+ options: ThrottlerOptions<TFn>;
121
+ constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
122
+ /**
123
+ * Updates the throttler options
124
+ */
125
+ setOptions: (newOptions: Partial<ThrottlerOptions<TFn>>) => void;
126
+ /**
127
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
128
+ *
129
+ * - If enough time has passed since the last execution (>= wait period):
130
+ * - With leading=true: Executes immediately
131
+ * - With leading=false: Waits for the next trailing execution
132
+ *
133
+ * - If within the wait period:
134
+ * - With trailing=true: Schedules execution for end of wait period
135
+ * - With trailing=false: Drops the execution
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * const throttled = new Throttler(fn, { wait: 1000 });
140
+ *
141
+ * // First call executes immediately
142
+ * throttled.maybeExecute('a', 'b');
143
+ *
144
+ * // Call during wait period - gets throttled
145
+ * throttled.maybeExecute('c', 'd');
146
+ * ```
147
+ */
148
+ maybeExecute: (...args: Parameters<TFn>) => void;
149
+ /**
150
+ * Processes the current pending execution immediately
151
+ */
152
+ flush: () => void;
153
+ /**
154
+ * Cancels any pending trailing execution and clears internal state.
155
+ *
156
+ * If a trailing execution is scheduled (due to throttling with trailing=true),
157
+ * this will prevent that execution from occurring. The internal timeout and
158
+ * stored arguments will be cleared.
159
+ *
160
+ * Has no effect if there is no pending execution.
161
+ */
162
+ cancel: () => void;
163
+ /**
164
+ * Resets the throttler state to its default values
165
+ */
166
+ reset: () => void;
167
+ }
168
+ /**
169
+ * Creates a throttled function that limits how often the provided function can execute.
170
+ *
171
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
172
+ *
173
+ * Throttling ensures a function executes at most once within a specified time window,
174
+ * regardless of how many times it is called. This is useful for rate-limiting
175
+ * expensive operations or UI updates.
176
+ *
177
+ * The throttled function can be configured to execute on the leading and/or trailing
178
+ * edge of the throttle window via options.
179
+ *
180
+ * For handling bursts of events, consider using debounce() instead. For hard execution
181
+ * limits, consider using rateLimit().
182
+ *
183
+ * State Management:
184
+ * - Uses TanStack Store for reactive state management
185
+ * - Use `initialState` to provide initial state values when creating the throttler
186
+ * - Use `onExecute` callback to react to function execution and implement custom logic
187
+ * - The state includes execution count, last execution time, pending status, and more
188
+ * - State can be accessed via the underlying Throttler instance's `store.state` property
189
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * // Basic throttling - max once per second
194
+ * const throttled = throttle(updateUI, { wait: 1000 });
195
+ *
196
+ * // Configure leading/trailing execution
197
+ * const throttled = throttle(saveData, {
198
+ * wait: 2000,
199
+ * leading: true, // Execute immediately on first call
200
+ * trailing: true // Execute again after delay if called during wait
201
+ * });
202
+ * ```
203
+ */
204
+ declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: ThrottlerOptions<TFn>): (...args: Parameters<TFn>) => void;
205
+ //#endregion
206
+ export { Throttler, ThrottlerOptions, ThrottlerState, throttle, throttlerOptions };
207
+ //# sourceMappingURL=throttler.d.ts.map