@tanstack/pacer 0.1.0

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 (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Options for configuring a Queuer instance
3
+ */
4
+ export interface QueuerOptions<TValue> {
5
+ /**
6
+ * Default position to add items to the queuer
7
+ * @default 'back'
8
+ */
9
+ addItemsTo?: QueuePosition;
10
+ /**
11
+ * Default position to get items from during processing
12
+ * @default 'front'
13
+ */
14
+ getItemsFrom?: QueuePosition;
15
+ /**
16
+ * Function to determine priority of items in the queuer
17
+ * Higher priority items will be processed first
18
+ */
19
+ getPriority?: (item: TValue) => number;
20
+ /**
21
+ * Initial items to populate the queuer with
22
+ */
23
+ initialItems?: Array<TValue>;
24
+ /**
25
+ * Maximum number of items allowed in the queuer
26
+ */
27
+ maxSize?: number;
28
+ /**
29
+ * Callback fired whenever an item is removed from the queuer
30
+ */
31
+ onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void;
32
+ /**
33
+ * Callback fired whenever an item is added or removed from the queuer
34
+ */
35
+ onUpdate?: (queuer: Queuer<TValue>) => void;
36
+ /**
37
+ * Whether the queuer should start processing tasks immediately
38
+ */
39
+ started?: boolean;
40
+ /**
41
+ * Time in milliseconds to wait between processing items
42
+ */
43
+ wait?: number;
44
+ }
45
+ /**
46
+ * Position type for addItem and getNextItem operations
47
+ */
48
+ export type QueuePosition = 'front' | 'back';
49
+ /**
50
+ * A flexible queue data structure that defaults to FIFO (First In First Out) behavior
51
+ * with optional position overrides for stack-like or double-ended operations.
52
+ *
53
+ * The queuer can automatically process items as they are added, with configurable
54
+ * wait times between processing each item. Processing can be started/stopped
55
+ * and the queuer will maintain its state.
56
+ *
57
+ * Supports priority-based ordering when a getPriority function is provided.
58
+ * Items with higher priority values will be processed first.
59
+ *
60
+ * Default queue behavior:
61
+ * - addItem(item): adds to back of queuer
62
+ * - getNextItem(): removes and returns from front of queuer
63
+ *
64
+ * Stack (LIFO) behavior:
65
+ * - addItem(item, 'back'): adds to back
66
+ * - getNextItem('back'): removes and returns from back
67
+ *
68
+ * Double-ended queuer behavior:
69
+ * - addItem(item, position): adds to specified position ('front' or 'back')
70
+ * - getNextItem(position): removes and returns from specified position
71
+ *
72
+ * Processing behavior:
73
+ * - start(): begins processing items in the queuer
74
+ * - stop(): pauses processing
75
+ * - wait: configurable delay between processing items
76
+ * - onUpdate/onGetNextItem: callbacks for monitoring queuer state
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * // FIFO queuer
81
+ * const queuer = new Queuer<number>();
82
+ * queuer.addItem(1); // [1]
83
+ * queuer.addItem(2); // [1, 2]
84
+ * queuer.getNextItem(); // returns 1, queuer is [2]
85
+ *
86
+ * // Priority queuer with processing
87
+ * const priorityQueue = new Queuer<number>({
88
+ * getPriority: (n) => n, // Higher numbers have priority
89
+ * started: true, // Begin processing immediately
90
+ * wait: 1000, // Wait 1s between items
91
+ * onGetNextItem: (item) => console.log(item)
92
+ * });
93
+ * priorityQueue.addItem(1); // [1]
94
+ * priorityQueue.addItem(3); // [3, 1] - 3 processed first
95
+ * priorityQueue.addItem(2); // [3, 2, 1]
96
+ * ```
97
+ */
98
+ export declare class Queuer<TValue> {
99
+ protected options: Required<QueuerOptions<TValue>>;
100
+ private items;
101
+ private executionCount;
102
+ private onUpdates;
103
+ private running;
104
+ private pendingTick;
105
+ constructor(initialOptions?: QueuerOptions<TValue>);
106
+ /**
107
+ * Processes items in the queuer
108
+ */
109
+ protected tick(): void;
110
+ /**
111
+ * Updates the queuer options
112
+ * Returns the new options state
113
+ */
114
+ setOptions(newOptions: Partial<QueuerOptions<TValue>>): QueuerOptions<TValue>;
115
+ /**
116
+ * Adds an item to the queuer and starts processing if not already running
117
+ * @returns true if item was added, false if queuer is full
118
+ */
119
+ addItem(item: TValue, position?: QueuePosition, runOnUpdate?: boolean): boolean;
120
+ /**
121
+ * Removes and returns an item from the queuer using shift (default) or pop
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * // Standard FIFO queuer
126
+ * queuer.getNextItem()
127
+ * // Stack-like behavior (LIFO)
128
+ * queuer.getNextItem('back')
129
+ * ```
130
+ */
131
+ getNextItem(position?: QueuePosition): TValue | undefined;
132
+ /**
133
+ * Returns an item without removing it
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * // Look at next item to getNextItem
138
+ * queuer.peek()
139
+ * // Look at last item (like stack top)
140
+ * queuer.peek('back')
141
+ * ```
142
+ */
143
+ peek(position?: QueuePosition): TValue | undefined;
144
+ /**
145
+ * Returns true if the queuer is empty
146
+ */
147
+ isEmpty(): boolean;
148
+ /**
149
+ * Returns true if the queuer is full
150
+ */
151
+ isFull(): boolean;
152
+ /**
153
+ * Returns the current size of the queuer
154
+ */
155
+ size(): number;
156
+ /**
157
+ * Removes all items from the queuer
158
+ */
159
+ clear(): void;
160
+ /**
161
+ * Resets the queuer to its initial state
162
+ */
163
+ reset(withInitialItems?: boolean): void;
164
+ /**
165
+ * Returns a copy of all items in the queuer
166
+ */
167
+ getAllItems(): Array<TValue>;
168
+ /**
169
+ * Returns the number of items that have been removed from the queuer
170
+ */
171
+ getExecutionCount(): number;
172
+ /**
173
+ * Adds a callback to be called when an item is processed
174
+ */
175
+ onUpdate(cb: (item: TValue) => void): () => void;
176
+ /**
177
+ * Stops the queuer from processing items
178
+ */
179
+ stop(): void;
180
+ /**
181
+ * Starts the queuer and processes items
182
+ */
183
+ start(): void;
184
+ /**
185
+ * Returns true if the queuer is running
186
+ */
187
+ isRunning(): boolean;
188
+ /**
189
+ * Returns true if the queuer is running but has no items to process
190
+ */
191
+ isIdle(): boolean;
192
+ }
193
+ /**
194
+ * Creates a queue that processes items in a queuer immediately upon addition.
195
+ * Items are processed sequentially in FIFO order by default.
196
+ *
197
+ * This is a simplified wrapper around the Queuer class that only exposes the
198
+ * `addItem` method. This queue is always running and will process items as they are added.
199
+ * For more control over queuer processing, use the Queuer class
200
+ * directly which provides methods like `start`, `stop`, `reset`, and more.
201
+ *
202
+ * @example
203
+ * ```ts
204
+ * // Basic sequential processing
205
+ * const processItems = queuer<number>({
206
+ * wait: 1000,
207
+ * onUpdate: (queuer) => console.log(queuer.getAllItems())
208
+ * })
209
+ * processItems(1) // Logs: 1
210
+ * processItems(2) // Logs: 2 after 1 completes
211
+ *
212
+ * // Priority queuer
213
+ * const processPriority = queuer<number>({
214
+ * process: async (n) => console.log(n),
215
+ * getPriority: n => n // Higher numbers processed first
216
+ * })
217
+ * processPriority(1)
218
+ * processPriority(3) // Processed before 1
219
+ * ```
220
+ */
221
+ export declare function queue<TValue>(options?: QueuerOptions<TValue>): (item: TValue, position?: QueuePosition, runOnUpdate?: boolean) => boolean;
@@ -0,0 +1,231 @@
1
+ const defaultOptions = {
2
+ addItemsTo: "back",
3
+ getItemsFrom: "front",
4
+ getPriority: () => 0,
5
+ initialItems: [],
6
+ maxSize: Infinity,
7
+ onGetNextItem: () => {
8
+ },
9
+ onUpdate: () => {
10
+ },
11
+ started: false,
12
+ wait: 0
13
+ };
14
+ class Queuer {
15
+ constructor(initialOptions = defaultOptions) {
16
+ this.items = [];
17
+ this.executionCount = 0;
18
+ this.onUpdates = [];
19
+ this.pendingTick = false;
20
+ this.options = { ...defaultOptions, ...initialOptions };
21
+ this.running = this.options.started;
22
+ for (let i = 0; i < this.options.initialItems.length; i++) {
23
+ const item = this.options.initialItems[i];
24
+ const isLast = i === this.options.initialItems.length - 1;
25
+ this.addItem(item, this.options.addItemsTo, isLast);
26
+ }
27
+ }
28
+ /**
29
+ * Processes items in the queuer
30
+ */
31
+ tick() {
32
+ if (!this.running) {
33
+ this.pendingTick = false;
34
+ return;
35
+ }
36
+ while (!this.isEmpty()) {
37
+ const nextItem = this.getNextItem(this.options.getItemsFrom);
38
+ if (nextItem === void 0) {
39
+ break;
40
+ }
41
+ this.onUpdates.forEach((cb) => cb(nextItem));
42
+ if (this.options.wait > 0) {
43
+ setTimeout(() => this.tick(), this.options.wait);
44
+ return;
45
+ }
46
+ this.tick();
47
+ }
48
+ this.pendingTick = false;
49
+ }
50
+ /**
51
+ * Updates the queuer options
52
+ * Returns the new options state
53
+ */
54
+ setOptions(newOptions) {
55
+ this.options = { ...this.options, ...newOptions };
56
+ return this.options;
57
+ }
58
+ /**
59
+ * Adds an item to the queuer and starts processing if not already running
60
+ * @returns true if item was added, false if queuer is full
61
+ */
62
+ addItem(item, position = this.options.addItemsTo, runOnUpdate = true) {
63
+ if (this.isFull()) {
64
+ return false;
65
+ }
66
+ if (this.options.getPriority !== defaultOptions.getPriority) {
67
+ const priority = this.options.getPriority(item);
68
+ const insertIndex = this.items.findIndex(
69
+ (existing) => this.options.getPriority(existing) > priority
70
+ );
71
+ if (insertIndex === -1) {
72
+ this.items.push(item);
73
+ } else {
74
+ this.items.splice(insertIndex, 0, item);
75
+ }
76
+ } else {
77
+ if (position === "front") {
78
+ this.items.unshift(item);
79
+ } else {
80
+ this.items.push(item);
81
+ }
82
+ }
83
+ if (this.running && !this.pendingTick) {
84
+ this.pendingTick = true;
85
+ this.tick();
86
+ }
87
+ if (runOnUpdate) {
88
+ this.options.onUpdate(this);
89
+ }
90
+ return true;
91
+ }
92
+ /**
93
+ * Removes and returns an item from the queuer using shift (default) or pop
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * // Standard FIFO queuer
98
+ * queuer.getNextItem()
99
+ * // Stack-like behavior (LIFO)
100
+ * queuer.getNextItem('back')
101
+ * ```
102
+ */
103
+ getNextItem(position = this.options.getItemsFrom) {
104
+ let item;
105
+ if (position === "front") {
106
+ item = this.items.shift();
107
+ } else {
108
+ item = this.items.pop();
109
+ }
110
+ if (item !== void 0) {
111
+ this.executionCount++;
112
+ this.options.onUpdate(this);
113
+ this.options.onGetNextItem(item, this);
114
+ }
115
+ return item;
116
+ }
117
+ /**
118
+ * Returns an item without removing it
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * // Look at next item to getNextItem
123
+ * queuer.peek()
124
+ * // Look at last item (like stack top)
125
+ * queuer.peek('back')
126
+ * ```
127
+ */
128
+ peek(position = this.options.getItemsFrom) {
129
+ if (position === "front") {
130
+ return this.items[0];
131
+ }
132
+ return this.items[this.items.length - 1];
133
+ }
134
+ /**
135
+ * Returns true if the queuer is empty
136
+ */
137
+ isEmpty() {
138
+ return this.items.length === 0;
139
+ }
140
+ /**
141
+ * Returns true if the queuer is full
142
+ */
143
+ isFull() {
144
+ return this.items.length >= this.options.maxSize;
145
+ }
146
+ /**
147
+ * Returns the current size of the queuer
148
+ */
149
+ size() {
150
+ return this.items.length;
151
+ }
152
+ /**
153
+ * Removes all items from the queuer
154
+ */
155
+ clear() {
156
+ this.items = [];
157
+ this.options.onUpdate(this);
158
+ }
159
+ /**
160
+ * Resets the queuer to its initial state
161
+ */
162
+ reset(withInitialItems) {
163
+ this.clear();
164
+ this.executionCount = 0;
165
+ if (withInitialItems) {
166
+ this.items = [...this.options.initialItems];
167
+ }
168
+ this.running = this.options.started;
169
+ }
170
+ /**
171
+ * Returns a copy of all items in the queuer
172
+ */
173
+ getAllItems() {
174
+ return [...this.items];
175
+ }
176
+ /**
177
+ * Returns the number of items that have been removed from the queuer
178
+ */
179
+ getExecutionCount() {
180
+ return this.executionCount;
181
+ }
182
+ /**
183
+ * Adds a callback to be called when an item is processed
184
+ */
185
+ onUpdate(cb) {
186
+ this.onUpdates.push(cb);
187
+ return () => {
188
+ this.onUpdates = this.onUpdates.filter((d) => d !== cb);
189
+ };
190
+ }
191
+ /**
192
+ * Stops the queuer from processing items
193
+ */
194
+ stop() {
195
+ this.running = false;
196
+ this.pendingTick = false;
197
+ this.options.onUpdate(this);
198
+ }
199
+ /**
200
+ * Starts the queuer and processes items
201
+ */
202
+ start() {
203
+ this.running = true;
204
+ if (!this.pendingTick && !this.isEmpty()) {
205
+ this.pendingTick = true;
206
+ this.tick();
207
+ }
208
+ this.options.onUpdate(this);
209
+ }
210
+ /**
211
+ * Returns true if the queuer is running
212
+ */
213
+ isRunning() {
214
+ return this.running;
215
+ }
216
+ /**
217
+ * Returns true if the queuer is running but has no items to process
218
+ */
219
+ isIdle() {
220
+ return this.running && this.isEmpty();
221
+ }
222
+ }
223
+ function queue(options = {}) {
224
+ const queuer = new Queuer({ ...options, started: true });
225
+ return queuer.addItem.bind(queuer);
226
+ }
227
+ export {
228
+ Queuer,
229
+ queue
230
+ };
231
+ //# sourceMappingURL=queuer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queuer.js","sources":["../../src/queuer.ts"],"sourcesContent":["/**\n * Options for configuring a Queuer instance\n */\nexport interface QueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\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 * 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 onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onUpdate?: (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 */\n wait?: number\n}\n\nconst defaultOptions: Required<QueuerOptions<any>> = {\n addItemsTo: 'back',\n getItemsFrom: 'front',\n getPriority: () => 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onUpdate: () => {},\n started: false,\n wait: 0,\n}\n\n/**\n * Position type for addItem and getNextItem operations\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * A flexible queue data structure that defaults to FIFO (First In First Out) behavior\n * with optional position overrides for stack-like or double-ended operations.\n *\n * The queuer can automatically process items as they are added, with configurable\n * wait times between processing each item. Processing can be started/stopped\n * and the queuer will maintain its state.\n *\n * Supports priority-based ordering when a getPriority function is provided.\n * Items with higher priority values will be processed first.\n *\n * Default queue behavior:\n * - addItem(item): adds to back of queuer\n * - getNextItem(): removes and returns from front of queuer\n *\n * Stack (LIFO) behavior:\n * - addItem(item, 'back'): adds to back\n * - getNextItem('back'): removes and returns from back\n *\n * Double-ended queuer behavior:\n * - addItem(item, position): adds to specified position ('front' or 'back')\n * - getNextItem(position): removes and returns from specified position\n *\n * Processing behavior:\n * - start(): begins processing items in the queuer\n * - stop(): pauses processing\n * - wait: configurable delay between processing items\n * - onUpdate/onGetNextItem: callbacks for monitoring queuer state\n *\n * @example\n * ```ts\n * // FIFO queuer\n * const queuer = new Queuer<number>();\n * queuer.addItem(1); // [1]\n * queuer.addItem(2); // [1, 2]\n * queuer.getNextItem(); // returns 1, queuer is [2]\n *\n * // Priority queuer with processing\n * const priorityQueue = new Queuer<number>({\n * getPriority: (n) => n, // Higher numbers have priority\n * started: true, // Begin processing immediately\n * wait: 1000, // Wait 1s between items\n * onGetNextItem: (item) => console.log(item)\n * });\n * priorityQueue.addItem(1); // [1]\n * priorityQueue.addItem(3); // [3, 1] - 3 processed first\n * priorityQueue.addItem(2); // [3, 2, 1]\n * ```\n */\nexport class Queuer<TValue> {\n protected options: Required<QueuerOptions<TValue>>\n private items: Array<TValue> = []\n private executionCount = 0\n private onUpdates: Array<(item: TValue) => void> = []\n private running: boolean\n private pendingTick = false\n\n constructor(initialOptions: QueuerOptions<TValue> = defaultOptions) {\n this.options = { ...defaultOptions, ...initialOptions }\n this.running = this.options.started\n\n for (let i = 0; i < this.options.initialItems.length; i++) {\n const item = this.options.initialItems[i]!\n const isLast = i === this.options.initialItems.length - 1\n this.addItem(item, this.options.addItemsTo, isLast)\n }\n }\n\n /**\n * Processes items in the queuer\n */\n protected tick() {\n if (!this.running) {\n this.pendingTick = false\n return\n }\n while (!this.isEmpty()) {\n const nextItem = this.getNextItem(this.options.getItemsFrom)\n if (nextItem === undefined) {\n break\n }\n this.onUpdates.forEach((cb) => cb(nextItem))\n\n if (this.options.wait > 0) {\n // Use setTimeout to wait before processing next item\n setTimeout(() => this.tick(), this.options.wait)\n return\n }\n\n this.tick()\n }\n this.pendingTick = false\n }\n\n /**\n * Updates the queuer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<QueuerOptions<TValue>>,\n ): QueuerOptions<TValue> {\n this.options = { ...this.options, ...newOptions }\n return this.options\n }\n\n /**\n * Adds an item to the queuer and starts processing if not already running\n * @returns true if item was added, false if queuer is full\n */\n addItem(\n item: TValue,\n position: QueuePosition = this.options.addItemsTo,\n runOnUpdate: boolean = true,\n ): boolean {\n if (this.isFull()) {\n return false\n }\n\n if (this.options.getPriority !== defaultOptions.getPriority) {\n // If custom priority function is provided, insert based on priority\n const priority = this.options.getPriority(item)\n const insertIndex = this.items.findIndex(\n (existing) => this.options.getPriority(existing) > priority,\n )\n\n if (insertIndex === -1) {\n this.items.push(item)\n } else {\n this.items.splice(insertIndex, 0, item)\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this.items.unshift(item)\n } else {\n this.items.push(item)\n }\n }\n\n if (this.running && !this.pendingTick) {\n this.pendingTick = true\n this.tick()\n }\n if (runOnUpdate) {\n this.options.onUpdate(this)\n }\n return true\n }\n\n /**\n * Removes and returns an item from the queuer using shift (default) or pop\n *\n * @example\n * ```ts\n * // Standard FIFO queuer\n * queuer.getNextItem()\n * // Stack-like behavior (LIFO)\n * queuer.getNextItem('back')\n * ```\n */\n getNextItem(\n position: QueuePosition = this.options.getItemsFrom,\n ): TValue | undefined {\n let item: TValue | undefined\n\n if (position === 'front') {\n item = this.items.shift()\n } else {\n item = this.items.pop()\n }\n\n if (item !== undefined) {\n this.executionCount++\n this.options.onUpdate(this)\n this.options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n *\n * @example\n * ```ts\n * // Look at next item to getNextItem\n * queuer.peek()\n * // Look at last item (like stack top)\n * queuer.peek('back')\n * ```\n */\n peek(\n position: QueuePosition = this.options.getItemsFrom,\n ): TValue | undefined {\n if (position === 'front') {\n return this.items[0]\n }\n return this.items[this.items.length - 1]\n }\n\n /**\n * Returns true if the queuer is empty\n */\n isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n isFull(): boolean {\n return this.items.length >= this.options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n size(): number {\n return this.items.length\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this.items = []\n this.options.onUpdate(this)\n }\n\n /**\n * Resets the queuer to its initial state\n */\n reset(withInitialItems?: boolean): void {\n this.clear()\n this.executionCount = 0\n if (withInitialItems) {\n this.items = [...this.options.initialItems]\n }\n this.running = this.options.started\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<TValue> {\n return [...this.items]\n }\n\n /**\n * Returns the number of items that have been removed from the queuer\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Adds a callback to be called when an item is processed\n */\n onUpdate(cb: (item: TValue) => void) {\n this.onUpdates.push(cb)\n return () => {\n this.onUpdates = this.onUpdates.filter((d) => d !== cb)\n }\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop() {\n this.running = false\n this.pendingTick = false\n this.options.onUpdate(this)\n }\n\n /**\n * Starts the queuer and processes items\n */\n start() {\n this.running = true\n if (!this.pendingTick && !this.isEmpty()) {\n this.pendingTick = true\n this.tick()\n }\n this.options.onUpdate(this)\n }\n\n /**\n * Returns true if the queuer is running\n */\n isRunning() {\n return this.running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n isIdle() {\n return this.running && this.isEmpty()\n }\n}\n\n/**\n * Creates a queue that processes items in a queuer immediately upon addition.\n * Items are processed sequentially in FIFO order by default.\n *\n * This is a simplified wrapper around the Queuer class that only exposes the\n * `addItem` method. This queue is always running and will process items as they are added.\n * For more control over queuer processing, use the Queuer class\n * directly which provides methods like `start`, `stop`, `reset`, and more.\n *\n * @example\n * ```ts\n * // Basic sequential processing\n * const processItems = queuer<number>({\n * wait: 1000,\n * onUpdate: (queuer) => console.log(queuer.getAllItems())\n * })\n * processItems(1) // Logs: 1\n * processItems(2) // Logs: 2 after 1 completes\n *\n * // Priority queuer\n * const processPriority = queuer<number>({\n * process: async (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>(options: QueuerOptions<TValue> = {}) {\n const queuer = new Queuer<TValue>({ ...options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AQ,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,QAAQ;AACN,SAAK,UAAU;AACf,QAAI,CAAC,KAAK,eAAe,CAAC,KAAK,WAAW;AACxC,WAAK,cAAc;AACnB,WAAK,KAAK;AAAA,IAAA;AAEP,SAAA,QAAQ,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,YAAY;AACV,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAS;AACA,WAAA,KAAK,WAAW,KAAK,QAAQ;AAAA,EAAA;AAExC;AA8BgB,SAAA,MAAc,UAAiC,IAAI;AAC3D,QAAA,SAAS,IAAI,OAAe,EAAE,GAAG,SAAS,SAAS,MAAM;AACxD,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;"}
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Information about a rate limit rejection
3
+ */
4
+ export interface RateLimitRejectionInfo {
5
+ /**
6
+ * Number of milliseconds until the next execution will be possible
7
+ */
8
+ msUntilNextWindow: number;
9
+ /**
10
+ * Current number of executions in the window
11
+ */
12
+ currentExecutions: number;
13
+ /**
14
+ * Maximum allowed executions per window
15
+ */
16
+ limit: number;
17
+ /**
18
+ * Total number of rejections that have occurred
19
+ */
20
+ rejectionCount: number;
21
+ }
22
+ /**
23
+ * Options for configuring a rate-limited function
24
+ */
25
+ export interface RateLimiterOptions {
26
+ /**
27
+ * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
28
+ * Defaults to true.
29
+ */
30
+ enabled?: boolean;
31
+ /**
32
+ * Maximum number of executions allowed within the time window
33
+ */
34
+ limit: number;
35
+ /**
36
+ * Time window in milliseconds within which the limit applies
37
+ */
38
+ window: number;
39
+ /**
40
+ * Optional callback function that is called when an execution is rejected due to rate limiting
41
+ */
42
+ onReject?: (info: RateLimitRejectionInfo) => void;
43
+ }
44
+ /**
45
+ * A class that creates a rate-limited function.
46
+ *
47
+ * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
48
+ * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
49
+ * all executions happen immediately, followed by a complete block.
50
+ *
51
+ * For smoother execution patterns, consider using:
52
+ * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
53
+ * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
54
+ *
55
+ * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
56
+ * smoothing out frequent events, throttling or debouncing usually provide better user experience.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const rateLimiter = new RateLimiter(
61
+ * (id: string) => api.getData(id),
62
+ * { limit: 5, window: 1000 } // 5 calls per second
63
+ * );
64
+ *
65
+ * // Will execute immediately until limit reached, then block
66
+ * rateLimiter.maybeExecute('123');
67
+ * ```
68
+ */
69
+ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
70
+ private fn;
71
+ private executionCount;
72
+ private rejectionCount;
73
+ private executionTimes;
74
+ private options;
75
+ constructor(fn: TFn, initialOptions: RateLimiterOptions);
76
+ /**
77
+ * Updates the rate limiter options
78
+ * Returns the new options state
79
+ */
80
+ setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions;
81
+ /**
82
+ * Returns the number of times the function has been executed
83
+ */
84
+ getExecutionCount(): number;
85
+ /**
86
+ * Returns the number of times the function has been rejected
87
+ */
88
+ getRejectionCount(): number;
89
+ /**
90
+ * Returns the number of remaining executions allowed in the current window
91
+ */
92
+ getRemainingInWindow(): number;
93
+ /**
94
+ * Attempts to execute the rate-limited function if within the configured limits.
95
+ * Will reject execution if the number of calls in the current window exceeds the limit.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
100
+ *
101
+ * // First 5 calls will return true
102
+ * rateLimiter.maybeExecute('arg1', 'arg2'); // true
103
+ *
104
+ * // Additional calls within the window will return false
105
+ * rateLimiter.maybeExecute('arg1', 'arg2'); // false
106
+ * ```
107
+ */
108
+ maybeExecute(...args: TArgs): boolean;
109
+ private executeFunction;
110
+ private rejectFunction;
111
+ private cleanupOldExecutions;
112
+ /**
113
+ * Resets the rate limiter state
114
+ */
115
+ reset(): void;
116
+ }
117
+ /**
118
+ * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
119
+ *
120
+ * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
121
+ * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
122
+ * - A throttler ensures even spacing between executions, which can be better for consistent performance
123
+ * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
124
+ *
125
+ * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
126
+ * need to enforce a hard limit on the number of executions within a time period.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * // Rate limit to 5 calls per minute
131
+ * const rateLimited = rateLimit(makeApiCall, {
132
+ * limit: 5,
133
+ * window: 60000,
134
+ * onReject: ({ msUntilNextWindow }) => {
135
+ * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
136
+ * }
137
+ * });
138
+ *
139
+ * // First 5 calls will execute immediately
140
+ * // Additional calls will be rejected until the minute window resets
141
+ * rateLimited();
142
+ *
143
+ * // For more even execution, consider using throttle instead:
144
+ * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
145
+ * ```
146
+ */
147
+ export declare function rateLimit<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<RateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => boolean;