@tanstack/solid-pacer 0.18.3 → 0.19.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 (141) hide show
  1. package/README.md +1 -1
  2. package/dist/async-batcher/createAsyncBatcher.cjs +32 -2
  3. package/dist/async-batcher/createAsyncBatcher.cjs.map +1 -1
  4. package/dist/async-batcher/createAsyncBatcher.d.cts +28 -2
  5. package/dist/async-batcher/createAsyncBatcher.d.ts +28 -2
  6. package/dist/async-batcher/createAsyncBatcher.js +32 -2
  7. package/dist/async-batcher/createAsyncBatcher.js.map +1 -1
  8. package/dist/async-batcher/index.cjs +1 -0
  9. package/dist/async-batcher/index.d.cts +2 -2
  10. package/dist/async-batcher/index.d.ts +2 -2
  11. package/dist/async-debouncer/createAsyncDebouncer.cjs +26 -3
  12. package/dist/async-debouncer/createAsyncDebouncer.cjs.map +1 -1
  13. package/dist/async-debouncer/createAsyncDebouncer.d.cts +27 -2
  14. package/dist/async-debouncer/createAsyncDebouncer.d.ts +27 -2
  15. package/dist/async-debouncer/createAsyncDebouncer.js +26 -3
  16. package/dist/async-debouncer/createAsyncDebouncer.js.map +1 -1
  17. package/dist/async-debouncer/index.cjs +1 -0
  18. package/dist/async-debouncer/index.d.cts +2 -2
  19. package/dist/async-debouncer/index.d.ts +2 -2
  20. package/dist/async-queuer/createAsyncQueuer.cjs +32 -2
  21. package/dist/async-queuer/createAsyncQueuer.cjs.map +1 -1
  22. package/dist/async-queuer/createAsyncQueuer.d.cts +28 -2
  23. package/dist/async-queuer/createAsyncQueuer.d.ts +28 -2
  24. package/dist/async-queuer/createAsyncQueuer.js +32 -2
  25. package/dist/async-queuer/createAsyncQueuer.js.map +1 -1
  26. package/dist/async-queuer/index.cjs +1 -0
  27. package/dist/async-queuer/index.d.cts +2 -2
  28. package/dist/async-queuer/index.d.ts +2 -2
  29. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +16 -2
  30. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +1 -1
  31. package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +15 -2
  32. package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +15 -2
  33. package/dist/async-rate-limiter/createAsyncRateLimiter.js +16 -2
  34. package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +1 -1
  35. package/dist/async-rate-limiter/index.cjs +1 -0
  36. package/dist/async-rate-limiter/index.d.cts +2 -2
  37. package/dist/async-rate-limiter/index.d.ts +2 -2
  38. package/dist/async-throttler/createAsyncThrottler.cjs +31 -2
  39. package/dist/async-throttler/createAsyncThrottler.cjs.map +1 -1
  40. package/dist/async-throttler/createAsyncThrottler.d.cts +27 -2
  41. package/dist/async-throttler/createAsyncThrottler.d.ts +27 -2
  42. package/dist/async-throttler/createAsyncThrottler.js +31 -2
  43. package/dist/async-throttler/createAsyncThrottler.js.map +1 -1
  44. package/dist/async-throttler/index.cjs +1 -0
  45. package/dist/async-throttler/index.d.cts +2 -2
  46. package/dist/async-throttler/index.d.ts +2 -2
  47. package/dist/batcher/createBatcher.cjs +23 -2
  48. package/dist/batcher/createBatcher.cjs.map +1 -1
  49. package/dist/batcher/createBatcher.d.cts +22 -2
  50. package/dist/batcher/createBatcher.d.ts +22 -2
  51. package/dist/batcher/createBatcher.js +23 -2
  52. package/dist/batcher/createBatcher.js.map +1 -1
  53. package/dist/batcher/index.cjs +1 -0
  54. package/dist/batcher/index.d.cts +2 -2
  55. package/dist/batcher/index.d.ts +2 -2
  56. package/dist/debouncer/createDebouncedSignal.cjs.map +1 -1
  57. package/dist/debouncer/createDebouncedSignal.d.cts +3 -4
  58. package/dist/debouncer/createDebouncedSignal.d.ts +3 -4
  59. package/dist/debouncer/createDebouncedSignal.js.map +1 -1
  60. package/dist/debouncer/createDebouncedValue.cjs.map +1 -1
  61. package/dist/debouncer/createDebouncedValue.d.cts +3 -4
  62. package/dist/debouncer/createDebouncedValue.d.ts +3 -4
  63. package/dist/debouncer/createDebouncedValue.js.map +1 -1
  64. package/dist/debouncer/createDebouncer.cjs +17 -3
  65. package/dist/debouncer/createDebouncer.cjs.map +1 -1
  66. package/dist/debouncer/createDebouncer.d.cts +21 -2
  67. package/dist/debouncer/createDebouncer.d.ts +21 -2
  68. package/dist/debouncer/createDebouncer.js +17 -3
  69. package/dist/debouncer/createDebouncer.js.map +1 -1
  70. package/dist/debouncer/index.cjs +1 -0
  71. package/dist/debouncer/index.d.cts +2 -2
  72. package/dist/debouncer/index.d.ts +2 -2
  73. package/dist/index.cjs +1 -0
  74. package/dist/index.d.cts +11 -11
  75. package/dist/index.d.ts +11 -11
  76. package/dist/provider/index.cjs +1 -0
  77. package/dist/queuer/createQueuedSignal.cjs.map +1 -1
  78. package/dist/queuer/createQueuedSignal.d.cts +3 -4
  79. package/dist/queuer/createQueuedSignal.d.ts +3 -4
  80. package/dist/queuer/createQueuedSignal.js.map +1 -1
  81. package/dist/queuer/createQueuer.cjs +23 -2
  82. package/dist/queuer/createQueuer.cjs.map +1 -1
  83. package/dist/queuer/createQueuer.d.cts +22 -2
  84. package/dist/queuer/createQueuer.d.ts +22 -2
  85. package/dist/queuer/createQueuer.js +23 -2
  86. package/dist/queuer/createQueuer.js.map +1 -1
  87. package/dist/queuer/index.cjs +1 -0
  88. package/dist/queuer/index.d.cts +2 -2
  89. package/dist/queuer/index.d.ts +2 -2
  90. package/dist/rate-limiter/createRateLimitedSignal.cjs.map +1 -1
  91. package/dist/rate-limiter/createRateLimitedSignal.d.cts +3 -4
  92. package/dist/rate-limiter/createRateLimitedSignal.d.ts +3 -4
  93. package/dist/rate-limiter/createRateLimitedSignal.js.map +1 -1
  94. package/dist/rate-limiter/createRateLimitedValue.cjs.map +1 -1
  95. package/dist/rate-limiter/createRateLimitedValue.d.cts +3 -4
  96. package/dist/rate-limiter/createRateLimitedValue.d.ts +3 -4
  97. package/dist/rate-limiter/createRateLimitedValue.js.map +1 -1
  98. package/dist/rate-limiter/createRateLimiter.cjs +9 -2
  99. package/dist/rate-limiter/createRateLimiter.cjs.map +1 -1
  100. package/dist/rate-limiter/createRateLimiter.d.cts +9 -2
  101. package/dist/rate-limiter/createRateLimiter.d.ts +9 -2
  102. package/dist/rate-limiter/createRateLimiter.js +9 -2
  103. package/dist/rate-limiter/createRateLimiter.js.map +1 -1
  104. package/dist/rate-limiter/index.cjs +1 -0
  105. package/dist/rate-limiter/index.d.cts +2 -2
  106. package/dist/rate-limiter/index.d.ts +2 -2
  107. package/dist/throttler/createThrottledSignal.cjs.map +1 -1
  108. package/dist/throttler/createThrottledSignal.d.cts +3 -4
  109. package/dist/throttler/createThrottledSignal.d.ts +3 -4
  110. package/dist/throttler/createThrottledSignal.js.map +1 -1
  111. package/dist/throttler/createThrottledValue.cjs.map +1 -1
  112. package/dist/throttler/createThrottledValue.d.cts +3 -4
  113. package/dist/throttler/createThrottledValue.d.ts +3 -4
  114. package/dist/throttler/createThrottledValue.js.map +1 -1
  115. package/dist/throttler/createThrottler.cjs +17 -3
  116. package/dist/throttler/createThrottler.cjs.map +1 -1
  117. package/dist/throttler/createThrottler.d.cts +21 -2
  118. package/dist/throttler/createThrottler.d.ts +21 -2
  119. package/dist/throttler/createThrottler.js +17 -3
  120. package/dist/throttler/createThrottler.js.map +1 -1
  121. package/dist/throttler/index.cjs +1 -0
  122. package/dist/throttler/index.d.cts +2 -2
  123. package/dist/throttler/index.d.ts +2 -2
  124. package/package.json +33 -32
  125. package/src/async-batcher/createAsyncBatcher.ts +44 -3
  126. package/src/async-debouncer/createAsyncDebouncer.ts +37 -4
  127. package/src/async-queuer/createAsyncQueuer.ts +44 -3
  128. package/src/async-rate-limiter/createAsyncRateLimiter.ts +30 -3
  129. package/src/async-throttler/createAsyncThrottler.ts +43 -3
  130. package/src/batcher/createBatcher.ts +38 -3
  131. package/src/debouncer/createDebouncedSignal.ts +3 -6
  132. package/src/debouncer/createDebouncedValue.ts +3 -6
  133. package/src/debouncer/createDebouncer.ts +30 -4
  134. package/src/queuer/createQueuedSignal.ts +3 -3
  135. package/src/queuer/createQueuer.ts +37 -3
  136. package/src/rate-limiter/createRateLimitedSignal.ts +6 -6
  137. package/src/rate-limiter/createRateLimitedValue.ts +6 -6
  138. package/src/rate-limiter/createRateLimiter.ts +22 -3
  139. package/src/throttler/createThrottledSignal.ts +3 -6
  140. package/src/throttler/createThrottledValue.ts +3 -6
  141. package/src/throttler/createThrottler.ts +30 -4
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the rate limiter state.\n *\n * This is useful for tracking specific parts of the rate limiter state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (createSignal, etc).\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `rateLimiter.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to track execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track results when available (optimized for data display)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to track error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for stats display)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to track execution times changes (optimized for window calculations)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as AsyncRateLimiterOptions<TFn>\n\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncRateLimiter<TFn, TSelected>\n\n asyncRateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncRateLimiter.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,SAAgB,uBAId,IACA,SACA,kBACG,EAAE,GACkC;CAMvC,MAAM,mBAAmB,IAAI,iBAC3B,IANoB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,kBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,WAAW,SAAS,iBAAiB,OAAO,MAAM,SAAS;AAEjE,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,iBAAiB,OAAO,SAAS;AAExD,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncRateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: SolidAsyncRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the rate limiter state.\n *\n * This is useful for tracking specific parts of the rate limiter state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (createSignal, etc).\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `rateLimiter.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * ## Unmount behavior\n *\n * By default, the primitive aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to track execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track results when available (optimized for data display)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to track error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for stats display)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to track execution times changes (optimized for window calculations)\n * const asyncRateLimiter = createAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncRateLimiterOptions<TFn, TSelected>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as SolidAsyncRateLimiterOptions<TFn, TSelected>\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncRateLimiter<TFn, TSelected>\n\n asyncRateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncRateLimiter.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncRateLimiter)\n } else {\n asyncRateLimiter.abort()\n }\n })\n })\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2NA,SAAgB,uBAId,IACA,SACA,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,mBAAmB,IAAI,iBAC3B,IACA,cACD;AAED,kBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,WAAW,SAAS,iBAAiB,OAAO,MAAM,SAAS;AAEjE,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,iBAAiB,OAAO,SAAS;AAExD,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;IAE1B;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -1,3 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
2
  const require_createAsyncRateLimiter = require('./createAsyncRateLimiter.cjs');
