@tanstack/pacer 0.16.3 → 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 (169) 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/dist/cjs/async-batcher.cjs +0 -222
  90. package/dist/cjs/async-batcher.cjs.map +0 -1
  91. package/dist/cjs/async-batcher.d.cts +0 -340
  92. package/dist/cjs/async-debouncer.cjs +0 -233
  93. package/dist/cjs/async-debouncer.cjs.map +0 -1
  94. package/dist/cjs/async-debouncer.d.cts +0 -295
  95. package/dist/cjs/async-queuer.cjs +0 -399
  96. package/dist/cjs/async-queuer.cjs.map +0 -1
  97. package/dist/cjs/async-queuer.d.cts +0 -435
  98. package/dist/cjs/async-rate-limiter.cjs +0 -254
  99. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  100. package/dist/cjs/async-retryer.cjs +0 -287
  101. package/dist/cjs/async-retryer.cjs.map +0 -1
  102. package/dist/cjs/async-retryer.d.cts +0 -308
  103. package/dist/cjs/async-throttler.cjs +0 -263
  104. package/dist/cjs/async-throttler.cjs.map +0 -1
  105. package/dist/cjs/async-throttler.d.cts +0 -315
  106. package/dist/cjs/batcher.cjs +0 -132
  107. package/dist/cjs/batcher.cjs.map +0 -1
  108. package/dist/cjs/batcher.d.cts +0 -176
  109. package/dist/cjs/debouncer.cjs +0 -139
  110. package/dist/cjs/debouncer.cjs.map +0 -1
  111. package/dist/cjs/debouncer.d.cts +0 -162
  112. package/dist/cjs/event-client.cjs +0 -20
  113. package/dist/cjs/event-client.cjs.map +0 -1
  114. package/dist/cjs/event-client.d.cts +0 -45
  115. package/dist/cjs/index.cjs +0 -51
  116. package/dist/cjs/index.cjs.map +0 -1
  117. package/dist/cjs/index.d.cts +0 -15
  118. package/dist/cjs/queuer.cjs +0 -308
  119. package/dist/cjs/queuer.cjs.map +0 -1
  120. package/dist/cjs/queuer.d.cts +0 -340
  121. package/dist/cjs/rate-limiter.cjs +0 -181
  122. package/dist/cjs/rate-limiter.cjs.map +0 -1
  123. package/dist/cjs/throttler.cjs +0 -153
  124. package/dist/cjs/throttler.cjs.map +0 -1
  125. package/dist/cjs/throttler.d.cts +0 -202
  126. package/dist/cjs/types.d.cts +0 -9
  127. package/dist/cjs/utils.cjs +0 -11
  128. package/dist/cjs/utils.cjs.map +0 -1
  129. package/dist/cjs/utils.d.cts +0 -3
  130. package/dist/esm/async-batcher.d.ts +0 -340
  131. package/dist/esm/async-batcher.js +0 -222
  132. package/dist/esm/async-batcher.js.map +0 -1
  133. package/dist/esm/async-debouncer.d.ts +0 -295
  134. package/dist/esm/async-debouncer.js +0 -233
  135. package/dist/esm/async-debouncer.js.map +0 -1
  136. package/dist/esm/async-queuer.d.ts +0 -435
  137. package/dist/esm/async-queuer.js +0 -399
  138. package/dist/esm/async-queuer.js.map +0 -1
  139. package/dist/esm/async-rate-limiter.js +0 -254
  140. package/dist/esm/async-rate-limiter.js.map +0 -1
  141. package/dist/esm/async-retryer.d.ts +0 -308
  142. package/dist/esm/async-retryer.js +0 -287
  143. package/dist/esm/async-retryer.js.map +0 -1
  144. package/dist/esm/async-throttler.d.ts +0 -315
  145. package/dist/esm/async-throttler.js +0 -263
  146. package/dist/esm/async-throttler.js.map +0 -1
  147. package/dist/esm/batcher.d.ts +0 -176
  148. package/dist/esm/batcher.js +0 -132
  149. package/dist/esm/batcher.js.map +0 -1
  150. package/dist/esm/debouncer.d.ts +0 -162
  151. package/dist/esm/debouncer.js +0 -139
  152. package/dist/esm/debouncer.js.map +0 -1
  153. package/dist/esm/event-client.d.ts +0 -45
  154. package/dist/esm/event-client.js +0 -20
  155. package/dist/esm/event-client.js.map +0 -1
  156. package/dist/esm/index.d.ts +0 -15
  157. package/dist/esm/index.js.map +0 -1
  158. package/dist/esm/queuer.d.ts +0 -340
  159. package/dist/esm/queuer.js +0 -308
  160. package/dist/esm/queuer.js.map +0 -1
  161. package/dist/esm/rate-limiter.js +0 -181
  162. package/dist/esm/rate-limiter.js.map +0 -1
  163. package/dist/esm/throttler.d.ts +0 -202
  164. package/dist/esm/throttler.js +0 -153
  165. package/dist/esm/throttler.js.map +0 -1
  166. package/dist/esm/types.d.ts +0 -9
  167. package/dist/esm/utils.d.ts +0 -3
  168. package/dist/esm/utils.js +0 -11
  169. package/dist/esm/utils.js.map +0 -1
