@tanstack/pacer 0.8.0 → 0.9.1

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 (91) hide show
  1. package/dist/cjs/async-batcher.cjs +163 -0
  2. package/dist/cjs/async-batcher.cjs.map +1 -0
  3. package/dist/cjs/async-batcher.d.cts +273 -0
  4. package/dist/cjs/async-debouncer.cjs +149 -162
  5. package/dist/cjs/async-debouncer.cjs.map +1 -1
  6. package/dist/cjs/async-debouncer.d.cts +76 -57
  7. package/dist/cjs/async-queuer.cjs +282 -343
  8. package/dist/cjs/async-queuer.cjs.map +1 -1
  9. package/dist/cjs/async-queuer.d.cts +121 -100
  10. package/dist/cjs/async-rate-limiter.cjs +128 -185
  11. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  12. package/dist/cjs/async-rate-limiter.d.cts +72 -61
  13. package/dist/cjs/async-throttler.cjs +168 -178
  14. package/dist/cjs/async-throttler.cjs.map +1 -1
  15. package/dist/cjs/async-throttler.d.cts +97 -69
  16. package/dist/cjs/batcher.cjs +110 -119
  17. package/dist/cjs/batcher.cjs.map +1 -1
  18. package/dist/cjs/batcher.d.cts +76 -51
  19. package/dist/cjs/debouncer.cjs +97 -85
  20. package/dist/cjs/debouncer.cjs.map +1 -1
  21. package/dist/cjs/debouncer.d.cts +54 -26
  22. package/dist/cjs/index.cjs +3 -6
  23. package/dist/cjs/index.cjs.map +1 -1
  24. package/dist/cjs/index.d.cts +1 -1
  25. package/dist/cjs/queuer.cjs +247 -294
  26. package/dist/cjs/queuer.cjs.map +1 -1
  27. package/dist/cjs/queuer.d.cts +102 -81
  28. package/dist/cjs/rate-limiter.cjs +97 -130
  29. package/dist/cjs/rate-limiter.cjs.map +1 -1
  30. package/dist/cjs/rate-limiter.d.cts +50 -37
  31. package/dist/cjs/throttler.cjs +107 -123
  32. package/dist/cjs/throttler.cjs.map +1 -1
  33. package/dist/cjs/throttler.d.cts +59 -35
  34. package/dist/cjs/utils.cjs +0 -13
  35. package/dist/cjs/utils.cjs.map +1 -1
  36. package/dist/cjs/utils.d.cts +0 -1
  37. package/dist/esm/async-batcher.d.ts +273 -0
  38. package/dist/esm/async-batcher.js +163 -0
  39. package/dist/esm/async-batcher.js.map +1 -0
  40. package/dist/esm/async-debouncer.d.ts +76 -57
  41. package/dist/esm/async-debouncer.js +149 -162
  42. package/dist/esm/async-debouncer.js.map +1 -1
  43. package/dist/esm/async-queuer.d.ts +121 -100
  44. package/dist/esm/async-queuer.js +282 -343
  45. package/dist/esm/async-queuer.js.map +1 -1
  46. package/dist/esm/async-rate-limiter.d.ts +72 -61
  47. package/dist/esm/async-rate-limiter.js +128 -185
  48. package/dist/esm/async-rate-limiter.js.map +1 -1
  49. package/dist/esm/async-throttler.d.ts +97 -69
  50. package/dist/esm/async-throttler.js +168 -178
  51. package/dist/esm/async-throttler.js.map +1 -1
  52. package/dist/esm/batcher.d.ts +76 -51
  53. package/dist/esm/batcher.js +110 -119
  54. package/dist/esm/batcher.js.map +1 -1
  55. package/dist/esm/debouncer.d.ts +54 -26
  56. package/dist/esm/debouncer.js +97 -85
  57. package/dist/esm/debouncer.js.map +1 -1
  58. package/dist/esm/index.d.ts +1 -1
  59. package/dist/esm/index.js +4 -7
  60. package/dist/esm/queuer.d.ts +102 -81
  61. package/dist/esm/queuer.js +247 -294
  62. package/dist/esm/queuer.js.map +1 -1
  63. package/dist/esm/rate-limiter.d.ts +50 -37
  64. package/dist/esm/rate-limiter.js +97 -130
  65. package/dist/esm/rate-limiter.js.map +1 -1
  66. package/dist/esm/throttler.d.ts +59 -35
  67. package/dist/esm/throttler.js +107 -123
  68. package/dist/esm/throttler.js.map +1 -1
  69. package/dist/esm/utils.d.ts +0 -1
  70. package/dist/esm/utils.js +0 -13
  71. package/dist/esm/utils.js.map +1 -1
  72. package/package.json +14 -11
  73. package/src/async-batcher.ts +475 -0
  74. package/src/async-debouncer.ts +201 -121
  75. package/src/async-queuer.ts +337 -216
  76. package/src/async-rate-limiter.ts +176 -136
  77. package/src/async-throttler.ts +233 -139
  78. package/src/batcher.ts +158 -92
  79. package/src/debouncer.ts +135 -52
  80. package/src/index.ts +1 -1
  81. package/src/queuer.ts +349 -226
  82. package/src/rate-limiter.ts +125 -80
  83. package/src/throttler.ts +152 -78
  84. package/src/utils.ts +0 -15
  85. package/dist/cjs/compare.cjs +0 -72
  86. package/dist/cjs/compare.cjs.map +0 -1
  87. package/dist/cjs/compare.d.cts +0 -12
  88. package/dist/esm/compare.d.ts +0 -12
  89. package/dist/esm/compare.js +0 -72
  90. package/dist/esm/compare.js.map +0 -1
  91. package/src/compare.ts +0 -105