2
3
 
3
4
  exports.createAsyncRateLimiter = require_createAsyncRateLimiter.createAsyncRateLimiter;
@@ -1,3 +1,3 @@
1
- import { SolidAsyncRateLimiter, createAsyncRateLimiter } from "./createAsyncRateLimiter.cjs";
1
+ import { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter } from "./createAsyncRateLimiter.cjs";
2
2
  export * from "@tanstack/pacer/async-rate-limiter";
3
- export { SolidAsyncRateLimiter, createAsyncRateLimiter };
3
+ export { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter };
@@ -1,3 +1,3 @@
1
- import { SolidAsyncRateLimiter, createAsyncRateLimiter } from "./createAsyncRateLimiter.js";
1
+ import { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter } from "./createAsyncRateLimiter.js";
2
2
  export * from "@tanstack/pacer/async-rate-limiter";
3
- export { SolidAsyncRateLimiter, createAsyncRateLimiter };
3
+ export { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter };
@@ -1,4 +1,5 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
+ let solid_js = require("solid-js");
2
3
  let _tanstack_solid_store = require("@tanstack/solid-store");
3
4
  let _tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler");
4
5
 
@@ -59,6 +60,24 @@ let _tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler")
59
60
  * - `nextExecutionTime`: Timestamp of the next allowed execution
