@tanstack/solid-pacer 0.20.1 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/async-batcher/createAsyncBatcher.cjs +2 -2
- package/dist/async-batcher/createAsyncBatcher.cjs.map +1 -1
- package/dist/async-batcher/createAsyncBatcher.d.cts +2 -2
- package/dist/async-batcher/createAsyncBatcher.d.ts +2 -2
- package/dist/async-batcher/createAsyncBatcher.js +3 -3
- package/dist/async-batcher/createAsyncBatcher.js.map +1 -1
- package/dist/async-debouncer/createAsyncDebouncer.cjs +2 -2
- package/dist/async-debouncer/createAsyncDebouncer.cjs.map +1 -1
- package/dist/async-debouncer/createAsyncDebouncer.d.cts +2 -2
- package/dist/async-debouncer/createAsyncDebouncer.d.ts +2 -2
- package/dist/async-debouncer/createAsyncDebouncer.js +3 -3
- package/dist/async-debouncer/createAsyncDebouncer.js.map +1 -1
- package/dist/async-queuer/createAsyncQueuer.cjs +2 -2
- package/dist/async-queuer/createAsyncQueuer.cjs.map +1 -1
- package/dist/async-queuer/createAsyncQueuer.d.cts +2 -2
- package/dist/async-queuer/createAsyncQueuer.d.ts +2 -2
- package/dist/async-queuer/createAsyncQueuer.js +3 -3
- package/dist/async-queuer/createAsyncQueuer.js.map +1 -1
- package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +2 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +1 -1
- package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +2 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +2 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.js +3 -3
- package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +1 -1
- package/dist/async-throttler/createAsyncThrottler.cjs +2 -2
- package/dist/async-throttler/createAsyncThrottler.cjs.map +1 -1
- package/dist/async-throttler/createAsyncThrottler.d.cts +2 -2
- package/dist/async-throttler/createAsyncThrottler.d.ts +2 -2
- package/dist/async-throttler/createAsyncThrottler.js +3 -3
- package/dist/async-throttler/createAsyncThrottler.js.map +1 -1
- package/dist/batcher/createBatcher.cjs +2 -2
- package/dist/batcher/createBatcher.cjs.map +1 -1
- package/dist/batcher/createBatcher.d.cts +2 -2
- package/dist/batcher/createBatcher.d.ts +2 -2
- package/dist/batcher/createBatcher.js +3 -3
- package/dist/batcher/createBatcher.js.map +1 -1
- package/dist/debouncer/createDebouncer.cjs +2 -2
- package/dist/debouncer/createDebouncer.cjs.map +1 -1
- package/dist/debouncer/createDebouncer.d.cts +2 -2
- package/dist/debouncer/createDebouncer.d.ts +2 -2
- package/dist/debouncer/createDebouncer.js +3 -3
- package/dist/debouncer/createDebouncer.js.map +1 -1
- package/dist/queuer/createQueuer.cjs +2 -2
- package/dist/queuer/createQueuer.cjs.map +1 -1
- package/dist/queuer/createQueuer.d.cts +2 -2
- package/dist/queuer/createQueuer.d.ts +2 -2
- package/dist/queuer/createQueuer.js +3 -3
- package/dist/queuer/createQueuer.js.map +1 -1
- package/dist/rate-limiter/createRateLimiter.cjs +2 -2
- package/dist/rate-limiter/createRateLimiter.cjs.map +1 -1
- package/dist/rate-limiter/createRateLimiter.d.cts +2 -2
- package/dist/rate-limiter/createRateLimiter.d.ts +2 -2
- package/dist/rate-limiter/createRateLimiter.js +3 -3
- package/dist/rate-limiter/createRateLimiter.js.map +1 -1
- package/dist/throttler/createThrottler.cjs +2 -2
- package/dist/throttler/createThrottler.cjs.map +1 -1
- package/dist/throttler/createThrottler.d.cts +2 -2
- package/dist/throttler/createThrottler.d.ts +2 -2
- package/dist/throttler/createThrottler.js +3 -3
- package/dist/throttler/createThrottler.js.map +1 -1
- package/package.json +4 -4
- package/src/async-batcher/createAsyncBatcher.ts +7 -5
- package/src/async-debouncer/createAsyncDebouncer.ts +9 -5
- package/src/async-queuer/createAsyncQueuer.ts +7 -5
- package/src/async-rate-limiter/createAsyncRateLimiter.ts +9 -5
- package/src/async-throttler/createAsyncThrottler.ts +9 -5
- package/src/batcher/createBatcher.ts +7 -5
- package/src/debouncer/createDebouncer.ts +9 -5
- package/src/queuer/createQueuer.ts +7 -5
- package/src/rate-limiter/createRateLimiter.ts +7 -5
- package/src/throttler/createThrottler.ts +9 -5
|
@@ -142,10 +142,10 @@ function createAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
142
142
|
};
|
|
143
143
|
const asyncBatcher = new _tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions);
|
|
144
144
|
asyncBatcher.Subscribe = function Subscribe(props) {
|
|
145
|
-
const selected = (0, _tanstack_solid_store.
|
|
145
|
+
const selected = (0, _tanstack_solid_store.useSelector)(asyncBatcher.store, props.selector, { compare: _tanstack_solid_store.shallow });
|
|
146
146
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
147
147
|
};
|
|
148
|
-
const state = (0, _tanstack_solid_store.
|
|
148
|
+
const state = (0, _tanstack_solid_store.useSelector)(asyncBatcher.store, selector, { compare: _tanstack_solid_store.shallow });
|
|
149
149
|
(0, solid_js.createEffect)(() => {
|
|
150
150
|
(0, solid_js.onCleanup)(() => {
|
|
151
151
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncBatcher);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher"],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-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 {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<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<AsyncBatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\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 (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher 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 `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 * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch 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 batcher = createAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch 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 usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: SolidAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as SolidAsyncBatcherOptions<TValue, TSelected>\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncBatcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncBatcher.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n })\n })\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,SAAgB,mBACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,eAAe,IAAIC,2CACvB,IACA,cACD;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,+CAAoB,aAAa,OAAO,MAAM,SAAS;AAE7D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,aAAa,OAAO,SAAS;AAEpD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;IAEtB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
1
|
+
{"version":3,"file":"createAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher","shallow"],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { shallow, useSelector } 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 {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\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 (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher 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 `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 * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch 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 batcher = createAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch 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 usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: SolidAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as SolidAsyncBatcherOptions<TValue, TSelected>\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncBatcher.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncBatcher.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n })\n })\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,SAAgB,mBACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,eAAe,IAAIC,2CACvB,IACA,cACD;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,kDAAuB,aAAa,OAAO,MAAM,UAAU,EAC/D,SAASC,+BACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,aAAa,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;AAE7E,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;IAEtB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -36,8 +36,8 @@ interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
|
|
|
36
36
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
37
37
|
/**
|
|
38
38
|
* @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
40
|
-
* Although, you can make the state reactive by using the `
|
|
39
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
41
|
*/
|
|
42
42
|
readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;
|
|
43
43
|
}
|
|
@@ -36,8 +36,8 @@ interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
|
|
|
36
36
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
37
37
|
/**
|
|
38
38
|
* @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
40
|
-
* Although, you can make the state reactive by using the `
|
|
39
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
41
|
*/
|
|
42
42
|
readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;
|
|
43
43
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { createEffect, onCleanup } from "solid-js";
|
|
3
3
|
import { AsyncBatcher } from "@tanstack/pacer/async-batcher";
|
|
4
|
-
import {
|
|
4
|
+
import { shallow, useSelector } from "@tanstack/solid-store";
|
|
5
5
|
|
|
6
6
|
//#region src/async-batcher/createAsyncBatcher.ts
|
|
7
7
|
/**
|
|
@@ -142,10 +142,10 @@ function createAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
142
142
|
};
|
|
143
143
|
const asyncBatcher = new AsyncBatcher(fn, mergedOptions);
|
|
144
144
|
asyncBatcher.Subscribe = function Subscribe(props) {
|
|
145
|
-
const selected =
|
|
145
|
+
const selected = useSelector(asyncBatcher.store, props.selector, { compare: shallow });
|
|
146
146
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
147
147
|
};
|
|
148
|
-
const state =
|
|
148
|
+
const state = useSelector(asyncBatcher.store, selector, { compare: shallow });
|
|
149
149
|
createEffect(() => {
|
|
150
150
|
onCleanup(() => {
|
|
151
151
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncBatcher);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-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 {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<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<AsyncBatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\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 (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher 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 `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 * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch 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 batcher = createAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch 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 usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: SolidAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as SolidAsyncBatcherOptions<TValue, TSelected>\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncBatcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncBatcher.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n })\n })\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,SAAgB,mBACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,eAAe,IAAI,aACvB,IACA,cACD;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,WAAW,SAAS,aAAa,OAAO,MAAM,SAAS;AAE7D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,aAAa,OAAO,SAAS;AAEpD,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;IAEtB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
1
|
+
{"version":3,"file":"createAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { shallow, useSelector } 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 {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\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 (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher 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 AsyncBatcher 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 `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 * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch 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 batcher = createAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch 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 usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: SolidAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as SolidAsyncBatcherOptions<TValue, TSelected>\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncBatcher.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncBatcher.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n })\n })\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,SAAgB,mBACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,eAAe,IAAI,aACvB,IACA,cACD;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,WAAW,YAAY,aAAa,OAAO,MAAM,UAAU,EAC/D,SAAS,SACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,aAAa,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;AAE7E,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;IAEtB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -127,10 +127,10 @@ function createAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
127
127
|
};
|
|
128
128
|
const asyncDebouncer = new _tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions);
|
|
129
129
|
asyncDebouncer.Subscribe = function Subscribe(props) {
|
|
130
|
-
const selected = (0, _tanstack_solid_store.
|
|
130
|
+
const selected = (0, _tanstack_solid_store.useSelector)(asyncDebouncer.store, props.selector, { compare: _tanstack_solid_store.shallow });
|
|
131
131
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
132
132
|
};
|
|
133
|
-
const state = (0, _tanstack_solid_store.
|
|
133
|
+
const state = (0, _tanstack_solid_store.useSelector)(asyncDebouncer.store, selector, { compare: _tanstack_solid_store.shallow });
|
|
134
134
|
(0, solid_js.createEffect)(() => {
|
|
135
135
|
(0, solid_js.onCleanup)(() => {
|
|
136
136
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer"],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\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 {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer 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 `debouncer.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 debouncer can execute on the leading 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 debouncer 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 * - `lastResult`: The result from the most recent successful 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 debouncer = createAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced 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 } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\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 } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as SolidAsyncDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncDebouncer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\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"}
|
|
1
|
+
{"version":3,"file":"createAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer","shallow"],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useSelector } 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 {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer 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 `debouncer.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 debouncer can execute on the leading 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 debouncer 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 * - `lastResult`: The result from the most recent successful 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 debouncer = createAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced 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 } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\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 } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as SolidAsyncDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncDebouncer.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncDebouncer.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\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,kDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,+BACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;AAEF,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"}
|
|
@@ -37,8 +37,8 @@ interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> exte
|
|
|
37
37
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.
|
|
40
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
40
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
41
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
42
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
|
|
44
44
|
}
|
|
@@ -37,8 +37,8 @@ interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> exte
|
|
|
37
37
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.
|
|
40
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
40
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
41
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
42
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
|
|
44
44
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { createEffect, onCleanup } from "solid-js";
|
|
3
|
-
import {
|
|
3
|
+
import { shallow, useSelector } from "@tanstack/solid-store";
|
|
4
4
|
import { AsyncDebouncer } from "@tanstack/pacer/async-debouncer";
|
|
5
5
|
|
|
6
6
|
//#region src/async-debouncer/createAsyncDebouncer.ts
|
|
@@ -127,10 +127,10 @@ function createAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
127
127
|
};
|
|
128
128
|
const asyncDebouncer = new AsyncDebouncer(fn, mergedOptions);
|
|
129
129
|
asyncDebouncer.Subscribe = function Subscribe(props) {
|
|
130
|
-
const selected =
|
|
130
|
+
const selected = useSelector(asyncDebouncer.store, props.selector, { compare: shallow });
|
|
131
131
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
132
132
|
};
|
|
133
|
-
const state =
|
|
133
|
+
const state = useSelector(asyncDebouncer.store, selector, { compare: shallow });
|
|
134
134
|
createEffect(() => {
|
|
135
135
|
onCleanup(() => {
|
|
136
136
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\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 {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer 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 `debouncer.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 debouncer can execute on the leading 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 debouncer 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 * - `lastResult`: The result from the most recent successful 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 debouncer = createAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced 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 } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\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 } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as SolidAsyncDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncDebouncer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\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
|
+
{"version":3,"file":"createAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useSelector } 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 {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer 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 `debouncer.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 debouncer can execute on the leading 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 debouncer 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 * - `lastResult`: The result from the most recent successful 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 debouncer = createAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced 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 } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\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 } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as SolidAsyncDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncDebouncer.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncDebouncer.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\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,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;AAEF,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"}
|
|
@@ -134,10 +134,10 @@ function createAsyncQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
134
134
|
};
|
|
135
135
|
const asyncQueuer = new _tanstack_pacer_async_queuer.AsyncQueuer(fn, mergedOptions);
|
|
136
136
|
asyncQueuer.Subscribe = function Subscribe(props) {
|
|
137
|
-
const selected = (0, _tanstack_solid_store.
|
|
137
|
+
const selected = (0, _tanstack_solid_store.useSelector)(asyncQueuer.store, props.selector, { compare: _tanstack_solid_store.shallow });
|
|
138
138
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
139
139
|
};
|
|
140
|
-
const state = (0, _tanstack_solid_store.
|
|
140
|
+
const state = (0, _tanstack_solid_store.useSelector)(asyncQueuer.store, selector, { compare: _tanstack_solid_store.shallow });
|
|
141
141
|
(0, solid_js.createEffect)(() => {
|
|
142
142
|
(0, solid_js.onCleanup)(() => {
|
|
143
143
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncQueuer);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncQueuer.cjs","names":["useDefaultPacerOptions","AsyncQueuer"],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport {
|
|
1
|
+
{"version":3,"file":"createAsyncQueuer.cjs","names":["useDefaultPacerOptions","AsyncQueuer","shallow"],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { shallow, useSelector } 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 {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the queuer state.\n *\n * This is useful for tracking specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>\n * {(state) => (\n * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncQueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Priority queueing via `getPriority` or item `priority` property\n * - Configurable concurrency limit\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume processing\n * - Task cancellation\n * - Item expiration\n * - Lifecycle callbacks for success, error, settled, items change, etc.\n * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer 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 `queuer.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 * - `activeItems`: Array of items currently being processed\n * - `errorCount`: Number of items that failed processing\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `pendingItems`: Array of items waiting to be processed\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n * - `settleCount`: Number of items that have completed processing (successful or failed)\n * - `successCount`: Number of items that were processed successfully\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer and aborts any in-flight task executions 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 items instead:\n *\n * ```tsx\n * const queuer = createAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task 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 usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = createAsyncQueuer(async (item) => {\n * // process item\n * return await fetchData(item);\n * }, {\n * initialItems: [],\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * });\n *\n * // Opt-in to track queue state changes (optimized for UI updates)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * pendingItems: state.pendingItems,\n * activeItems: state.activeItems,\n * isRunning: state.isRunning\n * })\n * );\n *\n * // Opt-in to track processing metrics changes (optimized for tracking progress)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { pendingItems, activeItems } = asyncQueuer.state();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: SolidAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as SolidAsyncQueuerOptions<TValue, TSelected>\n const asyncQueuer = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncQueuer<TValue, TSelected>\n\n asyncQueuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncQueuer.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncQueuer.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n })\n })\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoLA,SAAgB,kBACd,IACA,UAAsD,EAAE,EACxD,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,cAAc,IAAIC,yCACtB,IACA,cACD;AAED,aAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,kDAAuB,YAAY,OAAO,MAAM,UAAU,EAC9D,SAASC,+BACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,YAAY,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;AAE5E,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;IAErB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -36,8 +36,8 @@ interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TVal
|
|
|
36
36
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
37
37
|
/**
|
|
38
38
|
* @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
40
|
-
* Although, you can make the state reactive by using the `
|
|
39
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
41
|
*/
|
|
42
42
|
readonly store: Store<Readonly<AsyncQueuerState<TValue>>>;
|
|
43
43
|
}
|
|
@@ -36,8 +36,8 @@ interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TVal
|
|
|
36
36
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
37
37
|
/**
|
|
38
38
|
* @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
40
|
-
* Although, you can make the state reactive by using the `
|
|
39
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
41
|
*/
|
|
42
42
|
readonly store: Store<Readonly<AsyncQueuerState<TValue>>>;
|
|
43
43
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
2
|
import { createEffect, onCleanup } from "solid-js";
|
|
3
|
-
import {
|
|
3
|
+
import { shallow, useSelector } from "@tanstack/solid-store";
|
|
4
4
|
import { AsyncQueuer } from "@tanstack/pacer/async-queuer";
|
|
5
5
|
|
|
6
6
|
//#region src/async-queuer/createAsyncQueuer.ts
|
|
@@ -134,10 +134,10 @@ function createAsyncQueuer(fn, options = {}, selector = () => ({})) {
|
|
|
134
134
|
};
|
|
135
135
|
const asyncQueuer = new AsyncQueuer(fn, mergedOptions);
|
|
136
136
|
asyncQueuer.Subscribe = function Subscribe(props) {
|
|
137
|
-
const selected =
|
|
137
|
+
const selected = useSelector(asyncQueuer.store, props.selector, { compare: shallow });
|
|
138
138
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
139
139
|
};
|
|
140
|
-
const state =
|
|
140
|
+
const state = useSelector(asyncQueuer.store, selector, { compare: shallow });
|
|
141
141
|
createEffect(() => {
|
|
142
142
|
onCleanup(() => {
|
|
143
143
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncQueuer);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport {
|
|
1
|
+
{"version":3,"file":"createAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { shallow, useSelector } 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 {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the queuer state.\n *\n * This is useful for tracking specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>\n * {(state) => (\n * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncQueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Priority queueing via `getPriority` or item `priority` property\n * - Configurable concurrency limit\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume processing\n * - Task cancellation\n * - Item expiration\n * - Lifecycle callbacks for success, error, settled, items change, etc.\n * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer 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 `queuer.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 * - `activeItems`: Array of items currently being processed\n * - `errorCount`: Number of items that failed processing\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `pendingItems`: Array of items waiting to be processed\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n * - `settleCount`: Number of items that have completed processing (successful or failed)\n * - `successCount`: Number of items that were processed successfully\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer and aborts any in-flight task executions 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 items instead:\n *\n * ```tsx\n * const queuer = createAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task 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 usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = createAsyncQueuer(async (item) => {\n * // process item\n * return await fetchData(item);\n * }, {\n * initialItems: [],\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * });\n *\n * // Opt-in to track queue state changes (optimized for UI updates)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * pendingItems: state.pendingItems,\n * activeItems: state.activeItems,\n * isRunning: state.isRunning\n * })\n * );\n *\n * // Opt-in to track processing metrics changes (optimized for tracking progress)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { pendingItems, activeItems } = asyncQueuer.state();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: SolidAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as SolidAsyncQueuerOptions<TValue, TSelected>\n const asyncQueuer = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncQueuer<TValue, TSelected>\n\n asyncQueuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncQueuer.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncQueuer.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n })\n })\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoLA,SAAgB,kBACd,IACA,UAAsD,EAAE,EACxD,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,cAAc,IAAI,YACtB,IACA,cACD;AAED,aAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,YAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAAS,SACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;AAE5E,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;IAErB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -172,10 +172,10 @@ function createAsyncRateLimiter(fn, options, selector = () => ({})) {
|
|
|
172
172
|
};
|
|
173
173
|
const asyncRateLimiter = new _tanstack_pacer_async_rate_limiter.AsyncRateLimiter(fn, mergedOptions);
|
|
174
174
|
asyncRateLimiter.Subscribe = function Subscribe(props) {
|
|
175
|
-
const selected = (0, _tanstack_solid_store.
|
|
175
|
+
const selected = (0, _tanstack_solid_store.useSelector)(asyncRateLimiter.store, props.selector, { compare: _tanstack_solid_store.shallow });
|
|
176
176
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
177
177
|
};
|
|
178
|
-
const state = (0, _tanstack_solid_store.
|
|
178
|
+
const state = (0, _tanstack_solid_store.useSelector)(asyncRateLimiter.store, selector, { compare: _tanstack_solid_store.shallow });
|
|
179
179
|
(0, solid_js.createEffect)(() => {
|
|
180
180
|
(0, solid_js.onCleanup)(() => {
|
|
181
181
|
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncRateLimiter);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter"],"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,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,mBAAmB,IAAIC,oDAC3B,IACA,cACD;AAED,kBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,+CAAoB,iBAAiB,OAAO,MAAM,SAAS;AAEjE,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,iBAAiB,OAAO,SAAS;AAExD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;IAE1B;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
1
|
+
{"version":3,"file":"createAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter","shallow"],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { shallow, useSelector } 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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` 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 = useSelector(asyncRateLimiter.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncRateLimiter.store, selector, {\n compare: shallow,\n })\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,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,mBAAmB,IAAIC,oDAC3B,IACA,cACD;AAED,kBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,kDAAuB,iBAAiB,OAAO,MAAM,UAAU,EACnE,SAASC,+BACV,CAAC;AAEF,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,iBAAiB,OAAO,UAAU,EAC1D,SAASA,+BACV,CAAC;AAEF,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;IAE1B;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -37,8 +37,8 @@ interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> ex
|
|
|
37
37
|
readonly state: Accessor<Readonly<TSelected>>;
|
|
38
38
|
/**
|
|
39
39
|
* @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
|
|
40
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `
|
|
41
|
-
* Although, you can make the state reactive by using the `
|
|
40
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
41
|
+
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
42
42
|
*/
|
|
43
43
|
readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
|
|
44
44
|
}
|