@tanstack/pacer 0.20.1 → 0.21.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 (51) hide show
  1. package/dist/async-batcher.cjs +72 -67
  2. package/dist/async-batcher.cjs.map +1 -1
  3. package/dist/async-batcher.js +72 -67
  4. package/dist/async-batcher.js.map +1 -1
  5. package/dist/async-debouncer.cjs +83 -74
  6. package/dist/async-debouncer.cjs.map +1 -1
  7. package/dist/async-debouncer.js +83 -74
  8. package/dist/async-debouncer.js.map +1 -1
  9. package/dist/async-queuer.cjs +102 -94
  10. package/dist/async-queuer.cjs.map +1 -1
  11. package/dist/async-queuer.js +102 -94
  12. package/dist/async-queuer.js.map +1 -1
  13. package/dist/async-rate-limiter.cjs +104 -93
  14. package/dist/async-rate-limiter.cjs.map +1 -1
  15. package/dist/async-rate-limiter.js +104 -93
  16. package/dist/async-rate-limiter.js.map +1 -1
  17. package/dist/async-retryer.cjs +67 -59
  18. package/dist/async-retryer.cjs.map +1 -1
  19. package/dist/async-retryer.js +67 -59
  20. package/dist/async-retryer.js.map +1 -1
  21. package/dist/async-throttler.cjs +81 -73
  22. package/dist/async-throttler.cjs.map +1 -1
  23. package/dist/async-throttler.js +81 -73
  24. package/dist/async-throttler.js.map +1 -1
  25. package/dist/batcher.cjs +45 -40
  26. package/dist/batcher.cjs.map +1 -1
  27. package/dist/batcher.js +45 -40
  28. package/dist/batcher.js.map +1 -1
  29. package/dist/debouncer.cjs +41 -36
  30. package/dist/debouncer.cjs.map +1 -1
  31. package/dist/debouncer.js +41 -36
  32. package/dist/debouncer.js.map +1 -1
  33. package/dist/event-client.cjs +8 -0
  34. package/dist/event-client.cjs.map +1 -1
  35. package/dist/event-client.js +8 -0
  36. package/dist/event-client.js.map +1 -1
  37. package/dist/queuer.cjs +92 -85
  38. package/dist/queuer.cjs.map +1 -1
  39. package/dist/queuer.js +92 -85
  40. package/dist/queuer.js.map +1 -1
  41. package/dist/rate-limiter.cjs +77 -66
  42. package/dist/rate-limiter.cjs.map +1 -1
  43. package/dist/rate-limiter.js +77 -66
  44. package/dist/rate-limiter.js.map +1 -1
  45. package/dist/throttler.cjs +49 -44
  46. package/dist/throttler.cjs.map +1 -1
  47. package/dist/throttler.js +49 -44
  48. package/dist/throttler.js.map +1 -1
  49. package/dist/utils.cjs.map +1 -1
  50. package/dist/utils.js.map +1 -1
  51. package/package.json +2 -2