60
61
  * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
61
62
  *
63
+ * ## Unmount behavior
64
+ *
65
+ * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
66
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
67
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
68
+ *
69
+ * ```tsx
70
+ * const throttler = createAsyncThrottler(fn, {
71
+ * wait: 1000,
72
+ * onUnmount: (t) => t.flush()
73
+ * });
74
+ * ```
75
+ *
76
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
77
+ * If your throttled function updates Solid signals, those updates may run after the component has
78
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
79
+ * using onUnmount with flush.
80
+ *
62
81
  * @example
63
82
  * ```tsx
64
83
  * // Default behavior - no reactive state subscriptions
@@ -102,15 +121,25 @@ let _tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler")
102
121
  * ```
103
122
  */
104
123
  function createAsyncThrottler(fn, options, selector = () => ({})) {
105
- const asyncThrottler = new _tanstack_pacer_async_throttler.AsyncThrottler(fn, {
124
+ const mergedOptions = {
106
125
  ...require_PacerProvider.useDefaultPacerOptions().asyncThrottler,
107
126
  ...options
108
- });
127
+ };
128
+ const asyncThrottler = new _tanstack_pacer_async_throttler.AsyncThrottler(fn, mergedOptions);
109
129
  asyncThrottler.Subscribe = function Subscribe(props) {
110
130
  const selected = (0, _tanstack_solid_store.useStore)(asyncThrottler.store, props.selector);
111
131
  return typeof props.children === "function" ? props.children(selected) : props.children;
112
132
  };
113
133
  const state = (0, _tanstack_solid_store.useStore)(asyncThrottler.store, selector);
134
+ (0, solid_js.createEffect)(() => {
135
+ (0, solid_js.onCleanup)(() => {
136
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncThrottler);
137
+ else {
138
+ asyncThrottler.cancel();
139
+ asyncThrottler.abort();
140
+ }
141
+ });
142
+ });
114
143
  return {
115
144
  ...asyncThrottler,
116
145
  state
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncThrottler.cjs","names":["AsyncThrottler","useDefaultPacerOptions"],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled 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 throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as AsyncThrottlerOptions<TFn>\n\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncThrottler.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CAMrC,MAAM,iBAAiB,IAAIA,+CACzB,IANoB;EACpB,GAAGC,8CAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,+CAAoB,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,eAAe,OAAO,SAAS;AAEtD,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler"],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { createEffect, onCleanup } from 'solid-js'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled 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 throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as SolidAsyncThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncThrottler.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncThrottler.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAIC,+CACzB,IACA,cACD;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,+CAAoB,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,eAAe,OAAO,SAAS;AAEtD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;IAExB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -4,6 +4,13 @@ import { AnyAsyncFunction } from "@tanstack/pacer/types";
4
4
  import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tanstack/pacer/async-throttler";
