@tanstack/pacer 0.4.0 → 0.5.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 +16 -3
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +14 -4
- package/dist/cjs/async-queuer.cjs +20 -6
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +21 -8
- package/dist/cjs/async-rate-limiter.cjs +28 -7
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +21 -6
- package/dist/cjs/async-throttler.cjs +19 -5
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +14 -4
- package/dist/cjs/debouncer.cjs +16 -3
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +14 -4
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/queuer.cjs +13 -5
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +9 -3
- package/dist/cjs/rate-limiter.cjs +26 -7
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +20 -6
- package/dist/cjs/throttler.cjs +19 -5
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +15 -4
- package/dist/cjs/utils.cjs +18 -7
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +3 -0
- package/dist/esm/async-debouncer.d.ts +14 -4
- package/dist/esm/async-debouncer.js +16 -3
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +21 -8
- package/dist/esm/async-queuer.js +20 -6
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +21 -6
- package/dist/esm/async-rate-limiter.js +28 -7
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +14 -4
- package/dist/esm/async-throttler.js +19 -5
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +14 -4
- package/dist/esm/debouncer.js +16 -3
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/queuer.d.ts +9 -3
- package/dist/esm/queuer.js +13 -5
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +20 -6
- package/dist/esm/rate-limiter.js +26 -7
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +15 -4
- package/dist/esm/throttler.js +19 -5
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/utils.d.ts +3 -0
- package/dist/esm/utils.js +19 -8
- package/dist/esm/utils.js.map +1 -1
- package/package.json +9 -3
- package/src/async-debouncer.ts +24 -7
- package/src/async-queuer.ts +32 -13
- package/src/async-rate-limiter.ts +41 -13
- package/src/async-throttler.ts +27 -9
- package/src/debouncer.ts +24 -7
- package/src/queuer.ts +19 -7
- package/src/rate-limiter.ts +37 -13
- package/src/throttler.ts +28 -9
- package/src/utils.ts +19 -5
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const utils = require("./utils.cjs");
|
|
3
4
|
const defaultOptions = {
|
|
4
5
|
enabled: true,
|
|
5
6
|
leading: false,
|
|
@@ -44,6 +45,18 @@ class AsyncDebouncer {
|
|
|
44
45
|
getOptions() {
|
|
45
46
|
return this._options;
|
|
46
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Returns the current debouncer enabled state
|
|
50
|
+
*/
|
|
51
|
+
getEnabled() {
|
|
52
|
+
return utils.parseFunctionOrValue(this._options.enabled, this);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Returns the current debouncer wait state
|
|
56
|
+
*/
|
|
57
|
+
getWait() {
|
|
58
|
+
return utils.parseFunctionOrValue(this._options.wait, this);
|
|
59
|
+
}
|
|
47
60
|
/**
|
|
48
61
|
* Attempts to execute the debounced function
|
|
49
62
|
* If a call is already in progress, it will be queued
|
|
@@ -66,11 +79,11 @@ class AsyncDebouncer {
|
|
|
66
79
|
}
|
|
67
80
|
this._canLeadingExecute = true;
|
|
68
81
|
resolve(this._lastResult);
|
|
69
|
-
}, this.
|
|
82
|
+
}, this.getWait());
|
|
70
83
|
});
|
|
71
84
|
}
|
|
72
85
|
async executeFunction(...args) {
|
|
73
|
-
if (!this.
|
|
86
|
+
if (!this.getEnabled()) return void 0;
|
|
74
87
|
this._abortController = new AbortController();
|
|
75
88
|
try {
|
|
76
89
|
this._isExecuting = true;
|
|
@@ -140,7 +153,7 @@ class AsyncDebouncer {
|
|
|
140
153
|
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
141
154
|
*/
|
|
142
155
|
getIsPending() {
|
|
143
|
-
return this.
|
|
156
|
+
return this.getEnabled() && this._isPending;
|
|
144
157
|
}
|
|
145
158
|
/**
|
|
146
159
|
* Returns `true` if there is currently an execution in progress
|
|
@@ -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<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;A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../../src/async-debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport 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 * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => 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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => 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 * Returns the current debouncer enabled state\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\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.getWait())\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) 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.getEnabled() && 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: AsyncDebouncerOptions<TFn>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AA2CA,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,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB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ACtB,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAAA,IAAA;AAEpB,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB,MAAM;AAC5B,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,gBAAgB,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnC,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;;;"}
|
|
@@ -5,9 +5,10 @@ import { AnyAsyncFunction } from './types.cjs';
|
|
|
5
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
|
+
* Can be a boolean or a function that returns a boolean.
|
|
8
9
|
* Defaults to true.
|
|
9
10
|
*/
|
|
10
|
-
enabled?: boolean;
|
|
11
|
+
enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean);
|
|
11
12
|
/**
|
|
12
13
|
* Whether to execute on the leading edge of the timeout.
|
|
13
14
|
* Defaults to false.
|
|
@@ -31,10 +32,11 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
31
32
|
*/
|
|
32
33
|
trailing?: boolean;
|
|
33
34
|
/**
|
|
34
|
-
* Delay in milliseconds to wait after the last call before executing
|
|
35
|
+
* Delay in milliseconds to wait after the last call before executing.
|
|
36
|
+
* Can be a number or a function that returns a number.
|
|
35
37
|
* Defaults to 0ms
|
|
36
38
|
*/
|
|
37
|
-
wait: number;
|
|
39
|
+
wait: number | ((debouncer: AsyncDebouncer<TFn>) => number);
|
|
38
40
|
}
|
|
39
41
|
/**
|
|
40
42
|
* A class that creates an async debounced function.
|
|
@@ -85,6 +87,14 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
85
87
|
* Returns the current debouncer options
|
|
86
88
|
*/
|
|
87
89
|
getOptions(): Required<AsyncDebouncerOptions<TFn>>;
|
|
90
|
+
/**
|
|
91
|
+
* Returns the current debouncer enabled state
|
|
92
|
+
*/
|
|
93
|
+
getEnabled(): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Returns the current debouncer wait state
|
|
96
|
+
*/
|
|
97
|
+
getWait(): number;
|
|
88
98
|
/**
|
|
89
99
|
* Attempts to execute the debounced function
|
|
90
100
|
* If a call is already in progress, it will be queued
|
|
@@ -145,4 +155,4 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
145
155
|
* const result = await debounced("third");
|
|
146
156
|
* ```
|
|
147
157
|
*/
|
|
148
|
-
export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions:
|
|
158
|
+
export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const utils = require("./utils.cjs");
|
|
3
4
|
const defaultOptions = {
|
|
4
5
|
addItemsTo: "back",
|
|
5
6
|
concurrency: 1,
|
|
@@ -55,6 +56,18 @@ class AsyncQueuer {
|
|
|
55
56
|
getOptions() {
|
|
56
57
|
return this._options;
|
|
57
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Returns the current wait time between processing items
|
|
61
|
+
*/
|
|
62
|
+
getWait() {
|
|
63
|
+
return utils.parseFunctionOrValue(this._options.wait, this);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Returns the current concurrency limit
|
|
67
|
+
*/
|
|
68
|
+
getConcurrency() {
|
|
69
|
+
return utils.parseFunctionOrValue(this._options.concurrency, this);
|
|
70
|
+
}
|
|
58
71
|
/**
|
|
59
72
|
* Processes items in the queuer
|
|
60
73
|
*/
|
|
@@ -64,7 +77,7 @@ class AsyncQueuer {
|
|
|
64
77
|
return;
|
|
65
78
|
}
|
|
66
79
|
this.checkExpiredItems();
|
|
67
|
-
while (this._activeItems.size < this.
|
|
80
|
+
while (this._activeItems.size < this.getConcurrency() && !this.getIsEmpty()) {
|
|
68
81
|
const nextFn = this.getNextItem();
|
|
69
82
|
if (!nextFn) {
|
|
70
83
|
break;
|
|
@@ -90,8 +103,9 @@ class AsyncQueuer {
|
|
|
90
103
|
this._onErrorCallbacks.forEach((cb) => cb(error));
|
|
91
104
|
}
|
|
92
105
|
this._onSettledCallbacks.forEach((cb) => cb(success ? res : error));
|
|
93
|
-
|
|
94
|
-
|
|
106
|
+
const wait = this.getWait();
|
|
107
|
+
if (wait > 0) {
|
|
108
|
+
setTimeout(() => this.tick(), wait);
|
|
95
109
|
return;
|
|
96
110
|
}
|
|
97
111
|
this.tick();
|
|
@@ -181,7 +195,7 @@ class AsyncQueuer {
|
|
|
181
195
|
/**
|
|
182
196
|
* Adds a task to the queuer
|
|
183
197
|
*/
|
|
184
|
-
addItem(fn, position = this._options.addItemsTo,
|
|
198
|
+
addItem(fn, position = this._options.addItemsTo, runOnItemsChange = true) {
|
|
185
199
|
if (this.getIsFull()) {
|
|
186
200
|
this._rejectionCount++;
|
|
187
201
|
this._options.onReject(fn, this);
|
|
@@ -223,7 +237,7 @@ class AsyncQueuer {
|
|
|
223
237
|
this._itemTimestamps.push(Date.now());
|
|
224
238
|
}
|
|
225
239
|
}
|
|
226
|
-
if (
|
|
240
|
+
if (runOnItemsChange) {
|
|
227
241
|
this._options.onItemsChange(this);
|
|
228
242
|
}
|
|
229
243
|
if (this._running && !this._pendingTick) {
|
|
@@ -358,7 +372,7 @@ class AsyncQueuer {
|
|
|
358
372
|
return this._expirationCount;
|
|
359
373
|
}
|
|
360
374
|
}
|
|
361
|
-
function asyncQueue(options
|
|
375
|
+
function asyncQueue(options) {
|
|
362
376
|
const queuer = new AsyncQueuer(options);
|
|
363
377
|
return queuer.addItem.bind(queuer);
|
|
364
378
|
}
|
|
@@ -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 * 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,MAAM;AAAA,EAAC;AAAA,EACjB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS;AAAA,EACT,MAAM;AACR;AAgCO,MAAM,YAAoB;AAAA,EAc/B,YAAY,iBAA6C,gBAAgB;AAZjE,SAAA,mCAA+C,IAAI;AAC3D,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ,mBAAmB;AAC3B,SAAQ,SAAuC,CAAC;AAChD,SAAQ,kBAAiC,CAAC;AAC1C,SAAQ,oBAAmD,CAAC;AAC5D,SAAQ,sBAA+D,CAAC;AACxE,SAAQ,sBAAuD,CAAC;AAChE,SAAQ,eAAe;AAIrB,SAAK,WAAW,EAAE,GAAG,gBAAgB,GAAG,e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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;AAAA;AAAA;AAAA;AAAA,EAMF,qBAA6B;AAC3B,WAAO,KAAK;AAAA,EAAA;AAEhB;AAmBgB,SAAA,WACd,UAAuD,IACvD;AACM,QAAA,SAAS,IAAI,YAAoB,OAAO;AACvC,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;;;"}
|
|
1
|
+
{"version":3,"file":"async-queuer.cjs","sources":["../../src/async-queuer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\nimport 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 * Can be a number or a function that returns a number.\n * @default 1\n */\n concurrency?: number | ((queuer: AsyncQueuer<TValue>) => 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 * Can be a number or a function that returns a number.\n * @default 0\n */\n wait?: number | ((queuer: AsyncQueuer<TValue>) => 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 * Returns the current wait time between processing items\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Returns the current concurrency limit\n */\n getConcurrency(): number {\n return parseFunctionOrValue(this._options.concurrency, this)\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.getConcurrency() &&\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 const wait = this.getWait()\n if (wait > 0) {\n setTimeout(() => this.tick(), 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: AnyAsyncFunction & { priority?: number },\n position: QueuePosition = this._options.addItemsTo,\n runOnItemsChange: 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 (runOnItemsChange) {\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>(options: AsyncQueuerOptions<TValue>) {\n const queuer = new AsyncQueuer<TValue>(options)\n return queuer.addItem.bind(queuer)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAgFA,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,MAAM;AAAA,EAAC;AAAA,EACjB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS;AAAA,EACT,MAAM;AACR;AAgCO,MAAM,YAAoB;AAAA,EAc/B,YAAY,iBAA6C,gBAAgB;AAZjE,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ue> {
|
|
3
4
|
/**
|
|
@@ -6,9 +7,11 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
6
7
|
*/
|
|
7
8
|
addItemsTo?: QueuePosition;
|
|
8
9
|
/**
|
|
9
|
-
* Maximum number of concurrent tasks to process
|
|
10
|
+
* Maximum number of concurrent tasks to process.
|
|
11
|
+
* Can be a number or a function that returns a number.
|
|
12
|
+
* @default 1
|
|
10
13
|
*/
|
|
11
|
-
concurrency?: number;
|
|
14
|
+
concurrency?: number | ((queuer: AsyncQueuer<TValue>) => number);
|
|
12
15
|
/**
|
|
13
16
|
* Maximum time in milliseconds that an item can stay in the queue
|
|
14
17
|
* If not provided, items will never expire
|
|
@@ -65,9 +68,11 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
65
68
|
*/
|
|
66
69
|
started?: boolean;
|
|
67
70
|
/**
|
|
68
|
-
* Time in milliseconds to wait between processing items
|
|
71
|
+
* Time in milliseconds to wait between processing items.
|
|
72
|
+
* Can be a number or a function that returns a number.
|
|
73
|
+
* @default 0
|
|
69
74
|
*/
|
|
70
|
-
wait?: number;
|
|
75
|
+
wait?: number | ((queuer: AsyncQueuer<TValue>) => number);
|
|
71
76
|
}
|
|
72
77
|
/**
|
|
73
78
|
* A flexible asynchronous queue that processes tasks with configurable concurrency control.
|
|
@@ -122,6 +127,14 @@ export declare class AsyncQueuer<TValue> {
|
|
|
122
127
|
* Returns the current queuer options
|
|
123
128
|
*/
|
|
124
129
|
getOptions(): Required<AsyncQueuerOptions<TValue>>;
|
|
130
|
+
/**
|
|
131
|
+
* Returns the current wait time between processing items
|
|
132
|
+
*/
|
|
133
|
+
getWait(): number;
|
|
134
|
+
/**
|
|
135
|
+
* Returns the current concurrency limit
|
|
136
|
+
*/
|
|
137
|
+
getConcurrency(): number;
|
|
125
138
|
/**
|
|
126
139
|
* Processes items in the queuer
|
|
127
140
|
*/
|
|
@@ -149,9 +162,9 @@ export declare class AsyncQueuer<TValue> {
|
|
|
149
162
|
/**
|
|
150
163
|
* Adds a task to the queuer
|
|
151
164
|
*/
|
|
152
|
-
addItem(fn:
|
|
165
|
+
addItem(fn: AnyAsyncFunction & {
|
|
153
166
|
priority?: number;
|
|
154
|
-
}, position?: QueuePosition,
|
|
167
|
+
}, position?: QueuePosition, runOnItemsChange?: boolean): Promise<TValue>;
|
|
155
168
|
/**
|
|
156
169
|
* Removes and returns an item from the queuer
|
|
157
170
|
*/
|
|
@@ -234,6 +247,6 @@ export declare class AsyncQueuer<TValue> {
|
|
|
234
247
|
* @param options - Configuration options for the AsyncQueuer
|
|
235
248
|
* @returns A bound addItem function that can be used to add tasks to the queuer
|
|
236
249
|
*/
|
|
237
|
-
export declare function asyncQueue<TValue>(options
|
|
250
|
+
export declare function asyncQueue<TValue>(options: AsyncQueuerOptions<TValue>): (fn: AnyAsyncFunction & {
|
|
238
251
|
priority?: number;
|
|
239
|
-
}, position?: QueuePosition,
|
|
252
|
+
}, position?: QueuePosition, runOnItemsChange?: boolean) => Promise<TValue>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const utils = require("./utils.cjs");
|
|
3
4
|
const defaultOptions = {
|
|
4
5
|
enabled: true,
|
|
5
6
|
onError: () => {
|
|
@@ -39,6 +40,24 @@ class AsyncRateLimiter {
|
|
|
39
40
|
getOptions() {
|
|
40
41
|
return this._options;
|
|
41
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Returns the current enabled state of the rate limiter
|
|
45
|
+
*/
|
|
46
|
+
getEnabled() {
|
|
47
|
+
return !!utils.parseFunctionOrValue(this._options.enabled, this);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Returns the current limit of executions allowed within the time window
|
|
51
|
+
*/
|
|
52
|
+
getLimit() {
|
|
53
|
+
return utils.parseFunctionOrValue(this._options.limit, this);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Returns the current time window in milliseconds
|
|
57
|
+
*/
|
|
58
|
+
getWindow() {
|
|
59
|
+
return utils.parseFunctionOrValue(this._options.window, this);
|
|
60
|
+
}
|
|
42
61
|
/**
|
|
43
62
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
44
63
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
@@ -57,16 +76,18 @@ class AsyncRateLimiter {
|
|
|
57
76
|
*/
|
|
58
77
|
async maybeExecute(...args) {
|
|
59
78
|
this.cleanupOldExecutions();
|
|
79
|
+
const limit = this.getLimit();
|
|
80
|
+
const window = this.getWindow();
|
|
60
81
|
if (this._options.windowType === "sliding") {
|
|
61
|
-
if (this._executionTimes.length <
|
|
82
|
+
if (this._executionTimes.length < limit) {
|
|
62
83
|
await this.executeFunction(...args);
|
|
63
84
|
return this._lastResult;
|
|
64
85
|
}
|
|
65
86
|
} else {
|
|
66
87
|
const now = Date.now();
|
|
67
88
|
const oldestExecution = Math.min(...this._executionTimes);
|
|
68
|
-
const isNewWindow = oldestExecution +
|
|
69
|
-
if (isNewWindow || this._executionTimes.length <
|
|
89
|
+
const isNewWindow = oldestExecution + window <= now;
|
|
90
|
+
if (isNewWindow || this._executionTimes.length < limit) {
|
|
70
91
|
await this.executeFunction(...args);
|
|
71
92
|
return this._lastResult;
|
|
72
93
|
}
|
|
@@ -76,7 +97,7 @@ class AsyncRateLimiter {
|
|
|
76
97
|
}
|
|
77
98
|
async executeFunction(...args) {
|
|
78
99
|
var _a, _b, _c, _d, _e, _f;
|
|
79
|
-
if (!this.
|
|
100
|
+
if (!this.getEnabled()) return;
|
|
80
101
|
this._isExecuting = true;
|
|
81
102
|
const now = Date.now();
|
|
82
103
|
this._executionTimes.push(now);
|
|
@@ -102,7 +123,7 @@ class AsyncRateLimiter {
|
|
|
102
123
|
}
|
|
103
124
|
cleanupOldExecutions() {
|
|
104
125
|
const now = Date.now();
|
|
105
|
-
const windowStart = now - this.
|
|
126
|
+
const windowStart = now - this.getWindow();
|
|
106
127
|
this._executionTimes = this._executionTimes.filter(
|
|
107
128
|
(time) => time > windowStart
|
|
108
129
|
);
|
|
@@ -112,7 +133,7 @@ class AsyncRateLimiter {
|
|
|
112
133
|
*/
|
|
113
134
|
getRemainingInWindow() {
|
|
114
135
|
this.cleanupOldExecutions();
|
|
115
|
-
return Math.max(0, this.
|
|
136
|
+
return Math.max(0, this.getLimit() - this._executionTimes.length);
|
|
116
137
|
}
|
|
117
138
|
/**
|
|
118
139
|
* Returns the number of milliseconds until the next execution will be possible
|
|
@@ -124,7 +145,7 @@ class AsyncRateLimiter {
|
|
|
124
145
|
return 0;
|
|
125
146
|
}
|
|
126
147
|
const oldestExecution = Math.min(...this._executionTimes);
|
|
127
|
-
return oldestExecution + this.
|
|
148
|
+
return oldestExecution + this.getWindow() - Date.now();
|
|
128
149
|
}
|
|
129
150
|
/**
|
|
130
151
|
* Returns the number of times the function has been executed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n windowType: 'fixed',\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptions<TFn>\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n private _isExecuting = false\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn>>\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + this._options.window <= now\n\n if (isNewWindow || this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return\n this._isExecuting = true\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\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._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this._options.window - Date.now()\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\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 the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns whether the function is currently executing\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 0\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited 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 rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";;AA+CA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,YAAY;AACd;AAsCO,MAAM,iBAA+C;AAAA,EAU1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;A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Ac;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AA4CgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
1
|
+
{"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean)\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a function that returns a number.\n */\n limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a function that returns a number.\n */\n window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n windowType: 'fixed',\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptions<TFn>\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n private _isExecuting = false\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn>>\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n getEnabled(): boolean {\n return !!parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n getLimit(): number {\n return parseFunctionOrValue(this._options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n getWindow(): number {\n return parseFunctionOrValue(this._options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n const limit = this.getLimit()\n const window = this.getWindow()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + window <= now\n\n if (isNewWindow || this._executionTimes.length < limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return\n this._isExecuting = true\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\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._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.getWindow()\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.getLimit() - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\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 the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns whether the function is currently executing\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 0\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited 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 rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAmDA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,YAAY;AACd;AAsCO,MAAM,iBAA+C;AAAA,EAU1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AA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O,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,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,gBAAgB;AACrB,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AA4CgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
@@ -5,13 +5,15 @@ import { AnyAsyncFunction } from './types.cjs';
|
|
|
5
5
|
export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
|
+
* Can be a boolean or a function that returns a boolean.
|
|
8
9
|
* Defaults to true.
|
|
9
10
|
*/
|
|
10
|
-
enabled?: boolean;
|
|
11
|
+
enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean);
|
|
11
12
|
/**
|
|
12
|
-
* Maximum number of executions allowed within the time window
|
|
13
|
+
* Maximum number of executions allowed within the time window.
|
|
14
|
+
* Can be a number or a function that returns a number.
|
|
13
15
|
*/
|
|
14
|
-
limit: number;
|
|
16
|
+
limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number);
|
|
15
17
|
/**
|
|
16
18
|
* Optional error handler for when the rate-limited function throws
|
|
17
19
|
*/
|
|
@@ -29,9 +31,10 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
|
|
|
29
31
|
*/
|
|
30
32
|
onSuccess?: (result: ReturnType<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
|
|
31
33
|
/**
|
|
32
|
-
* Time window in milliseconds within which the limit applies
|
|
34
|
+
* Time window in milliseconds within which the limit applies.
|
|
35
|
+
* Can be a number or a function that returns a number.
|
|
33
36
|
*/
|
|
34
|
-
window: number;
|
|
37
|
+
window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number);
|
|
35
38
|
/**
|
|
36
39
|
* Type of window to use for rate limiting
|
|
37
40
|
* - 'fixed': Uses a fixed window that resets after the window period
|
|
@@ -96,6 +99,18 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
|
96
99
|
* Returns the current rate limiter options
|
|
97
100
|
*/
|
|
98
101
|
getOptions(): Required<AsyncRateLimiterOptions<TFn>>;
|
|
102
|
+
/**
|
|
103
|
+
* Returns the current enabled state of the rate limiter
|
|
104
|
+
*/
|
|
105
|
+
getEnabled(): boolean;
|
|
106
|
+
/**
|
|
107
|
+
* Returns the current limit of executions allowed within the time window
|
|
108
|
+
*/
|
|
109
|
+
getLimit(): number;
|
|
110
|
+
/**
|
|
111
|
+
* Returns the current time window in milliseconds
|
|
112
|
+
*/
|
|
113
|
+
getWindow(): number;
|
|
99
114
|
/**
|
|
100
115
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
101
116
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
@@ -193,4 +208,4 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
|
|
|
193
208
|
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
194
209
|
* ```
|
|
195
210
|
*/
|
|
196
|
-
export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions:
|
|
211
|
+
export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|