@tanstack/pacer-lite 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.
- package/LICENSE +21 -0
- package/README.md +165 -0
- package/dist/cjs/index.cjs +18 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/index.d.cts +5 -0
- package/dist/cjs/lite-batcher.cjs +92 -0
- package/dist/cjs/lite-batcher.cjs.map +1 -0
- package/dist/cjs/lite-batcher.d.cts +180 -0
- package/dist/cjs/lite-debouncer.cjs +59 -0
- package/dist/cjs/lite-debouncer.cjs.map +1 -0
- package/dist/cjs/lite-debouncer.d.cts +121 -0
- package/dist/cjs/lite-queuer.cjs +171 -0
- package/dist/cjs/lite-queuer.cjs.map +1 -0
- package/dist/cjs/lite-queuer.d.cts +239 -0
- package/dist/cjs/lite-rate-limiter.cjs +95 -0
- package/dist/cjs/lite-rate-limiter.cjs.map +1 -0
- package/dist/cjs/lite-rate-limiter.d.cts +143 -0
- package/dist/cjs/lite-throttler.cjs +63 -0
- package/dist/cjs/lite-throttler.cjs.map +1 -0
- package/dist/cjs/lite-throttler.d.cts +128 -0
- package/dist/esm/index.d.ts +5 -0
- package/dist/esm/index.js +18 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/lite-batcher.d.ts +180 -0
- package/dist/esm/lite-batcher.js +92 -0
- package/dist/esm/lite-batcher.js.map +1 -0
- package/dist/esm/lite-debouncer.d.ts +121 -0
- package/dist/esm/lite-debouncer.js +59 -0
- package/dist/esm/lite-debouncer.js.map +1 -0
- package/dist/esm/lite-queuer.d.ts +239 -0
- package/dist/esm/lite-queuer.js +171 -0
- package/dist/esm/lite-queuer.js.map +1 -0
- package/dist/esm/lite-rate-limiter.d.ts +143 -0
- package/dist/esm/lite-rate-limiter.js +95 -0
- package/dist/esm/lite-rate-limiter.js.map +1 -0
- package/dist/esm/lite-throttler.d.ts +128 -0
- package/dist/esm/lite-throttler.js +63 -0
- package/dist/esm/lite-throttler.js.map +1 -0
- package/package.json +113 -0
- package/src/index.ts +5 -0
- package/src/lite-batcher.ts +267 -0
- package/src/lite-debouncer.ts +184 -0
- package/src/lite-queuer.ts +434 -0
- package/src/lite-rate-limiter.ts +246 -0
- package/src/lite-throttler.ts +195 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { AnyFunction } from '@tanstack/pacer/types';
|
|
2
|
+
/**
|
|
3
|
+
* Options for configuring a lite debounced function
|
|
4
|
+
*/
|
|
5
|
+
export interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
|
|
6
|
+
/**
|
|
7
|
+
* Whether to execute on the leading edge of the timeout.
|
|
8
|
+
* The first call will execute immediately and the rest will wait the delay.
|
|
9
|
+
* Defaults to false.
|
|
10
|
+
*/
|
|
11
|
+
leading?: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Callback function that is called after the function is executed
|
|
14
|
+
*/
|
|
15
|
+
onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void;
|
|
16
|
+
/**
|
|
17
|
+
* Whether to execute on the trailing edge of the timeout.
|
|
18
|
+
* Defaults to true.
|
|
19
|
+
*/
|
|
20
|
+
trailing?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Delay in milliseconds before executing the function.
|
|
23
|
+
*/
|
|
24
|
+
wait: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* A lightweight class that creates a debounced function.
|
|
28
|
+
*
|
|
29
|
+
* This is an alternative to the Debouncer in the core @tanstack/pacer package, but is more
|
|
30
|
+
* suitable for libraries and npm packages that need minimal overhead. Unlike the core Debouncer,
|
|
31
|
+
* this version does not use TanStack Store for state management, has no devtools integration,
|
|
32
|
+
* and provides only essential debouncing functionality.
|
|
33
|
+
*
|
|
34
|
+
* Debouncing ensures that a function is only executed after a certain amount of time has passed
|
|
35
|
+
* since its last invocation. This is useful for handling frequent events like window resizing,
|
|
36
|
+
* scroll events, or input changes where you want to limit the rate of execution.
|
|
37
|
+
*
|
|
38
|
+
* The debounced function can be configured to execute either at the start of the delay period
|
|
39
|
+
* (leading edge) or at the end (trailing edge, default). Each new call during the wait period
|
|
40
|
+
* will reset the timer.
|
|
41
|
+
*
|
|
42
|
+
* Features:
|
|
43
|
+
* - Zero dependencies - no external libraries required
|
|
44
|
+
* - Minimal API surface - only essential methods (maybeExecute, flush, cancel)
|
|
45
|
+
* - Simple state management - uses basic private properties instead of reactive stores
|
|
46
|
+
* - Callback support for monitoring execution events
|
|
47
|
+
* - Lightweight - designed for use in npm packages where bundle size matters
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* const debouncer = new LiteDebouncer((value: string) => {
|
|
52
|
+
* saveToDatabase(value);
|
|
53
|
+
* }, {
|
|
54
|
+
* wait: 500,
|
|
55
|
+
* onExecute: (args, debouncer) => {
|
|
56
|
+
* console.log('Saved value:', args[0]);
|
|
57
|
+
* }
|
|
58
|
+
* });
|
|
59
|
+
*
|
|
60
|
+
* // Will only save after 500ms of no new input
|
|
61
|
+
* inputElement.addEventListener('input', () => {
|
|
62
|
+
* debouncer.maybeExecute(inputElement.value);
|
|
63
|
+
* });
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
export declare class LiteDebouncer<TFn extends AnyFunction> {
|
|
67
|
+
fn: TFn;
|
|
68
|
+
options: LiteDebouncerOptions<TFn>;
|
|
69
|
+
private timeoutId;
|
|
70
|
+
private lastArgs;
|
|
71
|
+
private canLeadingExecute;
|
|
72
|
+
constructor(fn: TFn, options: LiteDebouncerOptions<TFn>);
|
|
73
|
+
/**
|
|
74
|
+
* Attempts to execute the debounced function.
|
|
75
|
+
* If leading is true and this is the first call, executes immediately.
|
|
76
|
+
* Otherwise, queues the execution for after the wait time.
|
|
77
|
+
* Each new call resets the timer.
|
|
78
|
+
*/
|
|
79
|
+
maybeExecute: (...args: Parameters<TFn>) => void;
|
|
80
|
+
/**
|
|
81
|
+
* Processes the current pending execution immediately.
|
|
82
|
+
* If there's a pending execution, it will be executed right away
|
|
83
|
+
* and the timeout will be cleared.
|
|
84
|
+
*/
|
|
85
|
+
flush: () => void;
|
|
86
|
+
/**
|
|
87
|
+
* Cancels any pending execution.
|
|
88
|
+
* Clears the timeout and resets the internal state.
|
|
89
|
+
*/
|
|
90
|
+
cancel: () => void;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Creates a lightweight debounced function that delays invoking the provided function until after a specified wait time.
|
|
94
|
+
* Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
|
|
95
|
+
*
|
|
96
|
+
* This is an alternative to the debounce function in the core @tanstack/pacer package, but is more
|
|
97
|
+
* suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
|
|
98
|
+
* this function creates a debouncer with no external dependencies, devtools integration, or reactive state.
|
|
99
|
+
*
|
|
100
|
+
* If leading option is true, the function will execute immediately on the first call, then wait the delay
|
|
101
|
+
* before allowing another execution.
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```ts
|
|
105
|
+
* const debouncedSave = liteDebounce(() => {
|
|
106
|
+
* saveChanges();
|
|
107
|
+
* }, { wait: 1000 });
|
|
108
|
+
*
|
|
109
|
+
* // Called repeatedly but executes at most once per second
|
|
110
|
+
* inputElement.addEventListener('input', debouncedSave);
|
|
111
|
+
* ```
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* // Leading edge execution - fires immediately then waits
|
|
116
|
+
* const debouncedSearch = liteDebounce((query: string) => {
|
|
117
|
+
* performSearch(query);
|
|
118
|
+
* }, { wait: 300, leading: true });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
export declare function liteDebounce<TFn extends AnyFunction>(fn: TFn, options: LiteDebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
class LiteQueuer {
|
|
4
|
+
constructor(fn, options = {}) {
|
|
5
|
+
this.fn = fn;
|
|
6
|
+
this.options = options;
|
|
7
|
+
this.items = [];
|
|
8
|
+
this.timeoutId = null;
|
|
9
|
+
this.isRunning = true;
|
|
10
|
+
this.pendingTick = false;
|
|
11
|
+
this.addItem = (item, position = this.options.addItemsTo, startProcessing = true) => {
|
|
12
|
+
if (this.items.length >= this.options.maxSize) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
if (this.options.getPriority) {
|
|
16
|
+
const priority = this.options.getPriority(item);
|
|
17
|
+
if (priority !== void 0) {
|
|
18
|
+
const insertIndex = this.items.findIndex((existing) => {
|
|
19
|
+
const existingPriority = this.options.getPriority(existing);
|
|
20
|
+
const effectivePriority = existingPriority ?? -Infinity;
|
|
21
|
+
return effectivePriority < priority;
|
|
22
|
+
});
|
|
23
|
+
if (insertIndex === -1) {
|
|
24
|
+
this.items.push(item);
|
|
25
|
+
} else {
|
|
26
|
+
this.items.splice(insertIndex, 0, item);
|
|
27
|
+
}
|
|
28
|
+
} else {
|
|
29
|
+
this.insertAtPosition(item, position);
|
|
30
|
+
}
|
|
31
|
+
} else {
|
|
32
|
+
this.insertAtPosition(item, position);
|
|
33
|
+
}
|
|
34
|
+
if (startProcessing && this.isRunning && !this.pendingTick) {
|
|
35
|
+
this.tick();
|
|
36
|
+
}
|
|
37
|
+
return true;
|
|
38
|
+
};
|
|
39
|
+
this.insertAtPosition = (item, position) => {
|
|
40
|
+
if (position === "front") {
|
|
41
|
+
this.items.unshift(item);
|
|
42
|
+
} else {
|
|
43
|
+
this.items.push(item);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
this.getNextItem = (position = this.options.getItemsFrom) => {
|
|
47
|
+
if (this.items.length === 0) {
|
|
48
|
+
return void 0;
|
|
49
|
+
}
|
|
50
|
+
let item;
|
|
51
|
+
if (this.options.getPriority || position === "front") {
|
|
52
|
+
item = this.items.shift();
|
|
53
|
+
} else {
|
|
54
|
+
item = this.items.pop();
|
|
55
|
+
}
|
|
56
|
+
return item;
|
|
57
|
+
};
|
|
58
|
+
this.execute = (position) => {
|
|
59
|
+
const item = this.getNextItem(position);
|
|
60
|
+
if (item !== void 0) {
|
|
61
|
+
this.fn(item);
|
|
62
|
+
}
|
|
63
|
+
return item;
|
|
64
|
+
};
|
|
65
|
+
this.tick = () => {
|
|
66
|
+
if (!this.isRunning) {
|
|
67
|
+
this.pendingTick = false;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
this.pendingTick = true;
|
|
71
|
+
while (this.items.length > 0) {
|
|
72
|
+
const item = this.execute(this.options.getItemsFrom);
|
|
73
|
+
if (item === void 0) {
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
const wait = this.options.wait;
|
|
77
|
+
if (wait > 0) {
|
|
78
|
+
this.timeoutId = setTimeout(() => this.tick(), wait);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
this.pendingTick = false;
|
|
83
|
+
};
|
|
84
|
+
this.start = () => {
|
|
85
|
+
this.isRunning = true;
|
|
86
|
+
if (!this.pendingTick && this.items.length > 0) {
|
|
87
|
+
this.tick();
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
this.stop = () => {
|
|
91
|
+
this.clearTimeout();
|
|
92
|
+
this.isRunning = false;
|
|
93
|
+
this.pendingTick = false;
|
|
94
|
+
};
|
|
95
|
+
this.clearTimeout = () => {
|
|
96
|
+
if (this.timeoutId) {
|
|
97
|
+
clearTimeout(this.timeoutId);
|
|
98
|
+
this.timeoutId = null;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
this.peekNextItem = (position = "front") => {
|
|
102
|
+
if (this.items.length === 0) {
|
|
103
|
+
return void 0;
|
|
104
|
+
}
|
|
105
|
+
if (this.options.getPriority || position === "front") {
|
|
106
|
+
return this.items[0];
|
|
107
|
+
} else {
|
|
108
|
+
return this.items[this.items.length - 1];
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
this.peekAllItems = () => {
|
|
112
|
+
return [...this.items];
|
|
113
|
+
};
|
|
114
|
+
this.flush = (numberOfItems = this.items.length, position) => {
|
|
115
|
+
this.clearTimeout();
|
|
116
|
+
for (let i = 0; i < numberOfItems && this.items.length > 0; i++) {
|
|
117
|
+
this.execute(position);
|
|
118
|
+
}
|
|
119
|
+
if (this.isRunning && this.items.length > 0 && !this.pendingTick) {
|
|
120
|
+
this.tick();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
this.flushAsBatch = (batchFunction) => {
|
|
124
|
+
const items = this.peekAllItems();
|
|
125
|
+
this.clear();
|
|
126
|
+
batchFunction(items);
|
|
127
|
+
};
|
|
128
|
+
this.clear = () => {
|
|
129
|
+
this.items = [];
|
|
130
|
+
};
|
|
131
|
+
this.options.addItemsTo = this.options.addItemsTo ?? "back";
|
|
132
|
+
this.options.getItemsFrom = this.options.getItemsFrom ?? "front";
|
|
133
|
+
this.options.maxSize = this.options.maxSize ?? Infinity;
|
|
134
|
+
this.options.started = this.options.started ?? true;
|
|
135
|
+
this.options.wait = this.options.wait ?? 0;
|
|
136
|
+
this.isRunning = this.options.started;
|
|
137
|
+
if (this.options.initialItems) {
|
|
138
|
+
for (const item of this.options.initialItems) {
|
|
139
|
+
this.addItem(item, this.options.addItemsTo, false);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (this.isRunning && this.items.length > 0) {
|
|
143
|
+
this.tick();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Number of items currently in the queue
|
|
148
|
+
*/
|
|
149
|
+
get size() {
|
|
150
|
+
return this.items.length;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Whether the queue is empty
|
|
154
|
+
*/
|
|
155
|
+
get isEmpty() {
|
|
156
|
+
return this.items.length === 0;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Whether the queue is currently running (auto-processing items)
|
|
160
|
+
*/
|
|
161
|
+
get isQueueRunning() {
|
|
162
|
+
return this.isRunning;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function liteQueue(fn, options = {}) {
|
|
166
|
+
const queuer = new LiteQueuer(fn, options);
|
|
167
|
+
return (item) => queuer.addItem(item);
|
|
168
|
+
}
|
|
169
|
+
exports.LiteQueuer = LiteQueuer;
|
|
170
|
+
exports.liteQueue = liteQueue;
|
|
171
|
+
//# sourceMappingURL=lite-queuer.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lite-queuer.cjs","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"],"names":[],"mappings":";;AA4GO,MAAM,WAAmB;AAAA,EAM9B,YACS,IACA,UAAqC,IAC5C;AAFO,SAAA,KAAA;AACA,SAAA,UA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A,EAKA,IAAI,iBAA0B;AAC5B,WAAO,KAAK;AAAA,EACd;AAwPF;AAoBO,SAAS,UACd,IACA,UAAqC,IACV;AAC3B,QAAM,SAAS,IAAI,WAAW,IAAI,OAAO;AACzC,SAAO,CAAC,SAAiB,OAAO,QAAQ,IAAI;AAC9C;;;"}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Position type for addItem and getNextItem operations.
|
|
3
|
+
*
|
|
4
|
+
* - 'front': Operate on the front of the queue (FIFO for getNextItem)
|
|
5
|
+
* - 'back': Operate on the back of the queue (LIFO for getNextItem)
|
|
6
|
+
*/
|
|
7
|
+
export type QueuePosition = 'front' | 'back';
|
|
8
|
+
/**
|
|
9
|
+
* Options for configuring a lite queuer instance
|
|
10
|
+
*/
|
|
11
|
+
export interface LiteQueuerOptions<TValue> {
|
|
12
|
+
/**
|
|
13
|
+
* Default position to add items to the queue
|
|
14
|
+
* @default 'back'
|
|
15
|
+
*/
|
|
16
|
+
addItemsTo?: QueuePosition;
|
|
17
|
+
/**
|
|
18
|
+
* Default position to get items from during processing
|
|
19
|
+
* @default 'front'
|
|
20
|
+
*/
|
|
21
|
+
getItemsFrom?: QueuePosition;
|
|
22
|
+
/**
|
|
23
|
+
* Function to determine priority of items in the queue
|
|
24
|
+
* Higher priority items will be processed first
|
|
25
|
+
* Return undefined for items that should use positional ordering
|
|
26
|
+
*/
|
|
27
|
+
getPriority?: (item: TValue) => number | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Initial items to populate the queue with
|
|
30
|
+
*/
|
|
31
|
+
initialItems?: Array<TValue>;
|
|
32
|
+
/**
|
|
33
|
+
* Maximum number of items allowed in the queue
|
|
34
|
+
*/
|
|
35
|
+
maxSize?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Whether the queuer should start processing items immediately
|
|
38
|
+
* @default true
|
|
39
|
+
*/
|
|
40
|
+
started?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Time in milliseconds to wait between processing items
|
|
43
|
+
* @default 0
|
|
44
|
+
*/
|
|
45
|
+
wait?: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A lightweight class that creates a queue for processing items.
|
|
49
|
+
*
|
|
50
|
+
* This is an alternative to the Queuer in the core @tanstack/pacer package, but is more
|
|
51
|
+
* suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,
|
|
52
|
+
* this version does not use TanStack Store for state management, has no devtools integration,
|
|
53
|
+
* no callbacks, and provides only essential queueing functionality.
|
|
54
|
+
*
|
|
55
|
+
* The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based
|
|
56
|
+
* processing of items. Items can be processed automatically with configurable wait times
|
|
57
|
+
* between executions, or processed manually using the execute methods.
|
|
58
|
+
*
|
|
59
|
+
* Features included:
|
|
60
|
+
* - Automatic or manual processing of items
|
|
61
|
+
* - FIFO, LIFO, and priority-based ordering
|
|
62
|
+
* - Queue size limits with item rejection
|
|
63
|
+
* - Configurable wait times between processing
|
|
64
|
+
* - Batch processing capabilities
|
|
65
|
+
* - Start/stop processing control
|
|
66
|
+
* - Callback support for monitoring execution, rejection, and state change events
|
|
67
|
+
*
|
|
68
|
+
* Features NOT included (compared to core Queuer):
|
|
69
|
+
* - No TanStack Store state management
|
|
70
|
+
* - No devtools integration
|
|
71
|
+
* - No item expiration functionality (no onExpire callback)
|
|
72
|
+
* - No dynamic options updates (setOptions)
|
|
73
|
+
* - No detailed state tracking (execution counts, etc.)
|
|
74
|
+
*
|
|
75
|
+
* Queue behavior:
|
|
76
|
+
* - Default: FIFO (add to back, process from front)
|
|
77
|
+
* - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'
|
|
78
|
+
* - Priority: Provide getPriority function; higher values processed first
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```ts
|
|
82
|
+
* // Basic FIFO queue
|
|
83
|
+
* const queue = new LiteQueuer((item: string) => {
|
|
84
|
+
* console.log('Processing:', item);
|
|
85
|
+
* }, { wait: 100 });
|
|
86
|
+
*
|
|
87
|
+
* queue.addItem('task1');
|
|
88
|
+
* queue.addItem('task2');
|
|
89
|
+
* // Processes: task1, then task2 after 100ms delay
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* // Priority queue
|
|
95
|
+
* const priorityQueue = new LiteQueuer((item: Task) => {
|
|
96
|
+
* processTask(item);
|
|
97
|
+
* }, {
|
|
98
|
+
* getPriority: task => task.priority,
|
|
99
|
+
* wait: 500
|
|
100
|
+
* });
|
|
101
|
+
*
|
|
102
|
+
* priorityQueue.addItem({ name: 'low', priority: 1 });
|
|
103
|
+
* priorityQueue.addItem({ name: 'high', priority: 10 });
|
|
104
|
+
* // Processes high priority task first
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
export declare class LiteQueuer<TValue> {
|
|
108
|
+
fn: (item: TValue) => void;
|
|
109
|
+
options: LiteQueuerOptions<TValue>;
|
|
110
|
+
private items;
|
|
111
|
+
private timeoutId;
|
|
112
|
+
private isRunning;
|
|
113
|
+
private pendingTick;
|
|
114
|
+
constructor(fn: (item: TValue) => void, options?: LiteQueuerOptions<TValue>);
|
|
115
|
+
/**
|
|
116
|
+
* Number of items currently in the queue
|
|
117
|
+
*/
|
|
118
|
+
get size(): number;
|
|
119
|
+
/**
|
|
120
|
+
* Whether the queue is empty
|
|
121
|
+
*/
|
|
122
|
+
get isEmpty(): boolean;
|
|
123
|
+
/**
|
|
124
|
+
* Whether the queue is currently running (auto-processing items)
|
|
125
|
+
*/
|
|
126
|
+
get isQueueRunning(): boolean;
|
|
127
|
+
/**
|
|
128
|
+
* Adds an item to the queue. If the queue is full, the item is rejected.
|
|
129
|
+
* Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.
|
|
130
|
+
*
|
|
131
|
+
* Returns true if the item was added, false if the queue is full.
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```ts
|
|
135
|
+
* queue.addItem('task1'); // Add to default position (back)
|
|
136
|
+
* queue.addItem('task2', 'front'); // Add to front
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
addItem: (item: TValue, position?: QueuePosition, startProcessing?: boolean) => boolean;
|
|
140
|
+
private insertAtPosition;
|
|
141
|
+
/**
|
|
142
|
+
* Removes and returns the next item from the queue without executing the function.
|
|
143
|
+
* Use for manual queue management. Normally, use execute() to process items.
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```ts
|
|
147
|
+
* const nextItem = queue.getNextItem(); // Get from default position (front)
|
|
148
|
+
* const lastItem = queue.getNextItem('back'); // Get from back (LIFO)
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
getNextItem: (position?: QueuePosition) => TValue | undefined;
|
|
152
|
+
/**
|
|
153
|
+
* Removes and returns the next item from the queue and processes it using the provided function.
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```ts
|
|
157
|
+
* queue.execute(); // Execute from default position
|
|
158
|
+
* queue.execute('back'); // Execute from back (LIFO)
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
execute: (position?: QueuePosition) => TValue | undefined;
|
|
162
|
+
/**
|
|
163
|
+
* Internal method that processes items in the queue with wait intervals
|
|
164
|
+
*/
|
|
165
|
+
private tick;
|
|
166
|
+
/**
|
|
167
|
+
* Starts processing items in the queue. If already running, does nothing.
|
|
168
|
+
*/
|
|
169
|
+
start: () => void;
|
|
170
|
+
/**
|
|
171
|
+
* Stops processing items in the queue. Does not clear the queue.
|
|
172
|
+
*/
|
|
173
|
+
stop: () => void;
|
|
174
|
+
/**
|
|
175
|
+
* Clears any pending timeout
|
|
176
|
+
*/
|
|
177
|
+
private clearTimeout;
|
|
178
|
+
/**
|
|
179
|
+
* Returns the next item in the queue without removing it.
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```ts
|
|
183
|
+
* const next = queue.peekNextItem(); // Peek at front
|
|
184
|
+
* const last = queue.peekNextItem('back'); // Peek at back
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
peekNextItem: (position?: QueuePosition) => TValue | undefined;
|
|
188
|
+
/**
|
|
189
|
+
* Returns a copy of all items in the queue.
|
|
190
|
+
*/
|
|
191
|
+
peekAllItems: () => Array<TValue>;
|
|
192
|
+
/**
|
|
193
|
+
* Processes a specified number of items immediately with no wait time.
|
|
194
|
+
* If no numberOfItems is provided, all items will be processed.
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```ts
|
|
198
|
+
* queue.flush(); // Process all items immediately
|
|
199
|
+
* queue.flush(3); // Process next 3 items immediately
|
|
200
|
+
* ```
|
|
201
|
+
*/
|
|
202
|
+
flush: (numberOfItems?: number, position?: QueuePosition) => void;
|
|
203
|
+
/**
|
|
204
|
+
* Processes all items in the queue as a batch using the provided function.
|
|
205
|
+
* The queue is cleared after processing.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```ts
|
|
209
|
+
* queue.flushAsBatch((items) => {
|
|
210
|
+
* console.log('Processing batch:', items);
|
|
211
|
+
* // Process all items together
|
|
212
|
+
* });
|
|
213
|
+
* ```
|
|
214
|
+
*/
|
|
215
|
+
flushAsBatch: (batchFunction: (items: Array<TValue>) => void) => void;
|
|
216
|
+
/**
|
|
217
|
+
* Removes all items from the queue. Does not affect items being processed.
|
|
218
|
+
*/
|
|
219
|
+
clear: () => void;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Creates a lightweight queue that processes items using the provided function.
|
|
223
|
+
*
|
|
224
|
+
* This is an alternative to the queue function in the core @tanstack/pacer package, but is more
|
|
225
|
+
* suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
|
|
226
|
+
* this function creates a queuer with no external dependencies, devtools integration, or reactive state.
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* ```ts
|
|
230
|
+
* const processItem = liteQueue((item: string) => {
|
|
231
|
+
* console.log('Processing:', item);
|
|
232
|
+
* }, { wait: 1000 });
|
|
233
|
+
*
|
|
234
|
+
* processItem('task1');
|
|
235
|
+
* processItem('task2');
|
|
236
|
+
* // Processes each item with 1 second delay between them
|
|
237
|
+
* ```
|
|
238
|
+
*/
|
|
239
|
+
export declare function liteQueue<TValue>(fn: (item: TValue) => void, options?: LiteQueuerOptions<TValue>): (item: TValue) => boolean;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
class LiteRateLimiter {
|
|
4
|
+
constructor(fn, options) {
|
|
5
|
+
this.fn = fn;
|
|
6
|
+
this.options = options;
|
|
7
|
+
this.executionTimes = [];
|
|
8
|
+
this.timeoutIds = /* @__PURE__ */ new Set();
|
|
9
|
+
this.maybeExecute = (...args) => {
|
|
10
|
+
this.cleanupOldExecutions();
|
|
11
|
+
const relevantExecutionTimes = this.getExecutionTimesInWindow();
|
|
12
|
+
if (relevantExecutionTimes.length < this.options.limit) {
|
|
13
|
+
this.execute(...args);
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
this.options.onReject?.(this);
|
|
17
|
+
return false;
|
|
18
|
+
};
|
|
19
|
+
this.execute = (...args) => {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
this.fn(...args);
|
|
22
|
+
this.options.onExecute?.(args, this);
|
|
23
|
+
this.executionTimes.push(now);
|
|
24
|
+
this.setCleanupTimeout(now);
|
|
25
|
+
};
|
|
26
|
+
this.getExecutionTimesInWindow = () => {
|
|
27
|
+
if (this.options.windowType === "sliding") {
|
|
28
|
+
return this.executionTimes.filter(
|
|
29
|
+
(time) => time > Date.now() - this.options.window
|
|
30
|
+
);
|
|
31
|
+
} else {
|
|
32
|
+
if (this.executionTimes.length === 0) {
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
const oldestExecution = Math.min(...this.executionTimes);
|
|
36
|
+
const windowStart = oldestExecution;
|
|
37
|
+
const windowEnd = windowStart + this.options.window;
|
|
38
|
+
const now = Date.now();
|
|
39
|
+
if (now > windowEnd) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
return this.executionTimes.filter(
|
|
43
|
+
(time) => time >= windowStart && time <= windowEnd
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
this.setCleanupTimeout = (executionTime) => {
|
|
48
|
+
if (this.options.windowType === "sliding" || this.timeoutIds.size === 0) {
|
|
49
|
+
const now = Date.now();
|
|
50
|
+
const timeUntilExpiration = executionTime - now + this.options.window + 1;
|
|
51
|
+
const timeoutId = setTimeout(() => {
|
|
52
|
+
this.cleanupOldExecutions();
|
|
53
|
+
this.clearTimeout(timeoutId);
|
|
54
|
+
}, timeUntilExpiration);
|
|
55
|
+
this.timeoutIds.add(timeoutId);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
this.clearTimeout = (timeoutId) => {
|
|
59
|
+
clearTimeout(timeoutId);
|
|
60
|
+
this.timeoutIds.delete(timeoutId);
|
|
61
|
+
};
|
|
62
|
+
this.clearTimeouts = () => {
|
|
63
|
+
this.timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
|
|
64
|
+
this.timeoutIds.clear();
|
|
65
|
+
};
|
|
66
|
+
this.cleanupOldExecutions = () => {
|
|
67
|
+
this.executionTimes = this.getExecutionTimesInWindow();
|
|
68
|
+
};
|
|
69
|
+
this.getRemainingInWindow = () => {
|
|
70
|
+
const relevantExecutionTimes = this.getExecutionTimesInWindow();
|
|
71
|
+
return Math.max(0, this.options.limit - relevantExecutionTimes.length);
|
|
72
|
+
};
|
|
73
|
+
this.getMsUntilNextWindow = () => {
|
|
74
|
+
if (this.getRemainingInWindow() > 0) {
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
const oldestExecution = this.executionTimes[0] ?? Infinity;
|
|
78
|
+
return oldestExecution + this.options.window - Date.now();
|
|
79
|
+
};
|
|
80
|
+
this.reset = () => {
|
|
81
|
+
this.executionTimes = [];
|
|
82
|
+
this.clearTimeouts();
|
|
83
|
+
};
|
|
84
|
+
if (this.options.windowType === void 0) {
|
|
85
|
+
this.options.windowType = "fixed";
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function liteRateLimit(fn, options) {
|
|
90
|
+
const rateLimiter = new LiteRateLimiter(fn, options);
|
|
91
|
+
return rateLimiter.maybeExecute;
|
|
92
|
+
}
|
|
93
|
+
exports.LiteRateLimiter = LiteRateLimiter;
|
|
94
|
+
exports.liteRateLimit = liteRateLimit;
|
|
95
|
+
//# sourceMappingURL=lite-rate-limiter.cjs.map
|