5
5
 
6
6
  //#region src/async-throttler/createAsyncThrottler.d.ts
7
+ interface SolidAsyncThrottlerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncThrottlerOptions<TFn> {
8
+ /**
9
+ * Optional callback invoked when the owning component unmounts. Receives the throttler instance.
10
+ * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
11
+ */
12
+ onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void;
13
+ }
7
14
  interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
8
15
  /**
9
16
  * A Solid component that allows you to subscribe to the throttler state.
@@ -91,6 +98,24 @@ interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
91
98
  * - `nextExecutionTime`: Timestamp of the next allowed execution
92
99
  * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
93
100
  *
101
+ * ## Unmount behavior
102
+ *
103
+ * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
104
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
105
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
106
+ *
107
+ * ```tsx
108
+ * const throttler = createAsyncThrottler(fn, {
109
+ * wait: 1000,
110
+ * onUnmount: (t) => t.flush()
111
+ * });
112
+ * ```
113
+ *
114
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
115
+ * If your throttled function updates Solid signals, those updates may run after the component has
116
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
117
+ * using onUnmount with flush.
118
+ *
94
119
  * @example
95
120
  * ```tsx
96
121
  * // Default behavior - no reactive state subscriptions
@@ -133,7 +158,7 @@ interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
133
158
  * const { isPending, isExecuting } = throttler.state();
134
159
  * ```
135
160
  */