@@ -1,4 +1,47 @@
1
+ import { Store } from '@tanstack/store';
1
2
  import { AnyAsyncFunction } from './types.cjs';
3
+ export interface AsyncThrottlerState<TFn extends AnyAsyncFunction> {
4
+ /**
5
+ * Number of function executions that have resulted in errors
6
+ */
7
+ errorCount: number;
8
+ /**
9
+ * Whether the throttled function is currently executing asynchronously
10
+ */
11
+ isExecuting: boolean;
12
+ /**
13
+ * Whether the throttler is waiting for the timeout to trigger execution
14
+ */
15
+ isPending: boolean;
16
+ /**
17
+ * The arguments from the most recent call to maybeExecute
18
+ */
19
+ lastArgs: Parameters<TFn> | undefined;
20
+ /**
21
+ * Timestamp of the last function execution in milliseconds
22
+ */
23
+ lastExecutionTime: number;
24
+ /**
25
+ * The result from the most recent successful function execution
26
+ */
27
+ lastResult: ReturnType<TFn> | undefined;
28
+ /**
29
+ * Timestamp when the next execution can occur in milliseconds
30
+ */
31
+ nextExecutionTime: number;
32
+ /**
33
+ * Number of function executions that have completed (either successfully or with errors)
34
+ */
35
+ settleCount: number;
36
+ /**
37
+ * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed
38
+ */
39
+ status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled';
40
+ /**
41
+ * Number of function executions that have completed successfully
42
+ */
43
+ successCount: number;
44
+ }
2
45
  /**
3
46
  * Options for configuring an async throttled function
4
47
  */
@@ -9,6 +52,10 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
9
52
  * Defaults to true.
10
53
  */
11
54
  enabled?: boolean | ((throttler: AsyncThrottler<TFn>) => boolean);
55
+ /**
56
+ * Initial state for the async throttler
57
+ */
58
+ initialState?: Partial<AsyncThrottlerState<TFn>>;
12
59
  /**
13
60
  * Whether to execute the function immediately when called
14
61
  * Defaults to true
@@ -67,6 +114,16 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
67
114
  * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
68
115
  * - The error state can be checked using the underlying AsyncThrottler instance
69
116
  *
117
+ * State Management:
118
+ * - Uses TanStack Store for reactive state management
119
+ * - Use `initialState` to provide initial state values when creating the async throttler
120
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
121
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
122
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
123
+ * - The state includes error count, execution status, last execution time, and success/settle counts
124
+ * - State can be accessed via `asyncThrottler.store.state` when using the class directly
125
+ * - When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`
126
+ *
70
127
  * @example
71
128
  * ```ts
72
129
  * const throttler = new AsyncThrottler(async (value: string) => {
@@ -85,89 +142,50 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
85
142
  * ```
86
143
  */
