@tanstack/pacer-lite 0.1.0 → 0.1.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 (62) hide show
  1. package/dist/index.cjs +16 -0
  2. package/dist/index.d.cts +6 -0
  3. package/dist/index.d.ts +6 -0
  4. package/dist/{esm/index.js → index.js} +2 -13
  5. package/dist/lite-batcher.cjs +175 -0
  6. package/dist/lite-batcher.cjs.map +1 -0
  7. package/dist/{cjs/lite-batcher.d.cts → lite-batcher.d.cts} +89 -85
  8. package/dist/{esm/lite-batcher.d.ts → lite-batcher.d.ts} +89 -85
  9. package/dist/lite-batcher.js +173 -0
  10. package/dist/lite-batcher.js.map +1 -0
  11. package/dist/lite-debouncer.cjs +125 -0
  12. package/dist/lite-debouncer.cjs.map +1 -0
  13. package/dist/{cjs/lite-debouncer.d.cts → lite-debouncer.d.cts} +53 -47
  14. package/dist/{esm/lite-debouncer.d.ts → lite-debouncer.d.ts} +53 -47
  15. package/dist/lite-debouncer.js +123 -0
  16. package/dist/lite-debouncer.js.map +1 -0
  17. package/dist/lite-queuer.cjs +208 -0
  18. package/dist/lite-queuer.cjs.map +1 -0
  19. package/dist/lite-queuer.d.cts +243 -0
  20. package/dist/lite-queuer.d.ts +243 -0
  21. package/dist/lite-queuer.js +206 -0
  22. package/dist/lite-queuer.js.map +1 -0
  23. package/dist/lite-rate-limiter.cjs +149 -0
  24. package/dist/lite-rate-limiter.cjs.map +1 -0
  25. package/dist/{cjs/lite-rate-limiter.d.cts → lite-rate-limiter.d.cts} +73 -67
  26. package/dist/{esm/lite-rate-limiter.d.ts → lite-rate-limiter.d.ts} +73 -67
  27. package/dist/lite-rate-limiter.js +147 -0
  28. package/dist/lite-rate-limiter.js.map +1 -0
  29. package/dist/lite-throttler.cjs +127 -0
  30. package/dist/lite-throttler.cjs.map +1 -0
  31. package/dist/{cjs/lite-throttler.d.cts → lite-throttler.d.cts} +60 -54
  32. package/dist/{esm/lite-throttler.d.ts → lite-throttler.d.ts} +60 -54
  33. package/dist/lite-throttler.js +125 -0
  34. package/dist/lite-throttler.js.map +1 -0
  35. package/package.json +22 -59
  36. package/dist/cjs/index.cjs +0 -18
  37. package/dist/cjs/index.cjs.map +0 -1
  38. package/dist/cjs/index.d.cts +0 -5
  39. package/dist/cjs/lite-batcher.cjs +0 -92
  40. package/dist/cjs/lite-batcher.cjs.map +0 -1
  41. package/dist/cjs/lite-debouncer.cjs +0 -59
  42. package/dist/cjs/lite-debouncer.cjs.map +0 -1
  43. package/dist/cjs/lite-queuer.cjs +0 -171
  44. package/dist/cjs/lite-queuer.cjs.map +0 -1
  45. package/dist/cjs/lite-queuer.d.cts +0 -239
  46. package/dist/cjs/lite-rate-limiter.cjs +0 -95
  47. package/dist/cjs/lite-rate-limiter.cjs.map +0 -1
  48. package/dist/cjs/lite-throttler.cjs +0 -63
  49. package/dist/cjs/lite-throttler.cjs.map +0 -1
  50. package/dist/esm/index.d.ts +0 -5
  51. package/dist/esm/index.js.map +0 -1
  52. package/dist/esm/lite-batcher.js +0 -92
  53. package/dist/esm/lite-batcher.js.map +0 -1
  54. package/dist/esm/lite-debouncer.js +0 -59
  55. package/dist/esm/lite-debouncer.js.map +0 -1
  56. package/dist/esm/lite-queuer.d.ts +0 -239
  57. package/dist/esm/lite-queuer.js +0 -171
  58. package/dist/esm/lite-queuer.js.map +0 -1
  59. package/dist/esm/lite-rate-limiter.js +0 -95
  60. package/dist/esm/lite-rate-limiter.js.map +0 -1
  61. package/dist/esm/lite-throttler.js +0 -63
  62. package/dist/esm/lite-throttler.js.map +0 -1
