@tanstack/pacer 0.22.0 → 0.23.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 (100) hide show
  1. package/README.md +4 -4
  2. package/dist/async-batcher.d.ts +11 -13
  3. package/dist/async-batcher.js +185 -131
  4. package/dist/async-debouncer.d.ts +6 -8
  5. package/dist/async-debouncer.js +186 -142
  6. package/dist/async-queuer.d.ts +11 -13
  7. package/dist/async-queuer.js +383 -290
  8. package/dist/async-rate-limiter.d.ts +6 -8
  9. package/dist/async-rate-limiter.js +197 -143
  10. package/dist/async-retryer.d.ts +6 -8
  11. package/dist/async-retryer.js +209 -179
  12. package/dist/async-throttler.d.ts +6 -8
  13. package/dist/async-throttler.js +214 -157
  14. package/dist/batcher.d.ts +5 -7
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -8
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -10
  19. package/dist/event-client.js +1 -2
  20. package/dist/queuer.d.ts +7 -9
  21. package/dist/queuer.js +277 -212
  22. package/dist/rate-limiter.d.ts +6 -8
  23. package/dist/rate-limiter.js +127 -109
  24. package/dist/throttler.d.ts +6 -8
  25. package/dist/throttler.js +127 -90
  26. package/dist/types.d.ts +4 -6
  27. package/dist/utils.d.ts +3 -5
  28. package/dist/utils.js +1 -2
  29. package/package.json +21 -68
  30. package/dist/async-batcher.cjs +0 -337
  31. package/dist/async-batcher.cjs.map +0 -1
  32. package/dist/async-batcher.d.cts +0 -343
  33. package/dist/async-batcher.js.map +0 -1
  34. package/dist/async-debouncer.cjs +0 -327
  35. package/dist/async-debouncer.cjs.map +0 -1
  36. package/dist/async-debouncer.d.cts +0 -299
  37. package/dist/async-debouncer.js.map +0 -1
  38. package/dist/async-queuer.cjs +0 -516
  39. package/dist/async-queuer.cjs.map +0 -1
  40. package/dist/async-queuer.d.cts +0 -440
  41. package/dist/async-queuer.js.map +0 -1
  42. package/dist/async-rate-limiter.cjs +0 -370
  43. package/dist/async-rate-limiter.cjs.map +0 -1
  44. package/dist/async-rate-limiter.d.cts +0 -356
  45. package/dist/async-rate-limiter.js.map +0 -1
  46. package/dist/async-retryer.cjs +0 -365
  47. package/dist/async-retryer.cjs.map +0 -1
  48. package/dist/async-retryer.d.cts +0 -321
  49. package/dist/async-retryer.js.map +0 -1
  50. package/dist/async-throttler.cjs +0 -344
  51. package/dist/async-throttler.cjs.map +0 -1
  52. package/dist/async-throttler.d.cts +0 -319
  53. package/dist/async-throttler.js.map +0 -1
  54. package/dist/batcher.cjs +0 -200
  55. package/dist/batcher.cjs.map +0 -1
  56. package/dist/batcher.d.cts +0 -179
  57. package/dist/batcher.js.map +0 -1
  58. package/dist/debouncer.cjs +0 -203
  59. package/dist/debouncer.cjs.map +0 -1
  60. package/dist/debouncer.d.cts +0 -166
  61. package/dist/debouncer.js.map +0 -1
  62. package/dist/event-client.cjs +0 -64
  63. package/dist/event-client.cjs.map +0 -1
  64. package/dist/event-client.d.cts +0 -65
  65. package/dist/event-client.js.map +0 -1
  66. package/dist/index.cjs +0 -52
  67. package/dist/index.d.cts +0 -15
  68. package/dist/queuer.cjs +0 -406
  69. package/dist/queuer.cjs.map +0 -1
  70. package/dist/queuer.d.cts +0 -345
  71. package/dist/queuer.js.map +0 -1
  72. package/dist/rate-limiter.cjs +0 -263
  73. package/dist/rate-limiter.cjs.map +0 -1
  74. package/dist/rate-limiter.d.cts +0 -214
  75. package/dist/rate-limiter.js.map +0 -1
  76. package/dist/throttler.cjs +0 -215
  77. package/dist/throttler.cjs.map +0 -1
  78. package/dist/throttler.d.cts +0 -206
  79. package/dist/throttler.js.map +0 -1
  80. package/dist/types.cjs +0 -0
  81. package/dist/types.d.cts +0 -13
  82. package/dist/utils.cjs +0 -13
  83. package/dist/utils.cjs.map +0 -1
  84. package/dist/utils.d.cts +0 -7
  85. package/dist/utils.js.map +0 -1
  86. package/src/async-batcher.ts +0 -594
  87. package/src/async-debouncer.ts +0 -566
  88. package/src/async-queuer.ts +0 -988
  89. package/src/async-rate-limiter.ts +0 -648
  90. package/src/async-retryer.ts +0 -673
  91. package/src/async-throttler.ts +0 -634
  92. package/src/batcher.ts +0 -329
  93. package/src/debouncer.ts +0 -334
  94. package/src/event-client.ts +0 -129
  95. package/src/index.ts +0 -24
  96. package/src/queuer.ts +0 -751
  97. package/src/rate-limiter.ts +0 -429
  98. package/src/throttler.ts +0 -380
  99. package/src/types.ts +0 -12
  100. package/src/utils.ts +0 -12
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-debouncer.js","names":["#getEnabled","#cancelPendingExecution","#setState","#execute","#resolvePreviousPromise","#timeoutId","#getWait","#clearTimeout","#resolvePreviousPromiseInternal"],"sources":["../src/async-debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { AsyncRetryer } from './async-retryer'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AsyncRetryerOptions } from './async-retryer'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\nexport interface AsyncDebouncerState<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have resulted in errors\n */\n errorCount: number\n /**\n * Whether the debounced function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * The result from the most recent successful function execution\n */\n lastResult: Awaited<ReturnType<TFn>> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed\n */\n status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled'\n /**\n * Number of function executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncDebouncerState<\n TFn extends AnyAsyncFunction,\n>(): AsyncDebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n errorCount: 0,\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n lastResult: undefined,\n maybeExecuteCount: 0,\n settleCount: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<TFn>\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 * Initial state for the async debouncer\n */\n initialState?: Partial<AsyncDebouncerState<TFn>>\n /**\n * Optional key to identify this async debouncer instance.\n * If provided, the async debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\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 * If provided, the handler will be called with the error and debouncer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (\n error: Error,\n args: Parameters<TFn>,\n debouncer: AsyncDebouncer<TFn>,\n ) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (\n result: Awaited<ReturnType<TFn>>,\n args: Parameters<TFn>,\n debouncer: AsyncDebouncer<TFn>,\n ) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: 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 * 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\n/**\n * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.\n */\nexport function asyncDebouncerOptions<\n TFn extends AnyAsyncFunction = AnyAsyncFunction,\n TOptions extends Partial<AsyncDebouncerOptions<TFn>> = Partial<\n AsyncDebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncDebouncerOptions<any>,\n 'initialState' | 'onError' | 'onSettled' | 'onSuccess' | 'key'\n>\n\nconst defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Debouncer:\n * - Returns promises that can be awaited for debounced function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Cancel support to prevent pending executions from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync Debouncer is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Debouncing?\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying store\n *\n * State Management:\n * - The debouncer uses a reactive store for state management\n * - Use `initialState` to provide initial state values when creating the async debouncer\n * - The state includes canLeadingExecute, error count, execution status, and success/settle counts\n * - State can be accessed via the `store` property and its `state` getter\n * - The store is reactive and will notify subscribers of state changes\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 * }, {\n * wait: 500,\n * onError: (error) => {\n * console.error('Search failed:', error);\n * }\n * });\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 readonly store: Store<Readonly<AsyncDebouncerState<TFn>>> = new Store<\n AsyncDebouncerState<TFn>\n >(getDefaultAsyncDebouncerState<TFn>())\n key: string | undefined\n options: AsyncDebouncerOptions<TFn>\n asyncRetryers = new Map<number, AsyncRetryer<TFn>>()\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n #resolvePreviousPromise:\n ((value?: Awaited<ReturnType<TFn>> | undefined) => void) | null = null\n\n constructor(\n public fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-AsyncDebouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<AsyncDebouncerState<TFn>>,\n )\n this.setOptions(\n event.payload.options as Partial<AsyncDebouncerOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the async debouncer options\n */\n setOptions = (newOptions: Partial<AsyncDebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<AsyncDebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, isExecuting, settleCount } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : isExecuting\n ? 'executing'\n : settleCount > 0\n ? 'settled'\n : 'idle',\n }\n })\n emitChange('AsyncDebouncer', this)\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 * Error Handling:\n * - If the debounced function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the debounced function if no onError handler is configured\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<Awaited<ReturnType<TFn>> | undefined> => {\n if (!this.#getEnabled()) return undefined\n this.#cancelPendingExecution()\n this.#setState({\n lastArgs: args,\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n await this.#execute(...args)\n return this.store.state.lastResult\n }\n\n // Handle trailing execution\n if (this.options.trailing && this.#getEnabled()) {\n this.#setState({ isPending: true })\n }\n\n return new Promise<Awaited<ReturnType<TFn>> | undefined>(\n (resolve, reject) => {\n this.#resolvePreviousPromise = resolve\n // this.#rejectPreviousPromise = reject\n this.#timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this.options.trailing && this.store.state.lastArgs) {\n try {\n await this.#execute(...this.store.state.lastArgs)\n } catch (error) {\n reject(error)\n }\n }\n\n // Reset state and resolve\n this.#setState({ canLeadingExecute: true })\n this.#resolvePreviousPromise = null\n resolve(this.store.state.lastResult)\n }, this.#getWait())\n },\n )\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<Awaited<ReturnType<TFn>> | undefined> => {\n if (!this.#getEnabled()) return undefined\n const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1\n\n try {\n this.#setState({ isExecuting: true })\n const currentAsyncRetryer = new AsyncRetryer(\n this.fn,\n this.options.asyncRetryerOptions,\n )\n this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer)\n const result = await currentAsyncRetryer.execute(...args) // EXECUTE!\n this.#setState({\n lastResult: result,\n successCount: this.store.state.successCount + 1,\n })\n this.options.onSuccess?.(result as Awaited<ReturnType<TFn>>, args, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, args, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentMaybeExecuteCount) // dispose retryer\n this.#setState({\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(args, this)\n }\n return this.store.state.lastResult\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = async (): Promise<Awaited<ReturnType<TFn>> | undefined> => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n const { lastArgs } = this.store.state\n this.#cancelPendingExecution()\n return await this.#execute(...lastArgs)\n }\n return undefined\n }\n\n #resolvePreviousPromiseInternal = (): void => {\n if (this.#resolvePreviousPromise) {\n this.#resolvePreviousPromise(this.store.state.lastResult)\n this.#resolvePreviousPromise = null\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Internal cancel without resetting the leading execute state\n */\n #cancelPendingExecution = (): void => {\n this.#clearTimeout()\n this.#resolvePreviousPromiseInternal()\n this.#setState({\n isPending: false,\n lastArgs: undefined,\n })\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no maybeExecuteCount is provided, returns the signal for the most recent execution.\n * Returns null if no execution is found or not currently executing.\n *\n * @param maybeExecuteCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const debouncer = new AsyncDebouncer(\n * async (searchTerm: string) => {\n * const signal = debouncer.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/search?q=${searchTerm}`, { signal })\n * return response.json()\n * }\n * },\n * { wait: 300 }\n * )\n * ```\n */\n getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {\n const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount\n const retryer = this.asyncRetryers.get(count)\n return retryer?.getAbortSignal() ?? null\n }\n\n /**\n * Aborts all ongoing executions with the internal abort controllers.\n * Does NOT cancel any pending execution that have not started yet.\n */\n abort = (): void => {\n this.asyncRetryers.forEach((retryer) => retryer.abort())\n this.asyncRetryers.clear()\n this.#setState({\n isExecuting: false,\n })\n }\n\n /**\n * Cancels any pending execution that have not started yet.\n * Does NOT abort any execution already in progress.\n */\n cancel = (): void => {\n this.#cancelPendingExecution()\n this.#setState({ canLeadingExecute: true })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncDebouncerState<TFn>())\n this.asyncRetryers.forEach((retryer) => retryer.reset())\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 * Async vs Sync Versions:\n * The async version provides advanced features over the sync debounce function:\n * - Returns promises that can be awaited for debounced function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Cancel support to prevent pending executions from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync debounce function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Debouncing?\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 * Configuration Options:\n * - `wait`: Delay in milliseconds to wait after the last call (required)\n * - `leading`: Execute on the leading edge of the timeout (default: false)\n * - `trailing`: Execute on the trailing edge of the timeout (default: true)\n * - `enabled`: Whether the debouncer is enabled (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for executions\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - The error state can be checked using the underlying AsyncDebouncer instance\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async debouncer\n * - Use `onSuccess` callback to react to successful function execution and implement custom logic\n * - Use `onError` callback to react to function execution errors and implement custom error handling\n * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic\n * - The state includes canLeadingExecute, error count, execution status, and success/settle counts\n * - State can be accessed via `asyncDebouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`\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 * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * throwOnError: true // Will both log the error and throw it\n * });\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\n}\n"],"mappings":";;;;;;A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EApQE,KAAK,MAAM,eAAe;EAC1B,KAAK,UAAU;GACb,GAAG;GACH,GAAG;GACH,cAAc,eAAe,gBAAgB,CAAC,eAAe;EAC/D;EACA,KAAKA,UAAU,KAAK,QAAQ,gBAAgB,CAAC,CAAC;EAE9C,IAAI,KAAK,KACP,iBAAiB,GAAG,qBAAqB,UAAU;GACjD,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKA,UACH,MAAM,QAAQ,MAAM,KACtB;GACA,KAAK,WACH,MAAM,QAAQ,OAChB;EACF,CAAC;CAEL;CAcA;;;;CA0BA;;;;CAOA;CA+DA;CAoDA;CAOA;;;;CAUA;AA+DF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAAgB,cACd,IACA,gBACA;CAEA,OAAO,IADoB,eAAe,IAAI,cAC1B,CAAC,CAAC;AACxB"}
@@ -1,516 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils.cjs');
3
- const require_async_retryer = require('./async-retryer.cjs');
4
- const require_event_client = require('./event-client.cjs');
5
- let _tanstack_store = require("@tanstack/store");
6
-
7
- //#region src/async-queuer.ts
8
- function getDefaultAsyncQueuerState() {
9
- return {
10
- activeItems: [],
11
- addItemCount: 0,
12
- errorCount: 0,
13
- executeCount: 0,
14
- expirationCount: 0,
15
- isEmpty: true,
16
- isExecuting: false,
17
- isFull: false,
18
- isIdle: true,
19
- isRunning: true,
20
- itemTimestamps: [],
21
- items: [],
22
- lastResult: null,
23
- pendingTick: false,
24
- rejectionCount: 0,
25
- settledCount: 0,
26
- size: 0,
27
- status: "idle",
28
- successCount: 0
29
- };
30
- }
31
- /**
32
- * Utility function for sharing common `AsyncQueuerOptions` options between different `AsyncQueuer` instances.
33
- */
34
- function asyncQueuerOptions(options) {
35
- return options;
36
- }
37
- const defaultOptions = {
38
- addItemsTo: "back",
39
- asyncRetryerOptions: { maxAttempts: 1 },
40
- concurrency: 1,
41
- expirationDuration: Infinity,
42
- getIsExpired: () => false,
43
- getItemsFrom: "front",
44
- getPriority: (item) => item?.priority ?? 0,
45
- initialItems: [],
46
- maxSize: Infinity,
47
- started: true,
48
- wait: 0
49
- };
50
- /**
51
- * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.
52
- *
53
- * Async vs Sync Versions:
54
- * The async version provides advanced features over the sync Queuer:
55
- * - Returns promises that can be awaited for task results
56
- * - Built-in retry support via AsyncRetryer integration for each queued task
57
- * - Abort support to cancel in-flight task executions
58
- * - Comprehensive error handling with onError callbacks and throwOnError control
59
- * - Detailed execution tracking (success/error/settle counts)
60
- * - Concurrent execution support (process multiple items simultaneously)
61
- *
62
- * The sync Queuer is lighter weight and simpler when you don't need async features,
63
- * return values, or execution control.
64
- *
65
- * What is Queuing?
66
- * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
67
- * Tasks are processed up to the configured concurrency limit. When a task completes,
68
- * the next pending task is processed if the concurrency limit allows.
69
- *
70
- * Key Features:
71
- * - Priority queue support via the getPriority option
72
- * - Configurable concurrency limit
73
- * - Callbacks for task success, error, completion, and queue state changes
74
- * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
75
- * - Pause and resume processing
76
- * - Item expiration to remove stale items from the queue
77
- *
78
- * Error Handling:
79
- * - If an `onError` handler is provided, it will be called with the error and queuer instance
80
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
81
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
82
- * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
83
- * - The error state can be checked using the AsyncQueuer instance
84
- *
85
- * State Management:
86
- * - Uses TanStack Store for reactive state management
87
- * - Use `initialState` to provide initial state values when creating the async queuer
88
- * - Use `onSuccess` callback to react to successful task execution and implement custom logic
89
- * - Use `onError` callback to react to task execution errors and implement custom error handling
90
- * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
91
- * - Use `onItemsChange` callback to react to items being added or removed from the queue
92
- * - Use `onExpire` callback to react to items expiring and implement custom logic
93
- * - Use `onReject` callback to react to items being rejected when the queue is full
94
- * - The state includes error count, expiration count, rejection count, running status, and success/settle counts
95
- * - State can be accessed via `asyncQueuer.store.state` when using the class directly
96
- * - When using framework adapters (React/Solid), state is accessed from `asyncQueuer.state`
97
- *
98
- * Example usage:
99
- * ```ts
100
- * const asyncQueuer = new AsyncQueuer<string>(async (item) => {
101
- * // process item
102
- * return item.toUpperCase();
103
- * }, {
104
- * concurrency: 2,
105
- * onSuccess: (result) => {
106
- * console.log(result);
107
- * }
108
- * });
109
- *
110
- * asyncQueuer.addItem('hello');
111
- * asyncQueuer.start();
112
- * ```
113
- */
114
- var AsyncQueuer = class {
115
- #timeoutIds;
116
- constructor(fn, initialOptions = {}) {
117
- this.fn = fn;
118
- this.store = new _tanstack_store.Store(getDefaultAsyncQueuerState());
119
- this.asyncRetryers = /* @__PURE__ */ new Map();
120
- this.#timeoutIds = /* @__PURE__ */ new Set();
121
- this.setOptions = (newOptions) => {
122
- this.options = {
123
- ...this.options,
124
- ...newOptions
125
- };
126
- };
127
- this.#setState = (newState) => {
128
- this.store.setState((state) => {
129
- const combinedState = {
130
- ...state,
131
- ...newState
132
- };
133
- const { activeItems, items, isRunning } = combinedState;
134
- const size = items.length;
135
- const isFull = size >= (this.options.maxSize ?? Infinity);
136
- const isEmpty = size === 0;
137
- const isIdle = isRunning && isEmpty && activeItems.length === 0;
138
- const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
139
- return {
140
- ...combinedState,
141
- isEmpty,
142
- isFull,
143
- isIdle,
144
- size,
145
- status
146
- };
147
- });
148
- require_event_client.emitChange("AsyncQueuer", this);
149
- };
150
- this.#getWait = () => {
151
- return require_utils.parseFunctionOrValue(this.options.wait ?? 0, this);
152
- };
153
- this.#getConcurrency = () => {
154
- return require_utils.parseFunctionOrValue(this.options.concurrency ?? 1, this);
155
- };
156
- this.#tick = () => {
157
- if (!this.store.state.isRunning) {
158
- this.#setState({ pendingTick: false });
159
- return;
160
- }
161
- this.#setState({ pendingTick: true });
162
- this.#checkExpiredItems();
163
- let scheduledAsyncWork = false;
164
- const activeItems = [...this.store.state.activeItems];
165
- while (activeItems.length < this.#getConcurrency() && this.store.state.items.length > 0) {
166
- const nextItem = this.peekNextItem();
167
- if (nextItem === void 0) break;
168
- activeItems.push(nextItem);
169
- this.#setState({ activeItems: [...activeItems] });
170
- scheduledAsyncWork = true;
171
- (async () => {
172
- try {
173
- await this.execute();
174
- } catch {}
175
- const wait = this.#getWait();
176
- if (wait > 0) {
177
- const timeoutId = setTimeout(() => {
178
- this.#timeoutIds.delete(timeoutId);
179
- this.#tick();
180
- }, wait);
181
- this.#timeoutIds.add(timeoutId);
182
- return;
183
- }
184
- this.#tick();
185
- })();
186
- }
187
- if (!scheduledAsyncWork) this.#setState({ pendingTick: false });
188
- };
189
- this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
190
- this.#setState({ addItemCount: this.store.state.addItemCount + 1 });
191
- if (item === void 0) {
192
- this.#setState({ rejectionCount: this.store.state.rejectionCount + 1 });
193
- this.options.onReject?.(item, this);
194
- return false;
195
- }
196
- if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
197
- this.#setState({ rejectionCount: this.store.state.rejectionCount + 1 });
198
- this.options.onReject?.(item, this);
199
- return false;
200
- }
201
- const priority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(item) : item?.priority;
202
- const items = this.store.state.items;
203
- const itemTimestamps = this.store.state.itemTimestamps;
204
- if (priority !== void 0) {
205
- const insertIndex = items.findIndex((existing) => {
206
- return (this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(existing) : existing?.priority) < priority;
207
- });
208
- if (insertIndex === -1) {
209
- items.push(item);
210
- itemTimestamps.push(Date.now());
211
- } else {
212
- items.splice(insertIndex, 0, item);
213
- itemTimestamps.splice(insertIndex, 0, Date.now());
214
- }
215
- } else if (position === "front") {
216
- items.unshift(item);
217
- itemTimestamps.unshift(Date.now());
218
- } else {
219
- items.push(item);
220
- itemTimestamps.push(Date.now());
221
- }
222
- this.#setState({
223
- items,
224
- itemTimestamps
225
- });
226
- if (runOnItemsChange) this.options.onItemsChange?.(this);
227
- if (this.store.state.isRunning && !this.store.state.pendingTick) this.#tick();
228
- return true;
229
- };
230
- this.getNextItem = (position = this.options.getItemsFrom ?? "front") => {
231
- const { items, itemTimestamps } = this.store.state;
232
- let item;
233
- if (this.options.getPriority !== defaultOptions.getPriority || position === "front") {
234
- item = items[0];
235
- if (item !== void 0) this.#setState({
236
- items: items.slice(1),
237
- itemTimestamps: itemTimestamps.slice(1)
238
- });
239
- } else {
240
- item = items[items.length - 1];
241
- if (item !== void 0) this.#setState({
242
- items: items.slice(0, -1),
243
- itemTimestamps: itemTimestamps.slice(0, -1)
244
- });
245
- }
246
- if (item !== void 0) this.options.onItemsChange?.(this);
247
- return item;
248
- };
249
- this.#getAllItems = () => {
250
- const items = this.peekAllItems();
251
- this.clear();
252
- return items;
253
- };
254
- this.execute = async (position) => {
255
- const item = this.getNextItem(position);
256
- if (item !== void 0) {
257
- const currentExecuteCount = this.store.state.executeCount + 1;
258
- this.#setState({
259
- executeCount: currentExecuteCount,
260
- isExecuting: true
261
- });
262
- try {
263
- const currentAsyncRetryer = new require_async_retryer.AsyncRetryer(this.fn, this.options.asyncRetryerOptions);
264
- this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer);
265
- const lastResult = await currentAsyncRetryer.execute(item);
266
- this.#setState({
267
- successCount: this.store.state.successCount + 1,
268
- lastResult
269
- });
270
- this.options.onSuccess?.(lastResult, item, this);
271
- } catch (error) {
272
- this.#setState({ errorCount: this.store.state.errorCount + 1 });
273
- this.options.onError?.(error, item, this);
274
- if (this.options.throwOnError) throw error;
275
- } finally {
276
- this.asyncRetryers.delete(currentExecuteCount);
277
- const remainingActiveItems = [...this.store.state.activeItems];
278
- const activeItemIndex = remainingActiveItems.indexOf(item);
279
- if (activeItemIndex !== -1) remainingActiveItems.splice(activeItemIndex, 1);
280
- this.#setState({
281
- activeItems: remainingActiveItems,
282
- isExecuting: this.asyncRetryers.size > 0,
283
- settledCount: this.store.state.settledCount + 1
284
- });
285
- this.options.onSettled?.(item, this);
286
- }
287
- }
288
- return item;
289
- };
290
- this.flush = async (numberOfItems = this.store.state.items.length, position) => {
291
- this.#clearTimeouts();
292
- const results = await Promise.allSettled(Array.from({ length: numberOfItems }, () => this.execute(position)));
293
- this.#setState({ pendingTick: false });
294
- if (this.store.state.isRunning && this.store.state.items.length > 0) {
295
- const wait = this.#getWait();
296
- if (wait > 0) {
297
- this.#setState({ pendingTick: true });
298
- const timeoutId = setTimeout(() => {
299
- this.#timeoutIds.delete(timeoutId);
300
- this.#tick();
301
- }, wait);
302
- this.#timeoutIds.add(timeoutId);
303
- } else this.#tick();
304
- }
305
- const failure = results.find((result) => result.status === "rejected");
306
- if (failure) throw failure.reason;
307
- };
308
- this.flushAsBatch = async (batchFunction) => {
309
- this.#clearTimeouts();
310
- const items = this.#getAllItems();
311
- try {
312
- await batchFunction(items);
313
- } finally {
314
- this.#setState({ pendingTick: false });
315
- if (this.store.state.isRunning && this.store.state.items.length > 0) this.#tick();
316
- }
317
- };
318
- this.#checkExpiredItems = () => {
319
- if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
320
- const now = Date.now();
321
- const expiredIndices = [];
322
- for (let i = 0; i < this.store.state.items.length; i++) {
323
- const timestamp = this.store.state.itemTimestamps[i];
324
- if (timestamp === void 0) continue;
325
- const item = this.store.state.items[i];
326
- if (item === void 0) continue;
327
- if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
328
- }
329
- for (let i = expiredIndices.length - 1; i >= 0; i--) {
330
- const index = expiredIndices[i];
331
- if (index === void 0) continue;
332
- const expiredItem = this.store.state.items[index];
333
- if (expiredItem === void 0) continue;
334
- const newItems = [...this.store.state.items];
335
- const newTimestamps = [...this.store.state.itemTimestamps];
336
- newItems.splice(index, 1);
337
- newTimestamps.splice(index, 1);
338
- this.#setState({
339
- items: newItems,
340
- itemTimestamps: newTimestamps,
341
- expirationCount: this.store.state.expirationCount + 1
342
- });
343
- this.options.onExpire?.(expiredItem, this);
344
- }
345
- if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
346
- };
347
- this.peekNextItem = (position = "front") => {
348
- if (position === "front") return this.store.state.items[0];
349
- return this.store.state.items[this.store.state.items.length - 1];
350
- };
351
- this.peekAllItems = () => {
352
- return [...this.peekActiveItems(), ...this.peekPendingItems()];
353
- };
354
- this.peekActiveItems = () => {
355
- return [...this.store.state.activeItems];
356
- };
357
- this.peekPendingItems = () => {
358
- return [...this.store.state.items];
359
- };
360
- this.start = () => {
361
- this.#setState({ isRunning: true });
362
- if (!this.store.state.pendingTick && this.store.state.items.length > 0) this.#tick();
363
- };
364
- this.stop = () => {
365
- this.#clearTimeouts();
366
- this.#setState({
367
- isRunning: false,
368
- pendingTick: false
369
- });
370
- };
371
- this.#clearTimeouts = () => {
372
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
373
- this.#timeoutIds.clear();
374
- };
375
- this.clear = () => {
376
- this.#setState({
377
- items: [],
378
- itemTimestamps: []
379
- });
380
- this.options.onItemsChange?.(this);
381
- };
382
- this.getAbortSignal = (executeCount) => {
383
- const count = executeCount ?? this.store.state.executeCount;
384
- return this.asyncRetryers.get(count)?.getAbortSignal() ?? null;
385
- };
386
- this.abort = () => {
387
- this.asyncRetryers.forEach((retryer) => retryer.abort());
388
- this.asyncRetryers.clear();
389
- this.#setState({ isExecuting: false });
390
- };
391
- this.reset = () => {
392
- this.#setState(getDefaultAsyncQueuerState());
393
- this.options.onItemsChange?.(this);
394
- this.asyncRetryers.forEach((retryer) => retryer.reset());
395
- };
396
- this.key = initialOptions.key;
397
- this.options = {
398
- ...defaultOptions,
399
- ...initialOptions,
400
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
401
- };
402
- const isInitiallyRunning = this.options.initialState?.isRunning ?? this.options.started ?? true;
403
- this.#setState({
404
- ...this.options.initialState,
405
- isRunning: isInitiallyRunning
406
- });
407
- if (this.options.initialState?.items) {
408
- if (this.store.state.isRunning) this.#tick();
409
- } else for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {
410
- const item = this.options.initialItems[i];
411
- const isLast = i === (this.options.initialItems?.length ?? 0) - 1;
412
- this.addItem(item, this.options.addItemsTo ?? "back", isLast);
413
- }
414
- if (this.key) require_event_client.pacerEventClient.on("d-AsyncQueuer", (e) => {
415
- if (e.payload.key !== this.key) return;
416
- this.#setState(e.payload.store.state);
417
- this.setOptions(e.payload.options);
418
- });
419
- }
420
- #setState;
421
- /**
422
- * Returns the current wait time (in milliseconds) between processing items.
423
- * If a function is provided, it is called with the queuer instance.
424
- */
425
- #getWait;
426
- /**
427
- * Returns the current concurrency limit for processing items.
428
- * If a function is provided, it is called with the queuer instance.
429
- */
430
- #getConcurrency;
431
- /**
432
- * Processes items in the queue up to the concurrency limit. Internal use only.
433
- */
434
- #tick;
435
- #getAllItems;
436
- /**
437
- * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
438
- * Internal use only.
439
- */
440
- #checkExpiredItems;
441
- #clearTimeouts;
442
- };
443
- /**
444
- * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.
445
- * The queuer is started automatically and ready to process items.
446
- *
447
- * Async vs Sync Versions:
448
- * The async version provides advanced features over the sync queue function:
449
- * - Returns promises that can be awaited for task results
450
- * - Built-in retry support via AsyncRetryer integration for each queued task
451
- * - Abort support to cancel in-flight task executions
452
- * - Comprehensive error handling with onError callbacks and throwOnError control
453
- * - Detailed execution tracking (success/error/settle counts)
454
- * - Concurrent execution support (process multiple items simultaneously)
455
- *
456
- * The sync queue function is lighter weight and simpler when you don't need async features,
457
- * return values, or execution control.
458
- *
459
- * What is Queuing?
460
- * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
461
- * Tasks are processed up to the configured concurrency limit. When a task completes,
462
- * the next pending task is processed if the concurrency limit allows.
463
- *
464
- * Configuration Options:
465
- * - `concurrency`: Maximum number of concurrent tasks (default: 1)
466
- * - `wait`: Time to wait between processing items (default: 0)
467
- * - `maxSize`: Maximum number of items allowed in the queue (default: Infinity)
468
- * - `getPriority`: Function to determine item priority
469
- * - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')
470
- * - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')
471
- * - `expirationDuration`: Maximum time items can stay in queue
472
- * - `started`: Whether to start processing immediately (default: true)
473
- * - `asyncRetryerOptions`: Configure retry behavior for task executions
474
- *
475
- * Error Handling:
476
- * - If an `onError` handler is provided, it will be called with the error and queuer instance
477
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
478
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
479
- * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
480
- * - The error state can be checked using the underlying AsyncQueuer instance
481
- *
482
- * State Management:
483
- * - Uses TanStack Store for reactive state management
484
- * - Use `initialState` to provide initial state values when creating the async queuer
485
- * - Use `onSuccess` callback to react to successful task execution and implement custom logic
486
- * - Use `onError` callback to react to task execution errors and implement custom error handling
487
- * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
488
- * - Use `onItemsChange` callback to react to items being added or removed from the queue
489
- * - Use `onExpire` callback to react to items expiring and implement custom logic
490
- * - Use `onReject` callback to react to items being rejected when the queue is full
491
- * - The state includes error count, expiration count, rejection count, running status, and success/settle counts
492
- * - State can be accessed via the underlying AsyncQueuer instance's `store.state` property
493
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
494
- *
495
- * @example
496
- * ```ts
497
- * const enqueue = asyncQueue<string>(async (item) => {
498
- * return item.toUpperCase();
499
- * }, {
500
- * concurrency: 2,
501
- * wait: 100,
502
- * onSuccess: (result) => console.log('Processed:', result)
503
- * });
504
- *
505
- * enqueue('hello');
506
- * ```
507
- */
508
- function asyncQueue(fn, initialOptions) {
509
- return new AsyncQueuer(fn, initialOptions).addItem;
510
- }
511
-
512
- //#endregion
513
- exports.AsyncQueuer = AsyncQueuer;
514
- exports.asyncQueue = asyncQueue;
515
- exports.asyncQueuerOptions = asyncQueuerOptions;
516
- //# sourceMappingURL=async-queuer.cjs.map