87
144
  export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
145
+ #private;
88
146
  private fn;
89
- private _options;
90
- private _abortController;
91
- private _errorCount;
92
- private _isExecuting;
93
- private _lastArgs;
94
- private _lastExecutionTime;
95
- private _lastResult;
96
- private _nextExecutionTime;
97
- private _settleCount;
98
- private _successCount;
99
- private _timeoutId;
100
- private _resolvePreviousPromise;
147
+ readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
148
+ options: AsyncThrottlerOptions<TFn>;
101
149
  constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>);
102
150
  /**
103
- * Updates the throttler options
151
+ * Updates the async throttler options
104
152
  */
105
- setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void;
153
+ setOptions: (newOptions: Partial<AsyncThrottlerOptions<TFn>>) => void;
106
154
  /**
107
- * Returns the current options
108
- */
109
- getOptions(): AsyncThrottlerOptions<TFn>;
110
- /**
111
- * Returns the current enabled state of the throttler
112
- */
113
- getEnabled(): boolean;
114
- /**
115
- * Returns the current wait time in milliseconds
116
- */
117
- getWait(): number;
118
- /**
119
- * Attempts to execute the throttled function.
120
- * If a call is already in progress, it may be blocked or queued depending on the `wait` option.
155
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
121
156
  *
122
- * Error Handling:
123
- * - If the throttled function throws and no `onError` handler is configured,
124
- * the error will be thrown from this method.
125
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
126
- * and this method will return undefined.
127
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
157
+ * - If enough time has passed since the last execution (>= wait period):
158
+ * - With leading=true: Executes immediately
159
+ * - With leading=false: Waits for the next trailing execution
128
160
  *
129
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
130
- * @throws The error from the throttled function if no onError handler is configured
131
- */
132
- maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
133
- private execute;
134
- private resolvePreviousPromise;
135
- /**
136
- * Cancels any pending execution or aborts any execution in progress
137
- */
138
- cancel(): void;
139
- /**
140
- * Returns the last execution time
141
- */
142
- getLastExecutionTime(): number;
143
- /**
144
- * Returns the next execution time
145
- */
146
- getNextExecutionTime(): number;
147
- /**
148
- * Returns the last result of the debounced function
149
- */
150
- getLastResult(): ReturnType<TFn> | undefined;
151
- /**
152
- * Returns the number of times the function has been executed successfully
153
- */
154
- getSuccessCount(): number;
155
- /**
156
- * Returns the number of times the function has settled (completed or errored)
161
+ * - If within the wait period:
162
+ * - With trailing=true: Schedules execution for end of wait period
163
+ * - With trailing=false: Drops the execution
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * const throttled = new AsyncThrottler(fn, { wait: 1000 });
168
+ *
169
+ * // First call executes immediately
170
+ * await throttled.maybeExecute('a', 'b');
171
+ *
172
+ * // Call during wait period - gets throttled
173
+ * await throttled.maybeExecute('c', 'd');
174
+ * ```
157
175
  */
158
- getSettleCount(): number;
176
+ maybeExecute: (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
159
177
  /**
160
- * Returns the number of times the function has errored
178
+ * Processes the current pending execution immediately
161
179
  */
162
- getErrorCount(): number;
180
+ flush: () => void;
163
181
  /**
164
- * Returns the current pending state
182
+ * Cancels any pending execution or aborts any execution in progress
165
183
  */
166
- getIsPending(): boolean;
184
+ cancel: () => void;
167
185
  /**
168
- * Returns the current executing state
186
+ * Resets the debouncer state to its default values
169
187
  */
170
- getIsExecuting(): boolean;
188
+ reset: () => void;
171
189
  }