136
- declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>;
161
+ declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncThrottlerOptions<TFn, TSelected>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>;
137
162
  //#endregion
138
- export { SolidAsyncThrottler, createAsyncThrottler };
163
+ export { SolidAsyncThrottler, SolidAsyncThrottlerOptions, createAsyncThrottler };
139
164
  //# sourceMappingURL=createAsyncThrottler.d.cts.map
@@ -4,6 +4,13 @@ import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tan
4
4
  import { AnyAsyncFunction } from "@tanstack/pacer/types";
5
5
 
6
6
  //#region src/async-throttler/createAsyncThrottler.d.ts
7
+ interface SolidAsyncThrottlerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncThrottlerOptions<TFn> {
8
+ /**
9
+ * Optional callback invoked when the owning component unmounts. Receives the throttler instance.
10
+ * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
11
+ */
12
+ onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void;
13
+ }
7
14
  interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
8
15
  /**
9
16
  * A Solid component that allows you to subscribe to the throttler state.
@@ -91,6 +98,24 @@ interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
91
98
  * - `nextExecutionTime`: Timestamp of the next allowed execution
92
99
  * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
93
100
  *
101
+ * ## Unmount behavior
102
+ *
103
+ * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
104
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
105
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
106
+ *
107
+ * ```tsx
108
+ * const throttler = createAsyncThrottler(fn, {
109
+ * wait: 1000,
110
+ * onUnmount: (t) => t.flush()
111
+ * });
112
+ * ```
113
+ *
114
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
115
+ * If your throttled function updates Solid signals, those updates may run after the component has
116
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
117
+ * using onUnmount with flush.
118
+ *
94
119
  * @example
95
120
  * ```tsx
96
121
  * // Default behavior - no reactive state subscriptions
@@ -133,7 +158,7 @@ interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
133
158
  * const { isPending, isExecuting } = throttler.state();
134
159
  * ```
135
160
  */
136
- declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>;
161
+ declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncThrottlerOptions<TFn, TSelected>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>;
137
162
  //#endregion
