@tanstack/pacer 0.2.0 → 0.4.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/dist/cjs/async-debouncer.cjs +78 -45
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +60 -24
- package/dist/cjs/async-queuer.cjs +53 -3
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +28 -3
- package/dist/cjs/async-rate-limiter.cjs +75 -38
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +76 -24
- package/dist/cjs/async-throttler.cjs +85 -57
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +66 -25
- package/dist/cjs/debouncer.cjs +12 -14
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -9
- package/dist/cjs/queuer.cjs +51 -1
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +30 -1
- package/dist/cjs/rate-limiter.cjs +19 -9
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +31 -11
- package/dist/cjs/throttler.cjs +29 -36
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +16 -17
- package/dist/cjs/types.d.cts +2 -6
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -1
- package/dist/esm/async-debouncer.d.ts +60 -24
- package/dist/esm/async-debouncer.js +78 -45
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +28 -3
- package/dist/esm/async-queuer.js +53 -3
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +76 -24
- package/dist/esm/async-rate-limiter.js +75 -38
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +66 -25
- package/dist/esm/async-throttler.js +85 -57
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -9
- package/dist/esm/debouncer.js +12 -14
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/queuer.d.ts +30 -1
- package/dist/esm/queuer.js +51 -1
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +31 -11
- package/dist/esm/rate-limiter.js +19 -9
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +16 -17
- package/dist/esm/throttler.js +29 -36
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +2 -6
- package/dist/esm/utils.d.ts +1 -1
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/async-debouncer.ts +130 -81
- package/src/async-queuer.ts +93 -8
- package/src/async-rate-limiter.ts +141 -67
- package/src/async-throttler.ts +152 -94
- package/src/debouncer.ts +26 -33
- package/src/queuer.ts +92 -4
- package/src/rate-limiter.ts +56 -32
- package/src/throttler.ts +45 -53
- package/src/types.ts +2 -10
- package/src/utils.ts +1 -1
|
@@ -3,21 +3,26 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
const defaultOptions = {
|
|
4
4
|
enabled: true,
|
|
5
5
|
leading: false,
|
|
6
|
-
trailing: true,
|
|
7
6
|
onError: () => {
|
|
8
7
|
},
|
|
9
|
-
|
|
8
|
+
onSettled: () => {
|
|
9
|
+
},
|
|
10
|
+
onSuccess: () => {
|
|
10
11
|
},
|
|
12
|
+
trailing: true,
|
|
11
13
|
wait: 0
|
|
12
14
|
};
|
|
13
15
|
class AsyncDebouncer {
|
|
14
16
|
constructor(fn, initialOptions) {
|
|
15
17
|
this.fn = fn;
|
|
16
18
|
this._abortController = null;
|
|
17
|
-
this.
|
|
19
|
+
this._canLeadingExecute = true;
|
|
20
|
+
this._errorCount = 0;
|
|
18
21
|
this._isExecuting = false;
|
|
22
|
+
this._isPending = false;
|
|
23
|
+
this._settleCount = 0;
|
|
24
|
+
this._successCount = 0;
|
|
19
25
|
this._timeoutId = null;
|
|
20
|
-
this._canLeadingExecute = true;
|
|
21
26
|
this._options = {
|
|
22
27
|
...defaultOptions,
|
|
23
28
|
...initialOptions
|
|
@@ -28,11 +33,10 @@ class AsyncDebouncer {
|
|
|
28
33
|
* Returns the new options state
|
|
29
34
|
*/
|
|
30
35
|
setOptions(newOptions) {
|
|
31
|
-
this._options = {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
return this._options;
|
|
36
|
+
this._options = { ...this._options, ...newOptions };
|
|
37
|
+
if (!this._options.enabled) {
|
|
38
|
+
this._isPending = false;
|
|
39
|
+
}
|
|
36
40
|
}
|
|
37
41
|
/**
|
|
38
42
|
* Returns the current debouncer options
|
|
@@ -45,53 +49,50 @@ class AsyncDebouncer {
|
|
|
45
49
|
* If a call is already in progress, it will be queued
|
|
46
50
|
*/
|
|
47
51
|
async maybeExecute(...args) {
|
|
48
|
-
this.
|
|
52
|
+
this._cancel();
|
|
49
53
|
this._lastArgs = args;
|
|
50
54
|
if (this._options.leading && this._canLeadingExecute) {
|
|
51
55
|
this._canLeadingExecute = false;
|
|
52
56
|
await this.executeFunction(...args);
|
|
57
|
+
return this._lastResult;
|
|
58
|
+
}
|
|
59
|
+
if (this._options.trailing) {
|
|
60
|
+
this._isPending = true;
|
|
53
61
|
}
|
|
54
62
|
return new Promise((resolve) => {
|
|
55
63
|
this._timeoutId = setTimeout(async () => {
|
|
56
|
-
if (this.
|
|
57
|
-
|
|
58
|
-
return;
|
|
64
|
+
if (this._options.trailing && this._lastArgs) {
|
|
65
|
+
await this.executeFunction(...this._lastArgs);
|
|
59
66
|
}
|
|
60
67
|
this._canLeadingExecute = true;
|
|
61
|
-
|
|
62
|
-
this._abortController = new AbortController();
|
|
63
|
-
try {
|
|
64
|
-
this._isExecuting = true;
|
|
65
|
-
if (this._lastArgs) {
|
|
66
|
-
await this.executeFunction(...this._lastArgs);
|
|
67
|
-
}
|
|
68
|
-
} catch (error) {
|
|
69
|
-
try {
|
|
70
|
-
this._options.onError(error);
|
|
71
|
-
} catch {
|
|
72
|
-
console.error("Error in error handler", error);
|
|
73
|
-
}
|
|
74
|
-
} finally {
|
|
75
|
-
this._isExecuting = false;
|
|
76
|
-
this._abortController = null;
|
|
77
|
-
resolve();
|
|
78
|
-
}
|
|
79
|
-
} else {
|
|
80
|
-
resolve();
|
|
81
|
-
}
|
|
68
|
+
resolve(this._lastResult);
|
|
82
69
|
}, this._options.wait);
|
|
83
70
|
});
|
|
84
71
|
}
|
|
85
72
|
async executeFunction(...args) {
|
|
86
|
-
if (!this._options.enabled) return;
|
|
87
|
-
this.
|
|
88
|
-
|
|
89
|
-
|
|
73
|
+
if (!this._options.enabled) return void 0;
|
|
74
|
+
this._abortController = new AbortController();
|
|
75
|
+
try {
|
|
76
|
+
this._isExecuting = true;
|
|
77
|
+
this._lastResult = await this.fn(...args);
|
|
78
|
+
this._successCount++;
|
|
79
|
+
this._options.onSuccess(this._lastResult, this);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
this._errorCount++;
|
|
82
|
+
this._options.onError(error, this);
|
|
83
|
+
} finally {
|
|
84
|
+
this._isExecuting = false;
|
|
85
|
+
this._isPending = false;
|
|
86
|
+
this._settleCount++;
|
|
87
|
+
this._abortController = null;
|
|
88
|
+
this._options.onSettled(this);
|
|
89
|
+
}
|
|
90
|
+
return this._lastResult;
|
|
90
91
|
}
|
|
91
92
|
/**
|
|
92
|
-
*
|
|
93
|
+
* Cancel without resetting _canLeadingExecute
|
|
93
94
|
*/
|
|
94
|
-
|
|
95
|
+
_cancel() {
|
|
95
96
|
if (this._timeoutId) {
|
|
96
97
|
clearTimeout(this._timeoutId);
|
|
97
98
|
this._timeoutId = null;
|
|
@@ -101,19 +102,51 @@ class AsyncDebouncer {
|
|
|
101
102
|
this._abortController = null;
|
|
102
103
|
}
|
|
103
104
|
this._lastArgs = void 0;
|
|
105
|
+
this._isPending = false;
|
|
106
|
+
this._isExecuting = false;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
110
|
+
*/
|
|
111
|
+
cancel() {
|
|
104
112
|
this._canLeadingExecute = true;
|
|
113
|
+
this._cancel();
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Returns the last result of the debounced function
|
|
117
|
+
*/
|
|
118
|
+
getLastResult() {
|
|
119
|
+
return this._lastResult;
|
|
105
120
|
}
|
|
106
121
|
/**
|
|
107
|
-
* Returns the number of times the function has been executed
|
|
122
|
+
* Returns the number of times the function has been executed successfully
|
|
108
123
|
*/
|
|
109
|
-
|
|
110
|
-
return this.
|
|
124
|
+
getSuccessCount() {
|
|
125
|
+
return this._successCount;
|
|
111
126
|
}
|
|
112
127
|
/**
|
|
113
|
-
* Returns
|
|
128
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
129
|
+
*/
|
|
130
|
+
getSettleCount() {
|
|
131
|
+
return this._settleCount;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Returns the number of times the function has errored
|
|
135
|
+
*/
|
|
136
|
+
getErrorCount() {
|
|
137
|
+
return this._errorCount;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
114
141
|
*/
|
|
115
142
|
getIsPending() {
|
|
116
|
-
return this._options.enabled &&
|
|
143
|
+
return this._options.enabled && this._isPending;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Returns `true` if there is currently an execution in progress
|
|
147
|
+
*/
|
|
148
|
+
getIsExecuting() {
|
|
149
|
+
return this._isExecuting;
|
|
117
150
|
}
|
|
118
151
|
}
|
|
119
152
|
function asyncDebounce(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-debouncer.cjs","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown) => void\n /**\n * Optional function to call when the debounced function is executed\n */\n onExecute?: (debouncer: AsyncDebouncer<TFn, TArgs>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any, any>> = {\n enabled: true,\n leading: false,\n trailing: true,\n onError: () => {},\n onExecute: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * await searchAPI(value);\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * inputElement.addEventListener('input', () => {\n * asyncDebouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _abortController: AbortController | null = null\n private _executionCount = 0\n private _isExecuting = false\n private _lastArgs: TArgs | undefined\n private _options: Required<AsyncDebouncerOptions<TFn, TArgs>>\n private _timeoutId: ReturnType<typeof setTimeout> | null = null\n private _canLeadingExecute = true\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn, TArgs>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncDebouncerOptions<TFn, TArgs>>,\n ): Required<AsyncDebouncerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn, TArgs>> {\n return this._options\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this.cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n if (this._isExecuting) {\n resolve()\n return\n }\n\n this._canLeadingExecute = true\n // Execute trailing only if enabled\n if (this._options.trailing) {\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n if (this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n } catch (error) {\n try {\n this._options.onError(error)\n } catch {\n console.error('Error in error handler', error)\n }\n } finally {\n this._isExecuting = false\n this._abortController = null\n resolve()\n }\n } else {\n resolve()\n }\n }, this._options.wait)\n })\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this._options.enabled) return\n this._executionCount++\n await this.fn(...args)\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._canLeadingExecute = true\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns `true` if there is a pending execution\n */\n getIsPending(): boolean {\n return (\n this._options.enabled && (this._timeoutId !== null || this._isExecuting)\n )\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * await debounced(\"first\"); // Cancelled\n * await debounced(\"second\"); // Cancelled\n * await debounced(\"third\"); // Executes after 1s\n * ```\n */\nexport function asyncDebounce<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn, TArgs>, 'enabled'>) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";;AAuCA,MAAM,iBAA4D;AAAA,EAChE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,MAAM;AACR;AAwBO,MAAM,eAGX;AAAA,EASA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,mBAA2C;AACnD,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AAGvB,SAAQ,aAAmD;AAC3D,SAAQ,qBAAqB;AAM3B,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YAC6C;AAC7C,SAAK,WAAW;AAAA,MACd,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAA0D;AACxD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA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;AAAA;AAAA;AAAA,EAM5B,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WACE,KAAK,SAAS,YAAY,KAAK,eAAe,QAAQ,KAAK;AAAA,EAAA;AAGjE;AAmBgB,SAAA,cAGd,IAAS,gBAAoE;AAC7E,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
|
|
1
|
+
{"version":3,"file":"async-debouncer.cjs","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _options: Required<AsyncDebouncerOptions<TFn>>\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this._options.wait)\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";;AAwCA,MAAM,iBAAuD;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AA4BO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAbV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAIrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAuD;AAChE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,aAAmD;AACjD,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5B,WAAK,mBAAmB;AAAA,IAAA;AAE1B,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,SAAK,eAAe;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtB,SAAe;AACb,SAAK,qBAAqB;AAC1B,SAAK,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
|
|
@@ -2,7 +2,7 @@ import { AnyAsyncFunction } from './types.cjs';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring an async debounced function
|
|
4
4
|
*/
|
|
5
|
-
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction
|
|
5
|
+
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -16,11 +16,15 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
16
16
|
/**
|
|
17
17
|
* Optional error handler for when the debounced function throws
|
|
18
18
|
*/
|
|
19
|
-
onError?: (error: unknown) => void;
|
|
19
|
+
onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
|
|
20
20
|
/**
|
|
21
|
-
* Optional
|
|
21
|
+
* Optional callback to call when the debounced function is executed
|
|
22
22
|
*/
|
|
23
|
-
|
|
23
|
+
onSettled?: (debouncer: AsyncDebouncer<TFn>) => void;
|
|
24
|
+
/**
|
|
25
|
+
* Optional callback to call when the debounced function is executed
|
|
26
|
+
*/
|
|
27
|
+
onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
|
|
24
28
|
/**
|
|
25
29
|
* Whether to execute on the trailing edge of the timeout.
|
|
26
30
|
* Defaults to true.
|
|
@@ -42,71 +46,103 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
42
46
|
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
|
|
43
47
|
* the function stops being called for the specified delay period.
|
|
44
48
|
*
|
|
49
|
+
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
50
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
51
|
+
* instead of setting the result on a state variable from within the debounced function.
|
|
52
|
+
*
|
|
45
53
|
* @example
|
|
46
54
|
* ```ts
|
|
47
55
|
* const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
|
|
48
|
-
* await searchAPI(value);
|
|
56
|
+
* const results = await searchAPI(value);
|
|
57
|
+
* return results; // Return value is preserved
|
|
49
58
|
* }, { wait: 500 });
|
|
50
59
|
*
|
|
51
60
|
* // Called on each keystroke but only executes after 500ms of no typing
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
* });
|
|
61
|
+
* // Returns the API response directly
|
|
62
|
+
* const results = await asyncDebouncer.maybeExecute(inputElement.value);
|
|
55
63
|
* ```
|
|
56
64
|
*/
|
|
57
|
-
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction
|
|
65
|
+
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
58
66
|
private fn;
|
|
59
67
|
private _abortController;
|
|
60
|
-
private
|
|
68
|
+
private _canLeadingExecute;
|
|
69
|
+
private _errorCount;
|
|
61
70
|
private _isExecuting;
|
|
71
|
+
private _isPending;
|
|
62
72
|
private _lastArgs;
|
|
73
|
+
private _lastResult;
|
|
63
74
|
private _options;
|
|
75
|
+
private _settleCount;
|
|
76
|
+
private _successCount;
|
|
64
77
|
private _timeoutId;
|
|
65
|
-
|
|
66
|
-
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn, TArgs>);
|
|
78
|
+
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
|
|
67
79
|
/**
|
|
68
80
|
* Updates the debouncer options
|
|
69
81
|
* Returns the new options state
|
|
70
82
|
*/
|
|
71
|
-
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn
|
|
83
|
+
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void;
|
|
72
84
|
/**
|
|
73
85
|
* Returns the current debouncer options
|
|
74
86
|
*/
|
|
75
|
-
getOptions(): Required<AsyncDebouncerOptions<TFn
|
|
87
|
+
getOptions(): Required<AsyncDebouncerOptions<TFn>>;
|
|
76
88
|
/**
|
|
77
89
|
* Attempts to execute the debounced function
|
|
78
90
|
* If a call is already in progress, it will be queued
|
|
79
91
|
*/
|
|
80
|
-
maybeExecute(...args:
|
|
92
|
+
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
81
93
|
private executeFunction;
|
|
82
94
|
/**
|
|
83
|
-
*
|
|
95
|
+
* Cancel without resetting _canLeadingExecute
|
|
96
|
+
*/
|
|
97
|
+
private _cancel;
|
|
98
|
+
/**
|
|
99
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
84
100
|
*/
|
|
85
101
|
cancel(): void;
|
|
86
102
|
/**
|
|
87
|
-
* Returns the
|
|
103
|
+
* Returns the last result of the debounced function
|
|
104
|
+
*/
|
|
105
|
+
getLastResult(): ReturnType<TFn> | undefined;
|
|
106
|
+
/**
|
|
107
|
+
* Returns the number of times the function has been executed successfully
|
|
108
|
+
*/
|
|
109
|
+
getSuccessCount(): number;
|
|
110
|
+
/**
|
|
111
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
112
|
+
*/
|
|
113
|
+
getSettleCount(): number;
|
|
114
|
+
/**
|
|
115
|
+
* Returns the number of times the function has errored
|
|
88
116
|
*/
|
|
89
|
-
|
|
117
|
+
getErrorCount(): number;
|
|
90
118
|
/**
|
|
91
|
-
* Returns `true` if there is a pending execution
|
|
119
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
92
120
|
*/
|
|
93
121
|
getIsPending(): boolean;
|
|
122
|
+
/**
|
|
123
|
+
* Returns `true` if there is currently an execution in progress
|
|
124
|
+
*/
|
|
125
|
+
getIsExecuting(): boolean;
|
|
94
126
|
}
|
|
95
127
|
/**
|
|
96
128
|
* Creates an async debounced function that delays execution until after a specified wait time.
|
|
97
129
|
* The debounced function will only execute once the wait period has elapsed without any new calls.
|
|
98
130
|
* If called again during the wait period, the timer resets and a new wait period begins.
|
|
99
131
|
*
|
|
132
|
+
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
133
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
134
|
+
* instead of setting the result on a state variable from within the debounced function.
|
|
135
|
+
*
|
|
100
136
|
* @example
|
|
101
137
|
* ```ts
|
|
102
138
|
* const debounced = asyncDebounce(async (value: string) => {
|
|
103
|
-
* await saveToAPI(value);
|
|
139
|
+
* const result = await saveToAPI(value);
|
|
140
|
+
* return result; // Return value is preserved
|
|
104
141
|
* }, { wait: 1000 });
|
|
105
142
|
*
|
|
106
143
|
* // Will only execute once, 1 second after the last call
|
|
107
|
-
*
|
|
108
|
-
* await debounced("
|
|
109
|
-
* await debounced("third"); // Executes after 1s
|
|
144
|
+
* // Returns the API response directly
|
|
145
|
+
* const result = await debounced("third");
|
|
110
146
|
* ```
|
|
111
147
|
*/
|
|
112
|
-
export declare function asyncDebounce<TFn extends AnyAsyncFunction
|
|
148
|
+
export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|
|
@@ -3,6 +3,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
const defaultOptions = {
|
|
4
4
|
addItemsTo: "back",
|
|
5
5
|
concurrency: 1,
|
|
6
|
+
expirationDuration: Infinity,
|
|
7
|
+
getIsExpired: () => false,
|
|
6
8
|
getItemsFrom: "front",
|
|
7
9
|
getPriority: (item) => (item == null ? void 0 : item.priority) ?? 0,
|
|
8
10
|
initialItems: [],
|
|
@@ -15,7 +17,9 @@ const defaultOptions = {
|
|
|
15
17
|
},
|
|
16
18
|
onReject: () => {
|
|
17
19
|
},
|
|
18
|
-
|
|
20
|
+
onExpire: () => {
|
|
21
|
+
},
|
|
22
|
+
started: true,
|
|
19
23
|
wait: 0
|
|
20
24
|
};
|
|
21
25
|
class AsyncQueuer {
|
|
@@ -23,7 +27,9 @@ class AsyncQueuer {
|
|
|
23
27
|
this._activeItems = /* @__PURE__ */ new Set();
|
|
24
28
|
this._executionCount = 0;
|
|
25
29
|
this._rejectionCount = 0;
|
|
30
|
+
this._expirationCount = 0;
|
|
26
31
|
this._items = [];
|
|
32
|
+
this._itemTimestamps = [];
|
|
27
33
|
this._onErrorCallbacks = [];
|
|
28
34
|
this._onSettledCallbacks = [];
|
|
29
35
|
this._onSuccessCallbacks = [];
|
|
@@ -42,7 +48,6 @@ class AsyncQueuer {
|
|
|
42
48
|
*/
|
|
43
49
|
setOptions(newOptions) {
|
|
44
50
|
this._options = { ...this._options, ...newOptions };
|
|
45
|
-
return this._options;
|
|
46
51
|
}
|
|
47
52
|
/**
|
|
48
53
|
* Returns the current queuer options
|
|
@@ -58,6 +63,7 @@ class AsyncQueuer {
|
|
|
58
63
|
this._pendingTick = false;
|
|
59
64
|
return;
|
|
60
65
|
}
|
|
66
|
+
this.checkExpiredItems();
|
|
61
67
|
while (this._activeItems.size < this._options.concurrency && !this.getIsEmpty()) {
|
|
62
68
|
const nextFn = this.getNextItem();
|
|
63
69
|
if (!nextFn) {
|
|
@@ -93,6 +99,38 @@ class AsyncQueuer {
|
|
|
93
99
|
}
|
|
94
100
|
this._pendingTick = false;
|
|
95
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Checks for and removes expired items from the queuer
|
|
104
|
+
*/
|
|
105
|
+
checkExpiredItems() {
|
|
106
|
+
if (this._options.expirationDuration === Infinity && this._options.getIsExpired === defaultOptions.getIsExpired)
|
|
107
|
+
return;
|
|
108
|
+
const now = Date.now();
|
|
109
|
+
const expiredIndices = [];
|
|
110
|
+
for (let i = 0; i < this._items.length; i++) {
|
|
111
|
+
const timestamp = this._itemTimestamps[i];
|
|
112
|
+
if (timestamp === void 0) continue;
|
|
113
|
+
const item = this._items[i];
|
|
114
|
+
if (item === void 0) continue;
|
|
115
|
+
const isExpired = this._options.getIsExpired !== defaultOptions.getIsExpired ? this._options.getIsExpired(item, timestamp) : now - timestamp > this._options.expirationDuration;
|
|
116
|
+
if (isExpired) {
|
|
117
|
+
expiredIndices.push(i);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (let i = expiredIndices.length - 1; i >= 0; i--) {
|
|
121
|
+
const index = expiredIndices[i];
|
|
122
|
+
if (index === void 0) continue;
|
|
123
|
+
const expiredItem = this._items[index];
|
|
124
|
+
if (expiredItem === void 0) continue;
|
|
125
|
+
this._items.splice(index, 1);
|
|
126
|
+
this._itemTimestamps.splice(index, 1);
|
|
127
|
+
this._expirationCount++;
|
|
128
|
+
this._options.onExpire(expiredItem, this);
|
|
129
|
+
}
|
|
130
|
+
if (expiredIndices.length > 0) {
|
|
131
|
+
this._options.onItemsChange(this);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
96
134
|
/**
|
|
97
135
|
* Starts the queuer and processes items
|
|
98
136
|
*/
|
|
@@ -171,14 +209,18 @@ class AsyncQueuer {
|
|
|
171
209
|
});
|
|
172
210
|
if (insertIndex === -1) {
|
|
173
211
|
this._items.push(task);
|
|
212
|
+
this._itemTimestamps.push(Date.now());
|
|
174
213
|
} else {
|
|
175
214
|
this._items.splice(insertIndex, 0, task);
|
|
215
|
+
this._itemTimestamps.splice(insertIndex, 0, Date.now());
|
|
176
216
|
}
|
|
177
217
|
} else {
|
|
178
218
|
if (position === "front") {
|
|
179
219
|
this._items.unshift(task);
|
|
220
|
+
this._itemTimestamps.unshift(Date.now());
|
|
180
221
|
} else {
|
|
181
222
|
this._items.push(task);
|
|
223
|
+
this._itemTimestamps.push(Date.now());
|
|
182
224
|
}
|
|
183
225
|
}
|
|
184
226
|
if (runOnUpdate) {
|
|
@@ -197,8 +239,10 @@ class AsyncQueuer {
|
|
|
197
239
|
let item;
|
|
198
240
|
if (position === "front") {
|
|
199
241
|
item = this._items.shift();
|
|
242
|
+
this._itemTimestamps.shift();
|
|
200
243
|
} else {
|
|
201
244
|
item = this._items.pop();
|
|
245
|
+
this._itemTimestamps.pop();
|
|
202
246
|
}
|
|
203
247
|
if (item !== void 0) {
|
|
204
248
|
this._executionCount++;
|
|
@@ -307,9 +351,15 @@ class AsyncQueuer {
|
|
|
307
351
|
);
|
|
308
352
|
};
|
|
309
353
|
}
|
|
354
|
+
/**
|
|
355
|
+
* Returns the number of items that have expired from the queuer
|
|
356
|
+
*/
|
|
357
|
+
getExpirationCount() {
|
|
358
|
+
return this._expirationCount;
|
|
359
|
+
}
|
|
310
360
|
}
|
|
311
361
|
function asyncQueue(options = {}) {
|
|
312
|
-
const queuer = new AsyncQueuer(
|
|
362
|
+
const queuer = new AsyncQueuer(options);
|
|
313
363
|
return queuer.addItem.bind(queuer);
|
|
314
364
|
}
|
|
315
365
|
exports.AsyncQueuer = AsyncQueuer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-queuer.cjs","sources":["../../src/async-queuer.ts"],"sourcesContent":["import type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum number of concurrent tasks to process\n */\n concurrency?: number\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 * If not provided, will use static priority values attached to tasks\n */\n getPriority?: (item: () => Promise<TValue>) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<(() => Promise<TValue>) & { priority?: number }>\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?: (\n item: () => Promise<TValue>,\n queuer: AsyncQueuer<TValue>,\n ) => void\n /**\n * Callback fired whenever the queuer's running state changes\n */\n onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<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<AsyncQueuerOptions<any>> = {\n addItemsTo: 'back',\n concurrency: 1,\n getItemsFrom: 'front',\n getPriority: (item) => (item as any)?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onIsRunningChange: () => {},\n onItemsChange: () => {},\n onReject: () => {},\n started: false,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queue that processes tasks with configurable concurrency control.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * @example\n * ```ts\n * const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });\n *\n * asyncQueuer.addItem(async () => {\n * return 'Hello';\n * });\n *\n * asyncQueuer.start();\n *\n * asyncQueuer.onSuccess((result) => {\n * console.log(result); // 'Hello'\n * });\n * ```\n */\nexport class AsyncQueuer<TValue> {\n private _options: Required<AsyncQueuerOptions<TValue>>\n private _activeItems: Set<() => Promise<TValue>> = new Set()\n private _executionCount = 0\n private _rejectionCount = 0\n private _items: Array<() => Promise<TValue>> = []\n private _onErrorCallbacks: Array<(error: Error) => void> = []\n private _onSettledCallbacks: Array<(result: TValue | Error) => void> = []\n private _onSuccessCallbacks: Array<(result: TValue) => void> = []\n private _pendingTick = false\n private _running: boolean\n\n constructor(initialOptions: AsyncQueuerOptions<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 * Updates the queuer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncQueuerOptions<TValue>>,\n ): AsyncQueuerOptions<TValue> {\n this._options = { ...this._options, ...newOptions }\n return this._options\n }\n\n /**\n * Returns the current queuer options\n */\n getOptions(): Required<AsyncQueuerOptions<TValue>> {\n return this._options\n }\n\n /**\n * Processes items in the queuer\n */\n private tick() {\n if (!this._running) {\n this._pendingTick = false\n return\n }\n\n while (\n this._activeItems.size < this._options.concurrency &&\n !this.getIsEmpty()\n ) {\n const nextFn = this.getNextItem()\n if (!nextFn) {\n break\n }\n this._activeItems.add(nextFn)\n this._options.onItemsChange(this)\n ;(async () => {\n let success = false\n let res!: TValue\n let error: Error | undefined\n\n try {\n res = await nextFn()\n success = true\n } catch (e) {\n error = e as Error\n } finally {\n this._activeItems.delete(nextFn)\n this._options.onItemsChange(this)\n }\n\n if (success) {\n this._onSuccessCallbacks.forEach((cb) => cb(res))\n } else {\n this._onErrorCallbacks.forEach((cb) => cb(error!))\n }\n this._onSettledCallbacks.forEach((cb) => cb(success ? res : error!))\n\n if (this._options.wait > 0) {\n setTimeout(() => this.tick(), this._options.wait)\n return\n }\n\n this.tick()\n })()\n }\n\n this._pendingTick = false\n }\n\n /**\n * Starts the queuer and processes items\n */\n start(): Promise<void> {\n this._running = true\n if (!this._pendingTick && !this.getIsEmpty()) {\n this._pendingTick = true\n this.tick()\n }\n this._options.onIsRunningChange(this)\n\n return new Promise<void>((resolve) => {\n const checkIdle = () => {\n if (this.getIsIdle()) {\n resolve()\n } else {\n setTimeout(checkIdle, 100)\n }\n }\n checkIdle()\n })\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop(): void {\n this._running = false\n this._pendingTick = false\n this._options.onIsRunningChange(this)\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this._items = []\n this._options.onItemsChange(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 * Adds a task to the queuer\n */\n addItem(\n fn: (() => Promise<TValue>) & { priority?: number },\n position: QueuePosition = this._options.addItemsTo,\n runOnUpdate: boolean = true,\n ): Promise<TValue> {\n if (this.getIsFull()) {\n this._rejectionCount++\n this._options.onReject(fn, this)\n return Promise.reject(new Error('Queuer is full'))\n }\n\n return new Promise<TValue>((resolve, reject) => {\n const task = Object.assign(\n async () => {\n try {\n const result = await fn()\n resolve(result)\n return result\n } catch (error) {\n reject(error)\n throw error\n }\n },\n { priority: fn.priority ?? undefined },\n )\n\n // Get priority either from the function or from getPriority option\n const priority =\n this._options.getPriority !== defaultOptions.getPriority\n ? this._options.getPriority(task)\n : task.priority\n\n if (priority !== undefined) {\n // Insert based on priority\n const insertIndex = this._items.findIndex((existing) => {\n const existingPriority =\n this._options.getPriority !== defaultOptions.getPriority\n ? this._options.getPriority(existing)\n : (existing as any).priority\n return existingPriority > priority\n })\n\n if (insertIndex === -1) {\n this._items.push(task)\n } else {\n this._items.splice(insertIndex, 0, task)\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this._items.unshift(task)\n } else {\n this._items.push(task)\n }\n }\n\n if (runOnUpdate) {\n this._options.onItemsChange(this)\n }\n\n if (this._running && !this._pendingTick) {\n this._pendingTick = true\n this.tick()\n }\n })\n }\n\n /**\n * Removes and returns an item from the queuer\n */\n getNextItem(\n position: QueuePosition = this._options.getItemsFrom,\n ): (() => Promise<TValue>) | undefined {\n let item: (() => Promise<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.onItemsChange(this)\n this._options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n */\n getPeek(\n position: QueuePosition = 'front',\n ): (() => Promise<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 getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n getIsFull(): boolean {\n return this._items.length >= this._options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<() => Promise<TValue>> {\n return [...this.getActiveItems(), ...this.getPendingItems()]\n }\n\n /**\n * Returns the active items\n */\n getActiveItems(): Array<() => Promise<TValue>> {\n return Array.from(this._activeItems)\n }\n\n /**\n * Returns the pending items\n */\n getPendingItems(): Array<() => Promise<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 * Returns the number of items that have been rejected from the queuer\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns true if the queuer is running\n */\n getIsRunning(): boolean {\n return this._running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n getIsIdle(): boolean {\n return this._running && this.getIsEmpty() && this._activeItems.size === 0\n }\n\n /**\n * Adds a callback to be called when a task succeeds\n */\n onSuccess(cb: (result: TValue) => void) {\n this._onSuccessCallbacks.push(cb)\n return () => {\n this._onSuccessCallbacks = this._onSuccessCallbacks.filter(\n (d) => d !== cb,\n )\n }\n }\n\n /**\n * Adds a callback to be called when a task errors\n */\n onError(cb: (error: Error) => void) {\n this._onErrorCallbacks.push(cb)\n return () => {\n this._onErrorCallbacks = this._onErrorCallbacks.filter((d) => d !== cb)\n }\n }\n\n /**\n * Adds a callback to be called when a task is settled\n */\n onSettled(cb: (result: TValue | Error) => void) {\n this._onSettledCallbacks.push(cb)\n return () => {\n this._onSettledCallbacks = this._onSettledCallbacks.filter(\n (d) => d !== cb,\n )\n }\n }\n}\n\n/**\n * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.\n * The queuer is automatically started and ready to process items.\n *\n * @example\n * ```ts\n * const enqueue = asyncQueue<string>();\n *\n * // Add items to be processed\n * enqueue(async () => {\n * return 'Hello';\n * });\n * ```\n *\n * @param options - Configuration options for the AsyncQueuer\n * @returns A bound addItem function that can be used to add tasks to the queuer\n */\nexport function asyncQueue<TValue>(options: AsyncQueuerOptions<TValue> = {}) {\n const queuer = new AsyncQueuer<TValue>({ ...options, started: true })\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":";;AA4DA,MAAM,iBAAoD;AAAA,EACxD,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,cAAc;AAAA,EACd,aAAa,CAAC,UAAU,6BAAc,aAAY;AAAA,EAClD,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,eAAe,MAAM;AAAA,EAAC;AAAA,E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G,KAAK,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMxB,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,YAAqB;AACnB,WAAO,KAAK,YAAY,KAAK,WAAgB,KAAA,KAAK,aAAa,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM1E,UAAU,IAA8B;AACjC,SAAA,oBAAoB,KAAK,EAAE;AAChC,WAAO,MAAM;AACN,WAAA,sBAAsB,KAAK,oBAAoB;AAAA,QAClD,CAAC,MAAM,MAAM;AAAA,MACf;AAAA,IACF;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAQ,IAA4B;AAC7B,SAAA,kBAAkB,KAAK,EAAE;AAC9B,WAAO,MAAM;AACX,WAAK,oBAAoB,KAAK,kBAAkB,OAAO,CAAC,MAAM,MAAM,EAAE;AAAA,IACxE;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,UAAU,IAAsC;AACzC,SAAA,oBAAoB,KAAK,EAAE;AAChC,WAAO,MAAM;AACN,WAAA,sBAAsB,KAAK,oBAAoB;AAAA,QAClD,CAAC,MAAM,MAAM;AAAA,MACf;AAAA,IACF;AAAA,EAAA;AAEJ;AAmBgB,SAAA,WAAmB,UAAsC,IAAI;AACrE,QAAA,SAAS,IAAI,YAAoB,EAAE,GAAG,SAAS,SAAS,MAAM;AAC7D,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;;;"}
|
|
1
|
+
{"version":3,"file":"async-queuer.cjs","sources":["../../src/async-queuer.ts"],"sourcesContent":["import type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum number of concurrent tasks to process\n */\n concurrency?: number\n /**\n * Maximum time in milliseconds that an item can stay in the queue\n * If not provided, items will never expire\n */\n expirationDuration?: number\n /**\n * Function to determine if an item has expired\n * If provided, this overrides the expirationDuration behavior\n */\n getIsExpired?: (item: () => Promise<TValue>, addedAt: number) => boolean\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n * If not provided, will use static priority values attached to tasks\n */\n getPriority?: (item: () => Promise<TValue>) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<(() => Promise<TValue>) & { priority?: number }>\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?: (\n item: () => Promise<TValue>,\n queuer: AsyncQueuer<TValue>,\n ) => void\n /**\n * Callback fired whenever the queuer's running state changes\n */\n onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately or not.\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n */\n wait?: number\n}\n\nconst defaultOptions: Required<AsyncQueuerOptions<any>> = {\n addItemsTo: 'back',\n concurrency: 1,\n expirationDuration: Infinity,\n getIsExpired: () => false,\n getItemsFrom: 'front',\n getPriority: (item) => (item as any)?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onIsRunningChange: () => {},\n onItemsChange: () => {},\n onReject: () => {},\n onExpire: () => {},\n started: true,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queue that processes tasks with configurable concurrency control.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * @example\n * ```ts\n * const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });\n *\n * asyncQueuer.addItem(async () => {\n * return 'Hello';\n * });\n *\n * asyncQueuer.start();\n *\n * asyncQueuer.onSuccess((result) => {\n * console.log(result); // 'Hello'\n * });\n * ```\n */\nexport class AsyncQueuer<TValue> {\n private _options: Required<AsyncQueuerOptions<TValue>>\n private _activeItems: Set<() => Promise<TValue>> = new Set()\n private _executionCount = 0\n private _rejectionCount = 0\n private _expirationCount = 0\n private _items: Array<() => Promise<TValue>> = []\n private _itemTimestamps: Array<number> = []\n private _onErrorCallbacks: Array<(error: Error) => void> = []\n private _onSettledCallbacks: Array<(result: TValue | Error) => void> = []\n private _onSuccessCallbacks: Array<(result: TValue) => void> = []\n private _pendingTick = false\n private _running: boolean\n\n constructor(initialOptions: AsyncQueuerOptions<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 * Updates the queuer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current queuer options\n */\n getOptions(): Required<AsyncQueuerOptions<TValue>> {\n return this._options\n }\n\n /**\n * Processes items in the queuer\n */\n private tick() {\n if (!this._running) {\n this._pendingTick = false\n return\n }\n\n // Check for expired items\n this.checkExpiredItems()\n\n while (\n this._activeItems.size < this._options.concurrency &&\n !this.getIsEmpty()\n ) {\n const nextFn = this.getNextItem()\n if (!nextFn) {\n break\n }\n this._activeItems.add(nextFn)\n this._options.onItemsChange(this)\n ;(async () => {\n let success = false\n let res!: TValue\n let error: Error | undefined\n\n try {\n res = await nextFn()\n success = true\n } catch (e) {\n error = e as Error\n } finally {\n this._activeItems.delete(nextFn)\n this._options.onItemsChange(this)\n }\n\n if (success) {\n this._onSuccessCallbacks.forEach((cb) => cb(res))\n } else {\n this._onErrorCallbacks.forEach((cb) => cb(error!))\n }\n this._onSettledCallbacks.forEach((cb) => cb(success ? res : error!))\n\n if (this._options.wait > 0) {\n setTimeout(() => this.tick(), this._options.wait)\n return\n }\n\n this.tick()\n })()\n }\n\n this._pendingTick = false\n }\n\n /**\n * Checks for and removes expired items from the queuer\n */\n private checkExpiredItems() {\n if (\n this._options.expirationDuration === Infinity &&\n this._options.getIsExpired === defaultOptions.getIsExpired\n )\n return\n\n const now = Date.now()\n const expiredIndices: Array<number> = []\n\n // Find indices of expired items\n for (let i = 0; i < this._items.length; i++) {\n const timestamp = this._itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this._items[i]\n if (item === undefined) continue\n\n const isExpired =\n this._options.getIsExpired !== defaultOptions.getIsExpired\n ? this._options.getIsExpired(item, timestamp)\n : now - timestamp > this._options.expirationDuration\n\n if (isExpired) {\n expiredIndices.push(i)\n }\n }\n\n // Remove expired items from back to front to maintain indices\n for (let i = expiredIndices.length - 1; i >= 0; i--) {\n const index = expiredIndices[i]\n if (index === undefined) continue\n\n const expiredItem = this._items[index]\n if (expiredItem === undefined) continue\n\n this._items.splice(index, 1)\n this._itemTimestamps.splice(index, 1)\n this._expirationCount++\n this._options.onExpire(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this._options.onItemsChange(this)\n }\n }\n\n /**\n * Starts the queuer and processes items\n */\n start(): Promise<void> {\n this._running = true\n if (!this._pendingTick && !this.getIsEmpty()) {\n this._pendingTick = true\n this.tick()\n }\n this._options.onIsRunningChange(this)\n\n return new Promise<void>((resolve) => {\n const checkIdle = () => {\n if (this.getIsIdle()) {\n resolve()\n } else {\n setTimeout(checkIdle, 100)\n }\n }\n checkIdle()\n })\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop(): void {\n this._running = false\n this._pendingTick = false\n this._options.onIsRunningChange(this)\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this._items = []\n this._options.onItemsChange(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 * Adds a task to the queuer\n */\n addItem(\n fn: (() => Promise<TValue>) & { priority?: number },\n position: QueuePosition = this._options.addItemsTo,\n runOnUpdate: boolean = true,\n ): Promise<TValue> {\n if (this.getIsFull()) {\n this._rejectionCount++\n this._options.onReject(fn, this)\n return Promise.reject(new Error('Queuer is full'))\n }\n\n return new Promise<TValue>((resolve, reject) => {\n const task = Object.assign(\n async () => {\n try {\n const result = await fn()\n resolve(result)\n return result\n } catch (error) {\n reject(error)\n throw error\n }\n },\n { priority: fn.priority ?? undefined },\n )\n\n // Get priority either from the function or from getPriority option\n const priority =\n this._options.getPriority !== defaultOptions.getPriority\n ? this._options.getPriority(task)\n : task.priority\n\n if (priority !== undefined) {\n // Insert based on priority\n const insertIndex = this._items.findIndex((existing) => {\n const existingPriority =\n this._options.getPriority !== defaultOptions.getPriority\n ? this._options.getPriority(existing)\n : (existing as any).priority\n return existingPriority > priority\n })\n\n if (insertIndex === -1) {\n this._items.push(task)\n this._itemTimestamps.push(Date.now())\n } else {\n this._items.splice(insertIndex, 0, task)\n this._itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this._items.unshift(task)\n this._itemTimestamps.unshift(Date.now())\n } else {\n this._items.push(task)\n this._itemTimestamps.push(Date.now())\n }\n }\n\n if (runOnUpdate) {\n this._options.onItemsChange(this)\n }\n\n if (this._running && !this._pendingTick) {\n this._pendingTick = true\n this.tick()\n }\n })\n }\n\n /**\n * Removes and returns an item from the queuer\n */\n getNextItem(\n position: QueuePosition = this._options.getItemsFrom,\n ): (() => Promise<TValue>) | undefined {\n let item: (() => Promise<TValue>) | undefined\n\n if (position === 'front') {\n item = this._items.shift()\n this._itemTimestamps.shift()\n } else {\n item = this._items.pop()\n this._itemTimestamps.pop()\n }\n\n if (item !== undefined) {\n this._executionCount++\n this._options.onItemsChange(this)\n this._options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n */\n getPeek(\n position: QueuePosition = 'front',\n ): (() => Promise<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 getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n getIsFull(): boolean {\n return this._items.length >= this._options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<() => Promise<TValue>> {\n return [...this.getActiveItems(), ...this.getPendingItems()]\n }\n\n /**\n * Returns the active items\n */\n getActiveItems(): Array<() => Promise<TValue>> {\n return Array.from(this._activeItems)\n }\n\n /**\n * Returns the pending items\n */\n getPendingItems(): Array<() => Promise<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 * Returns the number of items that have been rejected from the queuer\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns true if the queuer is running\n */\n getIsRunning(): boolean {\n return this._running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n getIsIdle(): boolean {\n return this._running && this.getIsEmpty() && this._activeItems.size === 0\n }\n\n /**\n * Adds a callback to be called when a task succeeds\n */\n onSuccess(cb: (result: TValue) => void) {\n this._onSuccessCallbacks.push(cb)\n return () => {\n this._onSuccessCallbacks = this._onSuccessCallbacks.filter(\n (d) => d !== cb,\n )\n }\n }\n\n /**\n * Adds a callback to be called when a task errors\n */\n onError(cb: (error: Error) => void) {\n this._onErrorCallbacks.push(cb)\n return () => {\n this._onErrorCallbacks = this._onErrorCallbacks.filter((d) => d !== cb)\n }\n }\n\n /**\n * Adds a callback to be called when a task is settled\n */\n onSettled(cb: (result: TValue | Error) => void) {\n this._onSettledCallbacks.push(cb)\n return () => {\n this._onSettledCallbacks = this._onSettledCallbacks.filter(\n (d) => d !== cb,\n )\n }\n }\n\n /**\n * Returns the number of items that have expired from the queuer\n */\n getExpirationCount(): number {\n return this._expirationCount\n }\n}\n\n/**\n * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.\n * The queuer is automatically started and ready to process items.\n *\n * @example\n * ```ts\n * const enqueue = asyncQueue<string>();\n *\n * // Add items to be processed\n * enqueue(async () => {\n * return 'Hello';\n * });\n * ```\n *\n * @param options - Configuration options for the AsyncQueuer\n * @returns A bound addItem function that can be used to add tasks to the queuer\n */\nexport function asyncQueue<TValue>(\n options: Omit<AsyncQueuerOptions<TValue>, 'started'> = {},\n) {\n const queuer = new AsyncQueuer<TValue>(options)\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":";;AA0EA,MAAM,iBAAoD;AAAA,EACxD,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,cAAc,MAAM;AAAA,EACpB,cAAc;AAAA,EACd,aAAa,CAAC,UAAU,6BAAc,aAAY;AAAA,EAClD,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,mBAAmB,MAAM;AAAA,EAAC;AAAA,EAC1B,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU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