172
190
  /**
173
191
  * Creates an async throttled function that limits how often the function can execute.
@@ -185,6 +203,16 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
185
203
  * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
186
204
  * - The error state can be checked using the underlying AsyncThrottler instance
187
205
  *
206
+ * State Management:
207
+ * - Uses TanStack Store for reactive state management
208
+ * - Use `initialState` to provide initial state values when creating the async throttler
209
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
210
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
211
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
212
+ * - The state includes error count, execution status, last execution time, and success/settle counts
213
+ * - State can be accessed via the underlying AsyncThrottler instance's `store.state` property
214
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
215
+ *
188
216
  * @example
189
217
  * ```ts
190
218
  * const throttled = asyncThrottle(async (value: string) => {
@@ -1,5 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const store = require("@tanstack/store");
4
+ const utils = require("./utils.cjs");
5
+ function getDefaultBatcherState() {
6
+ return {
7
+ executionCount: 0,
8
+ isEmpty: true,
9
+ isPending: false,
10
+ isRunning: true,
11
+ totalItemsProcessed: 0,
12
+ items: [],
13
+ size: 0,
14
+ status: "idle"
15
+ };
16
+ }
3
17
  const defaultOptions = {
4
18
  getShouldExecute: () => false,
5
19
  maxSize: Infinity,
@@ -9,129 +23,106 @@ const defaultOptions = {
9
23
  class Batcher {
10
24
  constructor(fn, initialOptions) {
11
25
  this.fn = fn;
12
- this._batchExecutionCount = 0;
13
- this._itemExecutionCount = 0;
14
- this._items = [];
15
- this._timeoutId = null;
16
- this._options = { ...defaultOptions, ...initialOptions };
17
- this._running = this._options.started;
18
- }
19
- /**
20
- * Updates the batcher options
21
- */
22
- setOptions(newOptions) {
23
- this._options = { ...this._options, ...newOptions };
24
- }
25
- /**
26
- * Returns the current batcher options
27
- */
28
- getOptions() {
29
- return this._options;
30
- }
31
- /**
32
- * Adds an item to the batcher
33
- * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
34
- */
35
- addItem(item) {
36
- var _a, _b;
37
- this._items.push(item);
38
- (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
39
- const shouldProcess = this._items.length >= this._options.maxSize || this._options.getShouldExecute(this._items, this);
40
- if (shouldProcess) {
41
- this.execute();
42
- } else if (this._running && !this._timeoutId && this._options.wait !== Infinity) {
43
- this._timeoutId = setTimeout(() => this.execute(), this._options.wait);
44
- }
45
- }
46
- /**
47
- * Processes the current batch of items.
48
- * This method will automatically be triggered if the batcher is running and any of these conditions are met:
49
- * - The number of items reaches batchSize
50
- * - The wait duration has elapsed
51
- * - The getShouldExecute function returns true upon adding an item
52
- *
53
- * You can also call this method manually to process the current batch at any time.
54
- */
55
- execute() {
56
- var _a, _b, _c, _d;
57
- if (this._timeoutId) {
58
- clearTimeout(this._timeoutId);
59
- this._timeoutId = null;
60
- }
61
- if (this._items.length === 0) {
62
- return;
63
- }
64
- const batch2 = this.peekAllItems();
65
- this._items = [];
66
- (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
67
- this.fn(batch2);
68
- this._batchExecutionCount++;
69
- this._itemExecutionCount += batch2.length;
70
- (_d = (_c = this._options).onExecute) == null ? void 0 : _d.call(_c, this);
71
- }
72
- /**
73
- * Stops the batcher from processing batches
74
- */
75
- stop() {
76
- var _a, _b;
77
- this._running = false;
78
- (_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
79
- if (this._timeoutId) {
80
- clearTimeout(this._timeoutId);
81
- this._timeoutId = null;
82
- }
83
- }
84
- /**
85
- * Starts the batcher and processes any pending items
86
- */
87
- start() {
88
- var _a, _b;
89
- this._running = true;
90
- (_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
91
- if (this._items.length > 0 && !this._timeoutId) {
92
- this._timeoutId = setTimeout(() => this.execute(), this._options.wait);
93
- }
94
- }
95
- /**
96
- * Returns the current number of items in the batcher
97
- */
98
- getSize() {
99
- return this._items.length;
100
- }
101
- /**
102
- * Returns true if the batcher is empty
103
- */
104
- getIsEmpty() {
105
- return this._items.length === 0;
106
- }
107
- /**
108
- * Returns true if the batcher is running
109
- */
110
- getIsRunning() {
111
- return this._running;
112
- }
113
- /**
114
- * Returns a copy of all items currently in the batcher
115
- */
116
- peekAllItems() {
117
- return [...this._items];
118
- }
119
- /**
120
- * Returns the number of times batches have been processed
121
- */
122
- getBatchExecutionCount() {
123
- return this._batchExecutionCount;
124
- }
125
- /**
126
- * Returns the total number of individual items that have been processed
127
- */
128
- getItemExecutionCount() {
129
- return this._itemExecutionCount;
26
+ this.store = new store.Store(
27
+ getDefaultBatcherState()
28
+ );
29
+ this.#timeoutId = null;
30
+ this.setOptions = (newOptions) => {
31
+ this.options = { ...this.options, ...newOptions };
32
+ };
33
+ this.#setState = (newState) => {
34
+ this.store.setState((state) => {
35
+ const combinedState = {
36
+ ...state,
37
+ ...newState
38
+ };
39
+ const { isPending, items } = combinedState;
40
+ const size = items.length;
41
+ const isEmpty = size === 0;
42
+ return {
43
+ ...combinedState,
44
+ isEmpty,
45
+ size,
46
+ status: isPending ? "pending" : "idle"
47
+ };
48
+ });
49
+ };
50
+ this.#getWait = () => {
51
+ return utils.parseFunctionOrValue(this.options.wait, this);
52
+ };
53
+ this.addItem = (item) => {
54
+ this.#setState({
55
+ items: [...this.store.state.items, item],
56
+ isPending: this.options.wait !== Infinity
57
+ });
58
+ this.options.onItemsChange?.(this);
59
+ const shouldProcess = this.store.state.items.length >= this.options.maxSize || this.options.getShouldExecute(this.store.state.items, this);
60
+ if (shouldProcess) {
61
+ this.#execute();
62
+ } else if (this.store.state.isRunning && this.options.wait !== Infinity) {
63
+ this.#clearTimeout();
64
+ this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait());
65
+ }
66
+ };
67
+ this.#execute = () => {
68
+ if (this.store.state.items.length === 0) {
69
+ return;
70
+ }
71
+ const batch2 = this.peekAllItems();
72
+ this.clear();
73
+ this.options.onItemsChange?.(this);
74
+ this.fn(batch2);
75
+ this.#setState({
76
+ executionCount: this.store.state.executionCount + 1,
77
+ totalItemsProcessed: this.store.state.totalItemsProcessed + batch2.length
78
+ });
79
+ this.options.onExecute?.(this);
80
+ };
81
+ this.flush = () => {
82
+ this.#clearTimeout();
83
+ this.#execute();
84
+ };
85
+ this.stop = () => {
86
+ this.#setState({ isRunning: false });
87
+ this.#clearTimeout();
88
+ };
89
+ this.start = () => {
90
+ this.#setState({ isRunning: true });
91
+ if (this.store.state.items.length > 0) {
92
+ this.#execute();
93
+ }
94
+ };
95
+ this.peekAllItems = () => {
96
+ return [...this.store.state.items];
97
+ };
98
+ this.#clearTimeout = () => {
99
+ if (this.#timeoutId) {
100
+ clearTimeout(this.#timeoutId);
101
+ this.#timeoutId = null;
102
+ }
103
+ };
104
+ this.clear = () => {
105
+ this.#setState({ items: [], isPending: false });
106
+ };
107
+ this.reset = () => {
108
+ this.#setState(getDefaultBatcherState());
109
+ this.options.onItemsChange?.(this);
110
+ };
111
+ this.options = {
112
+ ...defaultOptions,
113
+ ...initialOptions
114
+ };
115
+ this.#setState(this.options.initialState ?? {});
130
116
  }
