@tanstack/pacer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Options for configuring a throttled function
3
+ */
4
+ export interface ThrottlerOptions {
5
+ /**
6
+ * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
7
+ * Defaults to true.
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Whether to execute on the leading edge of the timeout.
12
+ * Defaults to true.
13
+ */
14
+ leading?: boolean;
15
+ /**
16
+ * Whether to execute on the trailing edge of the timeout.
17
+ * Defaults to true.
18
+ */
19
+ trailing?: boolean;
20
+ /**
21
+ * Time window in milliseconds during which the function can only be executed once
22
+ */
23
+ wait: number;
24
+ }
25
+ /**
26
+ * A class that creates a throttled function.
27
+ *
28
+ * Throttling ensures a function is called at most once within a specified time window.
29
+ * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
30
+ * execution timing regardless of call frequency.
31
+ *
32
+ * Supports both leading and trailing edge execution:
33
+ * - Leading: Execute immediately on first call (default: true)
34
+ * - Trailing: Execute after wait period if called during throttle (default: true)
35
+ *
36
+ * For rate limiting or hard API limits, consider using RateLimiter instead.
37
+ * For collapsing rapid-fire events, consider using Debouncer.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const throttler = new Throttler(
42
+ * (id: string) => api.getData(id),
43
+ * { wait: 1000 } // Execute at most once per second
44
+ * );
45
+ *
46
+ * // First call executes immediately
47
+ * throttler.maybeExecute('123');
48
+ *
49
+ * // Subsequent calls within 1000ms are throttled
50
+ * throttler.maybeExecute('123'); // Throttled
51
+ * ```
52
+ */
53
+ export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
54
+ private fn;
55
+ private executionCount;
56
+ private lastArgs;
57
+ private lastExecutionTime;
58
+ private options;
59
+ private timeoutId;
60
+ constructor(fn: TFn, initialOptions: ThrottlerOptions);
61
+ /**
62
+ * Updates the throttler options
63
+ * Returns the new options state
64
+ */
65
+ setOptions(newOptions: Partial<ThrottlerOptions>): Required<ThrottlerOptions>;
66
+ /**
67
+ * Returns the number of times the function has been executed
68
+ */
69
+ getExecutionCount(): number;
70
+ /**
71
+ * Returns the last execution time
72
+ */
73
+ getLastExecutionTime(): number;
74
+ /**
75
+ * Returns the next execution time
76
+ */
77
+ getNextExecutionTime(): number;
78
+ /**
79
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
80
+ *
81
+ * - If enough time has passed since the last execution (>= wait period):
82
+ * - With leading=true: Executes immediately
83
+ * - With leading=false: Waits for the next trailing execution
84
+ *
85
+ * - If within the wait period:
86
+ * - With trailing=true: Schedules execution for end of wait period
87
+ * - With trailing=false: Drops the execution
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * const throttled = new Throttler(fn, { wait: 1000 });
92
+ *
93
+ * // First call executes immediately
94
+ * throttled.maybeExecute('a', 'b');
95
+ *
96
+ * // Call during wait period - gets throttled
97
+ * throttled.maybeExecute('c', 'd');
98
+ * ```
99
+ */
100
+ maybeExecute(...args: TArgs): void;
101
+ private executeFunction;
102
+ /**
103
+ * Cancels any pending trailing execution and clears internal state.
104
+ *
105
+ * If a trailing execution is scheduled (due to throttling with trailing=true),
106
+ * this will prevent that execution from occurring. The internal timeout and
107
+ * stored arguments will be cleared.
108
+ *
109
+ * Has no effect if there is no pending execution.
110
+ */
111
+ cancel(): void;
112
+ }
113
+ /**
114
+ * Creates a throttled function that limits how often the provided function can execute.
115
+ *
116
+ * Throttling ensures a function executes at most once within a specified time window,
117
+ * regardless of how many times it is called. This is useful for rate-limiting
118
+ * expensive operations or UI updates.
119
+ *
120
+ * The throttled function can be configured to execute on the leading and/or trailing
121
+ * edge of the throttle window via options.
122
+ *
123
+ * For handling bursts of events, consider using debounce() instead. For hard execution
124
+ * limits, consider using rateLimit().
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * // Basic throttling - max once per second
129
+ * const throttled = throttle(updateUI, { wait: 1000 });
130
+ *
131
+ * // Configure leading/trailing execution
132
+ * const throttled = throttle(saveData, {
133
+ * wait: 2000,
134
+ * leading: true, // Execute immediately on first call
135
+ * trailing: true // Execute again after delay if called during wait
136
+ * });
137
+ * ```
138
+ */
139
+ export declare function throttle<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<ThrottlerOptions, 'enabled'>): (...args: Parameters<TFn>) => void;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Options for configuring an async debounced function
3
+ */
4
+ export interface AsyncDebouncerOptions {
5
+ /**
6
+ * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
7
+ * Defaults to true.
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Whether to execute on the leading edge of the timeout.
12
+ * Defaults to false.
13
+ */
14
+ leading?: boolean;
15
+ /**
16
+ * Whether to execute on the trailing edge of the timeout.
17
+ * Defaults to true.
18
+ */
19
+ trailing?: boolean;
20
+ /**
21
+ * Delay in milliseconds to wait after the last call before executing
22
+ * Defaults to 0ms
23
+ */
24
+ wait: number;
25
+ /**
26
+ * Optional error handler for when the debounced function throws
27
+ */
28
+ onError?: (error: unknown) => void;
29
+ }
30
+ /**
31
+ * A class that creates an async debounced function.
32
+ *
33
+ * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
34
+ * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
35
+ * or input changes where you only want to execute the handler after the events have stopped occurring.
36
+ *
37
+ * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
38
+ * the function stops being called for the specified delay period.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const debouncer = new AsyncDebouncer(async (value: string) => {
43
+ * await searchAPI(value);
44
+ * }, { wait: 500 });
45
+ *
46
+ * // Called on each keystroke but only executes after 500ms of no typing
47
+ * inputElement.addEventListener('input', () => {
48
+ * debouncer.maybeExecute(inputElement.value);
49
+ * });
50
+ * ```
51
+ */
52
+ export declare class AsyncDebouncer<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
53
+ private fn;
54
+ private abortController;
55
+ private executionCount;
56
+ private isExecuting;
57
+ private lastArgs;
58
+ private options;
59
+ private timeoutId;
60
+ private canLeadingExecute;
61
+ constructor(fn: TFn, initialOptions: AsyncDebouncerOptions);
62
+ /**
63
+ * Updates the debouncer options
64
+ * Returns the new options state
65
+ */
66
+ setOptions(newOptions: Partial<AsyncDebouncerOptions>): Required<AsyncDebouncerOptions>;
67
+ /**
68
+ * Returns the number of times the function has been executed
69
+ */
70
+ getExecutionCount(): number;
71
+ /**
72
+ * Cancels any pending execution
73
+ */
74
+ cancel(): void;
75
+ /**
76
+ * Attempts to execute the debounced function
77
+ * If a call is already in progress, it will be queued
78
+ */
79
+ maybeExecute(...args: TArgs): Promise<void>;
80
+ private executeFunction;
81
+ }
82
+ /**
83
+ * Creates an async debounced function that delays execution until after a specified wait time.
84
+ * The debounced function will only execute once the wait period has elapsed without any new calls.
85
+ * If called again during the wait period, the timer resets and a new wait period begins.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const debounced = asyncDebounce(async (value: string) => {
90
+ * await saveToAPI(value);
91
+ * }, { wait: 1000 });
92
+ *
93
+ * // Will only execute once, 1 second after the last call
94
+ * await debounced("first"); // Cancelled
95
+ * await debounced("second"); // Cancelled
96
+ * await debounced("third"); // Executes after 1s
97
+ * ```
98
+ */
99
+ export declare function asyncDebounce<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<void>;
@@ -0,0 +1,109 @@
1
+ const defaultOptions = {
2
+ enabled: true,
3
+ leading: false,
4
+ trailing: true,
5
+ onError: () => {
6
+ },
7
+ wait: 0
8
+ };
9
+ class AsyncDebouncer {
10
+ constructor(fn, initialOptions) {
11
+ this.fn = fn;
12
+ this.abortController = null;
13
+ this.executionCount = 0;
14
+ this.isExecuting = false;
15
+ this.timeoutId = null;
16
+ this.canLeadingExecute = true;
17
+ this.options = {
18
+ ...defaultOptions,
19
+ ...initialOptions
20
+ };
21
+ }
22
+ /**
23
+ * Updates the debouncer options
24
+ * Returns the new options state
25
+ */
26
+ setOptions(newOptions) {
27
+ this.options = {
28
+ ...this.options,
29
+ ...newOptions
30
+ };
31
+ return this.options;
32
+ }
33
+ /**
34
+ * Returns the number of times the function has been executed
35
+ */
36
+ getExecutionCount() {
37
+ return this.executionCount;
38
+ }
39
+ /**
40
+ * Cancels any pending execution
41
+ */
42
+ cancel() {
43
+ if (this.timeoutId) {
44
+ clearTimeout(this.timeoutId);
45
+ this.timeoutId = null;
46
+ }
47
+ if (this.abortController) {
48
+ this.abortController.abort();
49
+ this.abortController = null;
50
+ }
51
+ this.lastArgs = void 0;
52
+ this.canLeadingExecute = true;
53
+ }
54
+ /**
55
+ * Attempts to execute the debounced function
56
+ * If a call is already in progress, it will be queued
57
+ */
58
+ async maybeExecute(...args) {
59
+ this.cancel();
60
+ this.lastArgs = args;
61
+ if (this.options.leading && this.canLeadingExecute) {
62
+ this.canLeadingExecute = false;
63
+ await this.executeFunction(...args);
64
+ }
65
+ return new Promise((resolve) => {
66
+ this.timeoutId = setTimeout(async () => {
67
+ if (this.isExecuting) {
68
+ resolve();
69
+ return;
70
+ }
71
+ this.canLeadingExecute = true;
72
+ if (this.options.trailing) {
73
+ this.abortController = new AbortController();
74
+ try {
75
+ this.isExecuting = true;
76
+ if (this.lastArgs) {
77
+ await this.executeFunction(...this.lastArgs);
78
+ }
79
+ } catch (error) {
80
+ try {
81
+ this.options.onError(error);
82
+ } catch {
83
+ }
84
+ } finally {
85
+ this.isExecuting = false;
86
+ this.abortController = null;
87
+ resolve();
88
+ }
89
+ } else {
90
+ resolve();
91
+ }
92
+ }, this.options.wait);
93
+ });
94
+ }
95
+ async executeFunction(...args) {
96
+ if (!this.options.enabled) return;
97
+ this.executionCount++;
98
+ await this.fn(...args);
99
+ }
100
+ }
101
+ function asyncDebounce(fn, initialOptions) {
102
+ const asyncDebouncer = new AsyncDebouncer(fn, initialOptions);
103
+ return asyncDebouncer.maybeExecute.bind(asyncDebouncer);
104
+ }
105
+ export {
106
+ AsyncDebouncer,
107
+ asyncDebounce
108
+ };
109
+ //# sourceMappingURL=async-debouncer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions {\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 * 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 * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown) => void\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions> = {\n enabled: true,\n leading: false,\n trailing: true,\n onError: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * @example\n * ```ts\n * const debouncer = new AsyncDebouncer(async (value: string) => {\n * await searchAPI(value);\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncDebouncer<\n TFn extends (...args: Array<any>) => Promise<any>,\n TArgs extends Parameters<TFn>,\n> {\n private abortController: AbortController | null = null\n private executionCount = 0\n private isExecuting = false\n private lastArgs: TArgs | undefined\n private options: Required<AsyncDebouncerOptions>\n private timeoutId: ReturnType<typeof setTimeout> | null = null\n private canLeadingExecute = true\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncDebouncerOptions>,\n ): Required<AsyncDebouncerOptions> {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.lastArgs = undefined\n this.canLeadingExecute = true\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this.cancel()\n this.lastArgs = args\n\n // Handle leading execution\n if (this.options.leading && this.canLeadingExecute) {\n this.canLeadingExecute = false\n await this.executeFunction(...args)\n }\n\n return new Promise((resolve) => {\n this.timeoutId = setTimeout(async () => {\n if (this.isExecuting) {\n resolve()\n return\n }\n\n this.canLeadingExecute = true\n // Execute trailing only if enabled\n if (this.options.trailing) {\n this.abortController = new AbortController()\n try {\n this.isExecuting = true\n if (this.lastArgs) {\n await this.executeFunction(...this.lastArgs)\n }\n } catch (error) {\n try {\n this.options.onError(error)\n } catch {\n // Ignore errors from error handler\n }\n } finally {\n this.isExecuting = false\n this.abortController = null\n resolve()\n }\n } else {\n resolve()\n }\n }, this.options.wait)\n })\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this.options.enabled) return\n this.executionCount++\n await this.fn(...args)\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * await debounced(\"first\"); // Cancelled\n * await debounced(\"second\"); // Cancelled\n * await debounced(\"third\"); // Executes after 1s\n * ```\n */\nexport function asyncDebounce<\n TFn extends (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions, 'enabled'>) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":"AA8BA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,MAAM;AACR;AAwBO,MAAM,eAGX;AAAA,EASA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,kBAA0C;AAClD,SAAQ,iBAAiB;AACzB,SAAQ,cAAc;AAGtB,SAAQ,YAAkD;AAC1D,SAAQ,oBAAoB;AAM1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACiC;AACjC,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAe;AACb,QAAI,KAAK,WAAW;AAClB,mBAAa,KAAK,SAAS;AAC3B,WAAK,YAAY;AAAA,IAAA;AAEnB,QAAI,KAAK,iBAAiB;AACxB,WAAK,gBAAgB,MAAM;AAC3B,WAAK,kBAAkB;AAAA,IAAA;AAEzB,SAAK,WAAW;AAChB,SAAK,oBAAoB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO3B,MAAM,gBAAgB,MAA4B;AAChD,SAAK,OAAO;AACZ,SAAK,WAAW;AAGhB,QAAI,KAAK,QAAQ,WAAW,KAAK,mBAAmB;AAClD,WAAK,oBAAoB;AACnB,YAAA,KAAK,gBAAgB,GAAG,IAAI;AAAA,IAAA;AAG7B,WAAA,IAAI,QAAQ,CAAC,YAAY;AACzB,WAAA,YAAY,WAAW,YAAY;AACtC,YAAI,KAAK,aAAa;AACZ,kBAAA;AACR;AAAA,QAAA;AAGF,aAAK,oBAAoB;AAErB,YAAA,KAAK,QAAQ,UAAU;AACpB,eAAA,kBAAkB,IAAI,gBAAgB;AACvC,cAAA;AACF,iBAAK,cAAc;AACnB,gBAAI,KAAK,UAAU;AACjB,oBAAM,KAAK,gBAAgB,GAAG,KAAK,QAAQ;AAAA,YAAA;AAAA,mBAEtC,OAAO;AACV,gBAAA;AACG,mBAAA,QAAQ,QAAQ,KAAK;AAAA,YAAA,QACpB;AAAA,YAAA;AAAA,UAER,UACA;AACA,iBAAK,cAAc;AACnB,iBAAK,kBAAkB;AACf,oBAAA;AAAA,UAAA;AAAA,QACV,OACK;AACG,kBAAA;AAAA,QAAA;AAAA,MACV,GACC,KAAK,QAAQ,IAAI;AAAA,IAAA,CACrB;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,QAAQ,QAAS;AACtB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAAA,EAAA;AAEzB;AAmBgB,SAAA,cAEd,IAAS,gBAAwD;AACjE,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
@@ -0,0 +1,197 @@
1
+ import { QueuePosition } from './queuer.js';
2
+ export interface AsyncQueuerOptions<TValue> {
3
+ /**
4
+ * Default position to add items to the queuer
5
+ * @default 'back'
6
+ */
7
+ addItemsTo?: QueuePosition;
8
+ /**
9
+ * Maximum number of concurrent tasks to process
10
+ */
11
+ concurrency?: number;
12
+ /**
13
+ * Default position to get items from during processing
14
+ * @default 'front'
15
+ */
16
+ getItemsFrom?: QueuePosition;
17
+ /**
18
+ * Function to determine priority of items in the queuer
19
+ * Higher priority items will be processed first
20
+ * If not provided, will use static priority values attached to tasks
21
+ */
22
+ getPriority?: (item: () => Promise<TValue>) => number;
23
+ /**
24
+ * Initial items to populate the queuer with
25
+ */
26
+ initialItems?: Array<(() => Promise<TValue>) & {
27
+ priority?: number;
28
+ }>;
29
+ /**
30
+ * Maximum number of items allowed in the queuer
31
+ */
32
+ maxSize?: number;
33
+ /**
34
+ * Callback fired whenever an item is removed from the queuer
35
+ */
36
+ onGetNextItem?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
37
+ /**
38
+ * Callback fired whenever an item is added or removed from the queuer
39
+ */
40
+ onUpdate?: (queuer: AsyncQueuer<TValue>) => void;
41
+ /**
42
+ * Whether the queuer should start processing tasks immediately
43
+ */
44
+ started?: boolean;
45
+ /**
46
+ * Time in milliseconds to wait between processing items
47
+ */
48
+ wait?: number;
49
+ }
50
+ /**
51
+ * A flexible asynchronous queuer that processes tasks with configurable concurrency control.
52
+ *
53
+ * Features:
54
+ * - Priority queuer support via getPriority option
55
+ * - Configurable concurrency limit
56
+ * - Task success/error/completion callbacks
57
+ * - FIFO (First In First Out) or LIFO (Last In First Out) queuer behavior
58
+ * - Pause/resume task processing
59
+ * - Task cancellation
60
+ *
61
+ * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
62
+ * the next pending task is processed if below the concurrency limit.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const queuer = new AsyncQueuer<string>({ concurrency: 2 });
67
+ *
68
+ * queuer.addItem(async () => {
69
+ * return 'Hello';
70
+ * });
71
+ *
72
+ * queuer.start();
73
+ *
74
+ * queuer.onSuccess((result) => {
75
+ * console.log(result); // 'Hello'
76
+ * });
77
+ * ```
78
+ */
79
+ export declare class AsyncQueuer<TValue> {
80
+ protected options: Required<AsyncQueuerOptions<TValue>>;
81
+ private items;
82
+ private activeItems;
83
+ private onSuccessCallbacks;
84
+ private onErrorCallbacks;
85
+ private onSettledCallbacks;
86
+ private running;
87
+ private pendingTick;
88
+ private executionCount;
89
+ constructor(initialOptions?: AsyncQueuerOptions<TValue>);
90
+ /**
91
+ * Updates the queuer options
92
+ * Returns the new options state
93
+ */
94
+ setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): AsyncQueuerOptions<TValue>;
95
+ /**
96
+ * Processes items in the queuer
97
+ */
98
+ protected tick(): void;
99
+ /**
100
+ * Adds a task to the queuer
101
+ */
102
+ addItem(fn: (() => Promise<TValue>) & {
103
+ priority?: number;
104
+ }, position?: QueuePosition, runOnUpdate?: boolean): Promise<TValue>;
105
+ /**
106
+ * Removes and returns an item from the queuer
107
+ */
108
+ getNextItem(position?: QueuePosition): (() => Promise<TValue>) | undefined;
109
+ /**
110
+ * Returns an item without removing it
111
+ */
112
+ peek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
113
+ /**
114
+ * Returns true if the queuer is empty
115
+ */
116
+ isEmpty(): boolean;
117
+ /**
118
+ * Returns true if the queuer is full
119
+ */
120
+ isFull(): boolean;
121
+ /**
122
+ * Returns the current size of the queuer
123
+ */
124
+ size(): number;
125
+ /**
126
+ * Removes all items from the queuer
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Resets the queuer to its initial state
131
+ */
132
+ reset(withInitialItems?: boolean): void;
133
+ /**
134
+ * Returns a copy of all items in the queuer
135
+ */
136
+ getAllItems(): Array<() => Promise<TValue>>;
137
+ /**
138
+ * Returns the number of items that have been removed from the queuer
139
+ */
140
+ getExecutionCount(): number;
141
+ /**
142
+ * Returns the active items
143
+ */
144
+ getActiveItems(): Array<() => Promise<TValue>>;
145
+ /**
146
+ * Returns the pending items
147
+ */
148
+ getPendingItems(): Array<() => Promise<TValue>>;
149
+ /**
150
+ * Adds a callback to be called when a task succeeds
151
+ */
152
+ onSuccess(cb: (result: TValue) => void): () => void;
153
+ /**
154
+ * Adds a callback to be called when a task errors
155
+ */
156
+ onError(cb: (error: Error) => void): () => void;
157
+ /**
158
+ * Adds a callback to be called when a task is settled
159
+ */
160
+ onSettled(cb: (result: TValue | Error) => void): () => void;
161
+ /**
162
+ * Starts the queuer and processes items
163
+ */
164
+ start(): Promise<void>;
165
+ /**
166
+ * Stops the queuer from processing items
167
+ */
168
+ stop(): void;
169
+ /**
170
+ * Returns true if the queuer is running
171
+ */
172
+ isRunning(): boolean;
173
+ /**
174
+ * Returns true if the queuer is running but has no items to process
175
+ */
176
+ isIdle(): boolean;
177
+ }
178
+ /**
179
+ * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
180
+ * The queuer is automatically started and ready to process items.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const enqueue = asyncQueue<string>();
185
+ *
186
+ * // Add items to be processed
187
+ * enqueue(async () => {
188
+ * return 'Hello';
189
+ * });
190
+ * ```
191
+ *
192
+ * @param options - Configuration options for the AsyncQueuer
193
+ * @returns A bound addItem function that can be used to add tasks to the queuer
194
+ */
195
+ export declare function asyncQueue<TValue>(options?: AsyncQueuerOptions<TValue>): (fn: (() => Promise<TValue>) & {
196
+ priority?: number;
197
+ }, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;