package/dist/queuer.cjs CHANGED
@@ -113,16 +113,61 @@ const defaultOptions = {
113
113
  * ```
114
114
  */
115
115
  var Queuer = class {
116
- #timeoutId = null;
116
+ #timeoutId;
117
117
  constructor(fn, initialOptions = {}) {
118
118
  this.fn = fn;
119
119
  this.store = new _tanstack_store.Store(getDefaultQueuerState());
120
+ this.#timeoutId = null;
120
121
  this.setOptions = (newOptions) => {
121
122
  this.options = {
122
123
  ...this.options,
123
124
  ...newOptions
124
125
  };
125
126
  };
127
+ this.#setState = (newState) => {
128
+ this.store.setState((state) => {
129
+ const combinedState = {
130
+ ...state,
131
+ ...newState
132
+ };
133
+ const { items, isRunning } = combinedState;
134
+ const size = items.length;
135
+ const isFull = size >= (this.options.maxSize ?? Infinity);
136
+ const isEmpty = size === 0;
137
+ const isIdle = isRunning && isEmpty;
138
+ const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
139
+ return {
140
+ ...combinedState,
141
+ isEmpty,
142
+ isFull,
143
+ isIdle,
144
+ size,
145
+ status
146
+ };
147
+ });
148
+ require_event_client.emitChange("Queuer", this);
149
+ };
150
+ this.#getWait = () => {
151
+ return require_utils.parseFunctionOrValue(this.options.wait ?? 0, this);
152
+ };
153
+ this.#tick = () => {
154
+ if (!this.store.state.isRunning) {
155
+ this.#setState({ pendingTick: false });
156
+ return;
157
+ }
158
+ this.#setState({ pendingTick: true });
159
+ this.#checkExpiredItems();
160
+ while (this.store.state.items.length > 0) {
161
+ if (this.execute(this.options.getItemsFrom ?? "front") === void 0) break;
162
+ const wait = this.#getWait();
163
+ if (wait > 0) {
164
+ this.#timeoutId = setTimeout(() => this.#tick(), wait);
165
+ return;
166
+ }
167
+ this.#tick();
168
+ }
169
+ this.#setState({ pendingTick: false });
170
+ };
126
171
  this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
127
172
  this.#setState({ addItemCount: this.store.state.addItemCount + 1 });
128
173
  if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
@@ -181,6 +226,11 @@ var Queuer = class {
181
226
  if (item !== void 0) this.options.onItemsChange?.(this);
182
227
  return item;
183
228
  };
229
+ this.#getAllItems = () => {
230
+ const items = this.peekAllItems();
231
+ this.clear();
232
+ return items;
233
+ };
184
234
  this.execute = (position) => {
185
235
  const item = this.getNextItem(position);
186
236
  if (item !== void 0) {
@@ -200,6 +250,35 @@ var Queuer = class {
200
250
  this.clear();
201
251
  batchFunction(items);
202
252
  };
253
+ this.#checkExpiredItems = () => {
254
+ if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
255
+ const now = Date.now();
256
+ const expiredIndices = [];
257
+ for (let i = 0; i < this.store.state.items.length; i++) {
258
+ const timestamp = this.store.state.itemTimestamps[i];
259
+ if (timestamp === void 0) continue;
260
+ const item = this.store.state.items[i];
261
+ if (item === void 0) continue;
262
+ if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
263
+ }
264
+ for (let i = expiredIndices.length - 1; i >= 0; i--) {
265
+ const index = expiredIndices[i];
266
+ if (index === void 0) continue;
267
+ const expiredItem = this.store.state.items[index];
268
+ if (expiredItem === void 0) continue;
269
+ const newItems = [...this.store.state.items];
270
+ const newTimestamps = [...this.store.state.itemTimestamps];
271
+ newItems.splice(index, 1);
272
+ newTimestamps.splice(index, 1);
273
+ this.#setState({
274
+ items: newItems,
275
+ itemTimestamps: newTimestamps,
276
+ expirationCount: this.store.state.expirationCount + 1
277
+ });
278
+ this.options.onExpire?.(expiredItem, this);
279
+ }
280
+ if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
281
+ };
203
282
  this.peekNextItem = (position = "front") => {
204
283
  if (position === "front") return this.store.state.items[0];
205
284
  return this.store.state.items[this.store.state.items.length - 1];
@@ -218,6 +297,12 @@ var Queuer = class {
218
297
  pendingTick: false
219
298
  });
220
299
  };
300
+ this.#clearTimeout = () => {
301
+ if (this.#timeoutId) {
302
+ clearTimeout(this.#timeoutId);
303
+ this.#timeoutId = null;
304
+ }
305
+ };
221
306
  this.clear = () => {
222
307
  this.#setState({
223
308
  items: [],
@@ -252,101 +337,23 @@ var Queuer = class {
252
337
  this.setOptions(event.payload.options);
253
338
  });
254
339
  }
255
- #setState = (newState) => {
256
- this.store.setState((state) => {
257
- const combinedState = {
258
- ...state,
259
- ...newState
260
- };
261
- const { items, isRunning } = combinedState;
262
- const size = items.length;
263
- const isFull = size >= (this.options.maxSize ?? Infinity);
264
- const isEmpty = size === 0;
265
- const isIdle = isRunning && isEmpty;
266
- const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
267
- return {
268
- ...combinedState,
269
- isEmpty,
270
- isFull,
271
- isIdle,
272
- size,
273
- status
274
- };
275
- });
276
- require_event_client.emitChange("Queuer", this);
277
- };
340
+ #setState;
278
341
  /**
279
342
  * Returns the current wait time (in milliseconds) between processing items.
280
343
  * If a function is provided, it is called with the queuer instance.
281
344
  */
282
- #getWait = () => {
283
- return require_utils.parseFunctionOrValue(this.options.wait ?? 0, this);
284
- };
345
+ #getWait;
285
346
  /**
286
347
  * Processes items in the queue up to the wait interval. Internal use only.
287
348
  */
288
- #tick = () => {
289
- if (!this.store.state.isRunning) {
290
- this.#setState({ pendingTick: false });
291
- return;
292
- }
293
- this.#setState({ pendingTick: true });
294
- this.#checkExpiredItems();
295
- while (this.store.state.items.length > 0) {
296
- if (this.execute(this.options.getItemsFrom ?? "front") === void 0) break;
297
- const wait = this.#getWait();
298
- if (wait > 0) {
299
- this.#timeoutId = setTimeout(() => this.#tick(), wait);
300
- return;
301
- }
302
- this.#tick();
303
- }
304
- this.#setState({ pendingTick: false });
305
- };
306
- #getAllItems = () => {
307
- const items = this.peekAllItems();
308
- this.clear();
309
- return items;
310
- };
349
+ #tick;
350
+ #getAllItems;
311
351
  /**
312
352
  * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
313
353
  * Internal use only.
314
354
  */
315
- #checkExpiredItems = () => {
316
- if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
317
- const now = Date.now();
318
- const expiredIndices = [];
319
- for (let i = 0; i < this.store.state.items.length; i++) {
320
- const timestamp = this.store.state.itemTimestamps[i];
321
- if (timestamp === void 0) continue;
322
- const item = this.store.state.items[i];
323
- if (item === void 0) continue;
324
- if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
325
- }
326
- for (let i = expiredIndices.length - 1; i >= 0; i--) {
327
- const index = expiredIndices[i];
328
- if (index === void 0) continue;
329
- const expiredItem = this.store.state.items[index];
330
- if (expiredItem === void 0) continue;
331
- const newItems = [...this.store.state.items];
332
- const newTimestamps = [...this.store.state.itemTimestamps];
333
- newItems.splice(index, 1);
334
- newTimestamps.splice(index, 1);
335
- this.#setState({
336
- items: newItems,
337
- itemTimestamps: newTimestamps,
338
- expirationCount: this.store.state.expirationCount + 1
339
- });
340
- this.options.onExpire?.(expiredItem, this);
341
- }
342
- if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
343
- };
344
- #clearTimeout = () => {
345
- if (this.#timeoutId) {
346
- clearTimeout(this.#timeoutId);
347
- this.#timeoutId = null;
348
- }
349
- };
355
+ #checkExpiredItems;
356
+ #clearTimeout;
350
357
  };
351
358
  /**
352
359
  * Creates a queue that processes items immediately upon addition.
@@ -1 +1 @@
1
- {"version":3,"file":"queuer.cjs","names":["Store","#setState","#tick","#clearTimeout","#getAllItems","parseFunctionOrValue","#checkExpiredItems","#getWait","#timeoutId"],"sources":["../src/queuer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\n\nexport interface QueuerState<TValue> {\n /**\n * Number of times addItem has been called (for reduction calculations)\n */\n addItemCount: number\n /**\n * Number of items that have been processed by the queuer\n */\n executionCount: number\n /**\n * Number of items that have been removed from the queue due to expiration\n */\n expirationCount: number\n /**\n * Whether the queuer has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the queuer has reached its maximum capacity\n */\n isFull: boolean\n /**\n * Whether the queuer is not currently processing any items\n */\n isIdle: boolean\n /**\n * Whether the queuer is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Array of items currently waiting to be processed\n */\n items: Array<TValue>\n /**\n * Timestamps when items were added to the queue for expiration tracking\n */\n itemTimestamps: Array<number>\n /**\n * Whether the queuer has a pending timeout for processing the next item\n */\n pendingTick: boolean\n /**\n * Number of items that have been rejected from being added to the queue\n */\n rejectionCount: number\n /**\n * Number of items currently in the queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused\n */\n status: 'idle' | 'running' | 'stopped'\n}\n\nfunction getDefaultQueuerState<TValue>(): QueuerState<TValue> {\n return {\n executionCount: 0,\n expirationCount: 0,\n isEmpty: true,\n isFull: false,\n isIdle: true,\n isRunning: true,\n itemTimestamps: [],\n items: [],\n pendingTick: false,\n rejectionCount: 0,\n size: 0,\n status: 'idle',\n addItemCount: 0,\n }\n}\n\n/**\n * Options for configuring a Queuer instance.\n *\n * These options control queue behavior, item expiration, callbacks, and more.\n */\nexport interface QueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum time in milliseconds that an item can stay in the queue\n * If not provided, items will never expire\n */\n expirationDuration?: number\n /**\n * Function to determine if an item has expired\n * If provided, this overrides the expirationDuration behavior\n */\n getIsExpired?: (item: TValue, addedAt: number) => boolean\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Initial state for the queuer\n */\n initialState?: Partial<QueuerState<TValue>>\n /**\n * Optional key to identify this queuer instance.\n * If provided, the queuer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Callback fired whenever an item is removed from the queuer\n */\n onExecute?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items.\n * Can be a number or a function that returns a number.\n * @default 0\n */\n wait?: number | ((queuer: Queuer<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `QueuerOptions` options between different `Queuer` instances.\n */\nexport function queuerOptions<\n TValue = any,\n TOptions extends Partial<QueuerOptions<TValue>> = Partial<\n QueuerOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<QueuerOptions<any>>,\n | 'initialState'\n | 'onExecute'\n | 'onIsRunningChange'\n | 'onItemsChange'\n | 'onReject'\n | 'onExpire'\n | 'key'\n> = {\n addItemsTo: 'back',\n getItemsFrom: 'front',\n getPriority: (item) => item?.priority ?? 0,\n getIsExpired: () => false,\n expirationDuration: Infinity,\n initialItems: [],\n maxSize: Infinity,\n started: true,\n wait: 0,\n}\n\n/**\n * Position type for addItem and getNextItem operations.\n *\n * - 'front': Operate on the front of the queue (FIFO)\n * - 'back': Operate on the back of the queue (LIFO)\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * A flexible queue that processes items with configurable wait times, expiration, and priority.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncQueuer when you need promises, retry support, abort capabilities, concurrent execution, or advanced error handling.\n *\n * Features:\n * - Automatic or manual processing of items\n * - FIFO (First In First Out), LIFO (Last In First Out), or double-ended queue behavior\n * - Priority-based ordering when getPriority is provided\n * - Item expiration and removal of stale items\n * - Callbacks for queue state changes, execution, rejection, and expiration\n *\n * Running behavior:\n * - `start()`: Begins automatically processing items in the queue (defaults to isRunning)\n * - `stop()`: Pauses processing but maintains queue state\n * - `wait`: Configurable delay between processing items\n * - `onItemsChange`/`onExecute`: Callbacks for monitoring queue state\n *\n * Manual processing is also supported when automatic processing is disabled:\n * - `execute()`: Processes the next item using the provided function\n * - `getNextItem()`: Removes and returns the next item without processing\n *\n * Queue behavior defaults to FIFO:\n * - `addItem(item)`: Adds to the back of the queue\n * - Items processed from the front of the queue\n *\n * Priority queue:\n * - Provide a `getPriority` function; higher values are processed first\n *\n * Stack (LIFO):\n * - `addItem(item, 'back')`: Adds to the back\n * - `getNextItem('back')`: Removes from the back\n *\n * Double-ended queue:\n * - `addItem(item, position)`: Adds to specified position ('front'/'back')\n * - `getNextItem(position)`: Removes from specified position\n *\n * Item expiration:\n * - `expirationDuration`: Maximum time items can stay in the queue\n * - `getIsExpired`: Function to override default expiration\n * - `onExpire`: Callback for expired items\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the queuer\n * - Use `onExecute` callback to react to item execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes execution count, expiration count, rejection count, and isRunning status\n * - State can be accessed via `queuer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `queuer.state`\n *\n * Example usage:\n * ```ts\n * // Auto-processing queue with wait time\n * const autoQueue = new Queuer<number>((n) => console.log(n), {\n * started: true, // Begin processing immediately\n * wait: 1000, // Wait 1s between items\n * onExecute: (item, queuer) => console.log(`Processed ${item}`)\n * });\n * autoQueue.addItem(1); // Will process after 1s\n * autoQueue.addItem(2); // Will process 1s after first item\n *\n * // Manual processing queue\n * const manualQueue = new Queuer<number>((n) => console.log(n), {\n * started: false\n * });\n * manualQueue.addItem(1); // [1]\n * manualQueue.addItem(2); // [1, 2]\n * manualQueue.execute(); // logs 1, queue is [2]\n * manualQueue.getNextItem(); // returns 2, queue is empty\n * ```\n */\nexport class Queuer<TValue> {\n readonly store: Store<Readonly<QueuerState<TValue>>> = new Store(\n getDefaultQueuerState<TValue>(),\n )\n key: string | undefined\n options: QueuerOptions<TValue>\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (item: TValue) => void,\n initialOptions: QueuerOptions<TValue> = {},\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n const isInitiallyRunning =\n this.options.initialState?.isRunning ?? this.options.started ?? true\n this.#setState({\n ...this.options.initialState,\n isRunning: isInitiallyRunning,\n })\n\n if (this.options.initialState?.items) {\n if (this.store.state.isRunning) {\n this.#tick()\n }\n } else {\n for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {\n const item = this.options.initialItems![i]!\n const isLast = i === (this.options.initialItems?.length ?? 0) - 1\n this.addItem(item, this.options.addItemsTo ?? 'back', isLast)\n }\n }\n\n if (this.key) {\n pacerEventClient.on('d-Queuer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<QueuerState<TValue>>,\n )\n this.setOptions(event.payload.options as Partial<QueuerOptions<TValue>>)\n })\n }\n }\n\n /**\n * Updates the queuer options. New options are merged with existing options.\n */\n setOptions = (newOptions: Partial<QueuerOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<QueuerState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n\n const { items, isRunning } = combinedState\n\n const size = items.length\n const isFull = size >= (this.options.maxSize ?? Infinity)\n const isEmpty = size === 0\n const isIdle = isRunning && isEmpty\n\n const status = isIdle ? 'idle' : isRunning ? 'running' : 'stopped'\n\n return {\n ...combinedState,\n isEmpty,\n isFull,\n isIdle,\n size,\n status,\n }\n })\n emitChange('Queuer', this)\n }\n\n /**\n * Returns the current wait time (in milliseconds) between processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait ?? 0, this)\n }\n\n /**\n * Processes items in the queue up to the wait interval. Internal use only.\n */\n #tick = () => {\n if (!this.store.state.isRunning) {\n this.#setState({ pendingTick: false })\n return\n }\n\n this.#setState({ pendingTick: true })\n\n // Check for expired items\n this.#checkExpiredItems()\n\n while (this.store.state.items.length > 0) {\n const nextItem = this.execute(this.options.getItemsFrom ?? 'front')\n if (nextItem === undefined) {\n break\n }\n\n const wait = this.#getWait()\n if (wait > 0) {\n // Use setTimeout to wait before processing next item\n this.#timeoutId = setTimeout(() => this.#tick(), wait)\n return\n }\n\n this.#tick()\n }\n this.#setState({ pendingTick: false })\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.\n * Items can be inserted based on priority or at the front/back depending on configuration.\n *\n * Returns true if the item was added, false if the queue is full.\n *\n * Example usage:\n * ```ts\n * queuer.addItem('task');\n * queuer.addItem('task2', 'front');\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo ?? 'back',\n runOnItemsChange: boolean = true,\n ): boolean => {\n this.#setState({\n addItemCount: this.store.state.addItemCount + 1,\n })\n\n if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n // Get priority either from the function or from getPriority option\n const priority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(item)\n : (item as any).priority\n\n const items = this.store.state.items\n const itemTimestamps = this.store.state.itemTimestamps\n\n if (priority !== undefined) {\n // Insert based on priority - higher priority items go to front\n const insertIndex = items.findIndex((existing) => {\n const existingPriority: number =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(existing)\n : (existing as any).priority\n return existingPriority < priority\n })\n\n if (insertIndex === -1) {\n items.push(item)\n itemTimestamps.push(Date.now())\n } else {\n items.splice(insertIndex, 0, item)\n itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n if (position === 'front') {\n // Default FIFO/LIFO behavior\n items.unshift(item)\n itemTimestamps.unshift(Date.now())\n } else {\n // LIFO\n items.push(item)\n itemTimestamps.push(Date.now())\n }\n }\n\n this.#setState({\n items,\n itemTimestamps,\n })\n\n if (runOnItemsChange) {\n this.options.onItemsChange?.(this)\n }\n\n if (this.store.state.isRunning && !this.store.state.pendingTick) {\n this.#setState({ pendingTick: true })\n this.#tick()\n }\n\n return true\n }\n\n /**\n * Removes and returns the next item from the queue without executing the function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * Example usage:\n * ```ts\n * // FIFO\n * queuer.getNextItem();\n * // LIFO\n * queuer.getNextItem('back');\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom ?? 'front',\n ): TValue | undefined => {\n const { items, itemTimestamps } = this.store.state\n let item: TValue | undefined\n\n // When priority function is provided, always get from front (highest priority)\n // Priority takes precedence over FIFO/LIFO behavior\n if (\n this.options.getPriority !== defaultOptions.getPriority ||\n position === 'front'\n ) {\n item = items[0]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(1),\n itemTimestamps: itemTimestamps.slice(1),\n })\n }\n } else {\n item = items[items.length - 1]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(0, -1),\n itemTimestamps: itemTimestamps.slice(0, -1),\n })\n }\n }\n\n if (item !== undefined) {\n this.options.onItemsChange?.(this)\n }\n\n return item\n }\n\n #getAllItems = (): Array<TValue> => {\n const items = this.peekAllItems()\n this.clear()\n return items\n }\n\n /**\n * Removes and returns the next item from the queue and processes it using the provided function.\n *\n * Example usage:\n * ```ts\n * queuer.execute();\n * // LIFO\n * queuer.execute('back');\n * ```\n */\n execute = (position?: QueuePosition): TValue | undefined => {\n const item = this.getNextItem(position)\n if (item !== undefined) {\n this.fn(item)\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(item, this)\n }\n return item\n }\n\n /**\n * Processes a specified number of items to execute immediately with no wait time\n * If no numberOfItems is provided, all items will be processed\n */\n flush = (\n numberOfItems: number = this.store.state.items.length,\n position?: QueuePosition,\n ): void => {\n this.#clearTimeout() // clear any pending timeout\n for (let i = 0; i < numberOfItems; i++) {\n this.execute(position)\n }\n this.#tick()\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function as an argument\n * The queue is cleared after processing\n */\n flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {\n const items = this.#getAllItems()\n this.clear()\n batchFunction(items)\n }\n\n /**\n * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.\n * Internal use only.\n */\n #checkExpiredItems = (): void => {\n if (\n (this.options.expirationDuration ?? Infinity) === Infinity &&\n this.options.getIsExpired === defaultOptions.getIsExpired\n ) {\n return\n }\n\n const now = Date.now()\n const expiredIndices: Array<number> = []\n\n // Find indices of expired items\n for (let i = 0; i < this.store.state.items.length; i++) {\n const timestamp = this.store.state.itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this.store.state.items[i]\n if (item === undefined) continue\n\n const isExpired =\n this.options.getIsExpired !== defaultOptions.getIsExpired\n ? this.options.getIsExpired!(item, timestamp)\n : now - timestamp > (this.options.expirationDuration ?? Infinity)\n\n if (isExpired) {\n expiredIndices.push(i)\n }\n }\n\n // Remove expired items from back to front to maintain indices\n for (let i = expiredIndices.length - 1; i >= 0; i--) {\n const index = expiredIndices[i]\n if (index === undefined) continue\n\n const expiredItem = this.store.state.items[index]\n if (expiredItem === undefined) continue\n\n const newItems = [...this.store.state.items]\n const newTimestamps = [...this.store.state.itemTimestamps]\n newItems.splice(index, 1)\n newTimestamps.splice(index, 1)\n this.#setState({\n items: newItems,\n itemTimestamps: newTimestamps,\n expirationCount: this.store.state.expirationCount + 1,\n })\n this.options.onExpire?.(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this.options.onItemsChange?.(this)\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * Example usage:\n * ```ts\n * queuer.peekNextItem(); // front\n * queuer.peekNextItem('back'); // back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (position === 'front') {\n return this.store.state.items[0]\n }\n return this.store.state.items[this.store.state.items.length - 1]\n }\n\n /**\n * Returns a copy of all items in the queue.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n /**\n * Starts processing items in the queue. If already isRunning, does nothing.\n */\n start = () => {\n this.#setState({ isRunning: true })\n if (!this.store.state.pendingTick && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = () => {\n this.#clearTimeout()\n this.#setState({ isRunning: false, pendingTick: false })\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all pending items from the queue. Does not affect items being processed.\n */\n clear = (): void => {\n this.#setState({ items: [], itemTimestamps: [] })\n this.options.onItemsChange?.(this)\n }\n\n /**\n * Resets the queuer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultQueuerState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a queue that processes items immediately upon addition.\n * Items are processed sequentially in FIFO order by default.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncQueue when you need promises, retry support, abort capabilities, concurrent execution, or advanced error handling.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the queuer\n * - Use `onExecute` callback to react to item execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes execution count, expiration count, rejection count, and isRunning status\n * - State can be accessed via the underlying Queuer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Example usage:\n * ```ts\n * // Basic sequential processing\n * const processItems = queue<number>((n) => console.log(n), {\n * wait: 1000,\n * onItemsChange: (queuer) => console.log(queuer.peekAllItems())\n * });\n * processItems(1); // Logs: 1\n * processItems(2); // Logs: 2 after 1 completes\n *\n * // Priority queue\n * const processPriority = queue<number>((n) => console.log(n), {\n * getPriority: n => n // Higher numbers processed first\n * });\n * processPriority(1);\n * processPriority(3); // Processed before 1\n * ```\n */\nexport function queue<TValue>(\n fn: (item: TValue) => void,\n initialOptions: QueuerOptions<TValue>,\n) {\n const queuer = new Queuer<TValue>(fn, initialOptions)\n return queuer.addItem\n}\n"],"mappings":";;;;;;AA2DA,SAAS,wBAAqD;AAC5D,QAAO;EACL,gBAAgB;EAChB,iBAAiB;EACjB,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,WAAW;EACX,gBAAgB,EAAE;EAClB,OAAO,EAAE;EACT,aAAa;EACb,gBAAgB;EAChB,MAAM;EACN,QAAQ;EACR,cAAc;EACf;;;;;AAkFH,SAAgB,cAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBASF;CACF,YAAY;CACZ,cAAc;CACd,cAAc,SAAS,MAAM,YAAY;CACzC,oBAAoB;CACpB,oBAAoB;CACpB,cAAc,EAAE;CAChB,SAAS;CACT,SAAS;CACT,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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I,KAAK,MAAM,MAAM,MAAM,QAAQ,KAAK;GACtD,MAAM,YAAY,KAAK,MAAM,MAAM,eAAe;AAClD,OAAI,cAAc,OAAW;GAE7B,MAAM,OAAO,KAAK,MAAM,MAAM,MAAM;AACpC,OAAI,SAAS,OAAW;AAOxB,OAJE,KAAK,QAAQ,iBAAiB,eAAe,eACzC,KAAK,QAAQ,aAAc,MAAM,UAAU,GAC3C,MAAM,aAAa,KAAK,QAAQ,sBAAsB,UAG1D,gBAAe,KAAK,EAAE;;AAK1B,OAAK,IAAI,IAAI,eAAe,SAAS,GAAG,KAAK,GAAG,KAAK;GACnD,MAAM,QAAQ,eAAe;AAC7B,OAAI,UAAU,OAAW;GAEzB,MAAM,cAAc,KAAK,MAAM,MAAM,MAAM;AAC3C,OAAI,gBAAgB,OAAW;GAE/B,MAAM,WAAW,CAAC,GAAG,KAAK,MAAM,MAAM,MAAM;GAC5C,MAAM,gBAAgB,CAAC,GAAG,KAAK,MAAM,MAAM,eAAe;AAC1D,YAAS,OAAO,OAAO,EAAE;AACzB,iBAAc,OAAO,OAAO,EAAE;AAC9B,SAAKA,SAAU;IACb,OAAO;IACP,gBAAgB;IAChB,iBAAiB,KAAK,MAAM,MAAM,kBAAkB;IACrD,CAAC;AACF,QAAK,QAAQ,WAAW,aAAa,KAAK;;AAG5C,MAAI,eAAe,SAAS,EAC1B,MAAK,QAAQ,gBAAgB,KAAK;;CA6CtC,sBAA4B;AAC1B,MAAI,MAAKO,WAAY;AACnB,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDxB,SAAgB,MACd,IACA,gBACA;AAEA,QADe,IAAI,OAAe,IAAI,eAAe,CACvC"}
1
+ {"version":3,"file":"queuer.cjs","names":["Store","parseFunctionOrValue","#setState","#checkExpiredItems","#getWait","#timeoutId","#tick","#clearTimeout","#getAllItems"],"sources":["../src/queuer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\n\nexport interface QueuerState<TValue> {\n /**\n * Number of times addItem has been called (for reduction calculations)\n */\n addItemCount: number\n /**\n * Number of items that have been processed by the queuer\n */\n executionCount: number\n /**\n * Number of items that have been removed from the queue due to expiration\n */\n expirationCount: number\n /**\n * Whether the queuer has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the queuer has reached its maximum capacity\n */\n isFull: boolean\n /**\n * Whether the queuer is not currently processing any items\n */\n isIdle: boolean\n /**\n * Whether the queuer is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Array of items currently waiting to be processed\n */\n items: Array<TValue>\n /**\n * Timestamps when items were added to the queue for expiration tracking\n */\n itemTimestamps: Array<number>\n /**\n * Whether the queuer has a pending timeout for processing the next item\n */\n pendingTick: boolean\n /**\n * Number of items that have been rejected from being added to the queue\n */\n rejectionCount: number\n /**\n * Number of items currently in the queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused\n */\n status: 'idle' | 'running' | 'stopped'\n}\n\nfunction getDefaultQueuerState<TValue>(): QueuerState<TValue> {\n return {\n executionCount: 0,\n expirationCount: 0,\n isEmpty: true,\n isFull: false,\n isIdle: true,\n isRunning: true,\n itemTimestamps: [],\n items: [],\n pendingTick: false,\n rejectionCount: 0,\n size: 0,\n status: 'idle',\n addItemCount: 0,\n }\n}\n\n/**\n * Options for configuring a Queuer instance.\n *\n * These options control queue behavior, item expiration, callbacks, and more.\n */\nexport interface QueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum time in milliseconds that an item can stay in the queue\n * If not provided, items will never expire\n */\n expirationDuration?: number\n /**\n * Function to determine if an item has expired\n * If provided, this overrides the expirationDuration behavior\n */\n getIsExpired?: (item: TValue, addedAt: number) => boolean\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Initial state for the queuer\n */\n initialState?: Partial<QueuerState<TValue>>\n /**\n * Optional key to identify this queuer instance.\n * If provided, the queuer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Callback fired whenever an item is removed from the queuer\n */\n onExecute?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items.\n * Can be a number or a function that returns a number.\n * @default 0\n */\n wait?: number | ((queuer: Queuer<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `QueuerOptions` options between different `Queuer` instances.\n */\nexport function queuerOptions<\n TValue = any,\n TOptions extends Partial<QueuerOptions<TValue>> = Partial<\n QueuerOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<QueuerOptions<any>>,\n | 'initialState'\n | 'onExecute'\n | 'onIsRunningChange'\n | 'onItemsChange'\n | 'onReject'\n | 'onExpire'\n | 'key'\n> = {\n addItemsTo: 'back',\n getItemsFrom: 'front',\n getPriority: (item) => item?.priority ?? 0,\n getIsExpired: () => false,\n expirationDuration: Infinity,\n initialItems: [],\n maxSize: Infinity,\n started: true,\n wait: 0,\n}\n\n/**\n * Position type for addItem and getNextItem operations.\n *\n * - 'front': Operate on the front of the queue (FIFO)\n * - 'back': Operate on the back of the queue (LIFO)\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * A flexible queue that processes items with configurable wait times, expiration, and priority.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncQueuer when you need promises, retry support, abort capabilities, concurrent execution, or advanced error handling.\n *\n * Features:\n * - Automatic or manual processing of items\n * - FIFO (First In First Out), LIFO (Last In First Out), or double-ended queue behavior\n * - Priority-based ordering when getPriority is provided\n * - Item expiration and removal of stale items\n * - Callbacks for queue state changes, execution, rejection, and expiration\n *\n * Running behavior:\n * - `start()`: Begins automatically processing items in the queue (defaults to isRunning)\n * - `stop()`: Pauses processing but maintains queue state\n * - `wait`: Configurable delay between processing items\n * - `onItemsChange`/`onExecute`: Callbacks for monitoring queue state\n *\n * Manual processing is also supported when automatic processing is disabled:\n * - `execute()`: Processes the next item using the provided function\n * - `getNextItem()`: Removes and returns the next item without processing\n *\n * Queue behavior defaults to FIFO:\n * - `addItem(item)`: Adds to the back of the queue\n * - Items processed from the front of the queue\n *\n * Priority queue:\n * - Provide a `getPriority` function; higher values are processed first\n *\n * Stack (LIFO):\n * - `addItem(item, 'back')`: Adds to the back\n * - `getNextItem('back')`: Removes from the back\n *\n * Double-ended queue:\n * - `addItem(item, position)`: Adds to specified position ('front'/'back')\n * - `getNextItem(position)`: Removes from specified position\n *\n * Item expiration:\n * - `expirationDuration`: Maximum time items can stay in the queue\n * - `getIsExpired`: Function to override default expiration\n * - `onExpire`: Callback for expired items\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the queuer\n * - Use `onExecute` callback to react to item execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes execution count, expiration count, rejection count, and isRunning status\n * - State can be accessed via `queuer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `queuer.state`\n *\n * Example usage:\n * ```ts\n * // Auto-processing queue with wait time\n * const autoQueue = new Queuer<number>((n) => console.log(n), {\n * started: true, // Begin processing immediately\n * wait: 1000, // Wait 1s between items\n * onExecute: (item, queuer) => console.log(`Processed ${item}`)\n * });\n * autoQueue.addItem(1); // Will process after 1s\n * autoQueue.addItem(2); // Will process 1s after first item\n *\n * // Manual processing queue\n * const manualQueue = new Queuer<number>((n) => console.log(n), {\n * started: false\n * });\n * manualQueue.addItem(1); // [1]\n * manualQueue.addItem(2); // [1, 2]\n * manualQueue.execute(); // logs 1, queue is [2]\n * manualQueue.getNextItem(); // returns 2, queue is empty\n * ```\n */\nexport class Queuer<TValue> {\n readonly store: Store<Readonly<QueuerState<TValue>>> = new Store(\n getDefaultQueuerState<TValue>(),\n )\n key: string | undefined\n options: QueuerOptions<TValue>\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (item: TValue) => void,\n initialOptions: QueuerOptions<TValue> = {},\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n const isInitiallyRunning =\n this.options.initialState?.isRunning ?? this.options.started ?? true\n this.#setState({\n ...this.options.initialState,\n isRunning: isInitiallyRunning,\n })\n\n if (this.options.initialState?.items) {\n if (this.store.state.isRunning) {\n this.#tick()\n }\n } else {\n for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {\n const item = this.options.initialItems![i]!\n const isLast = i === (this.options.initialItems?.length ?? 0) - 1\n this.addItem(item, this.options.addItemsTo ?? 'back', isLast)\n }\n }\n\n if (this.key) {\n pacerEventClient.on('d-Queuer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<QueuerState<TValue>>,\n )\n this.setOptions(event.payload.options as Partial<QueuerOptions<TValue>>)\n })\n }\n }\n\n /**\n * Updates the queuer options. New options are merged with existing options.\n */\n setOptions = (newOptions: Partial<QueuerOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<QueuerState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n\n const { items, isRunning } = combinedState\n\n const size = items.length\n const isFull = size >= (this.options.maxSize ?? Infinity)\n const isEmpty = size === 0\n const isIdle = isRunning && isEmpty\n\n const status = isIdle ? 'idle' : isRunning ? 'running' : 'stopped'\n\n return {\n ...combinedState,\n isEmpty,\n isFull,\n isIdle,\n size,\n status,\n }\n })\n emitChange('Queuer', this)\n }\n\n /**\n * Returns the current wait time (in milliseconds) between processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait ?? 0, this)\n }\n\n /**\n * Processes items in the queue up to the wait interval. Internal use only.\n */\n #tick = () => {\n if (!this.store.state.isRunning) {\n this.#setState({ pendingTick: false })\n return\n }\n\n this.#setState({ pendingTick: true })\n\n // Check for expired items\n this.#checkExpiredItems()\n\n while (this.store.state.items.length > 0) {\n const nextItem = this.execute(this.options.getItemsFrom ?? 'front')\n if (nextItem === undefined) {\n break\n }\n\n const wait = this.#getWait()\n if (wait > 0) {\n // Use setTimeout to wait before processing next item\n this.#timeoutId = setTimeout(() => this.#tick(), wait)\n return\n }\n\n this.#tick()\n }\n this.#setState({ pendingTick: false })\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.\n * Items can be inserted based on priority or at the front/back depending on configuration.\n *\n * Returns true if the item was added, false if the queue is full.\n *\n * Example usage:\n * ```ts\n * queuer.addItem('task');\n * queuer.addItem('task2', 'front');\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo ?? 'back',\n runOnItemsChange: boolean = true,\n ): boolean => {\n this.#setState({\n addItemCount: this.store.state.addItemCount + 1,\n })\n\n if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n // Get priority either from the function or from getPriority option\n const priority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(item)\n : (item as any).priority\n\n const items = this.store.state.items\n const itemTimestamps = this.store.state.itemTimestamps\n\n if (priority !== undefined) {\n // Insert based on priority - higher priority items go to front\n const insertIndex = items.findIndex((existing) => {\n const existingPriority: number =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(existing)\n : (existing as any).priority\n return existingPriority < priority\n })\n\n if (insertIndex === -1) {\n items.push(item)\n itemTimestamps.push(Date.now())\n } else {\n items.splice(insertIndex, 0, item)\n itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n if (position === 'front') {\n // Default FIFO/LIFO behavior\n items.unshift(item)\n itemTimestamps.unshift(Date.now())\n } else {\n // LIFO\n items.push(item)\n itemTimestamps.push(Date.now())\n }\n }\n\n this.#setState({\n items,\n itemTimestamps,\n })\n\n if (runOnItemsChange) {\n this.options.onItemsChange?.(this)\n }\n\n if (this.store.state.isRunning && !this.store.state.pendingTick) {\n this.#setState({ pendingTick: true })\n this.#tick()\n }\n\n return true\n }\n\n /**\n * Removes and returns the next item from the queue without executing the function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * Example usage:\n * ```ts\n * // FIFO\n * queuer.getNextItem();\n * // LIFO\n * queuer.getNextItem('back');\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom ?? 'front',\n ): TValue | undefined => {\n const { items, itemTimestamps } = this.store.state\n let item: TValue | undefined\n\n // When priority function is provided, always get from front (highest priority)\n // Priority takes precedence over FIFO/LIFO behavior\n if (\n this.options.getPriority !== defaultOptions.getPriority ||\n position === 'front'\n ) {\n item = items[0]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(1),\n itemTimestamps: itemTimestamps.slice(1),\n })\n }\n } else {\n item = items[items.length - 1]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(0, -1),\n itemTimestamps: itemTimestamps.slice(0, -1),\n })\n }\n }\n\n if (item !== undefined) {\n this.options.onItemsChange?.(this)\n }\n\n return item\n }\n\n #getAllItems = (): Array<TValue> => {\n const items = this.peekAllItems()\n this.clear()\n return items\n }\n\n /**\n * Removes and returns the next item from the queue and processes it using the provided function.\n *\n * Example usage:\n * ```ts\n * queuer.execute();\n * // LIFO\n * queuer.execute('back');\n * ```\n */\n execute = (position?: QueuePosition): TValue | undefined => {\n const item = this.getNextItem(position)\n if (item !== undefined) {\n this.fn(item)\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(item, this)\n }\n return item\n }\n\n /**\n * Processes a specified number of items to execute immediately with no wait time\n * If no numberOfItems is provided, all items will be processed\n */\n flush = (\n numberOfItems: number = this.store.state.items.length,\n position?: QueuePosition,\n ): void => {\n this.#clearTimeout() // clear any pending timeout\n for (let i = 0; i < numberOfItems; i++) {\n this.execute(position)\n }\n this.#tick()\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function as an argument\n * The queue is cleared after processing\n */\n flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {\n const items = this.#getAllItems()\n this.clear()\n batchFunction(items)\n }\n\n /**\n * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.\n * Internal use only.\n */\n #checkExpiredItems = (): void => {\n if (\n (this.options.expirationDuration ?? Infinity) === Infinity &&\n this.options.getIsExpired === defaultOptions.getIsExpired\n ) {\n return\n }\n\n const now = Date.now()\n const expiredIndices: Array<number> = []\n\n // Find indices of expired items\n for (let i = 0; i < this.store.state.items.length; i++) {\n const timestamp = this.store.state.itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this.store.state.items[i]\n if (item === undefined) continue\n\n const isExpired =\n this.options.getIsExpired !== defaultOptions.getIsExpired\n ? this.options.getIsExpired!(item, timestamp)\n : now - timestamp > (this.options.expirationDuration ?? Infinity)\n\n if (isExpired) {\n expiredIndices.push(i)\n }\n }\n\n // Remove expired items from back to front to maintain indices\n for (let i = expiredIndices.length - 1; i >= 0; i--) {\n const index = expiredIndices[i]\n if (index === undefined) continue\n\n const expiredItem = this.store.state.items[index]\n if (expiredItem === undefined) continue\n\n const newItems = [...this.store.state.items]\n const newTimestamps = [...this.store.state.itemTimestamps]\n newItems.splice(index, 1)\n newTimestamps.splice(index, 1)\n this.#setState({\n items: newItems,\n itemTimestamps: newTimestamps,\n expirationCount: this.store.state.expirationCount + 1,\n })\n this.options.onExpire?.(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this.options.onItemsChange?.(this)\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * Example usage:\n * ```ts\n * queuer.peekNextItem(); // front\n * queuer.peekNextItem('back'); // back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (position === 'front') {\n return this.store.state.items[0]\n }\n return this.store.state.items[this.store.state.items.length - 1]\n }\n\n /**\n * Returns a copy of all items in the queue.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n /**\n * Starts processing items in the queue. If already isRunning, does nothing.\n */\n start = () => {\n this.#setState({ isRunning: true })\n if (!this.store.state.pendingTick && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = () => {\n this.#clearTimeout()\n this.#setState({ isRunning: false, pendingTick: false })\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all pending items from the queue. Does not affect items being processed.\n */\n clear = (): void => {\n this.#setState({ items: [], itemTimestamps: [] })\n this.options.onItemsChange?.(this)\n }\n\n /**\n * Resets the queuer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultQueuerState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a queue that processes items immediately upon addition.\n * Items are processed sequentially in FIFO order by default.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncQueue when you need promises, retry support, abort capabilities, concurrent execution, or advanced error handling.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the queuer\n * - Use `onExecute` callback to react to item execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes execution count, expiration count, rejection count, and isRunning status\n * - State can be accessed via the underlying Queuer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Example usage:\n * ```ts\n * // Basic sequential processing\n * const processItems = queue<number>((n) => console.log(n), {\n * wait: 1000,\n * onItemsChange: (queuer) => console.log(queuer.peekAllItems())\n * });\n * processItems(1); // Logs: 1\n * processItems(2); // Logs: 2 after 1 completes\n *\n * // Priority queue\n * const processPriority = queue<number>((n) => console.log(n), {\n * getPriority: n => n // Higher numbers processed first\n * });\n * processPriority(1);\n * processPriority(3); // Processed before 1\n * ```\n */\nexport function queue<TValue>(\n fn: (item: TValue) => void,\n initialOptions: QueuerOptions<TValue>,\n) {\n const queuer = new Queuer<TValue>(fn, initialOptions)\n return queuer.addItem\n}\n"],"mappings":";;;;;;AA2DA,SAAS,wBAAqD;CAC5D,OAAO;EACL,gBAAgB;EAChB,iBAAiB;EACjB,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,WAAW;EACX,gBAAgB,EAAE;EAClB,OAAO,EAAE;EACT,aAAa;EACb,gBAAgB;EAChB,MAAM;EACN,QAAQ;EACR,cAAc;EACf;;;;;AAkFH,SAAgB,cAKd,SAA6B;CAC7B,OAAO;;AAGT,MAAM,iBASF;CACF,YAAY;CACZ,cAAc;CACd,cAAc,SAAS,MAAM,YAAY;CACzC,oBAAoB;CACpB,oBAAoB;CACpB,cAAc,EAAE;CAChB,SAAS;CACT,SAAS;CACT,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFD,IAAa,SAAb,MAA4B;CAM1B;CAEA,YACE,AAAO,IACP,iBAAwC,EAAE,EAC1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,QAAQ,gBAAgB,KAAK;;qBAMhB;GAClB,KAAKA,UAAU,uBAA+B,CAAC;GAC/C,KAAK,QAAQ,gBAAgB,KAAK;;EA9ZlC,KAAK,MAAM,eAAe;EAC1B,KAAK,UAAU;GACb,GAAG;GACH,GAAG;GACJ;EACD,MAAM,qBACJ,KAAK,QAAQ,cAAc,aAAa,KAAK,QAAQ,WAAW;EAClE,KAAKA,UAAU;GACb,GAAG,KAAK,QAAQ;GAChB,WAAW;GACZ,CAAC;EAEF,IAAI,KAAK,QAAQ,cAAc,OAC7B;OAAI,KAAK,MAAM,MAAM,WACnB,KAAKI,OAAO;SAGd,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,QAAQ,cAAc,UAAU,IAAI,KAAK;GACjE,MAAM,OAAO,KAAK,QAAQ,aAAc;GACxC,MAAM,SAAS,OAAO,KAAK,QAAQ,cAAc,UAAU,KAAK;GAChE,KAAK,QAAQ,MAAM,KAAK,QAAQ,cAAc,QAAQ,OAAO;;EAIjE,IAAI,KAAK,KACP,sCAAiB,GAAG,aAAa,UAAU;GACzC,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKJ,UACH,MAAM,QAAQ,MAAM,MACrB;GACD,KAAK,WAAW,MAAM,QAAQ,QAA0C;IACxE;;CAWN;;;;;CAgCA;;;;CAOA;CAiKA;;;;;CAyDA;CA+FA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DF,SAAgB,MACd,IACA,gBACA;CAEA,OAAO,IADY,OAAe,IAAI,eACzB,CAAC"}
package/dist/queuer.js CHANGED
@@ -112,16 +112,61 @@ const defaultOptions = {
112
112
  * ```
113
113
  */
114
114
  var Queuer = class {
115
- #timeoutId = null;
115
+ #timeoutId;
116
116
  constructor(fn, initialOptions = {}) {
117
117
  this.fn = fn;
118
118
  this.store = new Store(getDefaultQueuerState());
119
+ this.#timeoutId = null;
119
120
  this.setOptions = (newOptions) => {
120
121
  this.options = {
121
122
  ...this.options,
122
123
  ...newOptions
123
124
  };
124
125
  };
126
+ this.#setState = (newState) => {
127
+ this.store.setState((state) => {
128
+ const combinedState = {
129
+ ...state,
130
+ ...newState
131
+ };
132
+ const { items, isRunning } = combinedState;
133
+ const size = items.length;
134
+ const isFull = size >= (this.options.maxSize ?? Infinity);
135
+ const isEmpty = size === 0;
136
+ const isIdle = isRunning && isEmpty;
137
+ const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
138
+ return {
139
+ ...combinedState,
140
+ isEmpty,
141
+ isFull,
142
+ isIdle,
143
+ size,
144
+ status
145
+ };
146
+ });
147
+ emitChange("Queuer", this);
148
+ };
149
+ this.#getWait = () => {
150
+ return parseFunctionOrValue(this.options.wait ?? 0, this);
151
+ };
152
+ this.#tick = () => {
153
+ if (!this.store.state.isRunning) {
154
+ this.#setState({ pendingTick: false });
155
+ return;
156
+ }
157
+ this.#setState({ pendingTick: true });
158
+ this.#checkExpiredItems();
159
+ while (this.store.state.items.length > 0) {
160
+ if (this.execute(this.options.getItemsFrom ?? "front") === void 0) break;
161
+ const wait = this.#getWait();
162
+ if (wait > 0) {
163
+ this.#timeoutId = setTimeout(() => this.#tick(), wait);
164
+ return;
165
+ }
166
+ this.#tick();
167
+ }
168
+ this.#setState({ pendingTick: false });
169
+ };
125
170
  this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
126
171
  this.#setState({ addItemCount: this.store.state.addItemCount + 1 });
127
172
  if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
@@ -180,6 +225,11 @@ var Queuer = class {
180
225
  if (item !== void 0) this.options.onItemsChange?.(this);
181
226
  return item;
182
227
  };
228
+ this.#getAllItems = () => {
229
+ const items = this.peekAllItems();
230
+ this.clear();
231
+ return items;
232
+ };
183
233
  this.execute = (position) => {
184
234
  const item = this.getNextItem(position);
185
235
  if (item !== void 0) {
@@ -199,6 +249,35 @@ var Queuer = class {
199
249
  this.clear();
200
250
  batchFunction(items);
201
251
  };
252
+ this.#checkExpiredItems = () => {
253
+ if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
254
+ const now = Date.now();
255
+ const expiredIndices = [];
256
+ for (let i = 0; i < this.store.state.items.length; i++) {
257
+ const timestamp = this.store.state.itemTimestamps[i];
258
+ if (timestamp === void 0) continue;
259
+ const item = this.store.state.items[i];
260
+ if (item === void 0) continue;
261
+ if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
262
+ }
263
+ for (let i = expiredIndices.length - 1; i >= 0; i--) {
264
+ const index = expiredIndices[i];
265
+ if (index === void 0) continue;
266
+ const expiredItem = this.store.state.items[index];
267
+ if (expiredItem === void 0) continue;
268
+ const newItems = [...this.store.state.items];
269
+ const newTimestamps = [...this.store.state.itemTimestamps];
270
+ newItems.splice(index, 1);
271
+ newTimestamps.splice(index, 1);
272
+ this.#setState({
273
+ items: newItems,
274
+ itemTimestamps: newTimestamps,
275
+ expirationCount: this.store.state.expirationCount + 1
276
+ });
277
+ this.options.onExpire?.(expiredItem, this);
278
+ }
279
+ if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
280
+ };
202
281
  this.peekNextItem = (position = "front") => {
203
282
  if (position === "front") return this.store.state.items[0];
204
283
  return this.store.state.items[this.store.state.items.length - 1];
@@ -217,6 +296,12 @@ var Queuer = class {
217
296
  pendingTick: false
218
297
  });
219
298
  };
299
+ this.#clearTimeout = () => {
300
+ if (this.#timeoutId) {
301
+ clearTimeout(this.#timeoutId);
302
+ this.#timeoutId = null;
303
+ }
304
+ };
220
305
  this.clear = () => {
221
306
  this.#setState({
222
307
  items: [],
@@ -251,101 +336,23 @@ var Queuer = class {
251
336
  this.setOptions(event.payload.options);
252
337
  });
253
338
  }
254
- #setState = (newState) => {
255
- this.store.setState((state) => {
256
- const combinedState = {
257
- ...state,
258
- ...newState
259
- };
260
- const { items, isRunning } = combinedState;
261
- const size = items.length;
262
- const isFull = size >= (this.options.maxSize ?? Infinity);
263
- const isEmpty = size === 0;
264
- const isIdle = isRunning && isEmpty;
265
- const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
266
- return {
267
- ...combinedState,
268
- isEmpty,
269
- isFull,
270
- isIdle,
271
- size,
272
- status
273
- };
274
- });
275
- emitChange("Queuer", this);
276
- };
339
+ #setState;
277
340
  /**
278
341
  * Returns the current wait time (in milliseconds) between processing items.
279
342
  * If a function is provided, it is called with the queuer instance.
280
343
  */
281
- #getWait = () => {
282
- return parseFunctionOrValue(this.options.wait ?? 0, this);
283
- };
344
+ #getWait;
284
345
  /**
285
346
  * Processes items in the queue up to the wait interval. Internal use only.
286
347
  */
287
- #tick = () => {
288
- if (!this.store.state.isRunning) {
289
- this.#setState({ pendingTick: false });
290
- return;
291
- }
292
- this.#setState({ pendingTick: true });
293
- this.#checkExpiredItems();
294
- while (this.store.state.items.length > 0) {
295
- if (this.execute(this.options.getItemsFrom ?? "front") === void 0) break;
296
- const wait = this.#getWait();
297
- if (wait > 0) {
298
- this.#timeoutId = setTimeout(() => this.#tick(), wait);
299
- return;
300
- }
301
- this.#tick();
302
- }
303
- this.#setState({ pendingTick: false });
304
- };
305
- #getAllItems = () => {
306
- const items = this.peekAllItems();
307
- this.clear();
308
- return items;
309
- };
348
+ #tick;
349
+ #getAllItems;
310
350
  /**
311
351
  * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
312
352
  * Internal use only.
313
353
  */
314
- #checkExpiredItems = () => {
315
- if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
316
- const now = Date.now();
317
- const expiredIndices = [];
318
- for (let i = 0; i < this.store.state.items.length; i++) {
319
- const timestamp = this.store.state.itemTimestamps[i];
320
- if (timestamp === void 0) continue;
321
- const item = this.store.state.items[i];
322
- if (item === void 0) continue;
323
- if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
324
- }
325
- for (let i = expiredIndices.length - 1; i >= 0; i--) {
326
- const index = expiredIndices[i];
327
- if (index === void 0) continue;
328
- const expiredItem = this.store.state.items[index];
329
- if (expiredItem === void 0) continue;
330
- const newItems = [...this.store.state.items];
331
- const newTimestamps = [...this.store.state.itemTimestamps];
332
- newItems.splice(index, 1);
333
- newTimestamps.splice(index, 1);
334
- this.#setState({
335
- items: newItems,
336
- itemTimestamps: newTimestamps,
337
- expirationCount: this.store.state.expirationCount + 1
338
- });
339
- this.options.onExpire?.(expiredItem, this);
340
- }
341
- if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
342
- };
343
- #clearTimeout = () => {
344
- if (this.#timeoutId) {
345
- clearTimeout(this.#timeoutId);
346
- this.#timeoutId = null;
347
- }
348
- };
354
+ #checkExpiredItems;
355
+ #clearTimeout;
349
356
  };
350
357
  /**
351
358
  * Creates a queue that processes items immediately upon addition.