138
- export { SolidAsyncThrottler, createAsyncThrottler };
163
+ export { SolidAsyncThrottler, SolidAsyncThrottlerOptions, createAsyncThrottler };
139
164
  //# sourceMappingURL=createAsyncThrottler.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
2
+ import { createEffect, onCleanup } from "solid-js";
2
3
  import { useStore } from "@tanstack/solid-store";
3
4
  import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
4
5
 
@@ -59,6 +60,24 @@ import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
59
60
  * - `nextExecutionTime`: Timestamp of the next allowed execution
60
61
  * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
61
62
  *
63
+ * ## Unmount behavior
64
+ *
65
+ * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
66
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
67
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
68
+ *
69
+ * ```tsx
70
+ * const throttler = createAsyncThrottler(fn, {
71
+ * wait: 1000,
72
+ * onUnmount: (t) => t.flush()
73
+ * });
74
+ * ```
75
+ *
76
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
77
+ * If your throttled function updates Solid signals, those updates may run after the component has
78
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
79
+ * using onUnmount with flush.
80
+ *
62
81
  * @example
63
82
  * ```tsx
64
83
  * // Default behavior - no reactive state subscriptions
@@ -102,15 +121,25 @@ import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
102
121
  * ```
103
122
  */
104
123
  function createAsyncThrottler(fn, options, selector = () => ({})) {
105
- const asyncThrottler = new AsyncThrottler(fn, {
124
+ const mergedOptions = {
106
125
  ...useDefaultPacerOptions().asyncThrottler,
107
126
  ...options
108
- });
127
+ };
128
+ const asyncThrottler = new AsyncThrottler(fn, mergedOptions);
109
129
  asyncThrottler.Subscribe = function Subscribe(props) {
110
130
  const selected = useStore(asyncThrottler.store, props.selector);
111
131
  return typeof props.children === "function" ? props.children(selected) : props.children;
112
132
  };
113
133
  const state = useStore(asyncThrottler.store, selector);
134
+ createEffect(() => {
135
+ onCleanup(() => {
136
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncThrottler);
137
+ else {
138
+ asyncThrottler.cancel();
139
+ asyncThrottler.abort();
140
+ }
141
+ });
142
+ });
114
143
  return {
115
144
  ...asyncThrottler,
116
145
  state
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled 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 throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as AsyncThrottlerOptions<TFn>\n\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncThrottler.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CAMrC,MAAM,iBAAiB,IAAI,eACzB,IANoB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAEtD,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { createEffect, onCleanup } from 'solid-js'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled 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 throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as SolidAsyncThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncThrottler.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncThrottler.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAI,eACzB,IACA,cACD;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAEtD,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;IAExB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -1,3 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
2
  const require_createAsyncThrottler = require('./createAsyncThrottler.cjs');
2
3
 
3
4
  exports.createAsyncThrottler = require_createAsyncThrottler.createAsyncThrottler;
@@ -1,3 +1,3 @@
1
- import { SolidAsyncThrottler, createAsyncThrottler } from "./createAsyncThrottler.cjs";
1
+ import { SolidAsyncThrottler, SolidAsyncThrottlerOptions, createAsyncThrottler } from "./createAsyncThrottler.cjs";
2
2
  export * from "@tanstack/pacer/async-throttler";
3
- export { SolidAsyncThrottler, createAsyncThrottler };
3
+ export { SolidAsyncThrottler, SolidAsyncThrottlerOptions, createAsyncThrottler };
@@ -1,3 +1,3 @@
1
- import { SolidAsyncThrottler, createAsyncThrottler } from "./createAsyncThrottler.js";
1
+ import { SolidAsyncThrottler, SolidAsyncThrottlerOptions, createAsyncThrottler } from "./createAsyncThrottler.js";
2
2
  export * from "@tanstack/pacer/async-throttler";
3
- export { SolidAsyncThrottler, createAsyncThrottler };
3
+ export { SolidAsyncThrottler, SolidAsyncThrottlerOptions, createAsyncThrottler };
@@ -1,4 +1,5 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
+ let solid_js = require("solid-js");
2
3
  let _tanstack_solid_store = require("@tanstack/solid-store");
3
4
  let _tanstack_pacer_batcher = require("@tanstack/pacer/batcher");
4
5
 
@@ -45,6 +46,19 @@ let _tanstack_pacer_batcher = require("@tanstack/pacer/batcher");
45
46
  * - `items`: Array of items currently queued for batching
46
47
  * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches
47
48
  *
49
+ * ## Unmount behavior
50
+ *
51
+ * By default, the primitive cancels any pending batch when the owning component unmounts.
52
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
53
+ *
54
+ * ```tsx
55
+ * const batcher = createBatcher(fn, {
56
+ * maxSize: 10,
57
+ * wait: 2000,
58
+ * onUnmount: (b) => b.flush()
59
+ * });
60
+ * ```
61
+ *
48
62
  * Example usage:
49
63
  * ```tsx
50
64
  * // Default behavior - no reactive state subscriptions
@@ -91,15 +105,22 @@ let _tanstack_pacer_batcher = require("@tanstack/pacer/batcher");
91
105
  * ```
92
106
  */
93
107
  function createBatcher(fn, options = {}, selector = () => ({})) {
94
- const batcher = new _tanstack_pacer_batcher.Batcher(fn, {
108
+ const mergedOptions = {
95
109
  ...require_PacerProvider.useDefaultPacerOptions().batcher,
96
110
  ...options
97
- });
111
+ };
112
+ const batcher = new _tanstack_pacer_batcher.Batcher(fn, mergedOptions);
98
113
  batcher.Subscribe = function Subscribe(props) {
99
114
  const selected = (0, _tanstack_solid_store.useStore)(batcher.store, props.selector);
100
115
  return typeof props.children === "function" ? props.children(selected) : props.children;
101
116
  };
102
117
  const state = (0, _tanstack_solid_store.useStore)(batcher.store, selector);
118
+ (0, solid_js.createEffect)(() => {
119
+ (0, solid_js.onCleanup)(() => {
120
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(batcher);
121
+ else batcher.cancel();
122
+ });
123
+ });
103
124
  return {
104
125
  ...batcher,
105
126
  state
@@ -1 +1 @@
1
- {"version":3,"file":"createBatcher.cjs","names":["Batcher","useDefaultPacerOptions"],"sources":["../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as BatcherOptions<TValue>\n\n const batcher = new Batcher(fn, mergedOptions) as unknown as SolidBatcher<\n TValue,\n TSelected\n >\n\n batcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(batcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(batcher.store, selector)\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,SAAgB,cACd,IACA,UAAkC,EAAE,EACpC,kBACG,EAAE,GAC4B;CAMjC,MAAM,UAAU,IAAIA,gCAAQ,IALN;EACpB,GAAGC,8CAAwB,CAAC;EAC5B,GAAG;EACJ,CAE6C;AAK9C,SAAQ,YAAY,SAAS,UAAqB,OAG/C;EACD,MAAM,+CAAoB,QAAQ,OAAO,MAAM,SAAS;AAExD,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,QAAQ,OAAO,SAAS;AAC/C,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createBatcher.cjs","names":["useDefaultPacerOptions","Batcher"],"sources":["../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = createBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: SolidBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as SolidBatcherOptions<TValue, TSelected>\n const batcher = new Batcher(fn, mergedOptions) as unknown as SolidBatcher<\n TValue,\n TSelected\n >\n\n batcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(batcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(batcher.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n })\n })\n\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0JA,SAAgB,cACd,IACA,UAAkD,EAAE,EACpD,kBACG,EAAE,GAC4B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,UAAU,IAAIC,gCAAQ,IAAI,cAAc;AAK9C,SAAQ,YAAY,SAAS,UAAqB,OAG/C;EACD,MAAM,+CAAoB,QAAQ,OAAO,MAAM,SAAS;AAExD,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,QAAQ,OAAO,SAAS;AAE/C,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,QAAQ;OAEhC,SAAQ,QAAQ;IAElB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -3,6 +3,13 @@ import { Accessor, JSX } from "solid-js";
3
3
  import { Batcher, BatcherOptions, BatcherState } from "@tanstack/pacer/batcher";
4
4
 
5
5
  //#region src/batcher/createBatcher.d.ts
6
+ interface SolidBatcherOptions<TValue, TSelected = {}> extends BatcherOptions<TValue> {
7
+ /**
8
+ * Optional callback invoked when the owning component unmounts. Receives the batcher instance.
9
+ * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.
10
+ */
11
+ onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void;
12
+ }
6
13
  interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'store'> {
7
14
  /**
8
15
  * A Solid component that allows you to subscribe to the batcher state.
@@ -76,6 +83,19 @@ interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'st
76
83
  * - `items`: Array of items currently queued for batching
77
84
  * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches
78
85
  *
86
+ * ## Unmount behavior
87
+ *
88
+ * By default, the primitive cancels any pending batch when the owning component unmounts.
89
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
90
+ *
91
+ * ```tsx
92
+ * const batcher = createBatcher(fn, {
93
+ * maxSize: 10,
94
+ * wait: 2000,
95
+ * onUnmount: (b) => b.flush()
96
+ * });
97
+ * ```
98
+ *
79
99
  * Example usage:
80
100
  * ```tsx
81
101
  * // Default behavior - no reactive state subscriptions
@@ -121,7 +141,7 @@ interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'st
121
141
  * const { items, isRunning } = batcher.state();
122
142
  * ```
123
143
  */
124
- declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, options?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>;
144
+ declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, options?: SolidBatcherOptions<TValue, TSelected>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>;
125
145
  //#endregion
126
- export { SolidBatcher, createBatcher };
146
+ export { SolidBatcher, SolidBatcherOptions, createBatcher };
127
147
  //# sourceMappingURL=createBatcher.d.cts.map
@@ -3,6 +3,13 @@ import { Store } from "@tanstack/solid-store";
3
3
  import { Batcher, BatcherOptions, BatcherState } from "@tanstack/pacer/batcher";
4
4
 
5
5
  //#region src/batcher/createBatcher.d.ts
6
+ interface SolidBatcherOptions<TValue, TSelected = {}> extends BatcherOptions<TValue> {
7
+ /**
8
+ * Optional callback invoked when the owning component unmounts. Receives the batcher instance.
9
+ * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.
10
+ */
11
+ onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void;
12
+ }
6
13
  interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'store'> {
7
14
  /**
8
15
  * A Solid component that allows you to subscribe to the batcher state.
@@ -76,6 +83,19 @@ interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'st
76
83
  * - `items`: Array of items currently queued for batching
77
84
  * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches
78
85
  *
86
+ * ## Unmount behavior
87
+ *
88
+ * By default, the primitive cancels any pending batch when the owning component unmounts.
89
+ * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
90
+ *
91
+ * ```tsx
92
+ * const batcher = createBatcher(fn, {
93
+ * maxSize: 10,
94
+ * wait: 2000,
95
+ * onUnmount: (b) => b.flush()
96
+ * });
97
+ * ```
98
+ *
79
99
  * Example usage:
80
100
  * ```tsx
81
101
  * // Default behavior - no reactive state subscriptions
@@ -121,7 +141,7 @@ interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'st
121
141
  * const { items, isRunning } = batcher.state();
122
142
  * ```
123
143
  */
124
- declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, options?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>;
144
+ declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, options?: SolidBatcherOptions<TValue, TSelected>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>;
125
145
  //#endregion
126
- export { SolidBatcher, createBatcher };
146
+ export { SolidBatcher, SolidBatcherOptions, createBatcher };
127
147
  //# sourceMappingURL=createBatcher.d.ts.map