@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
@@ -0,0 +1,197 @@
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/debouncer.ts
6
+ function getDefaultDebouncerState() {
7
+ return {
8
+ canLeadingExecute: true,
9
+ executionCount: 0,
10
+ isPending: false,
11
+ lastArgs: void 0,
12
+ status: "idle",
13
+ maybeExecuteCount: 0
14
+ };
15
+ }
16
+ /**
17
+ * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
18
+ */
19
+ function debouncerOptions(options) {
20
+ return options;
21
+ }
22
+ const defaultOptions = {
23
+ enabled: true,
24
+ leading: false,
25
+ trailing: true,
26
+ wait: 0
27
+ };
28
+ /**
29
+ * A class that creates a debounced function.
30
+ *
31
+ * Debouncing ensures that a function is only executed after a certain amount of time has passed
32
+ * since its last invocation. This is useful for handling frequent events like window resizing,
33
+ * scroll events, or input changes where you want to limit the rate of execution.
34
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
35
+ *
36
+ * The debounced function can be configured to execute either at the start of the delay period
37
+ * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
38
+ * will reset the timer.
39
+ *
40
+ * State Management:
41
+ * - Uses TanStack Store for reactive state management
42
+ * - Use `initialState` to provide initial state values when creating the debouncer
43
+ * - Use `onExecute` callback to react to function execution and implement custom logic
44
+ * - The state includes canLeadingExecute, execution count, and isPending status
45
+ * - State can be accessed via `debouncer.store.state` when using the class directly
46
+ * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const debouncer = new Debouncer((value: string) => {
51
+ * saveToDatabase(value);
52
+ * }, { wait: 500 });
53
+ *
54
+ * // Will only save after 500ms of no new input
55
+ * inputElement.addEventListener('input', () => {
56
+ * debouncer.maybeExecute(inputElement.value);
57
+ * });
58
+ * ```
59
+ */
60
+ var Debouncer = class {
61
+ #timeoutId;
62
+ constructor(fn, initialOptions) {
63
+ this.fn = fn;
64
+ this.store = new __tanstack_store.Store(getDefaultDebouncerState());
65
+ this.setOptions = (newOptions) => {
66
+ this.options = {
67
+ ...this.options,
68
+ ...newOptions
69
+ };
70
+ if (!this.#getEnabled()) this.cancel();
71
+ };
72
+ this.maybeExecute = (...args) => {
73
+ if (!this.#getEnabled()) return void 0;
74
+ this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
75
+ let _didLeadingExecute = false;
76
+ if (this.options.leading && this.store.state.canLeadingExecute) {
77
+ this.#setState({ canLeadingExecute: false });
78
+ _didLeadingExecute = true;
79
+ this.#execute(...args);
80
+ }
81
+ if (this.options.trailing) this.#setState({
82
+ isPending: true,
83
+ lastArgs: args
84
+ });
85
+ if (this.#timeoutId) clearTimeout(this.#timeoutId);
86
+ this.#timeoutId = setTimeout(() => {
87
+ this.#setState({ canLeadingExecute: true });
88
+ if (this.options.trailing && !_didLeadingExecute) this.#execute(...args);
89
+ }, this.#getWait());
90
+ };
91
+ this.flush = () => {
92
+ if (this.store.state.isPending && this.store.state.lastArgs) {
93
+ this.#clearTimeout();
94
+ this.#execute(...this.store.state.lastArgs);
95
+ }
96
+ };
97
+ this.cancel = () => {
98
+ this.#clearTimeout();
99
+ this.#setState({
100
+ canLeadingExecute: true,
101
+ isPending: false
102
+ });
103
+ };
104
+ this.reset = () => {
105
+ this.#setState(getDefaultDebouncerState());
106
+ };
107
+ this.key = initialOptions.key;
108
+ this.options = {
109
+ ...defaultOptions,
110
+ ...initialOptions
111
+ };
112
+ this.#setState(this.options.initialState ?? {});
113
+ if (this.key) require_event_client.pacerEventClient.on("d-Debouncer", (event) => {
114
+ if (event.payload.key !== this.key) return;
115
+ this.#setState(event.payload.store.state);
116
+ this.setOptions(event.payload.options);
117
+ });
118
+ }
119
+ #setState = (newState) => {
120
+ this.store.setState((state) => {
121
+ const combinedState = {
122
+ ...state,
123
+ ...newState
124
+ };
125
+ const { isPending } = combinedState;
126
+ return {
127
+ ...combinedState,
128
+ status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
129
+ };
130
+ });
131
+ require_event_client.emitChange("Debouncer", this);
132
+ };
133
+ /**
134
+ * Returns the current enabled state of the debouncer
135
+ */
136
+ #getEnabled = () => {
137
+ return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
138
+ };
139
+ /**
140
+ * Returns the current wait time in milliseconds
141
+ */
142
+ #getWait = () => {
143
+ return require_utils.parseFunctionOrValue(this.options.wait, this);
144
+ };
145
+ #execute = (...args) => {
146
+ if (!this.#getEnabled()) return void 0;
147
+ this.fn(...args);
148
+ this.#setState({
149
+ executionCount: this.store.state.executionCount + 1,
150
+ isPending: false,
151
+ lastArgs: void 0
152
+ });
153
+ this.options.onExecute?.(args, this);
154
+ };
155
+ #clearTimeout = () => {
156
+ if (this.#timeoutId) {
157
+ clearTimeout(this.#timeoutId);
158
+ this.#timeoutId = void 0;
159
+ }
160
+ };
161
+ };
162
+ /**
163
+ * Creates a debounced function that delays invoking the provided function until after a specified wait time.
164
+ * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
165
+ *
166
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
167
+ *
168
+ * If leading option is true, the function will execute immediately on the first call, then wait the delay
169
+ * before allowing another execution.
170
+ *
171
+ * State Management:
172
+ * - Uses TanStack Store for reactive state management
173
+ * - Use `initialState` to provide initial state values when creating the debouncer
174
+ * - Use `onExecute` callback to react to function execution and implement custom logic
175
+ * - The state includes canLeadingExecute, execution count, and isPending status
176
+ * - State can be accessed via the underlying Debouncer instance's `store.state` property
177
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * const debounced = debounce(() => {
182
+ * saveChanges();
183
+ * }, { wait: 1000 });
184
+ *
185
+ * // Called repeatedly but executes at most once per second
186
+ * inputElement.addEventListener('input', debounced);
187
+ * ```
188
+ */
189
+ function debounce(fn, initialOptions) {
190
+ return new Debouncer(fn, initialOptions).maybeExecute;
191
+ }
192
+
193
+ //#endregion
194
+ exports.Debouncer = Debouncer;
195
+ exports.debounce = debounce;
196
+ exports.debouncerOptions = debouncerOptions;
197
+ //# sourceMappingURL=debouncer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debouncer.cjs","names":["defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n>","fn: TFn","Store","#getEnabled","#setState","#execute","#timeoutId","#getWait","#clearTimeout","parseFunctionOrValue"],"sources":["../src/debouncer.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 DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer 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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer 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 | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer 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 * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<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-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as DebouncerState<TFn>)\n this.setOptions(event.payload.options)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<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('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\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.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\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 execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer 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 * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":"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"}
@@ -0,0 +1,167 @@
1
+ import { AnyFunction } from "./types.cjs";
2
+ import { Store } from "@tanstack/store";
3
+
4
+ //#region src/debouncer.d.ts
5
+ interface DebouncerState<TFn extends AnyFunction> {
6
+ /**
7
+ * Whether the debouncer can execute on the leading edge of the timeout
8
+ */
9
+ canLeadingExecute: boolean;
10
+ /**
11
+ * Number of function executions that have been completed
12
+ */
13
+ executionCount: number;
14
+ /**
15
+ * Whether the debouncer is waiting for the timeout to trigger execution
16
+ */
17
+ isPending: boolean;
18
+ /**
19
+ * The arguments from the most recent call to maybeExecute
20
+ */
21
+ lastArgs: Parameters<TFn> | undefined;
22
+ /**
23
+ * Number of times maybeExecute has been called (for reduction calculations)
24
+ */
25
+ maybeExecuteCount: number;
26
+ /**
27
+ * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
28
+ */
29
+ status: 'disabled' | 'idle' | 'pending';
30
+ }
31
+ /**
32
+ * Options for configuring a debounced function
33
+ */
34
+ interface DebouncerOptions<TFn extends AnyFunction> {
35
+ /**
36
+ * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
37
+ * Can be a boolean or a function that returns a boolean.
38
+ * Defaults to true.
39
+ */
40
+ enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean);
41
+ /**
42
+ * Initial state for the debouncer
43
+ */
44
+ initialState?: Partial<DebouncerState<TFn>>;
45
+ /**
46
+ * A key to identify the debouncer.
47
+ * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.
48
+ */
49
+ key?: string;
50
+ /**
51
+ * Whether to execute on the leading edge of the timeout.
52
+ * The first call will execute immediately and the rest will wait the delay.
53
+ * Defaults to false.
54
+ */
55
+ leading?: boolean;
56
+ /**
57
+ * Callback function that is called after the function is executed
58
+ */
59
+ onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void;
60
+ /**
61
+ * Whether to execute on the trailing edge of the timeout.
62
+ * Defaults to true.
63
+ */
64
+ trailing?: boolean;
65
+ /**
66
+ * Delay in milliseconds before executing the function.
67
+ * Can be a number or a function that returns a number.
68
+ * Defaults to 0ms
69
+ */
70
+ wait: number | ((debouncer: Debouncer<TFn>) => number);
71
+ }
72
+ /**
73
+ * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
74
+ */
75
+ declare function debouncerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<DebouncerOptions<TFn>> = Partial<DebouncerOptions<TFn>>>(options: TOptions): TOptions;
76
+ /**
77
+ * A class that creates a debounced function.
78
+ *
79
+ * Debouncing ensures that a function is only executed after a certain amount of time has passed
80
+ * since its last invocation. This is useful for handling frequent events like window resizing,
81
+ * scroll events, or input changes where you want to limit the rate of execution.
82
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
83
+ *
84
+ * The debounced function can be configured to execute either at the start of the delay period
85
+ * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
86
+ * will reset the timer.
87
+ *
88
+ * State Management:
89
+ * - Uses TanStack Store for reactive state management
90
+ * - Use `initialState` to provide initial state values when creating the debouncer
91
+ * - Use `onExecute` callback to react to function execution and implement custom logic
92
+ * - The state includes canLeadingExecute, execution count, and isPending status
93
+ * - State can be accessed via `debouncer.store.state` when using the class directly
94
+ * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * const debouncer = new Debouncer((value: string) => {
99
+ * saveToDatabase(value);
100
+ * }, { wait: 500 });
101
+ *
102
+ * // Will only save after 500ms of no new input
103
+ * inputElement.addEventListener('input', () => {
104
+ * debouncer.maybeExecute(inputElement.value);
105
+ * });
106
+ * ```
107
+ */
108
+ declare class Debouncer<TFn extends AnyFunction> {
109
+ #private;
110
+ fn: TFn;
111
+ readonly store: Store<Readonly<DebouncerState<TFn>>>;
112
+ key: string | undefined;
113
+ options: DebouncerOptions<TFn>;
114
+ constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
115
+ /**
116
+ * Updates the debouncer options
117
+ */
118
+ setOptions: (newOptions: Partial<DebouncerOptions<TFn>>) => void;
119
+ /**
120
+ * Attempts to execute the debounced function
121
+ * If a call is already in progress, it will be queued
122
+ */
123
+ maybeExecute: (...args: Parameters<TFn>) => void;
124
+ /**
125
+ * Processes the current pending execution immediately
126
+ */
127
+ flush: () => void;
128
+ /**
129
+ * Cancels any pending execution
130
+ */
131
+ cancel: () => void;
132
+ /**
133
+ * Resets the debouncer state to its default values
134
+ */
135
+ reset: () => void;
136
+ }
137
+ /**
138
+ * Creates a debounced function that delays invoking the provided function until after a specified wait time.
139
+ * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
140
+ *
141
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
142
+ *
143
+ * If leading option is true, the function will execute immediately on the first call, then wait the delay
144
+ * before allowing another execution.
145
+ *
146
+ * State Management:
147
+ * - Uses TanStack Store for reactive state management
148
+ * - Use `initialState` to provide initial state values when creating the debouncer
149
+ * - Use `onExecute` callback to react to function execution and implement custom logic
150
+ * - The state includes canLeadingExecute, execution count, and isPending status
151
+ * - State can be accessed via the underlying Debouncer instance's `store.state` property
152
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const debounced = debounce(() => {
157
+ * saveChanges();
158
+ * }, { wait: 1000 });
159
+ *
160
+ * // Called repeatedly but executes at most once per second
161
+ * inputElement.addEventListener('input', debounced);
162
+ * ```
163
+ */
164
+ declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: DebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
165
+ //#endregion
166
+ export { Debouncer, DebouncerOptions, DebouncerState, debounce, debouncerOptions };
167
+ //# sourceMappingURL=debouncer.d.cts.map
@@ -0,0 +1,167 @@
1
+ import { AnyFunction } from "./types.js";
2
+ import { Store } from "@tanstack/store";
3
+
4
+ //#region src/debouncer.d.ts
5
+ interface DebouncerState<TFn extends AnyFunction> {
6
+ /**
7
+ * Whether the debouncer can execute on the leading edge of the timeout
8
+ */
9
+ canLeadingExecute: boolean;
10
+ /**
11
+ * Number of function executions that have been completed
12
+ */
13
+ executionCount: number;
14
+ /**
15
+ * Whether the debouncer is waiting for the timeout to trigger execution
16
+ */
17
+ isPending: boolean;
18
+ /**
19
+ * The arguments from the most recent call to maybeExecute
20
+ */
21
+ lastArgs: Parameters<TFn> | undefined;
22
+ /**
23
+ * Number of times maybeExecute has been called (for reduction calculations)
24
+ */
25
+ maybeExecuteCount: number;
26
+ /**
27
+ * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
28
+ */
29
+ status: 'disabled' | 'idle' | 'pending';
30
+ }
31
+ /**
32
+ * Options for configuring a debounced function
33
+ */
34
+ interface DebouncerOptions<TFn extends AnyFunction> {
35
+ /**
36
+ * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
37
+ * Can be a boolean or a function that returns a boolean.
38
+ * Defaults to true.
39
+ */
40
+ enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean);
41
+ /**
42
+ * Initial state for the debouncer
43
+ */
44
+ initialState?: Partial<DebouncerState<TFn>>;
45
+ /**
46
+ * A key to identify the debouncer.
47
+ * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.
48
+ */
49
+ key?: string;
50
+ /**
51
+ * Whether to execute on the leading edge of the timeout.
52
+ * The first call will execute immediately and the rest will wait the delay.
53
+ * Defaults to false.
54
+ */
55
+ leading?: boolean;
56
+ /**
57
+ * Callback function that is called after the function is executed
58
+ */
59
+ onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void;
60
+ /**
61
+ * Whether to execute on the trailing edge of the timeout.
62
+ * Defaults to true.
63
+ */
64
+ trailing?: boolean;
65
+ /**
66
+ * Delay in milliseconds before executing the function.
67
+ * Can be a number or a function that returns a number.
68
+ * Defaults to 0ms
69
+ */
70
+ wait: number | ((debouncer: Debouncer<TFn>) => number);
71
+ }
72
+ /**
73
+ * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
74
+ */
75
+ declare function debouncerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<DebouncerOptions<TFn>> = Partial<DebouncerOptions<TFn>>>(options: TOptions): TOptions;
76
+ /**
77
+ * A class that creates a debounced function.
78
+ *
79
+ * Debouncing ensures that a function is only executed after a certain amount of time has passed
80
+ * since its last invocation. This is useful for handling frequent events like window resizing,
81
+ * scroll events, or input changes where you want to limit the rate of execution.
82
+ * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
83
+ *
84
+ * The debounced function can be configured to execute either at the start of the delay period
85
+ * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
86
+ * will reset the timer.
87
+ *
88
+ * State Management:
89
+ * - Uses TanStack Store for reactive state management
90
+ * - Use `initialState` to provide initial state values when creating the debouncer
91
+ * - Use `onExecute` callback to react to function execution and implement custom logic
92
+ * - The state includes canLeadingExecute, execution count, and isPending status
93
+ * - State can be accessed via `debouncer.store.state` when using the class directly
94
+ * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * const debouncer = new Debouncer((value: string) => {
99
+ * saveToDatabase(value);
100
+ * }, { wait: 500 });
101
+ *
102
+ * // Will only save after 500ms of no new input
103
+ * inputElement.addEventListener('input', () => {
104
+ * debouncer.maybeExecute(inputElement.value);
105
+ * });
106
+ * ```
107
+ */
108
+ declare class Debouncer<TFn extends AnyFunction> {
109
+ #private;
110
+ fn: TFn;
111
+ readonly store: Store<Readonly<DebouncerState<TFn>>>;
112
+ key: string | undefined;
113
+ options: DebouncerOptions<TFn>;
114
+ constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
115
+ /**
116
+ * Updates the debouncer options
117
+ */
118
+ setOptions: (newOptions: Partial<DebouncerOptions<TFn>>) => void;
119
+ /**
120
+ * Attempts to execute the debounced function
121
+ * If a call is already in progress, it will be queued
122
+ */
123
+ maybeExecute: (...args: Parameters<TFn>) => void;
124
+ /**
125
+ * Processes the current pending execution immediately
126
+ */
127
+ flush: () => void;
128
+ /**
129
+ * Cancels any pending execution
130
+ */
131
+ cancel: () => void;
132
+ /**
133
+ * Resets the debouncer state to its default values
134
+ */
135
+ reset: () => void;
136
+ }
137
+ /**
138
+ * Creates a debounced function that delays invoking the provided function until after a specified wait time.
139
+ * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
140
+ *
141
+ * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
142
+ *
143
+ * If leading option is true, the function will execute immediately on the first call, then wait the delay
144
+ * before allowing another execution.
145
+ *
146
+ * State Management:
147
+ * - Uses TanStack Store for reactive state management
148
+ * - Use `initialState` to provide initial state values when creating the debouncer
149
+ * - Use `onExecute` callback to react to function execution and implement custom logic
150
+ * - The state includes canLeadingExecute, execution count, and isPending status
151
+ * - State can be accessed via the underlying Debouncer instance's `store.state` property
152
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const debounced = debounce(() => {
157
+ * saveChanges();
158
+ * }, { wait: 1000 });
159
+ *
160
+ * // Called repeatedly but executes at most once per second
161
+ * inputElement.addEventListener('input', debounced);
162
+ * ```
163
+ */
164
+ declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: DebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
165
+ //#endregion
166
+ export { Debouncer, DebouncerOptions, DebouncerState, debounce, debouncerOptions };
167
+ //# sourceMappingURL=debouncer.d.ts.map