@@ -0,0 +1,243 @@
1
+ //#region src/lite-queuer.d.ts
2
+ /**
3
+ * Position type for addItem and getNextItem operations.
4
+ *
5
+ * - 'front': Operate on the front of the queue (FIFO for getNextItem)
6
+ * - 'back': Operate on the back of the queue (LIFO for getNextItem)
7
+ */
8
+ type QueuePosition = 'front' | 'back';
9
+ /**
10
+ * Options for configuring a lite queuer instance
11
+ */
12
+ interface LiteQueuerOptions<TValue> {
13
+ /**
14
+ * Default position to add items to the queue
15
+ * @default 'back'
16
+ */
17
+ addItemsTo?: QueuePosition;
18
+ /**
19
+ * Default position to get items from during processing
20
+ * @default 'front'
21
+ */
22
+ getItemsFrom?: QueuePosition;
23
+ /**
24
+ * Function to determine priority of items in the queue
25
+ * Higher priority items will be processed first
26
+ * Return undefined for items that should use positional ordering
27
+ */
28
+ getPriority?: (item: TValue) => number | undefined;
29
+ /**
30
+ * Initial items to populate the queue with
31
+ */
32
+ initialItems?: Array<TValue>;
33
+ /**
34
+ * Maximum number of items allowed in the queue
35
+ */
36
+ maxSize?: number;
37
+ /**
38
+ * Whether the queuer should start processing items immediately
39
+ * @default true
40
+ */
41
+ started?: boolean;
42
+ /**
43
+ * Time in milliseconds to wait between processing items
44
+ * @default 0
45
+ */
46
+ wait?: number;
47
+ }
48
+ /**
49
+ * A lightweight class that creates a queue for processing items.
50
+ *
51
+ * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more
52
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,
53
+ * this version does not use TanStack Store for state management, has no devtools integration,
54
+ * no callbacks, and provides only essential queueing functionality.
55
+ *
56
+ * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based
57
+ * processing of items. Items can be processed automatically with configurable wait times
58
+ * between executions, or processed manually using the execute methods.
59
+ *
60
+ * Features included:
61
+ * - Automatic or manual processing of items
62
+ * - FIFO, LIFO, and priority-based ordering
63
+ * - Queue size limits with item rejection
64
+ * - Configurable wait times between processing
65
+ * - Batch processing capabilities
66
+ * - Start/stop processing control
67
+ * - Callback support for monitoring execution, rejection, and state change events
68
+ *
69
+ * Features NOT included (compared to core Queuer):
70
+ * - No TanStack Store state management
71
+ * - No devtools integration
72
+ * - No item expiration functionality (no onExpire callback)
73
+ * - No dynamic options updates (setOptions)
74
+ * - No detailed state tracking (execution counts, etc.)
75
+ *
76
+ * Queue behavior:
77
+ * - Default: FIFO (add to back, process from front)
78
+ * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'
79
+ * - Priority: Provide getPriority function; higher values processed first
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * // Basic FIFO queue
84
+ * const queue = new LiteQueuer((item: string) => {
85
+ * console.log('Processing:', item);
86
+ * }, { wait: 100 });
87
+ *
88
+ * queue.addItem('task1');
89
+ * queue.addItem('task2');
90
+ * // Processes: task1, then task2 after 100ms delay
91
+ * ```
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * // Priority queue
96
+ * const priorityQueue = new LiteQueuer((item: Task) => {
97
+ * processTask(item);
98
+ * }, {
99
+ * getPriority: task => task.priority,
100
+ * wait: 500
101
+ * });
102
+ *
103
+ * priorityQueue.addItem({ name: 'low', priority: 1 });
104
+ * priorityQueue.addItem({ name: 'high', priority: 10 });
105
+ * // Processes high priority task first
106
+ * ```
107
+ */
108
+ declare class LiteQueuer<TValue> {
109
+ fn: (item: TValue) => void;
110
+ options: LiteQueuerOptions<TValue>;
111
+ private items;
112
+ private timeoutId;
113
+ private isRunning;
114
+ private pendingTick;
115
+ constructor(fn: (item: TValue) => void, options?: LiteQueuerOptions<TValue>);
116
+ /**
117
+ * Number of items currently in the queue
118
+ */
119
+ get size(): number;
120
+ /**
121
+ * Whether the queue is empty
122
+ */
123
+ get isEmpty(): boolean;
124
+ /**
125
+ * Whether the queue is currently running (auto-processing items)
126
+ */
127
+ get isQueueRunning(): boolean;
128
+ /**
129
+ * Adds an item to the queue. If the queue is full, the item is rejected.
130
+ * Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.
131
+ *
132
+ * Returns true if the item was added, false if the queue is full.
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * queue.addItem('task1'); // Add to default position (back)
137
+ * queue.addItem('task2', 'front'); // Add to front
138
+ * ```
139
+ */
140
+ addItem: (item: TValue, position?: QueuePosition, startProcessing?: boolean) => boolean;
141
+ private insertAtPosition;
142
+ /**
143
+ * Removes and returns the next item from the queue without executing the function.
144
+ * Use for manual queue management. Normally, use execute() to process items.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * const nextItem = queue.getNextItem(); // Get from default position (front)
149
+ * const lastItem = queue.getNextItem('back'); // Get from back (LIFO)
150
+ * ```
151
+ */
152
+ getNextItem: (position?: QueuePosition) => TValue | undefined;
153
+ /**
154
+ * Removes and returns the next item from the queue and processes it using the provided function.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * queue.execute(); // Execute from default position
159
+ * queue.execute('back'); // Execute from back (LIFO)
160
+ * ```
161
+ */
162
+ execute: (position?: QueuePosition) => TValue | undefined;
163
+ /**
164
+ * Internal method that processes items in the queue with wait intervals
165
+ */
166
+ private tick;
167
+ /**
168
+ * Starts processing items in the queue. If already running, does nothing.
169
+ */
170
+ start: () => void;
171
+ /**
172
+ * Stops processing items in the queue. Does not clear the queue.
173
+ */
174
+ stop: () => void;
175
+ /**
176
+ * Clears any pending timeout
177
+ */
178
+ private clearTimeout;
179
+ /**
180
+ * Returns the next item in the queue without removing it.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const next = queue.peekNextItem(); // Peek at front
185
+ * const last = queue.peekNextItem('back'); // Peek at back
186
+ * ```
187
+ */
188
+ peekNextItem: (position?: QueuePosition) => TValue | undefined;
189
+ /**
190
+ * Returns a copy of all items in the queue.
191
+ */
192
+ peekAllItems: () => Array<TValue>;
193
+ /**
194
+ * Processes a specified number of items immediately with no wait time.
195
+ * If no numberOfItems is provided, all items will be processed.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * queue.flush(); // Process all items immediately
200
+ * queue.flush(3); // Process next 3 items immediately
201
+ * ```
202
+ */
203
+ flush: (numberOfItems?: number, position?: QueuePosition) => void;
204
+ /**
205
+ * Processes all items in the queue as a batch using the provided function.
206
+ * The queue is cleared after processing.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * queue.flushAsBatch((items) => {
211
+ * console.log('Processing batch:', items);
212
+ * // Process all items together
213
+ * });
214
+ * ```
215
+ */
216
+ flushAsBatch: (batchFunction: (items: Array<TValue>) => void) => void;
217
+ /**
218
+ * Removes all items from the queue. Does not affect items being processed.
219
+ */
220
+ clear: () => void;
221
+ }
222
+ /**
223
+ * Creates a lightweight queue that processes items using the provided function.
224
+ *
225
+ * This is an alternative to the queue function in the core @tanstack/pacer package, but is more
226
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
227
+ * this function creates a queuer with no external dependencies, devtools integration, or reactive state.
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * const processItem = liteQueue((item: string) => {
232
+ * console.log('Processing:', item);
233
+ * }, { wait: 1000 });
234
+ *
235
+ * processItem('task1');
236
+ * processItem('task2');
237
+ * // Processes each item with 1 second delay between them
238
+ * ```
239
+ */
240
+ declare function liteQueue<TValue>(fn: (item: TValue) => void, options?: LiteQueuerOptions<TValue>): (item: TValue) => boolean;
241
+ //#endregion
242
+ export { LiteQueuer, LiteQueuerOptions, QueuePosition, liteQueue };
243
+ //# sourceMappingURL=lite-queuer.d.ts.map
@@ -0,0 +1,206 @@
1
+ //#region src/lite-queuer.ts
2
+ /**
3
+ * A lightweight class that creates a queue for processing items.
4
+ *
5
+ * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more
6
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,
7
+ * this version does not use TanStack Store for state management, has no devtools integration,
8
+ * no callbacks, and provides only essential queueing functionality.
9
+ *
10
+ * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based
11
+ * processing of items. Items can be processed automatically with configurable wait times
12
+ * between executions, or processed manually using the execute methods.
13
+ *
14
+ * Features included:
15
+ * - Automatic or manual processing of items
16
+ * - FIFO, LIFO, and priority-based ordering
17
+ * - Queue size limits with item rejection
18
+ * - Configurable wait times between processing
19
+ * - Batch processing capabilities
20
+ * - Start/stop processing control
21
+ * - Callback support for monitoring execution, rejection, and state change events
22
+ *
23
+ * Features NOT included (compared to core Queuer):
24
+ * - No TanStack Store state management
25
+ * - No devtools integration
26
+ * - No item expiration functionality (no onExpire callback)
27
+ * - No dynamic options updates (setOptions)
28
+ * - No detailed state tracking (execution counts, etc.)
29
+ *
30
+ * Queue behavior:
31
+ * - Default: FIFO (add to back, process from front)
32
+ * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'
33
+ * - Priority: Provide getPriority function; higher values processed first
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * // Basic FIFO queue
38
+ * const queue = new LiteQueuer((item: string) => {
39
+ * console.log('Processing:', item);
40
+ * }, { wait: 100 });
41
+ *
42
+ * queue.addItem('task1');
43
+ * queue.addItem('task2');
44
+ * // Processes: task1, then task2 after 100ms delay
45
+ * ```
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * // Priority queue
50
+ * const priorityQueue = new LiteQueuer((item: Task) => {
51
+ * processTask(item);
52
+ * }, {
53
+ * getPriority: task => task.priority,
54
+ * wait: 500
55
+ * });
56
+ *
57
+ * priorityQueue.addItem({ name: 'low', priority: 1 });
58
+ * priorityQueue.addItem({ name: 'high', priority: 10 });
59
+ * // Processes high priority task first
60
+ * ```
61
+ */
62
+ var LiteQueuer = class {
63
+ constructor(fn, options = {}) {
64
+ this.fn = fn;
65
+ this.options = options;
66
+ this.items = [];
67
+ this.timeoutId = null;
68
+ this.isRunning = true;
69
+ this.pendingTick = false;
70
+ this.addItem = (item, position = this.options.addItemsTo, startProcessing = true) => {
71
+ if (this.items.length >= this.options.maxSize) return false;
72
+ if (this.options.getPriority) {
73
+ const priority = this.options.getPriority(item);
74
+ if (priority !== void 0) {
75
+ const insertIndex = this.items.findIndex((existing) => {
76
+ return (this.options.getPriority(existing) ?? -Infinity) < priority;
77
+ });
78
+ if (insertIndex === -1) this.items.push(item);
79
+ else this.items.splice(insertIndex, 0, item);
80
+ } else this.insertAtPosition(item, position);
81
+ } else this.insertAtPosition(item, position);
82
+ if (startProcessing && this.isRunning && !this.pendingTick) this.tick();
83
+ return true;
84
+ };
85
+ this.insertAtPosition = (item, position) => {
86
+ if (position === "front") this.items.unshift(item);
87
+ else this.items.push(item);
88
+ };
89
+ this.getNextItem = (position = this.options.getItemsFrom) => {
90
+ if (this.items.length === 0) return;
91
+ let item;
92
+ if (this.options.getPriority || position === "front") item = this.items.shift();
93
+ else item = this.items.pop();
94
+ return item;
95
+ };
96
+ this.execute = (position) => {
97
+ const item = this.getNextItem(position);
98
+ if (item !== void 0) this.fn(item);
99
+ return item;
100
+ };
101
+ this.tick = () => {
102
+ if (!this.isRunning) {
103
+ this.pendingTick = false;
104
+ return;
105
+ }
106
+ this.pendingTick = true;
107
+ while (this.items.length > 0) {
108
+ if (this.execute(this.options.getItemsFrom) === void 0) break;
109
+ const wait = this.options.wait;
110
+ if (wait > 0) {
111
+ this.timeoutId = setTimeout(() => this.tick(), wait);
112
+ return;
113
+ }
114
+ }
115
+ this.pendingTick = false;
116
+ };
117
+ this.start = () => {
118
+ this.isRunning = true;
119
+ if (!this.pendingTick && this.items.length > 0) this.tick();
120
+ };
121
+ this.stop = () => {
122
+ this.clearTimeout();
123
+ this.isRunning = false;
124
+ this.pendingTick = false;
125
+ };
126
+ this.clearTimeout = () => {
127
+ if (this.timeoutId) {
128
+ clearTimeout(this.timeoutId);
129
+ this.timeoutId = null;
130
+ }
131
+ };
132
+ this.peekNextItem = (position = "front") => {
133
+ if (this.items.length === 0) return;
134
+ if (this.options.getPriority || position === "front") return this.items[0];
135
+ else return this.items[this.items.length - 1];
136
+ };
137
+ this.peekAllItems = () => {
138
+ return [...this.items];
139
+ };
140
+ this.flush = (numberOfItems = this.items.length, position) => {
141
+ this.clearTimeout();
142
+ for (let i = 0; i < numberOfItems && this.items.length > 0; i++) this.execute(position);
143
+ if (this.isRunning && this.items.length > 0 && !this.pendingTick) this.tick();
144
+ };
145
+ this.flushAsBatch = (batchFunction) => {
146
+ const items = this.peekAllItems();
147
+ this.clear();
148
+ batchFunction(items);
149
+ };
150
+ this.clear = () => {
151
+ this.items = [];
152
+ };
153
+ this.options.addItemsTo = this.options.addItemsTo ?? "back";
154
+ this.options.getItemsFrom = this.options.getItemsFrom ?? "front";
155
+ this.options.maxSize = this.options.maxSize ?? Infinity;
156
+ this.options.started = this.options.started ?? true;
157
+ this.options.wait = this.options.wait ?? 0;
158
+ this.isRunning = this.options.started;
159
+ if (this.options.initialItems) for (const item of this.options.initialItems) this.addItem(item, this.options.addItemsTo, false);
160
+ if (this.isRunning && this.items.length > 0) this.tick();
161
+ }
162
+ /**
163
+ * Number of items currently in the queue
164
+ */
165
+ get size() {
166
+ return this.items.length;
167
+ }
168
+ /**
169
+ * Whether the queue is empty
170
+ */
171
+ get isEmpty() {
172
+ return this.items.length === 0;
173
+ }
174
+ /**
175
+ * Whether the queue is currently running (auto-processing items)
176
+ */
177
+ get isQueueRunning() {
178
+ return this.isRunning;
179
+ }
180
+ };
181
+ /**
182
+ * Creates a lightweight queue that processes items using the provided function.
183
+ *
184
+ * This is an alternative to the queue function in the core @tanstack/pacer package, but is more
185
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
186
+ * this function creates a queuer with no external dependencies, devtools integration, or reactive state.
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * const processItem = liteQueue((item: string) => {
191
+ * console.log('Processing:', item);
192
+ * }, { wait: 1000 });
193
+ *
194
+ * processItem('task1');
195
+ * processItem('task2');
196
+ * // Processes each item with 1 second delay between them
197
+ * ```
198
+ */
199
+ function liteQueue(fn, options = {}) {
200
+ const queuer = new LiteQueuer(fn, options);
201
+ return (item) => queuer.addItem(item);
202
+ }
203
+
204
+ //#endregion
205
+ export { LiteQueuer, liteQueue };
206
+ //# sourceMappingURL=lite-queuer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-queuer.js","names":["fn: (item: TValue) => void","options: LiteQueuerOptions<TValue>","item: TValue | undefined"],"sources":["../src/lite-queuer.ts"],"sourcesContent":["/**\n * Position type for addItem and getNextItem operations.\n *\n * - 'front': Operate on the front of the queue (FIFO for getNextItem)\n * - 'back': Operate on the back of the queue (LIFO for getNextItem)\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * Options for configuring a lite queuer instance\n */\nexport interface LiteQueuerOptions<TValue> {\n /**\n * Default position to add items to the queue\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 queue\n * Higher priority items will be processed first\n * Return undefined for items that should use positional ordering\n */\n getPriority?: (item: TValue) => number | undefined\n /**\n * Initial items to populate the queue with\n */\n initialItems?: Array<TValue>\n /**\n * Maximum number of items allowed in the queue\n */\n maxSize?: number\n /**\n * Whether the queuer should start processing items immediately\n * @default true\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n * @default 0\n */\n wait?: number\n}\n\n/**\n * A lightweight class that creates a queue for processing items.\n *\n * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * no callbacks, and provides only essential queueing functionality.\n *\n * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based\n * processing of items. Items can be processed automatically with configurable wait times\n * between executions, or processed manually using the execute methods.\n *\n * Features included:\n * - Automatic or manual processing of items\n * - FIFO, LIFO, and priority-based ordering\n * - Queue size limits with item rejection\n * - Configurable wait times between processing\n * - Batch processing capabilities\n * - Start/stop processing control\n * - Callback support for monitoring execution, rejection, and state change events\n *\n * Features NOT included (compared to core Queuer):\n * - No TanStack Store state management\n * - No devtools integration\n * - No item expiration functionality (no onExpire callback)\n * - No dynamic options updates (setOptions)\n * - No detailed state tracking (execution counts, etc.)\n *\n * Queue behavior:\n * - Default: FIFO (add to back, process from front)\n * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'\n * - Priority: Provide getPriority function; higher values processed first\n *\n * @example\n * ```ts\n * // Basic FIFO queue\n * const queue = new LiteQueuer((item: string) => {\n * console.log('Processing:', item);\n * }, { wait: 100 });\n *\n * queue.addItem('task1');\n * queue.addItem('task2');\n * // Processes: task1, then task2 after 100ms delay\n * ```\n *\n * @example\n * ```ts\n * // Priority queue\n * const priorityQueue = new LiteQueuer((item: Task) => {\n * processTask(item);\n * }, {\n * getPriority: task => task.priority,\n * wait: 500\n * });\n *\n * priorityQueue.addItem({ name: 'low', priority: 1 });\n * priorityQueue.addItem({ name: 'high', priority: 10 });\n * // Processes high priority task first\n * ```\n */\nexport class LiteQueuer<TValue> {\n private items: Array<TValue> = []\n private timeoutId: NodeJS.Timeout | null = null\n private isRunning = true\n private pendingTick = false\n\n constructor(\n public fn: (item: TValue) => void,\n public options: LiteQueuerOptions<TValue> = {},\n ) {\n // Set defaults\n this.options.addItemsTo = this.options.addItemsTo ?? 'back'\n this.options.getItemsFrom = this.options.getItemsFrom ?? 'front'\n this.options.maxSize = this.options.maxSize ?? Infinity\n this.options.started = this.options.started ?? true\n this.options.wait = this.options.wait ?? 0\n\n this.isRunning = this.options.started\n\n // Add initial items if provided\n if (this.options.initialItems) {\n for (const item of this.options.initialItems) {\n this.addItem(item, this.options.addItemsTo, false)\n }\n }\n\n // Start processing if enabled and has items\n if (this.isRunning && this.items.length > 0) {\n this.tick()\n }\n }\n\n /**\n * Number of items currently in the queue\n */\n get size(): number {\n return this.items.length\n }\n\n /**\n * Whether the queue is empty\n */\n get isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Whether the queue is currently running (auto-processing items)\n */\n get isQueueRunning(): boolean {\n return this.isRunning\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected.\n * Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.\n *\n * Returns true if the item was added, false if the queue is full.\n *\n * @example\n * ```ts\n * queue.addItem('task1'); // Add to default position (back)\n * queue.addItem('task2', 'front'); // Add to front\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo!,\n startProcessing: boolean = true,\n ): boolean => {\n // Check size limit\n if (this.items.length >= this.options.maxSize!) {\n return false\n }\n\n // Handle priority insertion\n if (this.options.getPriority) {\n const priority = this.options.getPriority(item)\n if (priority !== undefined) {\n // Find insertion point for priority\n const insertIndex = this.items.findIndex((existing) => {\n const existingPriority = this.options.getPriority!(existing)\n // Treat undefined priority as negative infinity for comparison\n const effectivePriority = existingPriority ?? -Infinity\n return effectivePriority < 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 // No priority, use position\n this.insertAtPosition(item, position)\n }\n } else {\n // No priority function, use position\n this.insertAtPosition(item, position)\n }\n\n // Start processing if running and not already processing\n if (startProcessing && this.isRunning && !this.pendingTick) {\n this.tick()\n }\n\n return true\n }\n\n private insertAtPosition = (item: TValue, position: QueuePosition): void => {\n if (position === 'front') {\n this.items.unshift(item)\n } else {\n this.items.push(item)\n }\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\n * ```ts\n * const nextItem = queue.getNextItem(); // Get from default position (front)\n * const lastItem = queue.getNextItem('back'); // Get from back (LIFO)\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom!,\n ): TValue | undefined => {\n if (this.items.length === 0) {\n return undefined\n }\n\n let item: TValue | undefined\n\n // When priority function is provided, always get from front (highest priority)\n if (this.options.getPriority || position === 'front') {\n item = this.items.shift()\n } else {\n item = this.items.pop()\n }\n\n return item\n }\n\n /**\n * Removes and returns the next item from the queue and processes it using the provided function.\n *\n * @example\n * ```ts\n * queue.execute(); // Execute from default position\n * queue.execute('back'); // Execute from back (LIFO)\n * ```\n */\n execute = (position?: QueuePosition): TValue | undefined => {\n const item = this.getNextItem(position)\n if (item !== undefined) {\n this.fn(item)\n }\n return item\n }\n\n /**\n * Internal method that processes items in the queue with wait intervals\n */\n private tick = (): void => {\n if (!this.isRunning) {\n this.pendingTick = false\n return\n }\n\n this.pendingTick = true\n\n // Process items while queue is not empty\n while (this.items.length > 0) {\n const item = this.execute(this.options.getItemsFrom)\n if (item === undefined) {\n break\n }\n\n const wait = this.options.wait!\n if (wait > 0) {\n // Schedule next processing after wait time\n this.timeoutId = setTimeout(() => this.tick(), wait)\n return\n }\n\n // No wait time, continue processing immediately\n }\n\n this.pendingTick = false\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start = (): void => {\n this.isRunning = true\n if (!this.pendingTick && this.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 = (): void => {\n this.clearTimeout()\n this.isRunning = false\n this.pendingTick = false\n }\n\n /**\n * Clears any pending timeout\n */\n private clearTimeout = (): void => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * @example\n * ```ts\n * const next = queue.peekNextItem(); // Peek at front\n * const last = queue.peekNextItem('back'); // Peek at back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (this.items.length === 0) {\n return undefined\n }\n\n if (this.options.getPriority || position === 'front') {\n return this.items[0]\n } else {\n return this.items[this.items.length - 1]\n }\n }\n\n /**\n * Returns a copy of all items in the queue.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.items]\n }\n\n /**\n * Processes a specified number of items immediately with no wait time.\n * If no numberOfItems is provided, all items will be processed.\n *\n * @example\n * ```ts\n * queue.flush(); // Process all items immediately\n * queue.flush(3); // Process next 3 items immediately\n * ```\n */\n flush = (\n numberOfItems: number = this.items.length,\n position?: QueuePosition,\n ): void => {\n this.clearTimeout() // Clear any pending timeout\n for (let i = 0; i < numberOfItems && this.items.length > 0; i++) {\n this.execute(position)\n }\n // Restart normal processing if still running and has items\n if (this.isRunning && this.items.length > 0 && !this.pendingTick) {\n this.tick()\n }\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function.\n * The queue is cleared after processing.\n *\n * @example\n * ```ts\n * queue.flushAsBatch((items) => {\n * console.log('Processing batch:', items);\n * // Process all items together\n * });\n * ```\n */\n flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {\n const items = this.peekAllItems()\n this.clear()\n batchFunction(items)\n }\n\n /**\n * Removes all items from the queue. Does not affect items being processed.\n */\n clear = (): void => {\n this.items = []\n }\n}\n\n/**\n * Creates a lightweight queue that processes items using the provided function.\n *\n * This is an alternative to the queue function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a queuer with no external dependencies, devtools integration, or reactive state.\n *\n * @example\n * ```ts\n * const processItem = liteQueue((item: string) => {\n * console.log('Processing:', item);\n * }, { wait: 1000 });\n *\n * processItem('task1');\n * processItem('task2');\n * // Processes each item with 1 second delay between them\n * ```\n */\nexport function liteQueue<TValue>(\n fn: (item: TValue) => void,\n options: LiteQueuerOptions<TValue> = {},\n): (item: TValue) => boolean {\n const queuer = new LiteQueuer(fn, options)\n return (item: TValue) => queuer.addItem(item)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAa,aAAb,MAAgC;CAM9B,YACE,AAAOA,IACP,AAAOC,UAAqC,EAAE,EAC9C;EAFO;EACA;eAPsB,EAAE;mBACU;mBACvB;qBACE;kBA8DpB,MACA,WAA0B,KAAK,QAAQ,YACvC,kBAA2B,SACf;AAEZ,OAAI,KAAK,MAAM,UAAU,KAAK,QAAQ,QACpC,QAAO;AAIT,OAAI,KAAK,QAAQ,aAAa;IAC5B,MAAM,WAAW,KAAK,QAAQ,YAAY,KAAK;AAC/C,QAAI,aAAa,QAAW;KAE1B,MAAM,cAAc,KAAK,MAAM,WAAW,aAAa;AAIrD,cAHyB,KAAK,QAAQ,YAAa,SAAS,IAEd,aACnB;OAC3B;AAEF,SAAI,gBAAgB,GAClB,MAAK,MAAM,KAAK,KAAK;SAErB,MAAK,MAAM,OAAO,aAAa,GAAG,KAAK;UAIzC,MAAK,i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rate-limited function.
5
+ *
6
+ * This is an alternative to the RateLimiter in the core @tanstack/pacer package, but is more
7
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core RateLimiter,
8
+ * this version does not use TanStack Store for state management, has no devtools integration,
9
+ * and provides only essential rate limiting functionality.
10
+ *
11
+ * Rate limiting allows a function to execute up to a limit within a time window,
12
+ * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
13
+ * all executions happen immediately, followed by a complete block.
14
+ *
15
+ * The rate limiter supports two types of windows:
16
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
17
+ * towards the limit, and the window resets completely after the period.
18
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
19
+ * consistent rate of execution over time.
20
+ *
21
+ * Features:
22
+ * - Zero dependencies - no external libraries required
23
+ * - Minimal API surface - only essential methods (maybeExecute, getRemainingInWindow, getMsUntilNextWindow, reset)
24
+ * - Simple state management - uses basic private properties instead of reactive stores
25
+ * - Lightweight - designed for use in npm packages where bundle size matters
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const rateLimiter = new LiteRateLimiter((id: string) => {
30
+ * api.getData(id);
31
+ * }, { limit: 5, window: 1000 });
32
+ *
33
+ * // First 5 calls will execute, then block until window resets
34
+ * if (rateLimiter.maybeExecute('123')) {
35
+ * console.log('API call made');
36
+ * } else {
37
+ * console.log('Rate limited - try again in', rateLimiter.getMsUntilNextWindow(), 'ms');
38
+ * }
39
+ * ```
40
+ */
41
+ var LiteRateLimiter = class {
42
+ constructor(fn, options) {
43
+ this.fn = fn;
44
+ this.options = options;
45
+ this.executionTimes = [];
46
+ this.timeoutIds = /* @__PURE__ */ new Set();
47
+ this.maybeExecute = (...args) => {
48
+ this.cleanupOldExecutions();
49
+ if (this.getExecutionTimesInWindow().length < this.options.limit) {
50
+ this.execute(...args);
51
+ return true;
52
+ }
53
+ this.options.onReject?.(this);
54
+ return false;
55
+ };
56
+ this.execute = (...args) => {
57
+ const now = Date.now();
58
+ this.fn(...args);
59
+ this.options.onExecute?.(args, this);
60
+ this.executionTimes.push(now);
61
+ this.setCleanupTimeout(now);
62
+ };
63
+ this.getExecutionTimesInWindow = () => {
64
+ if (this.options.windowType === "sliding") return this.executionTimes.filter((time) => time > Date.now() - this.options.window);
65
+ else {
66
+ if (this.executionTimes.length === 0) return [];
67
+ const windowStart = Math.min(...this.executionTimes);
68
+ const windowEnd = windowStart + this.options.window;
69
+ if (Date.now() > windowEnd) return [];
70
+ return this.executionTimes.filter((time) => time >= windowStart && time <= windowEnd);
71
+ }
72
+ };
73
+ this.setCleanupTimeout = (executionTime) => {
74
+ if (this.options.windowType === "sliding" || this.timeoutIds.size === 0) {
75
+ const timeUntilExpiration = executionTime - Date.now() + this.options.window + 1;
76
+ const timeoutId = setTimeout(() => {
77
+ this.cleanupOldExecutions();
78
+ this.clearTimeout(timeoutId);
79
+ }, timeUntilExpiration);
80
+ this.timeoutIds.add(timeoutId);
81
+ }
82
+ };
83
+ this.clearTimeout = (timeoutId) => {
84
+ clearTimeout(timeoutId);
85
+ this.timeoutIds.delete(timeoutId);
86
+ };
87
+ this.clearTimeouts = () => {
88
+ this.timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
89
+ this.timeoutIds.clear();
90
+ };
91
+ this.cleanupOldExecutions = () => {
92
+ this.executionTimes = this.getExecutionTimesInWindow();
93
+ };
94
+ this.getRemainingInWindow = () => {
95
+ const relevantExecutionTimes = this.getExecutionTimesInWindow();
96
+ return Math.max(0, this.options.limit - relevantExecutionTimes.length);
97
+ };
98
+ this.getMsUntilNextWindow = () => {
99
+ if (this.getRemainingInWindow() > 0) return 0;
100
+ return (this.executionTimes[0] ?? Infinity) + this.options.window - Date.now();
101
+ };
102
+ this.reset = () => {
103
+ this.executionTimes = [];
104
+ this.clearTimeouts();
105
+ };
106
+ if (this.options.windowType === void 0) this.options.windowType = "fixed";
107
+ }
108
+ };
109
+ /**
110
+ * Creates a lightweight rate-limited function that will execute the provided function up to a maximum number of times within a time window.
111
+ *
112
+ * This is an alternative to the rateLimit function in the core @tanstack/pacer package, but is more
113
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
114
+ * this function creates a rate limiter with no external dependencies, devtools integration, or reactive state.
115
+ *
116
+ * Rate limiting allows all executions until the limit is reached, then blocks all subsequent calls until the window resets.
117
+ * This differs from throttling (which ensures even spacing) and debouncing (which waits for pauses).
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * const rateLimitedApi = liteRateLimit(makeApiCall, {
122
+ * limit: 5,
123
+ * window: 60000, // 1 minute
124
+ * windowType: 'sliding'
125
+ * });
126
+ *
127
+ * // First 5 calls execute immediately
128
+ * // Additional calls are rejected until window allows
129
+ * rateLimitedApi();
130
+ * ```
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * // Fixed window - all 10 calls happen in first second, then 10 second wait
135
+ * const rateLimitedFixed = liteRateLimit(logEvent, {
136
+ * limit: 10,
137
+ * window: 10000,
138
+ * windowType: 'fixed'
139
+ * });
140
+ * ```
141
+ */
142
+ function liteRateLimit(fn, options) {
143
+ return new LiteRateLimiter(fn, options).maybeExecute;
144
+ }
145
+
146
+ //#endregion
147
+ exports.LiteRateLimiter = LiteRateLimiter;
148
+ exports.liteRateLimit = liteRateLimit;
149
+ //# sourceMappingURL=lite-rate-limiter.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-rate-limiter.cjs","names":["fn: TFn","options: LiteRateLimiterOptions<TFn>"],"sources":["../src/lite-rate-limiter.ts"],"sourcesContent":["import type { AnyFunction } from '@tanstack/pacer/types'\n\n/**\n * Options for configuring a lite rate-limited function\n */\nexport interface LiteRateLimiterOptions<TFn extends AnyFunction = AnyFunction> {\n /**\n * Maximum number of executions allowed within the time window.\n */\n limit: number\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: LiteRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: LiteRateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n */\n window: number\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\n/**\n * A lightweight class that creates a rate-limited function.\n *\n * This is an alternative to the RateLimiter in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core RateLimiter,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * and provides only essential rate limiting functionality.\n *\n * Rate limiting allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Features:\n * - Zero dependencies - no external libraries required\n * - Minimal API surface - only essential methods (maybeExecute, getRemainingInWindow, getMsUntilNextWindow, reset)\n * - Simple state management - uses basic private properties instead of reactive stores\n * - Lightweight - designed for use in npm packages where bundle size matters\n *\n * @example\n * ```ts\n * const rateLimiter = new LiteRateLimiter((id: string) => {\n * api.getData(id);\n * }, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute, then block until window resets\n * if (rateLimiter.maybeExecute('123')) {\n * console.log('API call made');\n * } else {\n * console.log('Rate limited - try again in', rateLimiter.getMsUntilNextWindow(), 'ms');\n * }\n * ```\n */\nexport class LiteRateLimiter<TFn extends AnyFunction> {\n private executionTimes: Array<number> = []\n private timeoutIds: Set<NodeJS.Timeout> = new Set()\n\n constructor(\n public fn: TFn,\n public options: LiteRateLimiterOptions<TFn>,\n ) {\n // Default windowType to 'fixed' if not specified\n if (this.options.windowType === undefined) {\n this.options.windowType = 'fixed'\n }\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Returns true if executed, false if rejected due to rate limiting.\n *\n * @example\n * ```ts\n * const rateLimiter = new LiteRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.cleanupOldExecutions()\n\n const relevantExecutionTimes = this.getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.options.limit) {\n this.execute(...args)\n return true\n }\n\n this.options.onReject?.(this)\n return false\n }\n\n private execute = (...args: Parameters<TFn>): void => {\n const now = Date.now()\n this.fn(...args)\n this.options.onExecute?.(args, this)\n this.executionTimes.push(now)\n this.setCleanupTimeout(now)\n }\n\n private getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.executionTimes.filter(\n (time) => time > Date.now() - this.options.window,\n )\n } else {\n // For fixed window, return all executions in the current window\n if (this.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.options.window\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n private setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.options.window + 1\n const timeoutId = setTimeout(() => {\n this.cleanupOldExecutions()\n this.clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.timeoutIds.add(timeoutId)\n }\n }\n\n private clearTimeout = (timeoutId: NodeJS.Timeout): void => {\n clearTimeout(timeoutId)\n this.timeoutIds.delete(timeoutId)\n }\n\n private clearTimeouts = (): void => {\n this.timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.timeoutIds.clear()\n }\n\n private cleanupOldExecutions = (): void => {\n this.executionTimes = this.getExecutionTimesInWindow()\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window.\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.getExecutionTimesInWindow()\n return Math.max(0, this.options.limit - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible.\n * Returns 0 if executions are currently allowed.\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.executionTimes[0] ?? Infinity\n return oldestExecution + this.options.window - Date.now()\n }\n\n /**\n * Resets the rate limiter state, clearing all execution history.\n */\n reset = (): void => {\n this.executionTimes = []\n this.clearTimeouts()\n }\n}\n\n/**\n * Creates a lightweight rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * This is an alternative to the rateLimit function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a rate limiter with no external dependencies, devtools integration, or reactive state.\n *\n * Rate limiting allows all executions until the limit is reached, then blocks all subsequent calls until the window resets.\n * This differs from throttling (which ensures even spacing) and debouncing (which waits for pauses).\n *\n * @example\n * ```ts\n * const rateLimitedApi = liteRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000, // 1 minute\n * windowType: 'sliding'\n * });\n *\n * // First 5 calls execute immediately\n * // Additional calls are rejected until window allows\n * rateLimitedApi();\n * ```\n *\n * @example\n * ```ts\n * // Fixed window - all 10 calls happen in first second, then 10 second wait\n * const rateLimitedFixed = liteRateLimit(logEvent, {\n * limit: 10,\n * window: 10000,\n * windowType: 'fixed'\n * });\n * ```\n */\nexport function liteRateLimit<TFn extends AnyFunction>(\n fn: TFn,\n options: LiteRateLimiterOptions<TFn>,\n): (...args: Parameters<TFn>) => boolean {\n const rateLimiter = new LiteRateLimiter(fn, options)\n return rateLimiter.maybeExecute\n}\n"],"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