@@ -1,153 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const store = require("@tanstack/store");
4
- const utils = require("./utils.cjs");
5
- const eventClient = require("./event-client.cjs");
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
- function throttlerOptions(options) {
18
- return options;
19
- }
20
- const defaultOptions = {
21
- enabled: true,
22
- leading: true,
23
- trailing: true,
24
- wait: 0
25
- };
26
- class Throttler {
27
- constructor(fn, initialOptions) {
28
- this.fn = fn;
29
- this.store = new store.Store(
30
- getDefaultThrottlerState()
31
- );
32
- this.setOptions = (newOptions) => {
33
- this.options = { ...this.options, ...newOptions };
34
- if (!this.#getEnabled()) {
35
- this.cancel();
36
- }
37
- };
38
- this.#setState = (newState) => {
39
- this.store.setState((state) => {
40
- const combinedState = {
41
- ...state,
42
- ...newState
43
- };
44
- const { isPending } = combinedState;
45
- return {
46
- ...combinedState,
47
- status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
48
- };
49
- });
50
- eventClient.emitChange("Throttler", this);
51
- };
52
- this.#getEnabled = () => {
53
- return !!utils.parseFunctionOrValue(this.options.enabled, this);
54
- };
55
- this.#getWait = () => {
56
- return utils.parseFunctionOrValue(this.options.wait, this);
57
- };
58
- this.maybeExecute = (...args) => {
59
- this.#setState({
60
- maybeExecuteCount: this.store.state.maybeExecuteCount + 1
61
- });
62
- const now = Date.now();
63
- const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
64
- const wait = this.#getWait();
65
- if (this.options.leading && timeSinceLastExecution >= wait) {
66
- this.#execute(...args);
67
- } else {
68
- this.#setState({
69
- lastArgs: args
70
- });
71
- if (!this.#timeoutId && this.options.trailing) {
72
- const _timeSinceLastExecution = this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0;
73
- const timeoutDuration = wait - _timeSinceLastExecution;
74
- this.#setState({ isPending: true });
75
- this.#timeoutId = setTimeout(() => {
76
- const { lastArgs } = this.store.state;
77
- if (lastArgs !== void 0) {
78
- this.#execute(...lastArgs);
79
- }
80
- }, timeoutDuration);
81
- }
82
- }
83
- };
84
- this.#execute = (...args) => {
85
- if (!this.#getEnabled()) return;
86
- this.fn(...args);
87
- const lastExecutionTime = Date.now();
88
- const nextExecutionTime = lastExecutionTime + this.#getWait();
89
- this.#clearTimeout();
90
- this.#setState({
91
- executionCount: this.store.state.executionCount + 1,
92
- lastExecutionTime,
93
- nextExecutionTime,
94
- isPending: false,
95
- lastArgs: void 0
96
- });
97
- this.options.onExecute?.(args, this);
98
- setTimeout(() => {
99
- if (!this.store.state.isPending) {
100
- this.#setState({ nextExecutionTime: void 0 });
101
- }
102
- }, this.#getWait());
103
- };
104
- this.flush = () => {
105
- if (this.store.state.isPending && this.store.state.lastArgs) {
106
- this.#execute(...this.store.state.lastArgs);
107
- }
108
- };
109
- this.#clearTimeout = () => {
110
- if (this.#timeoutId) {
111
- clearTimeout(this.#timeoutId);
112
- this.#timeoutId = void 0;
113
- }
114
- };
115
- this.cancel = () => {
116
- this.#clearTimeout();
117
- this.#setState({
118
- lastArgs: void 0,
119
- isPending: false
120
- });
121
- };
122
- this.reset = () => {
123
- this.#setState(getDefaultThrottlerState());
124
- };
125
- this.key = initialOptions.key;
126
- this.options = {
127
- ...defaultOptions,
128
- ...initialOptions
129
- };
130
- this.#setState(this.options.initialState ?? {});
131
- if (this.key) {
132
- eventClient.pacerEventClient.on("d-Throttler", (event) => {
133
- if (event.payload.key !== this.key) return;
134
- this.#setState(event.payload.store.state);
135
- this.setOptions(event.payload.options);
136
- });
137
- }
138
- }
139
- #timeoutId;
140
- #setState;
141
- #getEnabled;
142
- #getWait;
143
- #execute;
144
- #clearTimeout;
145
- }
146
- function throttle(fn, initialOptions) {
147
- const throttler = new Throttler(fn, initialOptions);
148
- return throttler.maybeExecute;
149
- }
150
- exports.Throttler = Throttler;
151
- exports.throttle = throttle;
152
- exports.throttlerOptions = throttlerOptions;
153
- //# sourceMappingURL=throttler.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"throttler.cjs","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"],"names":["Store","emitChange","parseFunctionOrValue","pacerEventClient"],"mappings":";;;;;AAoCA,SAAS,2BAEgB;AACvB,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB;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A,SAAA,gBAAgB,MAAY;AAC1B,UAAI,KAAK,YAAY;AACnB,qBAAa,KAAK,UAAU;AAC5B,aAAK,aAAa;AAAA,MACpB;AAAA,IACF;AAWA,SAAA,SAAS,MAAY;AACnB,WAAK,cAAA;AACL,WAAK,UAAU;AAAA,QACb,UAAU;AAAA,QACV,WAAW;AAAA,MAAA,CACZ;AAAA,IACH;AAKA,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,0BAA+B;AAAA,IAChD;AA3KE,SAAK,MAAM,eAAe;AAC1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAE9C,QAAI,KAAK,KAAK;AACZC,kBAAAA,iBAAiB,GAAG,eAAe,CAAC,UAAU;AAC5C,YAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,aAAK,UAAU,MAAM,QAAQ,MAAM,KAA4B;AAC/D,aAAK,WAAW,MAAM,QAAQ,OAAO;AAAA,MACvC,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EApBA;AAAA,EAkCA;AAAA,EAmBA;AAAA,EAIA;AAAA,EA6DA;AAAA,EA8BA;AA8BF;AAsCO,SAAS,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;;;;"}
@@ -1,202 +0,0 @@
1
- import { Store } from '@tanstack/store';
2
- import { AnyFunction } from './types.cjs';
3
- export interface ThrottlerState<TFn extends AnyFunction> {
4
- /**
5
- * Number of function executions that have been completed
6
- */
7
- executionCount: number;
8
- /**
9
- * Whether the throttler is waiting for the timeout to trigger execution
10
- */
11
- isPending: boolean;
12
- /**
13
- * The arguments from the most recent call to maybeExecute
14
- */
15
- lastArgs: Parameters<TFn> | undefined;
16
- /**
17
- * Timestamp of the last function execution in milliseconds
18
- */
19
- lastExecutionTime: number;
20
- /**
21
- * Number of times maybeExecute has been called (for reduction calculations)
22
- */
23
- maybeExecuteCount: number;
24
- /**
25
- * Timestamp when the next execution can occur in milliseconds
26
- */
27
- nextExecutionTime: number | undefined;
28
- /**
29
- * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
30
- */
31
- status: 'disabled' | 'idle' | 'pending';
32
- }
33
- /**
34
- * Options for configuring a throttled function
35
- */
36
- export interface ThrottlerOptions<TFn extends AnyFunction> {
37
- /**
38
- * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
39
- * Can be a boolean or a function that returns a boolean.
40
- * Defaults to true.
41
- */
42
- enabled?: boolean | ((throttler: Throttler<TFn>) => boolean);
43
- /**
44
- * Initial state for the throttler
45
- */
46
- initialState?: Partial<ThrottlerState<TFn>>;
47
- /**
48
- * A key to identify the throttler.
49
- * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.
50
- */
51
- key?: string;
52
- /**
53
- * Whether to execute on the leading edge of the timeout.
54
- * Defaults to true.
55
- */
56
- leading?: boolean;
57
- /**
58
- * Callback function that is called after the function is executed
59
- */
60
- onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void;
61
- /**
62
- * Whether to execute on the trailing edge of the timeout.
63
- * Defaults to true.
64
- */
65
- trailing?: boolean;
66
- /**
67
- * Time window in milliseconds during which the function can only be executed once.
68
- * Can be a number or a function that returns a number.
69
- * Defaults to 0ms
70
- */
71
- wait: number | ((throttler: Throttler<TFn>) => number);
72
- }
73
- /**
74
- * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
75
- */
76
- export declare function throttlerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<ThrottlerOptions<TFn>>>(options: TOptions): TOptions;
77
- /**
78
- * A class that creates a throttled function.
79
- *
80
- * Throttling ensures a function is called at most once within a specified time window.
81
- * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
82
- * execution timing regardless of call frequency.
83
- * 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.
84
- *
85
- * Supports both leading and trailing edge execution:
86
- * - Leading: Execute immediately on first call (default: true)
87
- * - Trailing: Execute after wait period if called during throttle (default: true)
88
- *
89
- * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
90
- *
91
- * State Management:
92
- * - Uses TanStack Store for reactive state management
93
- * - Use `initialState` to provide initial state values when creating the throttler
94
- * - Use `onExecute` callback to react to function execution and implement custom logic
95
- * - The state includes execution count, last execution time, pending status, and more
96
- * - State can be accessed via `throttler.store.state` when using the class directly
97
- * - When using framework adapters (React/Solid), state is accessed from `throttler.state`
98
- *
99
- * @example
100
- * ```ts
101
- * const throttler = new Throttler(
102
- * (id: string) => api.getData(id),
103
- * { wait: 1000 } // Execute at most once per second
104
- * );
105
- *
106
- * // First call executes immediately
107
- * throttler.maybeExecute('123');
108
- *
109
- * // Subsequent calls within 1000ms are throttled
110
- * throttler.maybeExecute('123'); // Throttled
111
- * ```
112
- */
113
- export declare class Throttler<TFn extends AnyFunction> {
114
- #private;
115
- fn: TFn;
116
- readonly store: Store<Readonly<ThrottlerState<TFn>>>;
117
- key: string | undefined;
118
- options: ThrottlerOptions<TFn>;
119
- constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
120
- /**
121
- * Updates the throttler options
122
- */
123
- setOptions: (newOptions: Partial<ThrottlerOptions<TFn>>) => void;
124
- /**
125
- * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
126
- *
127
- * - If enough time has passed since the last execution (>= wait period):
128
- * - With leading=true: Executes immediately
129
- * - With leading=false: Waits for the next trailing execution
130
- *
131
- * - If within the wait period:
132
- * - With trailing=true: Schedules execution for end of wait period
133
- * - With trailing=false: Drops the execution
134
- *
135
- * @example
136
- * ```ts
137
- * const throttled = new Throttler(fn, { wait: 1000 });
138
- *
139
- * // First call executes immediately
140
- * throttled.maybeExecute('a', 'b');
141
- *
142
- * // Call during wait period - gets throttled
143
- * throttled.maybeExecute('c', 'd');
144
- * ```
145
- */
146
- maybeExecute: (...args: Parameters<TFn>) => void;
147
- /**
148
- * Processes the current pending execution immediately
149
- */
150
- flush: () => void;
151
- /**
152
- * Cancels any pending trailing execution and clears internal state.
153
- *
154
- * If a trailing execution is scheduled (due to throttling with trailing=true),
155
- * this will prevent that execution from occurring. The internal timeout and
156
- * stored arguments will be cleared.
157
- *
158
- * Has no effect if there is no pending execution.
159
- */
160
- cancel: () => void;
161
- /**
162
- * Resets the throttler state to its default values
163
- */
164
- reset: () => void;
165
- }
166
- /**
167
- * Creates a throttled function that limits how often the provided function can execute.
168
- *
169
- * 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.
170
- *
171
- * Throttling ensures a function executes at most once within a specified time window,
172
- * regardless of how many times it is called. This is useful for rate-limiting
173
- * expensive operations or UI updates.
174
- *
175
- * The throttled function can be configured to execute on the leading and/or trailing
176
- * edge of the throttle window via options.
177
- *
178
- * For handling bursts of events, consider using debounce() instead. For hard execution
179
- * limits, consider using rateLimit().
180
- *
181
- * State Management:
182
- * - Uses TanStack Store for reactive state management
183
- * - Use `initialState` to provide initial state values when creating the throttler
184
- * - Use `onExecute` callback to react to function execution and implement custom logic
185
- * - The state includes execution count, last execution time, pending status, and more
186
- * - State can be accessed via the underlying Throttler instance's `store.state` property
187
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
188
- *
189
- * @example
190
- * ```ts
191
- * // Basic throttling - max once per second
192
- * const throttled = throttle(updateUI, { wait: 1000 });
193
- *
194
- * // Configure leading/trailing execution
195
- * const throttled = throttle(saveData, {
196
- * wait: 2000,
197
- * leading: true, // Execute immediately on first call
198
- * trailing: true // Execute again after delay if called during wait
199
- * });
200
- * ```
201
- */
202
- export declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: ThrottlerOptions<TFn>): (...args: Parameters<TFn>) => void;
@@ -1,9 +0,0 @@
1
- /**
2
- * Represents a function that can be called with any arguments and returns any value.
3
- */
4
- export type AnyFunction = (...args: Array<any>) => any;
5
- /**
6
- * Represents an asynchronous function that can be called with any arguments and returns a promise.
7
- */
8
- export type AnyAsyncFunction = (...args: Array<any>) => Promise<any>;
9
- export type OptionalKeys<T, TKey extends keyof T> = Omit<T, TKey> & Partial<Pick<T, TKey>>;
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- function isFunction(value) {
4
- return typeof value === "function";
5
- }
6
- function parseFunctionOrValue(value, ...args) {
7
- return isFunction(value) ? value(...args) : value;
8
- }
9
- exports.isFunction = isFunction;
10
- exports.parseFunctionOrValue = parseFunctionOrValue;
11
- //# sourceMappingURL=utils.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n"],"names":[],"mappings":";;AAEO,SAAS,WAAkC,OAAwB;AACxE,SAAO,OAAO,UAAU;AAC1B;AAEO,SAAS,qBACd,UACG,MACA;AACH,SAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C;;;"}
@@ -1,3 +0,0 @@
1
- import { AnyFunction } from './types.cjs';
2
- export declare function isFunction<T extends AnyFunction>(value: any): value is T;
3
- export declare function parseFunctionOrValue<T, TArgs extends Array<any>>(value: T | ((...args: TArgs) => T), ...args: TArgs): T;