117
+ #timeoutId;
118
+ #setState;
119
+ #getWait;
120
+ #execute;
121
+ #clearTimeout;
131
122
  }
132
123
  function batch(fn, options) {
133
124
  const batcher = new Batcher(fn, options);
134
- return batcher.addItem.bind(batcher);
125
+ return batcher.addItem;
135
126
  }
136
127
  exports.Batcher = Batcher;
137
128
  exports.batch = batch;
@@ -1 +1 @@
1
- {"version":3,"file":"batcher.cjs","sources":["../../src/batcher.ts"],"sourcesContent":["import type { OptionalKeys } from './types'\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batcher: Batcher<TValue>) => void\n /**\n * Callback fired when the batcher's running state changes\n */\n onIsRunningChange?: (batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'onExecute' | 'onItemsChange' | 'onIsRunningChange'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecuteBatch: (items) => console.log('Batch executed:', items)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.execute() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n private _options: BatcherOptionsWithOptionalCallbacks<TValue>\n private _batchExecutionCount = 0\n private _itemExecutionCount = 0\n private _items: Array<TValue> = []\n private _running: boolean\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this._options = { ...defaultOptions, ...initialOptions }\n this._running = this._options.started\n }\n\n /**\n * Updates the batcher options\n */\n setOptions(newOptions: Partial<BatcherOptions<TValue>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current batcher options\n */\n getOptions(): BatcherOptions<TValue> {\n return this._options\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem(item: TValue): void {\n this._items.push(item)\n this._options.onItemsChange?.(this)\n\n const shouldProcess =\n this._items.length >= this._options.maxSize ||\n this._options.getShouldExecute(this._items, this)\n\n if (shouldProcess) {\n this.execute()\n } else if (\n this._running &&\n !this._timeoutId &&\n this._options.wait !== Infinity\n ) {\n this._timeoutId = setTimeout(() => this.execute(), this._options.wait)\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n execute(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n\n if (this._items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this._items = [] // Clear items before processing to prevent race conditions\n this._options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch)\n this._batchExecutionCount++\n this._itemExecutionCount += batch.length\n this._options.onExecute?.(this)\n }\n\n /**\n * Stops the batcher from processing batches\n */\n stop(): void {\n this._running = false\n this._options.onIsRunningChange?.(this)\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n }\n\n /**\n * Starts the batcher and processes any pending items\n */\n start(): void {\n this._running = true\n this._options.onIsRunningChange?.(this)\n if (this._items.length > 0 && !this._timeoutId) {\n this._timeoutId = setTimeout(() => this.execute(), this._options.wait)\n }\n }\n\n /**\n * Returns the current number of items in the batcher\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns true if the batcher is empty\n */\n getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the batcher is running\n */\n getIsRunning(): boolean {\n return this._running\n }\n\n /**\n * Returns a copy of all items currently in the batcher\n */\n peekAllItems(): Array<TValue> {\n return [...this._items]\n }\n\n /**\n * Returns the number of times batches have been processed\n */\n getBatchExecutionCount(): number {\n return this._batchExecutionCount\n }\n\n /**\n * Returns the total number of individual items that have been processed\n */\n getItemExecutionCount(): number {\n return this._itemExecutionCount\n }\n}\n\n/**\n * Creates a batcher that processes items in batches\n *\n * @example\n * ```ts\n * const batchItems = batch<number>({\n * batchSize: 3,\n * processBatch: (items) => console.log('Processing:', items)\n * });\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.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{ parseFunctionOrValue } from './utils'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Whether the batcher is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout\n */\n status: 'idle' | 'pending'\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n isRunning: true,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed:', batcher.peekAllItems())\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n this.#execute()\n } else if (this.store.state.isRunning && this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Stops the batcher from processing batches\n */\n stop = (): void => {\n this.#setState({ isRunning: false })\n this.#clearTimeout()\n }\n\n /**\n * Starts the batcher and processes any pending items\n */\n start = (): void => {\n this.#setState({ isRunning: true })\n if (this.store.state.items.length > 0) {\n this.#execute()\n }\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batcher) => console.log('Batch executed')\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"names":["Store","parseFunctionOrValue","batch"],"mappings":";;;;AAuCA,SAAS,yBAAuD;AAC9D,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,SAAS;AAAA,IACT,WAAW;AAAA,IACX,WAAW;AAAA,IACX,qBAAqB;AAAA,IACrB,OAAO,CAAA;AAAA,IACP,MAAM;AAAA,IACN,QAAQ;AAAA,EAAA;AAEZ;AA+CA,MAAM,iBAA2D;AAAA,EAC/D,kBAAkB,MAAM;AAAA,EACxB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AACR;AAwCO,MAAM,QAAgB;AAAA,EAO3B,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAS,QAA+C,IAAIA,MAAAA;AAAAA,MAC1D,uBAAA;AAAA,IAA+B;AAGjC,SAAA,aAAoC;AAgBpC,SAAA,aAAa,CAAC,eAAsD;AAClE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AA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