@tanstack/solid-pacer
Advanced tools
@@ -1,1 +0,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;CAED,aAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,kDAAuB,aAAa,OAAO,MAAM,UAAU,EAC/D,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,aAAa,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;CAE7E,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,aAAa;QAChC;IACL,aAAa,QAAQ;IACrB,aAAa,OAAO;;IAEtB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher","useSelector","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,CAAC,GACxD,kBACG,CAAC,IACkC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,eAAe,IAAIC,2CACvB,IACA,aACF;CAEA,aAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,eAAWC,mCAAY,aAAa,OAAO,MAAM,UAAU,EAC/D,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,aAAa,OAAO,UAAU,EAAE,SAASC,8BAAQ,CAAC;CAE5E,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;QAC/B;IACL,aAAa,OAAO;IACpB,aAAa,MAAM;GACrB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
| import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/pacer/async-batcher"; | ||
| import { Store } from "@tanstack/solid-store"; | ||
| import { Accessor, JSX } from "solid-js"; | ||
| //#region src/async-batcher/createAsyncBatcher.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidAsyncBatcherOptions<TValue, TSelected = {}> extends AsyncBatcherOptions<TValue> { |
| import { Accessor, JSX } from "solid-js"; | ||
| import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/pacer/async-batcher"; | ||
| import { Store } from "@tanstack/solid-store"; | ||
| //#region src/async-batcher/createAsyncBatcher.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidAsyncBatcherOptions<TValue, TSelected = {}> extends AsyncBatcherOptions<TValue> { |
@@ -1,1 +0,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;CAED,aAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,WAAW,YAAY,aAAa,OAAO,MAAM,UAAU,EAC/D,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,aAAa,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAE7E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,aAAa;QAChC;IACL,aAAa,QAAQ;IACrB,aAAa,OAAO;;IAEtB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"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,CAAC,GACxD,kBACG,CAAC,IACkC;CACtC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,eAAe,IAAI,aACvB,IACA,aACF;CAEA,aAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,WAAW,YAAY,aAAa,OAAO,MAAM,UAAU,EAC/D,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,aAAa,OAAO,UAAU,EAAE,SAAS,QAAQ,CAAC;CAE5E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;QAC/B;IACL,aAAa,OAAO;IACpB,aAAa,MAAM;GACrB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,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;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,kDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAClC;IACL,eAAe,QAAQ;IACvB,eAAe,OAAO;;IAExB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer","useSelector","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,CAAC,IACiC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAIC,+CACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,eAAWC,mCAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,eAAe,OAAO,UAAU,EACxD,SAASC,8BACX,CAAC;CAED,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QACjC;IACL,eAAe,OAAO;IACtB,eAAe,MAAM;GACvB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -5,3 +5,2 @@ import { Store } from "@tanstack/solid-store"; | ||
| import { AnyAsyncFunction } from "@tanstack/pacer/types"; | ||
| //#region src/async-debouncer/createAsyncDebouncer.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidAsyncDebouncerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncDebouncerOptions<TFn> { |
@@ -5,3 +5,2 @@ import { Accessor, JSX } from "solid-js"; | ||
| import { AnyAsyncFunction } from "@tanstack/pacer/types"; | ||
| //#region src/async-debouncer/createAsyncDebouncer.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidAsyncDebouncerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncDebouncerOptions<TFn> { |
@@ -1,1 +0,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;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;CAEF,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAClC;IACL,eAAe,QAAQ;IACvB,eAAe,OAAO;;IAExB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"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,CAAC,IACiC;CACrC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAI,eACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,QACX,CAAC;CAED,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QACjC;IACL,eAAe,OAAO;IACtB,eAAe,MAAM;GACvB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,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;CAED,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,kDAAuB,YAAY,OAAO,MAAM,UAAU,EAC9D,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,YAAY,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;CAE5E,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;QAC/B;IACL,YAAY,MAAM;IAClB,YAAY,OAAO;;IAErB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncQueuer.cjs","names":["useDefaultPacerOptions","AsyncQueuer","useSelector","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,CAAC,GACvD,kBACG,CAAC,IACiC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,cAAc,IAAIC,yCACtB,IACA,aACF;CAEA,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,eAAWC,mCAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,YAAY,OAAO,UAAU,EAAE,SAASC,8BAAQ,CAAC;CAE3E,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,WAAW;QAC9B;IACL,YAAY,KAAK;IACjB,YAAY,MAAM;GACpB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
| import { Store } from "@tanstack/solid-store"; | ||
| import { Accessor, JSX } from "solid-js"; | ||
| import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from "@tanstack/pacer/async-queuer"; | ||
| //#region src/async-queuer/createAsyncQueuer.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidAsyncQueuerOptions<TValue, TSelected = {}> extends AsyncQueuerOptions<TValue> { |
| import { Accessor, JSX } from "solid-js"; | ||
| import { Store } from "@tanstack/solid-store"; | ||
| import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from "@tanstack/pacer/async-queuer"; | ||
| //#region src/async-queuer/createAsyncQueuer.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidAsyncQueuerOptions<TValue, TSelected = {}> extends AsyncQueuerOptions<TValue> { |
@@ -1,1 +0,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;CAED,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,YAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAE5E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;QAC/B;IACL,YAAY,MAAM;IAClB,YAAY,OAAO;;IAErB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"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,CAAC,GACvD,kBACG,CAAC,IACiC;CACrC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,cAAc,IAAI,YACtB,IACA,aACF;CAEA,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,YAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,QAAQ,CAAC;CAE3E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,WAAW;QAC9B;IACL,YAAY,KAAK;IACjB,YAAY,MAAM;GACpB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,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;CAED,iBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,kDAAuB,iBAAiB,OAAO,MAAM,UAAU,EACnE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,iBAAiB,OAAO,UAAU,EAC1D,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,iBAAiB;QAEzC,iBAAiB,OAAO;IAE1B;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter","useSelector","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,CAAC,IACmC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,mBAAmB,IAAIC,oDAC3B,IACA,aACF;CAEA,iBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,eAAWC,mCAAY,iBAAiB,OAAO,MAAM,UAAU,EACnE,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,iBAAiB,OAAO,UAAU,EAC1D,SAASC,8BACX,CAAC;CAED,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,gBAAgB;QAExC,iBAAiB,MAAM;EAE3B,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -5,3 +5,2 @@ import { Store } from "@tanstack/solid-store"; | ||
| import { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState } from "@tanstack/pacer/async-rate-limiter"; | ||
| //#region src/async-rate-limiter/createAsyncRateLimiter.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidAsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncRateLimiterOptions<TFn> { |
@@ -5,3 +5,2 @@ import { Accessor, JSX } from "solid-js"; | ||
| import { AnyAsyncFunction } from "@tanstack/pacer/types"; | ||
| //#region src/async-rate-limiter/createAsyncRateLimiter.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidAsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncRateLimiterOptions<TFn> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { 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,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,mBAAmB,IAAI,iBAC3B,IACA,cACD;CAED,iBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,WAAW,YAAY,iBAAiB,OAAO,MAAM,UAAU,EACnE,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,iBAAiB,OAAO,UAAU,EAC1D,SAAS,SACV,CAAC;CAEF,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,iBAAiB;QAEzC,iBAAiB,OAAO;IAE1B;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { 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,CAAC,IACmC;CACvC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,mBAAmB,IAAI,iBAC3B,IACA,aACF;CAEA,iBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,WAAW,YAAY,iBAAiB,OAAO,MAAM,UAAU,EACnE,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,iBAAiB,OAAO,UAAU,EAC1D,SAAS,QACX,CAAC;CAED,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,gBAAgB;QAExC,iBAAiB,MAAM;EAE3B,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler","shallow"],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { createEffect, onCleanup } from 'solid-js'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\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 AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as SolidAsyncThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAIC,+CACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,kDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAClC;IACL,eAAe,QAAQ;IACvB,eAAe,OAAO;;IAExB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler","useSelector","shallow"],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { createEffect, onCleanup } from 'solid-js'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\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 AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as SolidAsyncThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,CAAC,IACiC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAIC,+CACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,eAAWC,mCAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,eAAe,OAAO,UAAU,EACxD,SAASC,8BACX,CAAC;CAED,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QACjC;IACL,eAAe,OAAO;IACtB,eAAe,MAAM;GACvB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -5,3 +5,2 @@ import { Store } from "@tanstack/solid-store"; | ||
| import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tanstack/pacer/async-throttler"; | ||
| //#region src/async-throttler/createAsyncThrottler.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidAsyncThrottlerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncThrottlerOptions<TFn> { |
@@ -5,3 +5,2 @@ import { Accessor, JSX } from "solid-js"; | ||
| import { AnyAsyncFunction } from "@tanstack/pacer/types"; | ||
| //#region src/async-throttler/createAsyncThrottler.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidAsyncThrottlerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncThrottlerOptions<TFn> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { createEffect, onCleanup } from 'solid-js'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { 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 AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as SolidAsyncThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAI,eACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;CAEF,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAClC;IACL,eAAe,QAAQ;IACvB,eAAe,OAAO;;IAExB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { createEffect, onCleanup } from 'solid-js'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { 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 AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { wait: 2000 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const throttler = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = throttler.state();\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as SolidAsyncThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new AsyncThrottler(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,CAAC,IACiC;CACrC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAI,eACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,QACX,CAAC;CAED,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QACjC;IACL,eAAe,OAAO;IACtB,eAAe,MAAM;GACvB;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createBatcher.cjs","names":["useDefaultPacerOptions","Batcher","shallow"],"sources":["../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/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 { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = createBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: SolidBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as SolidBatcherOptions<TValue, TSelected>\n const batcher = new Batcher(fn, mergedOptions) as unknown as SolidBatcher<\n TValue,\n TSelected\n >\n\n batcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(batcher.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(batcher.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n })\n })\n\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0JA,SAAgB,cACd,IACA,UAAkD,EAAE,EACpD,kBACG,EAAE,GAC4B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,UAAU,IAAIC,gCAAQ,IAAI,cAAc;CAK9C,QAAQ,YAAY,SAAS,UAAqB,OAG/C;EACD,MAAM,kDAAuB,QAAQ,OAAO,MAAM,UAAU,EAC1D,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,QAAQ,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;CAExE,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,QAAQ;QAEhC,QAAQ,QAAQ;IAElB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createBatcher.cjs","names":["useDefaultPacerOptions","Batcher","useSelector","shallow"],"sources":["../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/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 { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = createBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: SolidBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as SolidBatcherOptions<TValue, TSelected>\n const batcher = new Batcher(fn, mergedOptions) as unknown as SolidBatcher<\n TValue,\n TSelected\n >\n\n batcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(batcher.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(batcher.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n })\n })\n\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0JA,SAAgB,cACd,IACA,UAAkD,CAAC,GACnD,kBACG,CAAC,IAC6B;CACjC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,UAAU,IAAIC,gCAAQ,IAAI,aAAa;CAK7C,QAAQ,YAAY,SAAS,UAAqB,OAG/C;EACD,MAAM,eAAWC,mCAAY,QAAQ,OAAO,MAAM,UAAU,EAC1D,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,QAAQ,OAAO,UAAU,EAAE,SAASC,8BAAQ,CAAC;CAEvE,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,OAAO;QAE/B,QAAQ,OAAO;EAEnB,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
| import { Store } from "@tanstack/solid-store"; | ||
| import { Accessor, JSX } from "solid-js"; | ||
| import { Batcher, BatcherOptions, BatcherState } from "@tanstack/pacer/batcher"; | ||
| //#region src/batcher/createBatcher.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidBatcherOptions<TValue, TSelected = {}> extends BatcherOptions<TValue> { |
| import { Accessor, JSX } from "solid-js"; | ||
| import { Store } from "@tanstack/solid-store"; | ||
| import { Batcher, BatcherOptions, BatcherState } from "@tanstack/pacer/batcher"; | ||
| //#region src/batcher/createBatcher.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidBatcherOptions<TValue, TSelected = {}> extends BatcherOptions<TValue> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createBatcher.js","names":[],"sources":["../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/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 { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = createBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: SolidBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as SolidBatcherOptions<TValue, TSelected>\n const batcher = new Batcher(fn, mergedOptions) as unknown as SolidBatcher<\n TValue,\n TSelected\n >\n\n batcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(batcher.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(batcher.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n })\n })\n\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0JA,SAAgB,cACd,IACA,UAAkD,EAAE,EACpD,kBACG,EAAE,GAC4B;CACjC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,UAAU,IAAI,QAAQ,IAAI,cAAc;CAK9C,QAAQ,YAAY,SAAS,UAAqB,OAG/C;EACD,MAAM,WAAW,YAAY,QAAQ,OAAO,MAAM,UAAU,EAC1D,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,QAAQ,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAExE,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,QAAQ;QAEhC,QAAQ,QAAQ;IAElB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createBatcher.js","names":[],"sources":["../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/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 { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: SolidBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = createBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const batcher = createBatcher(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Add items to batch\n * batcher.addItem('task1');\n * batcher.addItem('task2');\n *\n * // Control the batcher\n * batcher.stop(); // Pause processing\n * batcher.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = batcher.state();\n * ```\n */\nexport function createBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: SolidBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as SolidBatcherOptions<TValue, TSelected>\n const batcher = new Batcher(fn, mergedOptions) as unknown as SolidBatcher<\n TValue,\n TSelected\n >\n\n batcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(batcher.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(batcher.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n })\n })\n\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0JA,SAAgB,cACd,IACA,UAAkD,CAAC,GACnD,kBACG,CAAC,IAC6B;CACjC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,UAAU,IAAI,QAAQ,IAAI,aAAa;CAK7C,QAAQ,YAAY,SAAS,UAAqB,OAG/C;EACD,MAAM,WAAW,YAAY,QAAQ,OAAO,MAAM,UAAU,EAC1D,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,QAAQ,OAAO,UAAU,EAAE,SAAS,QAAQ,CAAC;CAEvE,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,OAAO;QAE/B,QAAQ,OAAO;EAEnB,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedSignal.cjs","names":["createDebouncer"],"sources":["../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced state value, combining Solid's createSignal with debouncing functionality.\n * This hook provides both the current debounced value and methods to update it.\n *\n * The state value is only updated after the specified wait time has elapsed since the last update attempt.\n * If another update is attempted before the wait time expires, the timer resets and starts waiting again.\n * This is useful for handling frequent state updates that should be throttled, like search input values\n * or window resize dimensions.\n *\n * The hook returns a tuple containing:\n * - The current debounced value accessor\n * - A function to update the debounced value\n * - The debouncer instance with additional control methods and state signals\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking executions)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Update value - will be debounced\n * const handleChange = (e) => {\n * setSearchTerm(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.state().executionCount);\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // In onExecute callback, use get* methods\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500,\n * onExecute: (debouncer) => {\n * console.log('Total executions:', debouncer.getExecutionCount());\n * }\n * });\n * ```\n */\nexport function createDebouncedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidDebouncer<Setter<TValue>, TSelected>,\n] {\n const [debouncedValue, setDebouncedValue] = createSignal<TValue>(value)\n\n const debouncer = createDebouncer(setDebouncedValue, initialOptions, selector)\n\n return [debouncedValue, debouncer.maybeExecute as Setter<TValue>, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,gDAA0C,MAAM;CAEvE,MAAM,YAAYA,wCAAgB,mBAAmB,gBAAgB,SAAS;CAE9E,OAAO;EAAC;EAAgB,UAAU;EAAgC;EAAU"} | ||
| {"version":3,"file":"createDebouncedSignal.cjs","names":["createSignal","createDebouncer"],"sources":["../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced state value, combining Solid's createSignal with debouncing functionality.\n * This hook provides both the current debounced value and methods to update it.\n *\n * The state value is only updated after the specified wait time has elapsed since the last update attempt.\n * If another update is attempted before the wait time expires, the timer resets and starts waiting again.\n * This is useful for handling frequent state updates that should be throttled, like search input values\n * or window resize dimensions.\n *\n * The hook returns a tuple containing:\n * - The current debounced value accessor\n * - A function to update the debounced value\n * - The debouncer instance with additional control methods and state signals\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking executions)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Update value - will be debounced\n * const handleChange = (e) => {\n * setSearchTerm(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.state().executionCount);\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // In onExecute callback, use get* methods\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500,\n * onExecute: (debouncer) => {\n * console.log('Total executions:', debouncer.getExecutionCount());\n * }\n * });\n * ```\n */\nexport function createDebouncedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidDebouncer<Setter<TValue>, TSelected>,\n] {\n const [debouncedValue, setDebouncedValue] = createSignal<TValue>(value)\n\n const debouncer = createDebouncer(setDebouncedValue, initialOptions, selector)\n\n return [debouncedValue, debouncer.maybeExecute as Setter<TValue>, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,yBAAqBA,uBAAqB,KAAK;CAEtE,MAAM,YAAYC,wCAAgB,mBAAmB,gBAAgB,QAAQ;CAE7E,OAAO;EAAC;EAAgB,UAAU;EAAgC;CAAS;AAC7E"} |
| import { SolidDebouncer, SolidDebouncerOptions } from "./createDebouncer.cjs"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { DebouncerState } from "@tanstack/pacer/debouncer"; | ||
| //#region src/debouncer/createDebouncedSignal.d.ts | ||
@@ -6,0 +5,0 @@ /** |
| import { SolidDebouncer, SolidDebouncerOptions } from "./createDebouncer.js"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { DebouncerState } from "@tanstack/pacer/debouncer"; | ||
| //#region src/debouncer/createDebouncedSignal.d.ts | ||
@@ -6,0 +5,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedSignal.js","names":[],"sources":["../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced state value, combining Solid's createSignal with debouncing functionality.\n * This hook provides both the current debounced value and methods to update it.\n *\n * The state value is only updated after the specified wait time has elapsed since the last update attempt.\n * If another update is attempted before the wait time expires, the timer resets and starts waiting again.\n * This is useful for handling frequent state updates that should be throttled, like search input values\n * or window resize dimensions.\n *\n * The hook returns a tuple containing:\n * - The current debounced value accessor\n * - A function to update the debounced value\n * - The debouncer instance with additional control methods and state signals\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking executions)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Update value - will be debounced\n * const handleChange = (e) => {\n * setSearchTerm(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.state().executionCount);\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // In onExecute callback, use get* methods\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500,\n * onExecute: (debouncer) => {\n * console.log('Total executions:', debouncer.getExecutionCount());\n * }\n * });\n * ```\n */\nexport function createDebouncedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidDebouncer<Setter<TValue>, TSelected>,\n] {\n const [debouncedValue, setDebouncedValue] = createSignal<TValue>(value)\n\n const debouncer = createDebouncer(setDebouncedValue, initialOptions, selector)\n\n return [debouncedValue, debouncer.maybeExecute as Setter<TValue>, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,qBAAqB,aAAqB,MAAM;CAEvE,MAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,SAAS;CAE9E,OAAO;EAAC;EAAgB,UAAU;EAAgC;EAAU"} | ||
| {"version":3,"file":"createDebouncedSignal.js","names":[],"sources":["../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced state value, combining Solid's createSignal with debouncing functionality.\n * This hook provides both the current debounced value and methods to update it.\n *\n * The state value is only updated after the specified wait time has elapsed since the last update attempt.\n * If another update is attempted before the wait time expires, the timer resets and starts waiting again.\n * This is useful for handling frequent state updates that should be throttled, like search input values\n * or window resize dimensions.\n *\n * The hook returns a tuple containing:\n * - The current debounced value accessor\n * - A function to update the debounced value\n * - The debouncer instance with additional control methods and state signals\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking executions)\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal(\n * '',\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Update value - will be debounced\n * const handleChange = (e) => {\n * setSearchTerm(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.state().executionCount);\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // In onExecute callback, use get* methods\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500,\n * onExecute: (debouncer) => {\n * console.log('Total executions:', debouncer.getExecutionCount());\n * }\n * });\n * ```\n */\nexport function createDebouncedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidDebouncer<Setter<TValue>, TSelected>,\n] {\n const [debouncedValue, setDebouncedValue] = createSignal<TValue>(value)\n\n const debouncer = createDebouncer(setDebouncedValue, initialOptions, selector)\n\n return [debouncedValue, debouncer.maybeExecute as Setter<TValue>, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,qBAAqB,aAAqB,KAAK;CAEtE,MAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;CAE7E,OAAO;EAAC;EAAgB,UAAU;EAAgC;CAAS;AAC7E"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedValue.cjs","names":["createDebouncedSignal"],"sources":["../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced value that updates only after a specified delay.\n * Unlike createDebouncedSignal, this hook automatically tracks changes to the input value\n * and updates the debounced value accordingly.\n *\n * The debounced value will only update after the specified wait time has elapsed since\n * the last change to the input value. If the input value changes again before the wait\n * time expires, the timer resets and starts waiting again.\n *\n * This is useful for deriving debounced values from props or state that change frequently,\n * like search queries or form inputs, where you want to limit how often downstream effects\n * or calculations occur.\n *\n * The hook returns a tuple containing:\n * - An Accessor that provides the current debounced value\n * - The debouncer instance with control methods\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [debouncedQuery, debouncer] = createDebouncedValue(\n * searchQuery,\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Access debouncer state via signals\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>] {\n const [debouncedValue, setDebouncedValue, debouncer] = createDebouncedSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setDebouncedValue(value() as any)\n })\n\n return [debouncedValue, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAaA,oDACrD,OAAO,EACP,gBACA,SACD;CAED,iCAAmB;EACjB,kBAAkB,OAAO,CAAQ;GACjC;CAEF,OAAO,CAAC,gBAAgB,UAAU"} | ||
| {"version":3,"file":"createDebouncedValue.cjs","names":["createDebouncedSignal"],"sources":["../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced value that updates only after a specified delay.\n * Unlike createDebouncedSignal, this hook automatically tracks changes to the input value\n * and updates the debounced value accordingly.\n *\n * The debounced value will only update after the specified wait time has elapsed since\n * the last change to the input value. If the input value changes again before the wait\n * time expires, the timer resets and starts waiting again.\n *\n * This is useful for deriving debounced values from props or state that change frequently,\n * like search queries or form inputs, where you want to limit how often downstream effects\n * or calculations occur.\n *\n * The hook returns a tuple containing:\n * - An Accessor that provides the current debounced value\n * - The debouncer instance with control methods\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [debouncedQuery, debouncer] = createDebouncedValue(\n * searchQuery,\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Access debouncer state via signals\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>] {\n const [debouncedValue, setDebouncedValue, debouncer] = createDebouncedSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setDebouncedValue(value() as any)\n })\n\n return [debouncedValue, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAaA,oDACrD,MAAM,GACN,gBACA,QACF;CAEA,iCAAmB;EACjB,kBAAkB,MAAM,CAAQ;CAClC,CAAC;CAED,OAAO,CAAC,gBAAgB,SAAS;AACnC"} |
| import { SolidDebouncer, SolidDebouncerOptions } from "./createDebouncer.cjs"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { DebouncerState } from "@tanstack/pacer/debouncer"; | ||
| //#region src/debouncer/createDebouncedValue.d.ts | ||
@@ -6,0 +5,0 @@ /** |
| import { SolidDebouncer, SolidDebouncerOptions } from "./createDebouncer.js"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { DebouncerState } from "@tanstack/pacer/debouncer"; | ||
| //#region src/debouncer/createDebouncedValue.d.ts | ||
@@ -6,0 +5,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedValue.js","names":[],"sources":["../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced value that updates only after a specified delay.\n * Unlike createDebouncedSignal, this hook automatically tracks changes to the input value\n * and updates the debounced value accordingly.\n *\n * The debounced value will only update after the specified wait time has elapsed since\n * the last change to the input value. If the input value changes again before the wait\n * time expires, the timer resets and starts waiting again.\n *\n * This is useful for deriving debounced values from props or state that change frequently,\n * like search queries or form inputs, where you want to limit how often downstream effects\n * or calculations occur.\n *\n * The hook returns a tuple containing:\n * - An Accessor that provides the current debounced value\n * - The debouncer instance with control methods\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [debouncedQuery, debouncer] = createDebouncedValue(\n * searchQuery,\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Access debouncer state via signals\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>] {\n const [debouncedValue, setDebouncedValue, debouncer] = createDebouncedSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setDebouncedValue(value() as any)\n })\n\n return [debouncedValue, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAa,sBACrD,OAAO,EACP,gBACA,SACD;CAED,mBAAmB;EACjB,kBAAkB,OAAO,CAAQ;GACjC;CAEF,OAAO,CAAC,gBAAgB,UAAU"} | ||
| {"version":3,"file":"createDebouncedValue.js","names":[],"sources":["../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer, SolidDebouncerOptions } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { DebouncerState } from '@tanstack/pacer/debouncer'\n\n/**\n * A Solid hook that creates a debounced value that updates only after a specified delay.\n * Unlike createDebouncedSignal, this hook automatically tracks changes to the input value\n * and updates the debounced value accordingly.\n *\n * The debounced value will only update after the specified wait time has elapsed since\n * the last change to the input value. If the input value changes again before the wait\n * time expires, the timer resets and starts waiting again.\n *\n * This is useful for deriving debounced values from props or state that change frequently,\n * like search queries or form inputs, where you want to limit how often downstream effects\n * or calculations occur.\n *\n * The hook returns a tuple containing:\n * - An Accessor that provides the current debounced value\n * - The debouncer instance with control methods\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying debouncer instance.\n * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available debouncer state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [debouncedQuery, debouncer] = createDebouncedValue(\n * searchQuery,\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Access debouncer state via signals\n * console.log('Is pending:', debouncer.state().isPending);\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidDebouncerOptions<Setter<TValue>, TSelected>,\n selector?: (state: DebouncerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>] {\n const [debouncedValue, setDebouncedValue, debouncer] = createDebouncedSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setDebouncedValue(value() as any)\n })\n\n return [debouncedValue, debouncer]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAa,sBACrD,MAAM,GACN,gBACA,QACF;CAEA,mBAAmB;EACjB,kBAAkB,MAAM,CAAQ;CAClC,CAAC;CAED,OAAO,CAAC,gBAAgB,SAAS;AACnC"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncer.cjs","names":["useDefaultPacerOptions","Debouncer","shallow"],"sources":["../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends DebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidDebouncer<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Debouncer<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 })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: DebouncerState<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<DebouncerState<TFn>>>\n}\n\n/**\n * A Solid hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (createSignal, Redux, Zustand, etc.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\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 * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = createDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending changes (optimized for loading states)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = debouncer.state();\n * ```\n */\nexport function createDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidDebouncerOptions<TFn, TSelected>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().debouncer,\n ...options,\n } as SolidDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new Debouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: DebouncerState<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 }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,gBACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAIC,oCACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,kDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAEvC,eAAe,QAAQ;IAEzB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createDebouncer.cjs","names":["useDefaultPacerOptions","Debouncer","useSelector","shallow"],"sources":["../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends DebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidDebouncer<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Debouncer<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 })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: DebouncerState<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<DebouncerState<TFn>>>\n}\n\n/**\n * A Solid hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (createSignal, Redux, Zustand, etc.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\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 * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = createDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending changes (optimized for loading states)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = debouncer.state();\n * ```\n */\nexport function createDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidDebouncerOptions<TFn, TSelected>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().debouncer,\n ...options,\n } as SolidDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new Debouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: DebouncerState<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 }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,gBACd,IACA,SACA,kBAA6D,CAAC,IAC9B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAIC,oCACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,eAAWC,mCAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,eAAe,OAAO,UAAU,EACxD,SAASC,8BACX,CAAC;CAED,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QAEtC,eAAe,OAAO;EAE1B,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -5,3 +5,2 @@ import { Store } from "@tanstack/solid-store"; | ||
| import { Debouncer, DebouncerOptions, DebouncerState } from "@tanstack/pacer/debouncer"; | ||
| //#region src/debouncer/createDebouncer.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidDebouncerOptions<TFn extends AnyFunction, TSelected = {}> extends DebouncerOptions<TFn> { |
@@ -5,3 +5,2 @@ import { Accessor, JSX } from "solid-js"; | ||
| import { AnyFunction } from "@tanstack/pacer/types"; | ||
| //#region src/debouncer/createDebouncer.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidDebouncerOptions<TFn extends AnyFunction, TSelected = {}> extends DebouncerOptions<TFn> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncer.js","names":[],"sources":["../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends DebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidDebouncer<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Debouncer<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 })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: DebouncerState<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<DebouncerState<TFn>>>\n}\n\n/**\n * A Solid hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (createSignal, Redux, Zustand, etc.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\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 * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = createDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending changes (optimized for loading states)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = debouncer.state();\n * ```\n */\nexport function createDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidDebouncerOptions<TFn, TSelected>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().debouncer,\n ...options,\n } as SolidDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new Debouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: DebouncerState<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 }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,gBACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAI,UACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;CAEF,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAEvC,eAAe,QAAQ;IAEzB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createDebouncer.js","names":[],"sources":["../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends DebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidDebouncer<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Debouncer<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 })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: DebouncerState<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<DebouncerState<TFn>>>\n}\n\n/**\n * A Solid hook that creates and manages a Debouncer instance.\n *\n * This is a lower-level hook that provides direct access to the Debouncer's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (createSignal, Redux, Zustand, etc.).\n *\n * This hook provides debouncing functionality to limit how often a function can be called,\n * waiting for a specified delay before executing the latest call. This is useful for handling\n * frequent events like window resizing, scroll events, or real-time search inputs.\n *\n * The debouncer will only execute the function after the specified wait time has elapsed\n * since the last call. If the function is called again before the wait time expires, the\n * timer resets and starts waiting again.\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 * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = createDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending changes (optimized for loading states)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * status: state.status\n * })\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending } = debouncer.state();\n * ```\n */\nexport function createDebouncer<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidDebouncerOptions<TFn, TSelected>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().debouncer,\n ...options,\n } as SolidDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new Debouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: DebouncerState<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 }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,gBACd,IACA,SACA,kBAA6D,CAAC,IAC9B;CAChC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAI,UACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,QACX,CAAC;CAED,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QAEtC,eAAe,OAAO;EAE1B,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"PacerProvider.cjs","names":["createContext","useContext","JSX","AnyAsyncFunction","AnyFunction","AsyncBatcherOptions","AsyncDebouncerOptions","AsyncQueuerOptions","AsyncRateLimiterOptions","AsyncThrottlerOptions","BatcherOptions","DebouncerOptions","QueuerOptions","RateLimiterOptions","ThrottlerOptions","PacerProviderOptions","asyncBatcher","Partial","asyncDebouncer","asyncQueuer","asyncRateLimiter","asyncThrottler","batcher","debouncer","queuer","rateLimiter","throttler","PacerContextValue","defaultOptions","PacerContext","PacerProviderProps","children","Element","DEFAULT_OPTIONS","PacerProvider","props","contextValue","_$createComponent","Provider","value","usePacerContext","useDefaultPacerOptions","context"],"sources":["../../src/provider/PacerProvider.tsx"],"sourcesContent":["import { createContext, useContext } from 'solid-js'\nimport type { JSX } from 'solid-js'\nimport type {\n AnyAsyncFunction,\n AnyFunction,\n AsyncBatcherOptions,\n AsyncDebouncerOptions,\n AsyncQueuerOptions,\n AsyncRateLimiterOptions,\n AsyncThrottlerOptions,\n BatcherOptions,\n DebouncerOptions,\n QueuerOptions,\n RateLimiterOptions,\n ThrottlerOptions,\n} from '@tanstack/pacer'\n\nexport interface PacerProviderOptions {\n asyncBatcher?: Partial<AsyncBatcherOptions<any>>\n asyncDebouncer?: Partial<AsyncDebouncerOptions<AnyAsyncFunction>>\n asyncQueuer?: Partial<AsyncQueuerOptions<any>>\n asyncRateLimiter?: Partial<AsyncRateLimiterOptions<AnyAsyncFunction>>\n asyncThrottler?: Partial<AsyncThrottlerOptions<AnyAsyncFunction>>\n batcher?: Partial<BatcherOptions<any>>\n debouncer?: Partial<DebouncerOptions<AnyFunction>>\n queuer?: Partial<QueuerOptions<any>>\n rateLimiter?: Partial<RateLimiterOptions<AnyFunction>>\n throttler?: Partial<ThrottlerOptions<AnyFunction>>\n}\n\ninterface PacerContextValue {\n defaultOptions: PacerProviderOptions\n}\n\nconst PacerContext = createContext<PacerContextValue | null>(null)\n\nexport interface PacerProviderProps {\n children: JSX.Element\n defaultOptions?: PacerProviderOptions\n}\n\nconst DEFAULT_OPTIONS: PacerProviderOptions = {}\n\nexport function PacerProvider(props: PacerProviderProps) {\n const contextValue: PacerContextValue = {\n defaultOptions: props.defaultOptions ?? DEFAULT_OPTIONS,\n }\n\n return (\n <PacerContext.Provider value={contextValue}>\n {props.children}\n </PacerContext.Provider>\n )\n}\n\nexport function usePacerContext() {\n return useContext(PacerContext)\n}\n\nexport function useDefaultPacerOptions() {\n const context = useContext(PacerContext)\n return context?.defaultOptions ?? {}\n}\n"],"mappings":";;;;AAkCA,MAAM6B,2CAAuD,KAAK;AAOlE,MAAMI,kBAAwC,EAAE;AAEhD,SAAgBC,cAAcC,OAA2B;CACvD,MAAMC,eAAkC,EACtCR,gBAAgBO,MAAMP,kBAAkBK,iBACzC;CAED,yCACGJ,aAAaS,UAAQ;EAACC,OAAOH;EAAY,IAAAL,WAAA;GAAA,OACvCI,MAAMJ;;EAAQ,CAAA;;AAKrB,SAAgBS,kBAAkB;CAChC,gCAAkBX,aAAa;;AAGjC,SAAgBY,yBAAyB;CAEvC,gCAD2BZ,aACb,EAAED,kBAAkB,EAAE"} | ||
| {"version":3,"file":"PacerProvider.cjs","names":["createContext","useContext","JSX","AnyAsyncFunction","AnyFunction","AsyncBatcherOptions","AsyncDebouncerOptions","AsyncQueuerOptions","AsyncRateLimiterOptions","AsyncThrottlerOptions","BatcherOptions","DebouncerOptions","QueuerOptions","RateLimiterOptions","ThrottlerOptions","PacerProviderOptions","asyncBatcher","Partial","asyncDebouncer","asyncQueuer","asyncRateLimiter","asyncThrottler","batcher","debouncer","queuer","rateLimiter","throttler","PacerContextValue","defaultOptions","PacerContext","PacerProviderProps","children","Element","DEFAULT_OPTIONS","PacerProvider","props","contextValue","_$createComponent","Provider","value","usePacerContext","useDefaultPacerOptions","context"],"sources":["../../src/provider/PacerProvider.tsx"],"sourcesContent":["import { createContext, useContext } from 'solid-js'\nimport type { JSX } from 'solid-js'\nimport type {\n AnyAsyncFunction,\n AnyFunction,\n AsyncBatcherOptions,\n AsyncDebouncerOptions,\n AsyncQueuerOptions,\n AsyncRateLimiterOptions,\n AsyncThrottlerOptions,\n BatcherOptions,\n DebouncerOptions,\n QueuerOptions,\n RateLimiterOptions,\n ThrottlerOptions,\n} from '@tanstack/pacer'\n\nexport interface PacerProviderOptions {\n asyncBatcher?: Partial<AsyncBatcherOptions<any>>\n asyncDebouncer?: Partial<AsyncDebouncerOptions<AnyAsyncFunction>>\n asyncQueuer?: Partial<AsyncQueuerOptions<any>>\n asyncRateLimiter?: Partial<AsyncRateLimiterOptions<AnyAsyncFunction>>\n asyncThrottler?: Partial<AsyncThrottlerOptions<AnyAsyncFunction>>\n batcher?: Partial<BatcherOptions<any>>\n debouncer?: Partial<DebouncerOptions<AnyFunction>>\n queuer?: Partial<QueuerOptions<any>>\n rateLimiter?: Partial<RateLimiterOptions<AnyFunction>>\n throttler?: Partial<ThrottlerOptions<AnyFunction>>\n}\n\ninterface PacerContextValue {\n defaultOptions: PacerProviderOptions\n}\n\nconst PacerContext = createContext<PacerContextValue | null>(null)\n\nexport interface PacerProviderProps {\n children: JSX.Element\n defaultOptions?: PacerProviderOptions\n}\n\nconst DEFAULT_OPTIONS: PacerProviderOptions = {}\n\nexport function PacerProvider(props: PacerProviderProps) {\n const contextValue: PacerContextValue = {\n defaultOptions: props.defaultOptions ?? DEFAULT_OPTIONS,\n }\n\n return (\n <PacerContext.Provider value={contextValue}>\n {props.children}\n </PacerContext.Provider>\n )\n}\n\nexport function usePacerContext() {\n return useContext(PacerContext)\n}\n\nexport function useDefaultPacerOptions() {\n const context = useContext(PacerContext)\n return context?.defaultOptions ?? {}\n}\n"],"mappings":";;;;AAkCA,MAAM6B,mBAAe7B,wBAAwC,IAAI;AAOjE,MAAMiC,kBAAwC,CAAC;AAE/C,SAAgBC,cAAcC,OAA2B;CACvD,MAAMC,eAAkC,EACtCR,gBAAgBO,MAAMP,kBAAkBK,gBAC1C;CAEA,WAAAI,8BACGR,aAAaS,UAAQ;EAACC,OAAOH;EAAY,IAAAL,WAAA;GAAA,OACvCI,MAAMJ;EAAQ;CAAA,CAAA;AAGrB;AAEA,SAAgBS,kBAAkB;CAChC,WAAOvC,qBAAW4B,YAAY;AAChC;AAEA,SAAgBY,yBAAyB;CAEvC,WADgBxC,qBAAW4B,YACpBa,CAAO,EAAEd,kBAAkB,CAAC;AACrC"} |
| import { JSX } from "solid-js"; | ||
| import { AnyAsyncFunction, AnyFunction, AsyncBatcherOptions, AsyncDebouncerOptions, AsyncQueuerOptions, AsyncRateLimiterOptions, AsyncThrottlerOptions, BatcherOptions, DebouncerOptions, QueuerOptions, RateLimiterOptions, ThrottlerOptions } from "@tanstack/pacer"; | ||
| //#region src/provider/PacerProvider.d.ts | ||
@@ -5,0 +4,0 @@ interface PacerProviderOptions { |
| import { AnyAsyncFunction, AnyFunction, AsyncBatcherOptions, AsyncDebouncerOptions, AsyncQueuerOptions, AsyncRateLimiterOptions, AsyncThrottlerOptions, BatcherOptions, DebouncerOptions, QueuerOptions, RateLimiterOptions, ThrottlerOptions } from "@tanstack/pacer"; | ||
| import { JSX } from "solid-js"; | ||
| //#region src/provider/PacerProvider.d.ts | ||
@@ -5,0 +4,0 @@ interface PacerProviderOptions { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"PacerProvider.js","names":["createContext","useContext","JSX","AnyAsyncFunction","AnyFunction","AsyncBatcherOptions","AsyncDebouncerOptions","AsyncQueuerOptions","AsyncRateLimiterOptions","AsyncThrottlerOptions","BatcherOptions","DebouncerOptions","QueuerOptions","RateLimiterOptions","ThrottlerOptions","PacerProviderOptions","asyncBatcher","Partial","asyncDebouncer","asyncQueuer","asyncRateLimiter","asyncThrottler","batcher","debouncer","queuer","rateLimiter","throttler","PacerContextValue","defaultOptions","PacerContext","PacerProviderProps","children","Element","DEFAULT_OPTIONS","PacerProvider","props","contextValue","_$createComponent","Provider","value","usePacerContext","useDefaultPacerOptions","context"],"sources":["../../src/provider/PacerProvider.tsx"],"sourcesContent":["import { createContext, useContext } from 'solid-js'\nimport type { JSX } from 'solid-js'\nimport type {\n AnyAsyncFunction,\n AnyFunction,\n AsyncBatcherOptions,\n AsyncDebouncerOptions,\n AsyncQueuerOptions,\n AsyncRateLimiterOptions,\n AsyncThrottlerOptions,\n BatcherOptions,\n DebouncerOptions,\n QueuerOptions,\n RateLimiterOptions,\n ThrottlerOptions,\n} from '@tanstack/pacer'\n\nexport interface PacerProviderOptions {\n asyncBatcher?: Partial<AsyncBatcherOptions<any>>\n asyncDebouncer?: Partial<AsyncDebouncerOptions<AnyAsyncFunction>>\n asyncQueuer?: Partial<AsyncQueuerOptions<any>>\n asyncRateLimiter?: Partial<AsyncRateLimiterOptions<AnyAsyncFunction>>\n asyncThrottler?: Partial<AsyncThrottlerOptions<AnyAsyncFunction>>\n batcher?: Partial<BatcherOptions<any>>\n debouncer?: Partial<DebouncerOptions<AnyFunction>>\n queuer?: Partial<QueuerOptions<any>>\n rateLimiter?: Partial<RateLimiterOptions<AnyFunction>>\n throttler?: Partial<ThrottlerOptions<AnyFunction>>\n}\n\ninterface PacerContextValue {\n defaultOptions: PacerProviderOptions\n}\n\nconst PacerContext = createContext<PacerContextValue | null>(null)\n\nexport interface PacerProviderProps {\n children: JSX.Element\n defaultOptions?: PacerProviderOptions\n}\n\nconst DEFAULT_OPTIONS: PacerProviderOptions = {}\n\nexport function PacerProvider(props: PacerProviderProps) {\n const contextValue: PacerContextValue = {\n defaultOptions: props.defaultOptions ?? DEFAULT_OPTIONS,\n }\n\n return (\n <PacerContext.Provider value={contextValue}>\n {props.children}\n </PacerContext.Provider>\n )\n}\n\nexport function usePacerContext() {\n return useContext(PacerContext)\n}\n\nexport function useDefaultPacerOptions() {\n const context = useContext(PacerContext)\n return context?.defaultOptions ?? {}\n}\n"],"mappings":";;;;AAkCA,MAAM6B,eAAe7B,cAAwC,KAAK;AAOlE,MAAMiC,kBAAwC,EAAE;AAEhD,SAAgBC,cAAcC,OAA2B;CACvD,MAAMC,eAAkC,EACtCR,gBAAgBO,MAAMP,kBAAkBK,iBACzC;CAED,OAAAI,gBACGR,aAAaS,UAAQ;EAACC,OAAOH;EAAY,IAAAL,WAAA;GAAA,OACvCI,MAAMJ;;EAAQ,CAAA;;AAKrB,SAAgBS,kBAAkB;CAChC,OAAOvC,WAAW4B,aAAa;;AAGjC,SAAgBY,yBAAyB;CAEvC,OADgBxC,WAAW4B,aACb,EAAED,kBAAkB,EAAE"} | ||
| {"version":3,"file":"PacerProvider.js","names":["createContext","useContext","JSX","AnyAsyncFunction","AnyFunction","AsyncBatcherOptions","AsyncDebouncerOptions","AsyncQueuerOptions","AsyncRateLimiterOptions","AsyncThrottlerOptions","BatcherOptions","DebouncerOptions","QueuerOptions","RateLimiterOptions","ThrottlerOptions","PacerProviderOptions","asyncBatcher","Partial","asyncDebouncer","asyncQueuer","asyncRateLimiter","asyncThrottler","batcher","debouncer","queuer","rateLimiter","throttler","PacerContextValue","defaultOptions","PacerContext","PacerProviderProps","children","Element","DEFAULT_OPTIONS","PacerProvider","props","contextValue","_$createComponent","Provider","value","usePacerContext","useDefaultPacerOptions","context"],"sources":["../../src/provider/PacerProvider.tsx"],"sourcesContent":["import { createContext, useContext } from 'solid-js'\nimport type { JSX } from 'solid-js'\nimport type {\n AnyAsyncFunction,\n AnyFunction,\n AsyncBatcherOptions,\n AsyncDebouncerOptions,\n AsyncQueuerOptions,\n AsyncRateLimiterOptions,\n AsyncThrottlerOptions,\n BatcherOptions,\n DebouncerOptions,\n QueuerOptions,\n RateLimiterOptions,\n ThrottlerOptions,\n} from '@tanstack/pacer'\n\nexport interface PacerProviderOptions {\n asyncBatcher?: Partial<AsyncBatcherOptions<any>>\n asyncDebouncer?: Partial<AsyncDebouncerOptions<AnyAsyncFunction>>\n asyncQueuer?: Partial<AsyncQueuerOptions<any>>\n asyncRateLimiter?: Partial<AsyncRateLimiterOptions<AnyAsyncFunction>>\n asyncThrottler?: Partial<AsyncThrottlerOptions<AnyAsyncFunction>>\n batcher?: Partial<BatcherOptions<any>>\n debouncer?: Partial<DebouncerOptions<AnyFunction>>\n queuer?: Partial<QueuerOptions<any>>\n rateLimiter?: Partial<RateLimiterOptions<AnyFunction>>\n throttler?: Partial<ThrottlerOptions<AnyFunction>>\n}\n\ninterface PacerContextValue {\n defaultOptions: PacerProviderOptions\n}\n\nconst PacerContext = createContext<PacerContextValue | null>(null)\n\nexport interface PacerProviderProps {\n children: JSX.Element\n defaultOptions?: PacerProviderOptions\n}\n\nconst DEFAULT_OPTIONS: PacerProviderOptions = {}\n\nexport function PacerProvider(props: PacerProviderProps) {\n const contextValue: PacerContextValue = {\n defaultOptions: props.defaultOptions ?? DEFAULT_OPTIONS,\n }\n\n return (\n <PacerContext.Provider value={contextValue}>\n {props.children}\n </PacerContext.Provider>\n )\n}\n\nexport function usePacerContext() {\n return useContext(PacerContext)\n}\n\nexport function useDefaultPacerOptions() {\n const context = useContext(PacerContext)\n return context?.defaultOptions ?? {}\n}\n"],"mappings":";;;;AAkCA,MAAM6B,eAAe7B,cAAwC,IAAI;AAOjE,MAAMiC,kBAAwC,CAAC;AAE/C,SAAgBC,cAAcC,OAA2B;CACvD,MAAMC,eAAkC,EACtCR,gBAAgBO,MAAMP,kBAAkBK,gBAC1C;CAEA,OAAAI,gBACGR,aAAaS,UAAQ;EAACC,OAAOH;EAAY,IAAAL,WAAA;GAAA,OACvCI,MAAMJ;EAAQ;CAAA,CAAA;AAGrB;AAEA,SAAgBS,kBAAkB;CAChC,OAAOvC,WAAW4B,YAAY;AAChC;AAEA,SAAgBY,yBAAyB;CAEvC,OADgBxC,WAAW4B,YACpBa,CAAO,EAAEd,kBAAkB,CAAC;AACrC"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createQueuedSignal.cjs","names":["createQueuer"],"sources":["../../src/queuer/createQueuedSignal.ts"],"sourcesContent":["import { createQueuer } from './createQueuer'\nimport type { SolidQueuer, SolidQueuerOptions } from './createQueuer'\nimport type { QueuerState } from '@tanstack/pacer/queuer'\n\n/**\n * A Solid primitive that creates a queuer with managed state, combining Solid's signals with queuing functionality.\n * This primitive provides both the current queue state and queue control methods.\n *\n * The queue state is automatically updated whenever items are added, removed, or reordered in the queue.\n * All queue operations are reflected in the state array returned by the primitive.\n *\n * The queue can be started and stopped to automatically process items at a specified interval,\n * making it useful as a scheduler. When started, it will process one item per tick, with an\n * optional wait time between ticks.\n *\n * The primitive returns a tuple containing:\n * - The current queue state as an array\n * - The queue instance with methods for queue manipulation\n *\n * ## State Management and Selector\n *\n * The primitive uses Solid's reactive state management via the underlying queuer instance.\n * The `selector` parameter allows you to specify which queuer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary updates when irrelevant 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. This prevents unnecessary updates and gives you\n * full control over when your component tracks state changes. Only when you provide a selector will the\n * component track changes to the selected state values.\n *\n * Available queuer state properties:\n * - `executionCount`: Number of items that have been processed by the queuer\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * {\n * initialItems: ['item1', 'item2'],\n * started: true,\n * wait: 1000,\n * getPriority: (item) => item.priority\n * }\n * );\n *\n * // Opt-in to track queue contents changes (optimized for displaying queue items)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * items: state.items,\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to track processing state changes (optimized for loading indicators)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for stats display)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to queue\n * const handleAdd = (item) => {\n * addItem(item);\n * };\n *\n * // Start automatic processing\n * const startProcessing = () => {\n * queue.start();\n * };\n *\n * // Stop automatic processing\n * const stopProcessing = () => {\n * queue.stop();\n * };\n *\n * // Manual processing still available\n * const handleProcess = () => {\n * const nextItem = queue.getNextItem();\n * if (nextItem) {\n * processItem(nextItem);\n * }\n * };\n *\n * // Access the selected queuer state (will be empty object {} unless selector provided)\n * const { size, isRunning, executionCount } = queue.state;\n * ```\n */\nexport function createQueuedSignal<\n TValue,\n TSelected extends Pick<QueuerState<TValue>, 'items'> = Pick<\n QueuerState<TValue>,\n 'items'\n >,\n>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = (state) =>\n ({ items: state.items }) as TSelected,\n): [\n () => Array<TValue>,\n SolidQueuer<TValue, TSelected>['addItem'],\n SolidQueuer<TValue, TSelected>,\n] {\n const queue = createQueuer(fn, options, selector)\n\n return [() => queue.state().items, queue.addItem, queue]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHA,SAAgB,mBAOd,IACA,UAAiD,EAAE,EACnD,YAAuD,WACpD,EAAE,OAAO,MAAM,OAAO,GAKzB;CACA,MAAM,QAAQA,kCAAa,IAAI,SAAS,SAAS;CAEjD,OAAO;QAAO,MAAM,OAAO,CAAC;EAAO,MAAM;EAAS;EAAM"} | ||
| {"version":3,"file":"createQueuedSignal.cjs","names":["createQueuer"],"sources":["../../src/queuer/createQueuedSignal.ts"],"sourcesContent":["import { createQueuer } from './createQueuer'\nimport type { SolidQueuer, SolidQueuerOptions } from './createQueuer'\nimport type { QueuerState } from '@tanstack/pacer/queuer'\n\n/**\n * A Solid primitive that creates a queuer with managed state, combining Solid's signals with queuing functionality.\n * This primitive provides both the current queue state and queue control methods.\n *\n * The queue state is automatically updated whenever items are added, removed, or reordered in the queue.\n * All queue operations are reflected in the state array returned by the primitive.\n *\n * The queue can be started and stopped to automatically process items at a specified interval,\n * making it useful as a scheduler. When started, it will process one item per tick, with an\n * optional wait time between ticks.\n *\n * The primitive returns a tuple containing:\n * - The current queue state as an array\n * - The queue instance with methods for queue manipulation\n *\n * ## State Management and Selector\n *\n * The primitive uses Solid's reactive state management via the underlying queuer instance.\n * The `selector` parameter allows you to specify which queuer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary updates when irrelevant 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. This prevents unnecessary updates and gives you\n * full control over when your component tracks state changes. Only when you provide a selector will the\n * component track changes to the selected state values.\n *\n * Available queuer state properties:\n * - `executionCount`: Number of items that have been processed by the queuer\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * {\n * initialItems: ['item1', 'item2'],\n * started: true,\n * wait: 1000,\n * getPriority: (item) => item.priority\n * }\n * );\n *\n * // Opt-in to track queue contents changes (optimized for displaying queue items)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * items: state.items,\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to track processing state changes (optimized for loading indicators)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for stats display)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to queue\n * const handleAdd = (item) => {\n * addItem(item);\n * };\n *\n * // Start automatic processing\n * const startProcessing = () => {\n * queue.start();\n * };\n *\n * // Stop automatic processing\n * const stopProcessing = () => {\n * queue.stop();\n * };\n *\n * // Manual processing still available\n * const handleProcess = () => {\n * const nextItem = queue.getNextItem();\n * if (nextItem) {\n * processItem(nextItem);\n * }\n * };\n *\n * // Access the selected queuer state (will be empty object {} unless selector provided)\n * const { size, isRunning, executionCount } = queue.state;\n * ```\n */\nexport function createQueuedSignal<\n TValue,\n TSelected extends Pick<QueuerState<TValue>, 'items'> = Pick<\n QueuerState<TValue>,\n 'items'\n >,\n>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = (state) =>\n ({ items: state.items }) as TSelected,\n): [\n () => Array<TValue>,\n SolidQueuer<TValue, TSelected>['addItem'],\n SolidQueuer<TValue, TSelected>,\n] {\n const queue = createQueuer(fn, options, selector)\n\n return [() => queue.state().items, queue.addItem, queue]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHA,SAAgB,mBAOd,IACA,UAAiD,CAAC,GAClD,YAAuD,WACpD,EAAE,OAAO,MAAM,MAAM,IAKxB;CACA,MAAM,QAAQA,kCAAa,IAAI,SAAS,QAAQ;CAEhD,OAAO;QAAO,MAAM,MAAM,CAAC,CAAC;EAAO,MAAM;EAAS;CAAK;AACzD"} |
| import { SolidQueuer, SolidQueuerOptions } from "./createQueuer.cjs"; | ||
| import { QueuerState } from "@tanstack/pacer/queuer"; | ||
| //#region src/queuer/createQueuedSignal.d.ts | ||
@@ -5,0 +4,0 @@ /** |
| import { SolidQueuer, SolidQueuerOptions } from "./createQueuer.js"; | ||
| import { QueuerState } from "@tanstack/pacer/queuer"; | ||
| //#region src/queuer/createQueuedSignal.d.ts | ||
@@ -5,0 +4,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createQueuedSignal.js","names":[],"sources":["../../src/queuer/createQueuedSignal.ts"],"sourcesContent":["import { createQueuer } from './createQueuer'\nimport type { SolidQueuer, SolidQueuerOptions } from './createQueuer'\nimport type { QueuerState } from '@tanstack/pacer/queuer'\n\n/**\n * A Solid primitive that creates a queuer with managed state, combining Solid's signals with queuing functionality.\n * This primitive provides both the current queue state and queue control methods.\n *\n * The queue state is automatically updated whenever items are added, removed, or reordered in the queue.\n * All queue operations are reflected in the state array returned by the primitive.\n *\n * The queue can be started and stopped to automatically process items at a specified interval,\n * making it useful as a scheduler. When started, it will process one item per tick, with an\n * optional wait time between ticks.\n *\n * The primitive returns a tuple containing:\n * - The current queue state as an array\n * - The queue instance with methods for queue manipulation\n *\n * ## State Management and Selector\n *\n * The primitive uses Solid's reactive state management via the underlying queuer instance.\n * The `selector` parameter allows you to specify which queuer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary updates when irrelevant 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. This prevents unnecessary updates and gives you\n * full control over when your component tracks state changes. Only when you provide a selector will the\n * component track changes to the selected state values.\n *\n * Available queuer state properties:\n * - `executionCount`: Number of items that have been processed by the queuer\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * {\n * initialItems: ['item1', 'item2'],\n * started: true,\n * wait: 1000,\n * getPriority: (item) => item.priority\n * }\n * );\n *\n * // Opt-in to track queue contents changes (optimized for displaying queue items)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * items: state.items,\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to track processing state changes (optimized for loading indicators)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for stats display)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to queue\n * const handleAdd = (item) => {\n * addItem(item);\n * };\n *\n * // Start automatic processing\n * const startProcessing = () => {\n * queue.start();\n * };\n *\n * // Stop automatic processing\n * const stopProcessing = () => {\n * queue.stop();\n * };\n *\n * // Manual processing still available\n * const handleProcess = () => {\n * const nextItem = queue.getNextItem();\n * if (nextItem) {\n * processItem(nextItem);\n * }\n * };\n *\n * // Access the selected queuer state (will be empty object {} unless selector provided)\n * const { size, isRunning, executionCount } = queue.state;\n * ```\n */\nexport function createQueuedSignal<\n TValue,\n TSelected extends Pick<QueuerState<TValue>, 'items'> = Pick<\n QueuerState<TValue>,\n 'items'\n >,\n>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = (state) =>\n ({ items: state.items }) as TSelected,\n): [\n () => Array<TValue>,\n SolidQueuer<TValue, TSelected>['addItem'],\n SolidQueuer<TValue, TSelected>,\n] {\n const queue = createQueuer(fn, options, selector)\n\n return [() => queue.state().items, queue.addItem, queue]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHA,SAAgB,mBAOd,IACA,UAAiD,EAAE,EACnD,YAAuD,WACpD,EAAE,OAAO,MAAM,OAAO,GAKzB;CACA,MAAM,QAAQ,aAAa,IAAI,SAAS,SAAS;CAEjD,OAAO;QAAO,MAAM,OAAO,CAAC;EAAO,MAAM;EAAS;EAAM"} | ||
| {"version":3,"file":"createQueuedSignal.js","names":[],"sources":["../../src/queuer/createQueuedSignal.ts"],"sourcesContent":["import { createQueuer } from './createQueuer'\nimport type { SolidQueuer, SolidQueuerOptions } from './createQueuer'\nimport type { QueuerState } from '@tanstack/pacer/queuer'\n\n/**\n * A Solid primitive that creates a queuer with managed state, combining Solid's signals with queuing functionality.\n * This primitive provides both the current queue state and queue control methods.\n *\n * The queue state is automatically updated whenever items are added, removed, or reordered in the queue.\n * All queue operations are reflected in the state array returned by the primitive.\n *\n * The queue can be started and stopped to automatically process items at a specified interval,\n * making it useful as a scheduler. When started, it will process one item per tick, with an\n * optional wait time between ticks.\n *\n * The primitive returns a tuple containing:\n * - The current queue state as an array\n * - The queue instance with methods for queue manipulation\n *\n * ## State Management and Selector\n *\n * The primitive uses Solid's reactive state management via the underlying queuer instance.\n * The `selector` parameter allows you to specify which queuer state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary updates when irrelevant 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. This prevents unnecessary updates and gives you\n * full control over when your component tracks state changes. Only when you provide a selector will the\n * component track changes to the selected state values.\n *\n * Available queuer state properties:\n * - `executionCount`: Number of items that have been processed by the queuer\n * - `expirationCount`: Number of items that have been removed due to expiration\n * - `isEmpty`: Whether the queuer has no items to process\n * - `isFull`: Whether the queuer has reached its maximum capacity\n * - `isIdle`: Whether the queuer is not currently processing any items\n * - `isRunning`: Whether the queuer is active and will process items automatically\n * - `items`: Array of items currently waiting to be processed\n * - `itemTimestamps`: Timestamps when items were added for expiration tracking\n * - `pendingTick`: Whether the queuer has a pending timeout for processing the next item\n * - `rejectionCount`: Number of items that have been rejected from being added\n * - `size`: Number of items currently in the queue\n * - `status`: Current processing status ('idle' | 'running' | 'stopped')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * {\n * initialItems: ['item1', 'item2'],\n * started: true,\n * wait: 1000,\n * getPriority: (item) => item.priority\n * }\n * );\n *\n * // Opt-in to track queue contents changes (optimized for displaying queue items)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * items: state.items,\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to track processing state changes (optimized for loading indicators)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * isRunning: state.isRunning,\n * isIdle: state.isIdle,\n * status: state.status,\n * pendingTick: state.pendingTick\n * })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for stats display)\n * const [items, addItem, queue] = createQueuedSignal(\n * (item) => console.log('Processing:', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * expirationCount: state.expirationCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to queue\n * const handleAdd = (item) => {\n * addItem(item);\n * };\n *\n * // Start automatic processing\n * const startProcessing = () => {\n * queue.start();\n * };\n *\n * // Stop automatic processing\n * const stopProcessing = () => {\n * queue.stop();\n * };\n *\n * // Manual processing still available\n * const handleProcess = () => {\n * const nextItem = queue.getNextItem();\n * if (nextItem) {\n * processItem(nextItem);\n * }\n * };\n *\n * // Access the selected queuer state (will be empty object {} unless selector provided)\n * const { size, isRunning, executionCount } = queue.state;\n * ```\n */\nexport function createQueuedSignal<\n TValue,\n TSelected extends Pick<QueuerState<TValue>, 'items'> = Pick<\n QueuerState<TValue>,\n 'items'\n >,\n>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = (state) =>\n ({ items: state.items }) as TSelected,\n): [\n () => Array<TValue>,\n SolidQueuer<TValue, TSelected>['addItem'],\n SolidQueuer<TValue, TSelected>,\n] {\n const queue = createQueuer(fn, options, selector)\n\n return [() => queue.state().items, queue.addItem, queue]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHA,SAAgB,mBAOd,IACA,UAAiD,CAAC,GAClD,YAAuD,WACpD,EAAE,OAAO,MAAM,MAAM,IAKxB;CACA,MAAM,QAAQ,aAAa,IAAI,SAAS,QAAQ;CAEhD,OAAO;QAAO,MAAM,MAAM,CAAC,CAAC;EAAO,MAAM;EAAS;CAAK;AACzD"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createQueuer.cjs","names":["useDefaultPacerOptions","Queuer","shallow"],"sources":["../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/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 { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidQueuer<TValue, TSelected = {}> extends Omit<\n Queuer<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) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Queue: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: QueuerState<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<QueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Queuer instance for managing a synchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Synchronous processing of items using the provided `fn` function\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Priority queueing via `getPriority` or item `priority` property\n * - Item expiration and removal of stale items\n * - Configurable wait time between processing items\n * - Pause/resume processing\n * - Callbacks for queue state changes, execution, rejection, and expiration\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The queue processes items synchronously in order, with optional delays between each item. When started, it will process one item per tick, with an optional wait time between ticks. You can pause and resume processing with `stop()` and `start()`.\n *\n * By default, the queue uses FIFO behavior, but you can configure LIFO or double-ended queueing by specifying the position when adding or removing items.\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 * - `executionCount`: Number of items that have been processed\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `items`: Array of items currently queued for processing\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = createQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const queue = createQueuer(\n * (item) => {\n * // process item synchronously\n * console.log('Processing', item);\n * },\n * {\n * started: true, // Start processing immediately\n * wait: 1000, // Process one item every second\n * getPriority: (item) => item.priority // Process higher priority items first\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to process - they'll be handled automatically\n * queue.addItem('task1');\n * queue.addItem('task2');\n *\n * // Control the scheduler\n * queue.stop(); // Pause processing\n * queue.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = queue.state();\n * ```\n */\nexport function createQueuer<TValue, TSelected = {}>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): SolidQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as SolidQueuerOptions<TValue, TSelected>\n const queuer = new Queuer(fn, mergedOptions) as unknown as SolidQueuer<\n TValue,\n TSelected\n >\n\n queuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: QueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(queuer.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(queuer.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n })\n })\n\n return {\n ...queuer,\n state,\n } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,aACd,IACA,UAAiD,EAAE,EACnD,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,SAAS,IAAIC,8BAAO,IAAI,cAAc;CAK5C,OAAO,YAAY,SAAS,UAAqB,OAG9C;EACD,MAAM,kDAAuB,OAAO,OAAO,MAAM,UAAU,EACzD,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,OAAO,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;CAEvE,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,OAAO;QAE/B,OAAO,MAAM;IAEf;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createQueuer.cjs","names":["useDefaultPacerOptions","Queuer","useSelector","shallow"],"sources":["../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/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 { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidQueuer<TValue, TSelected = {}> extends Omit<\n Queuer<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) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Queue: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: QueuerState<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<QueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Queuer instance for managing a synchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Synchronous processing of items using the provided `fn` function\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Priority queueing via `getPriority` or item `priority` property\n * - Item expiration and removal of stale items\n * - Configurable wait time between processing items\n * - Pause/resume processing\n * - Callbacks for queue state changes, execution, rejection, and expiration\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The queue processes items synchronously in order, with optional delays between each item. When started, it will process one item per tick, with an optional wait time between ticks. You can pause and resume processing with `stop()` and `start()`.\n *\n * By default, the queue uses FIFO behavior, but you can configure LIFO or double-ended queueing by specifying the position when adding or removing items.\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 * - `executionCount`: Number of items that have been processed\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `items`: Array of items currently queued for processing\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = createQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const queue = createQueuer(\n * (item) => {\n * // process item synchronously\n * console.log('Processing', item);\n * },\n * {\n * started: true, // Start processing immediately\n * wait: 1000, // Process one item every second\n * getPriority: (item) => item.priority // Process higher priority items first\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to process - they'll be handled automatically\n * queue.addItem('task1');\n * queue.addItem('task2');\n *\n * // Control the scheduler\n * queue.stop(); // Pause processing\n * queue.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = queue.state();\n * ```\n */\nexport function createQueuer<TValue, TSelected = {}>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): SolidQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as SolidQueuerOptions<TValue, TSelected>\n const queuer = new Queuer(fn, mergedOptions) as unknown as SolidQueuer<\n TValue,\n TSelected\n >\n\n queuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: QueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(queuer.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(queuer.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n })\n })\n\n return {\n ...queuer,\n state,\n } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,aACd,IACA,UAAiD,CAAC,GAClD,kBAA6D,CAAC,IAC9B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,SAAS,IAAIC,8BAAO,IAAI,aAAa;CAK3C,OAAO,YAAY,SAAS,UAAqB,OAG9C;EACD,MAAM,eAAWC,mCAAY,OAAO,OAAO,MAAM,UAAU,EACzD,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,OAAO,OAAO,UAAU,EAAE,SAASC,8BAAQ,CAAC;CAEtE,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,MAAM;QAE9B,OAAO,KAAK;EAEhB,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
| import { Store } from "@tanstack/solid-store"; | ||
| import { Accessor, JSX } from "solid-js"; | ||
| import { Queuer, QueuerOptions, QueuerState } from "@tanstack/pacer/queuer"; | ||
| //#region src/queuer/createQueuer.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidQueuerOptions<TValue, TSelected = {}> extends QueuerOptions<TValue> { |
| import { Accessor, JSX } from "solid-js"; | ||
| import { Store } from "@tanstack/solid-store"; | ||
| import { Queuer, QueuerOptions, QueuerState } from "@tanstack/pacer/queuer"; | ||
| //#region src/queuer/createQueuer.d.ts | ||
@@ -6,0 +5,0 @@ interface SolidQueuerOptions<TValue, TSelected = {}> extends QueuerOptions<TValue> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createQueuer.js","names":[],"sources":["../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/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 { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidQueuer<TValue, TSelected = {}> extends Omit<\n Queuer<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) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Queue: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: QueuerState<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<QueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Queuer instance for managing a synchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Synchronous processing of items using the provided `fn` function\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Priority queueing via `getPriority` or item `priority` property\n * - Item expiration and removal of stale items\n * - Configurable wait time between processing items\n * - Pause/resume processing\n * - Callbacks for queue state changes, execution, rejection, and expiration\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The queue processes items synchronously in order, with optional delays between each item. When started, it will process one item per tick, with an optional wait time between ticks. You can pause and resume processing with `stop()` and `start()`.\n *\n * By default, the queue uses FIFO behavior, but you can configure LIFO or double-ended queueing by specifying the position when adding or removing items.\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 * - `executionCount`: Number of items that have been processed\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `items`: Array of items currently queued for processing\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = createQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const queue = createQueuer(\n * (item) => {\n * // process item synchronously\n * console.log('Processing', item);\n * },\n * {\n * started: true, // Start processing immediately\n * wait: 1000, // Process one item every second\n * getPriority: (item) => item.priority // Process higher priority items first\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to process - they'll be handled automatically\n * queue.addItem('task1');\n * queue.addItem('task2');\n *\n * // Control the scheduler\n * queue.stop(); // Pause processing\n * queue.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = queue.state();\n * ```\n */\nexport function createQueuer<TValue, TSelected = {}>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): SolidQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as SolidQueuerOptions<TValue, TSelected>\n const queuer = new Queuer(fn, mergedOptions) as unknown as SolidQueuer<\n TValue,\n TSelected\n >\n\n queuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: QueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(queuer.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(queuer.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n })\n })\n\n return {\n ...queuer,\n state,\n } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,aACd,IACA,UAAiD,EAAE,EACnD,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,SAAS,IAAI,OAAO,IAAI,cAAc;CAK5C,OAAO,YAAY,SAAS,UAAqB,OAG9C;EACD,MAAM,WAAW,YAAY,OAAO,OAAO,MAAM,UAAU,EACzD,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,OAAO,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAEvE,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,OAAO;QAE/B,OAAO,MAAM;IAEf;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createQueuer.js","names":[],"sources":["../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/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 { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuerOptions<\n TValue,\n TSelected = {},\n> extends QueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidQueuer<TValue, TSelected = {}> extends Omit<\n Queuer<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) => ({ size: state.size, isRunning: state.isRunning })}>\n * {(state) => (\n * <div>Queue: {state().size} items, {state().isRunning ? 'Processing' : 'Idle'}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: QueuerState<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<QueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Queuer instance for managing a synchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Synchronous processing of items using the provided `fn` function\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Priority queueing via `getPriority` or item `priority` property\n * - Item expiration and removal of stale items\n * - Configurable wait time between processing items\n * - Pause/resume processing\n * - Callbacks for queue state changes, execution, rejection, and expiration\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The queue processes items synchronously in order, with optional delays between each item. When started, it will process one item per tick, with an optional wait time between ticks. You can pause and resume processing with `stop()` and `start()`.\n *\n * By default, the queue uses FIFO behavior, but you can configure LIFO or double-ended queueing by specifying the position when adding or removing items.\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 * - `executionCount`: Number of items that have been processed\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `items`: Array of items currently queued for processing\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending items instead:\n *\n * ```tsx\n * const queue = createQueuer(fn, {\n * started: true,\n * wait: 1000,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const queue = createQueuer(\n * (item) => {\n * // process item synchronously\n * console.log('Processing', item);\n * },\n * {\n * started: true, // Start processing immediately\n * wait: 1000, // Process one item every second\n * getPriority: (item) => item.priority // Process higher priority items first\n * }\n * );\n *\n * // Opt-in to track items or isRunning changes (optimized for UI updates)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({ items: state.items, isRunning: state.isRunning })\n * );\n *\n * // Opt-in to track execution metrics changes (optimized for tracking progress)\n * const queue = createQueuer(\n * (item) => console.log('Processing', item),\n * { started: true, wait: 1000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Add items to process - they'll be handled automatically\n * queue.addItem('task1');\n * queue.addItem('task2');\n *\n * // Control the scheduler\n * queue.stop(); // Pause processing\n * queue.start(); // Resume processing\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { items, isRunning } = queue.state();\n * ```\n */\nexport function createQueuer<TValue, TSelected = {}>(\n fn: (item: TValue) => void,\n options: SolidQueuerOptions<TValue, TSelected> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): SolidQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().queuer,\n ...options,\n } as SolidQueuerOptions<TValue, TSelected>\n const queuer = new Queuer(fn, mergedOptions) as unknown as SolidQueuer<\n TValue,\n TSelected\n >\n\n queuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: QueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(queuer.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(queuer.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(queuer)\n } else {\n queuer.stop()\n }\n })\n })\n\n return {\n ...queuer,\n state,\n } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,SAAgB,aACd,IACA,UAAiD,CAAC,GAClD,kBAA6D,CAAC,IAC9B;CAChC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,SAAS,IAAI,OAAO,IAAI,aAAa;CAK3C,OAAO,YAAY,SAAS,UAAqB,OAG9C;EACD,MAAM,WAAW,YAAY,OAAO,OAAO,MAAM,UAAU,EACzD,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,OAAO,OAAO,UAAU,EAAE,SAAS,QAAQ,CAAC;CAEtE,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,MAAM;QAE9B,OAAO,KAAK;EAEhB,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedSignal.cjs","names":["createRateLimiter"],"sources":["../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A Solid hook that creates a rate-limited state value that enforces a hard limit on state updates within a time window.\n * This hook combines Solid's createSignal with rate limiting functionality to provide controlled state updates.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledSignal: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedSignal: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - The rate-limited state value accessor\n * - A rate-limited setter function that respects the configured limits\n * - The rateLimiter instance for additional control\n *\n * For more direct control over rate limiting without state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `callsInWindow`: Number of calls made in the current window\n * - `remainingInWindow`: Number of calls remaining in the current window\n * - `windowStart`: Unix timestamp when the current window started\n * - `nextWindowStart`: Unix timestamp when the next window will start\n * - `msUntilNextWindow`: Milliseconds until the next window starts\n * - `isAtLimit`: Whether the call limit for the current window has been reached\n * - `status`: Current status ('disabled' | 'idle' | 'at-limit')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when limit state changes (optimized for UI feedback)\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(\n * 0,\n * { limit: 5, window: 60000 },\n * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow })\n * );\n *\n * // With rejection callback and fixed window\n * const [value, setValue] = createRateLimitedSignal(0, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access rateLimiter state via signals\n * const handleSubmit = () => {\n * const remaining = rateLimiter.state().remainingInWindow;\n * if (remaining > 0) {\n * setValue(newValue);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n * ```\n */\nexport function createRateLimitedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidRateLimiter<Setter<TValue>, TSelected>,\n] {\n const [rateLimitedValue, setRateLimitedValue] = createSignal<TValue>(value)\n\n const rateLimiter = createRateLimiter(\n setRateLimitedValue,\n initialOptions,\n selector,\n )\n\n return [\n rateLimitedValue,\n rateLimiter.maybeExecute as Setter<TValue>,\n rateLimiter,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,wBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,kBAAkB,kDAA4C,MAAM;CAE3E,MAAM,cAAcA,4CAClB,qBACA,gBACA,SACD;CAED,OAAO;EACL;EACA,YAAY;EACZ;EACD"} | ||
| {"version":3,"file":"createRateLimitedSignal.cjs","names":["createSignal","createRateLimiter"],"sources":["../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A Solid hook that creates a rate-limited state value that enforces a hard limit on state updates within a time window.\n * This hook combines Solid's createSignal with rate limiting functionality to provide controlled state updates.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledSignal: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedSignal: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - The rate-limited state value accessor\n * - A rate-limited setter function that respects the configured limits\n * - The rateLimiter instance for additional control\n *\n * For more direct control over rate limiting without state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `callsInWindow`: Number of calls made in the current window\n * - `remainingInWindow`: Number of calls remaining in the current window\n * - `windowStart`: Unix timestamp when the current window started\n * - `nextWindowStart`: Unix timestamp when the next window will start\n * - `msUntilNextWindow`: Milliseconds until the next window starts\n * - `isAtLimit`: Whether the call limit for the current window has been reached\n * - `status`: Current status ('disabled' | 'idle' | 'at-limit')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when limit state changes (optimized for UI feedback)\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(\n * 0,\n * { limit: 5, window: 60000 },\n * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow })\n * );\n *\n * // With rejection callback and fixed window\n * const [value, setValue] = createRateLimitedSignal(0, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access rateLimiter state via signals\n * const handleSubmit = () => {\n * const remaining = rateLimiter.state().remainingInWindow;\n * if (remaining > 0) {\n * setValue(newValue);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n * ```\n */\nexport function createRateLimitedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidRateLimiter<Setter<TValue>, TSelected>,\n] {\n const [rateLimitedValue, setRateLimitedValue] = createSignal<TValue>(value)\n\n const rateLimiter = createRateLimiter(\n setRateLimitedValue,\n initialOptions,\n selector,\n )\n\n return [\n rateLimitedValue,\n rateLimiter.maybeExecute as Setter<TValue>,\n rateLimiter,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,wBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,kBAAkB,2BAAuBA,uBAAqB,KAAK;CAE1E,MAAM,cAAcC,4CAClB,qBACA,gBACA,QACF;CAEA,OAAO;EACL;EACA,YAAY;EACZ;CACF;AACF"} |
| import { SolidRateLimiter, SolidRateLimiterOptions } from "./createRateLimiter.cjs"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { RateLimiterState } from "@tanstack/pacer/rate-limiter"; | ||
| //#region src/rate-limiter/createRateLimitedSignal.d.ts | ||
@@ -6,0 +5,0 @@ /** |
| import { SolidRateLimiter, SolidRateLimiterOptions } from "./createRateLimiter.js"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { RateLimiterState } from "@tanstack/pacer/rate-limiter"; | ||
| //#region src/rate-limiter/createRateLimitedSignal.d.ts | ||
@@ -6,0 +5,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedSignal.js","names":[],"sources":["../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A Solid hook that creates a rate-limited state value that enforces a hard limit on state updates within a time window.\n * This hook combines Solid's createSignal with rate limiting functionality to provide controlled state updates.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledSignal: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedSignal: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - The rate-limited state value accessor\n * - A rate-limited setter function that respects the configured limits\n * - The rateLimiter instance for additional control\n *\n * For more direct control over rate limiting without state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `callsInWindow`: Number of calls made in the current window\n * - `remainingInWindow`: Number of calls remaining in the current window\n * - `windowStart`: Unix timestamp when the current window started\n * - `nextWindowStart`: Unix timestamp when the next window will start\n * - `msUntilNextWindow`: Milliseconds until the next window starts\n * - `isAtLimit`: Whether the call limit for the current window has been reached\n * - `status`: Current status ('disabled' | 'idle' | 'at-limit')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when limit state changes (optimized for UI feedback)\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(\n * 0,\n * { limit: 5, window: 60000 },\n * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow })\n * );\n *\n * // With rejection callback and fixed window\n * const [value, setValue] = createRateLimitedSignal(0, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access rateLimiter state via signals\n * const handleSubmit = () => {\n * const remaining = rateLimiter.state().remainingInWindow;\n * if (remaining > 0) {\n * setValue(newValue);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n * ```\n */\nexport function createRateLimitedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidRateLimiter<Setter<TValue>, TSelected>,\n] {\n const [rateLimitedValue, setRateLimitedValue] = createSignal<TValue>(value)\n\n const rateLimiter = createRateLimiter(\n setRateLimitedValue,\n initialOptions,\n selector,\n )\n\n return [\n rateLimitedValue,\n rateLimiter.maybeExecute as Setter<TValue>,\n rateLimiter,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,wBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,kBAAkB,uBAAuB,aAAqB,MAAM;CAE3E,MAAM,cAAc,kBAClB,qBACA,gBACA,SACD;CAED,OAAO;EACL;EACA,YAAY;EACZ;EACD"} | ||
| {"version":3,"file":"createRateLimitedSignal.js","names":[],"sources":["../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A Solid hook that creates a rate-limited state value that enforces a hard limit on state updates within a time window.\n * This hook combines Solid's createSignal with rate limiting functionality to provide controlled state updates.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledSignal: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedSignal: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - The rate-limited state value accessor\n * - A rate-limited setter function that respects the configured limits\n * - The rateLimiter instance for additional control\n *\n * For more direct control over rate limiting without state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `callsInWindow`: Number of calls made in the current window\n * - `remainingInWindow`: Number of calls remaining in the current window\n * - `windowStart`: Unix timestamp when the current window started\n * - `nextWindowStart`: Unix timestamp when the next window will start\n * - `msUntilNextWindow`: Milliseconds until the next window starts\n * - `isAtLimit`: Whether the call limit for the current window has been reached\n * - `status`: Current status ('disabled' | 'idle' | 'at-limit')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when limit state changes (optimized for UI feedback)\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(\n * 0,\n * { limit: 5, window: 60000 },\n * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow })\n * );\n *\n * // With rejection callback and fixed window\n * const [value, setValue] = createRateLimitedSignal(0, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access rateLimiter state via signals\n * const handleSubmit = () => {\n * const remaining = rateLimiter.state().remainingInWindow;\n * if (remaining > 0) {\n * setValue(newValue);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n * ```\n */\nexport function createRateLimitedSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidRateLimiter<Setter<TValue>, TSelected>,\n] {\n const [rateLimitedValue, setRateLimitedValue] = createSignal<TValue>(value)\n\n const rateLimiter = createRateLimiter(\n setRateLimitedValue,\n initialOptions,\n selector,\n )\n\n return [\n rateLimitedValue,\n rateLimiter.maybeExecute as Setter<TValue>,\n rateLimiter,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,wBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,kBAAkB,uBAAuB,aAAqB,KAAK;CAE1E,MAAM,cAAc,kBAClB,qBACA,gBACA,QACF;CAEA,OAAO;EACL;EACA,YAAY;EACZ;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedValue.cjs","names":["createRateLimitedSignal"],"sources":["../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A high-level Solid hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.\n * This hook uses Solid's createSignal internally to manage the rate-limited state.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledValue: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the rate-limited value\n * - The rate limiter instance with control methods\n *\n * For more direct control over rate limiting behavior without Solid state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking successful updates)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to reactive updates when rejection count changes (optimized for tracking rate limit violations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to reactive updates when execution times change (optimized for window calculations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With rejection callback and fixed window\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access the selected rate limiter state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>] {\n const [rateLimitedValue, setRateLimitedValue, rateLimiter] =\n createRateLimitedSignal(value(), initialOptions, selector)\n\n createEffect(() => {\n setRateLimitedValue(value() as any)\n })\n\n return [rateLimitedValue, rateLimiter]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,uBACd,OACA,gBACA,UACiE;CACjE,MAAM,CAAC,kBAAkB,qBAAqB,eAC5CA,wDAAwB,OAAO,EAAE,gBAAgB,SAAS;CAE5D,iCAAmB;EACjB,oBAAoB,OAAO,CAAQ;GACnC;CAEF,OAAO,CAAC,kBAAkB,YAAY"} | ||
| {"version":3,"file":"createRateLimitedValue.cjs","names":["createRateLimitedSignal"],"sources":["../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A high-level Solid hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.\n * This hook uses Solid's createSignal internally to manage the rate-limited state.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledValue: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the rate-limited value\n * - The rate limiter instance with control methods\n *\n * For more direct control over rate limiting behavior without Solid state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking successful updates)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to reactive updates when rejection count changes (optimized for tracking rate limit violations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to reactive updates when execution times change (optimized for window calculations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With rejection callback and fixed window\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access the selected rate limiter state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>] {\n const [rateLimitedValue, setRateLimitedValue, rateLimiter] =\n createRateLimitedSignal(value(), initialOptions, selector)\n\n createEffect(() => {\n setRateLimitedValue(value() as any)\n })\n\n return [rateLimitedValue, rateLimiter]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,uBACd,OACA,gBACA,UACiE;CACjE,MAAM,CAAC,kBAAkB,qBAAqB,eAC5CA,wDAAwB,MAAM,GAAG,gBAAgB,QAAQ;CAE3D,iCAAmB;EACjB,oBAAoB,MAAM,CAAQ;CACpC,CAAC;CAED,OAAO,CAAC,kBAAkB,WAAW;AACvC"} |
| import { SolidRateLimiter, SolidRateLimiterOptions } from "./createRateLimiter.cjs"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { RateLimiterState } from "@tanstack/pacer/rate-limiter"; | ||
| //#region src/rate-limiter/createRateLimitedValue.d.ts | ||
@@ -6,0 +5,0 @@ /** |
| import { SolidRateLimiter, SolidRateLimiterOptions } from "./createRateLimiter.js"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { RateLimiterState } from "@tanstack/pacer/rate-limiter"; | ||
| //#region src/rate-limiter/createRateLimitedValue.d.ts | ||
@@ -6,0 +5,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedValue.js","names":[],"sources":["../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A high-level Solid hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.\n * This hook uses Solid's createSignal internally to manage the rate-limited state.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledValue: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the rate-limited value\n * - The rate limiter instance with control methods\n *\n * For more direct control over rate limiting behavior without Solid state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking successful updates)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to reactive updates when rejection count changes (optimized for tracking rate limit violations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to reactive updates when execution times change (optimized for window calculations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With rejection callback and fixed window\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access the selected rate limiter state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>] {\n const [rateLimitedValue, setRateLimitedValue, rateLimiter] =\n createRateLimitedSignal(value(), initialOptions, selector)\n\n createEffect(() => {\n setRateLimitedValue(value() as any)\n })\n\n return [rateLimitedValue, rateLimiter]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,uBACd,OACA,gBACA,UACiE;CACjE,MAAM,CAAC,kBAAkB,qBAAqB,eAC5C,wBAAwB,OAAO,EAAE,gBAAgB,SAAS;CAE5D,mBAAmB;EACjB,oBAAoB,OAAO,CAAQ;GACnC;CAEF,OAAO,CAAC,kBAAkB,YAAY"} | ||
| {"version":3,"file":"createRateLimitedValue.js","names":[],"sources":["../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type {\n SolidRateLimiter,\n SolidRateLimiterOptions,\n} from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { RateLimiterState } from '@tanstack/pacer/rate-limiter'\n\n/**\n * A high-level Solid hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.\n * This hook uses Solid's createSignal internally to manage the rate-limited state.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - createThrottledValue: When you want consistent spacing between updates (e.g. UI changes)\n * - createDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the rate-limited value\n * - The rate limiter instance with control methods\n *\n * For more direct control over rate limiting behavior without Solid state management,\n * consider using the lower-level createRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available rate limiter state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to reactive updates when execution count changes (optimized for tracking successful updates)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to reactive updates when rejection count changes (optimized for tracking rate limit violations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to reactive updates when execution times change (optimized for window calculations)\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With rejection callback and fixed window\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access the selected rate limiter state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidRateLimiterOptions<Setter<TValue>, TSelected>,\n selector?: (state: RateLimiterState) => TSelected,\n): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>] {\n const [rateLimitedValue, setRateLimitedValue, rateLimiter] =\n createRateLimitedSignal(value(), initialOptions, selector)\n\n createEffect(() => {\n setRateLimitedValue(value() as any)\n })\n\n return [rateLimitedValue, rateLimiter]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,uBACd,OACA,gBACA,UACiE;CACjE,MAAM,CAAC,kBAAkB,qBAAqB,eAC5C,wBAAwB,MAAM,GAAG,gBAAgB,QAAQ;CAE3D,mBAAmB;EACjB,oBAAoB,MAAM,CAAQ;CACpC,CAAC;CAED,OAAO,CAAC,kBAAkB,WAAW;AACvC"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter","shallow"],"sources":["../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\n\nexport interface SolidRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: SolidRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface SolidRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<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 })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: RateLimiterState) => 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<RateLimiterState>>\n}\n\n/**\n * A low-level Solid hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\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 \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\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 * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 * - `executionCount`: Number of function executions that have been completed\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `currentWindowStart`: Timestamp when the current window started\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = createRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to track execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to track rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to track execution times changes (optimized for window calculations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state();\n * ```\n */\nexport function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as SolidRateLimiterOptions<TFn, TSelected>\n const rateLimiter = new RateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidRateLimiter<TFn, TSelected>\n\n rateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(rateLimiter.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(rateLimiter.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n })\n })\n\n return {\n ...rateLimiter,\n state,\n } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwLA,SAAgB,kBACd,IACA,SACA,kBAA0D,EAAE,GAC1B;CAClC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,cAAc,IAAIC,yCACtB,IACA,cACD;CAED,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,kDAAuB,YAAY,OAAO,MAAM,UAAU,EAC9D,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,YAAY,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;CAE5E,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;IAEtC;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter","useSelector","shallow"],"sources":["../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\n\nexport interface SolidRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: SolidRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface SolidRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<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 })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: RateLimiterState) => 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<RateLimiterState>>\n}\n\n/**\n * A low-level Solid hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\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 \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\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 * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 * - `executionCount`: Number of function executions that have been completed\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `currentWindowStart`: Timestamp when the current window started\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = createRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to track execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to track rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to track execution times changes (optimized for window calculations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state();\n * ```\n */\nexport function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as SolidRateLimiterOptions<TFn, TSelected>\n const rateLimiter = new RateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidRateLimiter<TFn, TSelected>\n\n rateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(rateLimiter.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(rateLimiter.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n })\n })\n\n return {\n ...rateLimiter,\n state,\n } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwLA,SAAgB,kBACd,IACA,SACA,kBAA0D,CAAC,IACzB;CAClC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,cAAc,IAAIC,yCACtB,IACA,aACF;CAEA,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,eAAWC,mCAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,YAAY,OAAO,UAAU,EAAE,SAASC,8BAAQ,CAAC;CAE3E,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,WAAW;EAEvC,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -5,3 +5,2 @@ import { Store } from "@tanstack/solid-store"; | ||
| import { RateLimiter, RateLimiterOptions, RateLimiterState } from "@tanstack/pacer/rate-limiter"; | ||
| //#region src/rate-limiter/createRateLimiter.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidRateLimiterOptions<TFn extends AnyFunction, TSelected = {}> extends RateLimiterOptions<TFn> { |
@@ -5,3 +5,2 @@ import { Accessor, JSX } from "solid-js"; | ||
| import { AnyFunction } from "@tanstack/pacer/types"; | ||
| //#region src/rate-limiter/createRateLimiter.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidRateLimiterOptions<TFn extends AnyFunction, TSelected = {}> extends RateLimiterOptions<TFn> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimiter.js","names":[],"sources":["../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\n\nexport interface SolidRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: SolidRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface SolidRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<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 })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: RateLimiterState) => 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<RateLimiterState>>\n}\n\n/**\n * A low-level Solid hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\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 \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\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 * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 * - `executionCount`: Number of function executions that have been completed\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `currentWindowStart`: Timestamp when the current window started\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = createRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to track execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to track rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to track execution times changes (optimized for window calculations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state();\n * ```\n */\nexport function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as SolidRateLimiterOptions<TFn, TSelected>\n const rateLimiter = new RateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidRateLimiter<TFn, TSelected>\n\n rateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(rateLimiter.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(rateLimiter.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n })\n })\n\n return {\n ...rateLimiter,\n state,\n } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwLA,SAAgB,kBACd,IACA,SACA,kBAA0D,EAAE,GAC1B;CAClC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,cAAc,IAAI,YACtB,IACA,cACD;CAED,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,YAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAE5E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;IAEtC;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createRateLimiter.js","names":[],"sources":["../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\n\nexport interface SolidRateLimiterOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends RateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: SolidRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface SolidRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<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 })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: RateLimiterState) => 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<RateLimiterState>>\n}\n\n/**\n * A low-level Solid hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\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 \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\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 * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 * - `executionCount`: Number of function executions that have been completed\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `currentWindowStart`: Timestamp when the current window started\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = createRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {(state) => (\n * <div>Rejections: {state().rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to track execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to track rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to track execution times changes (optimized for window calculations)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state();\n * ```\n */\nexport function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidRateLimiterOptions<TFn, TSelected>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as SolidRateLimiterOptions<TFn, TSelected>\n const rateLimiter = new RateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidRateLimiter<TFn, TSelected>\n\n rateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: RateLimiterState) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(rateLimiter.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(rateLimiter.store, selector, { compare: shallow })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(rateLimiter)\n }\n })\n })\n\n return {\n ...rateLimiter,\n state,\n } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwLA,SAAgB,kBACd,IACA,SACA,kBAA0D,CAAC,IACzB;CAClC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,cAAc,IAAI,YACtB,IACA,aACF;CAEA,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,YAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,QAAQ,CAAC;CAE3E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,WAAW;EAEvC,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledSignal.cjs","names":["createThrottler"],"sources":["../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A Solid hook that creates a throttled state value that updates at most once within a specified time window.\n * This hook combines Solid's createSignal with throttling functionality to provide controlled state updates.\n *\n * Throttling ensures state updates occur at a controlled rate regardless of how frequently the setter is called.\n * This is useful for rate-limiting expensive updates or operations that depend on rapidly changing state.\n *\n * The hook returns a tuple containing:\n * - The throttled state value accessor\n * - A throttled setter function that respects the configured wait time\n * - The throttler instance for additional control\n *\n * For more direct control over throttling without state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [value, setValue, throttler] = createThrottledSignal(\n * 0,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // With custom leading/trailing behavior\n * const [value, setValue] = createThrottledSignal(0, {\n * wait: 1000,\n * leading: true, // Update immediately on first change\n * trailing: false // Skip trailing edge updates\n * });\n *\n * // Access throttler state via signals\n * console.log('Executions:', throttler.state().executionCount);\n * console.log('Is pending:', throttler.state().isPending);\n * console.log('Last execution:', throttler.state().lastExecutionTime);\n * console.log('Next execution:', throttler.state().nextExecutionTime);\n * ```\n */\nexport function createThrottledSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidThrottler<Setter<TValue>, TSelected>,\n] {\n const [throttledValue, setThrottledValue] = createSignal<TValue>(value)\n const throttler = createThrottler(setThrottledValue, initialOptions, selector)\n return [throttledValue, throttler.maybeExecute as Setter<TValue>, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,gDAA0C,MAAM;CACvE,MAAM,YAAYA,wCAAgB,mBAAmB,gBAAgB,SAAS;CAC9E,OAAO;EAAC;EAAgB,UAAU;EAAgC;EAAU"} | ||
| {"version":3,"file":"createThrottledSignal.cjs","names":["createSignal","createThrottler"],"sources":["../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A Solid hook that creates a throttled state value that updates at most once within a specified time window.\n * This hook combines Solid's createSignal with throttling functionality to provide controlled state updates.\n *\n * Throttling ensures state updates occur at a controlled rate regardless of how frequently the setter is called.\n * This is useful for rate-limiting expensive updates or operations that depend on rapidly changing state.\n *\n * The hook returns a tuple containing:\n * - The throttled state value accessor\n * - A throttled setter function that respects the configured wait time\n * - The throttler instance for additional control\n *\n * For more direct control over throttling without state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [value, setValue, throttler] = createThrottledSignal(\n * 0,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // With custom leading/trailing behavior\n * const [value, setValue] = createThrottledSignal(0, {\n * wait: 1000,\n * leading: true, // Update immediately on first change\n * trailing: false // Skip trailing edge updates\n * });\n *\n * // Access throttler state via signals\n * console.log('Executions:', throttler.state().executionCount);\n * console.log('Is pending:', throttler.state().isPending);\n * console.log('Last execution:', throttler.state().lastExecutionTime);\n * console.log('Next execution:', throttler.state().nextExecutionTime);\n * ```\n */\nexport function createThrottledSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidThrottler<Setter<TValue>, TSelected>,\n] {\n const [throttledValue, setThrottledValue] = createSignal<TValue>(value)\n const throttler = createThrottler(setThrottledValue, initialOptions, selector)\n return [throttledValue, throttler.maybeExecute as Setter<TValue>, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,yBAAqBA,uBAAqB,KAAK;CACtE,MAAM,YAAYC,wCAAgB,mBAAmB,gBAAgB,QAAQ;CAC7E,OAAO;EAAC;EAAgB,UAAU;EAAgC;CAAS;AAC7E"} |
| import { SolidThrottler, SolidThrottlerOptions } from "./createThrottler.cjs"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { ThrottlerState } from "@tanstack/pacer/throttler"; | ||
| //#region src/throttler/createThrottledSignal.d.ts | ||
@@ -6,0 +5,0 @@ /** |
| import { SolidThrottler, SolidThrottlerOptions } from "./createThrottler.js"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { ThrottlerState } from "@tanstack/pacer/throttler"; | ||
| //#region src/throttler/createThrottledSignal.d.ts | ||
@@ -6,0 +5,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledSignal.js","names":[],"sources":["../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A Solid hook that creates a throttled state value that updates at most once within a specified time window.\n * This hook combines Solid's createSignal with throttling functionality to provide controlled state updates.\n *\n * Throttling ensures state updates occur at a controlled rate regardless of how frequently the setter is called.\n * This is useful for rate-limiting expensive updates or operations that depend on rapidly changing state.\n *\n * The hook returns a tuple containing:\n * - The throttled state value accessor\n * - A throttled setter function that respects the configured wait time\n * - The throttler instance for additional control\n *\n * For more direct control over throttling without state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [value, setValue, throttler] = createThrottledSignal(\n * 0,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // With custom leading/trailing behavior\n * const [value, setValue] = createThrottledSignal(0, {\n * wait: 1000,\n * leading: true, // Update immediately on first change\n * trailing: false // Skip trailing edge updates\n * });\n *\n * // Access throttler state via signals\n * console.log('Executions:', throttler.state().executionCount);\n * console.log('Is pending:', throttler.state().isPending);\n * console.log('Last execution:', throttler.state().lastExecutionTime);\n * console.log('Next execution:', throttler.state().nextExecutionTime);\n * ```\n */\nexport function createThrottledSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidThrottler<Setter<TValue>, TSelected>,\n] {\n const [throttledValue, setThrottledValue] = createSignal<TValue>(value)\n const throttler = createThrottler(setThrottledValue, initialOptions, selector)\n return [throttledValue, throttler.maybeExecute as Setter<TValue>, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,qBAAqB,aAAqB,MAAM;CACvE,MAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,SAAS;CAC9E,OAAO;EAAC;EAAgB,UAAU;EAAgC;EAAU"} | ||
| {"version":3,"file":"createThrottledSignal.js","names":[],"sources":["../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A Solid hook that creates a throttled state value that updates at most once within a specified time window.\n * This hook combines Solid's createSignal with throttling functionality to provide controlled state updates.\n *\n * Throttling ensures state updates occur at a controlled rate regardless of how frequently the setter is called.\n * This is useful for rate-limiting expensive updates or operations that depend on rapidly changing state.\n *\n * The hook returns a tuple containing:\n * - The throttled state value accessor\n * - A throttled setter function that respects the configured wait time\n * - The throttler instance for additional control\n *\n * For more direct control over throttling without state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [value, setValue, throttler] = createThrottledSignal(\n * 0,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // With custom leading/trailing behavior\n * const [value, setValue] = createThrottledSignal(0, {\n * wait: 1000,\n * leading: true, // Update immediately on first change\n * trailing: false // Skip trailing edge updates\n * });\n *\n * // Access throttler state via signals\n * console.log('Executions:', throttler.state().executionCount);\n * console.log('Is pending:', throttler.state().isPending);\n * console.log('Last execution:', throttler.state().lastExecutionTime);\n * console.log('Next execution:', throttler.state().nextExecutionTime);\n * ```\n */\nexport function createThrottledSignal<TValue, TSelected = {}>(\n value: TValue,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [\n Accessor<TValue>,\n Setter<TValue>,\n SolidThrottler<Setter<TValue>, TSelected>,\n] {\n const [throttledValue, setThrottledValue] = createSignal<TValue>(value)\n const throttler = createThrottler(setThrottledValue, initialOptions, selector)\n return [throttledValue, throttler.maybeExecute as Setter<TValue>, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,sBACd,OACA,gBACA,UAKA;CACA,MAAM,CAAC,gBAAgB,qBAAqB,aAAqB,KAAK;CACtE,MAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;CAC7E,OAAO;EAAC;EAAgB,UAAU;EAAgC;CAAS;AAC7E"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledValue.cjs","names":["createThrottledSignal"],"sources":["../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A high-level Solid hook that creates a throttled version of a value that updates at most once within a specified time window.\n * This hook uses Solid's createSignal internally to manage the throttled state.\n *\n * Throttling ensures the value updates occur at a controlled rate regardless of how frequently the input value changes.\n * This is useful for rate-limiting expensive updates or API calls that depend on rapidly changing values.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the throttled value\n * - The throttler instance with control methods\n *\n * The throttled value will update according to the leading/trailing edge behavior specified in the options.\n *\n * For more direct control over throttling behavior without Solid state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [throttledValue, throttler] = createThrottledValue(\n * rawValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Use the throttled value\n * console.log(throttledValue()); // Access the current throttled value\n *\n * // Access throttler state via signals\n * console.log('Is pending:', throttler.state().isPending);\n *\n * // Control the throttler\n * throttler.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createThrottledValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>] {\n const [throttledValue, setThrottledValue, throttler] = createThrottledSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setThrottledValue(value() as any)\n })\n\n return [throttledValue, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAaA,oDACrD,OAAO,EACP,gBACA,SACD;CAED,iCAAmB;EACjB,kBAAkB,OAAO,CAAQ;GACjC;CAEF,OAAO,CAAC,gBAAgB,UAAU"} | ||
| {"version":3,"file":"createThrottledValue.cjs","names":["createThrottledSignal"],"sources":["../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A high-level Solid hook that creates a throttled version of a value that updates at most once within a specified time window.\n * This hook uses Solid's createSignal internally to manage the throttled state.\n *\n * Throttling ensures the value updates occur at a controlled rate regardless of how frequently the input value changes.\n * This is useful for rate-limiting expensive updates or API calls that depend on rapidly changing values.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the throttled value\n * - The throttler instance with control methods\n *\n * The throttled value will update according to the leading/trailing edge behavior specified in the options.\n *\n * For more direct control over throttling behavior without Solid state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [throttledValue, throttler] = createThrottledValue(\n * rawValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Use the throttled value\n * console.log(throttledValue()); // Access the current throttled value\n *\n * // Access throttler state via signals\n * console.log('Is pending:', throttler.state().isPending);\n *\n * // Control the throttler\n * throttler.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createThrottledValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>] {\n const [throttledValue, setThrottledValue, throttler] = createThrottledSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setThrottledValue(value() as any)\n })\n\n return [throttledValue, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAaA,oDACrD,MAAM,GACN,gBACA,QACF;CAEA,iCAAmB;EACjB,kBAAkB,MAAM,CAAQ;CAClC,CAAC;CAED,OAAO,CAAC,gBAAgB,SAAS;AACnC"} |
| import { SolidThrottler, SolidThrottlerOptions } from "./createThrottler.cjs"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { ThrottlerState } from "@tanstack/pacer/throttler"; | ||
| //#region src/throttler/createThrottledValue.d.ts | ||
@@ -6,0 +5,0 @@ /** |
| import { SolidThrottler, SolidThrottlerOptions } from "./createThrottler.js"; | ||
| import { Accessor, Setter } from "solid-js"; | ||
| import { ThrottlerState } from "@tanstack/pacer/throttler"; | ||
| //#region src/throttler/createThrottledValue.d.ts | ||
@@ -6,0 +5,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledValue.js","names":[],"sources":["../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A high-level Solid hook that creates a throttled version of a value that updates at most once within a specified time window.\n * This hook uses Solid's createSignal internally to manage the throttled state.\n *\n * Throttling ensures the value updates occur at a controlled rate regardless of how frequently the input value changes.\n * This is useful for rate-limiting expensive updates or API calls that depend on rapidly changing values.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the throttled value\n * - The throttler instance with control methods\n *\n * The throttled value will update according to the leading/trailing edge behavior specified in the options.\n *\n * For more direct control over throttling behavior without Solid state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [throttledValue, throttler] = createThrottledValue(\n * rawValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Use the throttled value\n * console.log(throttledValue()); // Access the current throttled value\n *\n * // Access throttler state via signals\n * console.log('Is pending:', throttler.state().isPending);\n *\n * // Control the throttler\n * throttler.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createThrottledValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>] {\n const [throttledValue, setThrottledValue, throttler] = createThrottledSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setThrottledValue(value() as any)\n })\n\n return [throttledValue, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAa,sBACrD,OAAO,EACP,gBACA,SACD;CAED,mBAAmB;EACjB,kBAAkB,OAAO,CAAQ;GACjC;CAEF,OAAO,CAAC,gBAAgB,UAAU"} | ||
| {"version":3,"file":"createThrottledValue.js","names":[],"sources":["../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler, SolidThrottlerOptions } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type { ThrottlerState } from '@tanstack/pacer/throttler'\n\n/**\n * A high-level Solid hook that creates a throttled version of a value that updates at most once within a specified time window.\n * This hook uses Solid's createSignal internally to manage the throttled state.\n *\n * Throttling ensures the value updates occur at a controlled rate regardless of how frequently the input value changes.\n * This is useful for rate-limiting expensive updates or API calls that depend on rapidly changing values.\n *\n * The hook returns a tuple containing:\n * - An accessor function that provides the throttled value\n * - The throttler instance with control methods\n *\n * The throttled value will update according to the leading/trailing edge behavior specified in the options.\n *\n * For more direct control over throttling behavior without Solid state management,\n * consider using the lower-level createThrottler hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying throttler instance.\n * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates,\n * optimizing performance by preventing unnecessary subscriptions when irrelevant 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. This prevents unnecessary reactive updates and gives you\n * full control over when your component subscribes to state changes. Only when you provide a selector will\n * the reactive system track the selected state values.\n *\n * Available throttler state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Unix timestamp of the last execution\n * - `nextExecutionTime`: Unix timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 });\n *\n * // Opt-in to reactive updates when pending state changes (optimized for loading indicators)\n * const [throttledValue, throttler] = createThrottledValue(\n * rawValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Use the throttled value\n * console.log(throttledValue()); // Access the current throttled value\n *\n * // Access throttler state via signals\n * console.log('Is pending:', throttler.state().isPending);\n *\n * // Control the throttler\n * throttler.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createThrottledValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: SolidThrottlerOptions<Setter<TValue>, TSelected>,\n selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected,\n): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>] {\n const [throttledValue, setThrottledValue, throttler] = createThrottledSignal(\n value(),\n initialOptions,\n selector,\n )\n\n createEffect(() => {\n setThrottledValue(value() as any)\n })\n\n return [throttledValue, throttler]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,qBACd,OACA,gBACA,UAC+D;CAC/D,MAAM,CAAC,gBAAgB,mBAAmB,aAAa,sBACrD,MAAM,GACN,gBACA,QACF;CAEA,mBAAmB;EACjB,kBAAkB,MAAM,CAAQ;CAClC,CAAC;CAED,OAAO,CAAC,gBAAgB,SAAS;AACnC"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottler.cjs","names":["useDefaultPacerOptions","Throttler","shallow"],"sources":["../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Solid's createSignal, see createThrottledSignal.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to track isPending changes at hook level (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const throttler = createThrottler(\n * setValue,\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, executionCount } = throttler.state();\n * ```\n */\nexport function createThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as SolidThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,gBACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAIC,oCACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,kDAAuB,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAEvC,eAAe,QAAQ;IAEzB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createThrottler.cjs","names":["useDefaultPacerOptions","Throttler","useSelector","shallow"],"sources":["../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Solid's createSignal, see createThrottledSignal.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to track isPending changes at hook level (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const throttler = createThrottler(\n * setValue,\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, executionCount } = throttler.state();\n * ```\n */\nexport function createThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as SolidThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,gBACd,IACA,SACA,kBAA6D,CAAC,IAC9B;CAChC,MAAM,gBAAgB;EACpB,GAAGA,6CAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAIC,oCACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,eAAWC,mCAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAASC,8BACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,YAAQD,mCAAY,eAAe,OAAO,UAAU,EACxD,SAASC,8BACX,CAAC;CAED,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QAEtC,eAAe,OAAO;EAE1B,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
@@ -5,3 +5,2 @@ import { Store } from "@tanstack/solid-store"; | ||
| import { Throttler, ThrottlerOptions, ThrottlerState } from "@tanstack/pacer/throttler"; | ||
| //#region src/throttler/createThrottler.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidThrottlerOptions<TFn extends AnyFunction, TSelected = {}> extends ThrottlerOptions<TFn> { |
@@ -5,3 +5,2 @@ import { Accessor, JSX } from "solid-js"; | ||
| import { AnyFunction } from "@tanstack/pacer/types"; | ||
| //#region src/throttler/createThrottler.d.ts | ||
@@ -8,0 +7,0 @@ interface SolidThrottlerOptions<TFn extends AnyFunction, TSelected = {}> extends ThrottlerOptions<TFn> { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottler.js","names":[],"sources":["../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Solid's createSignal, see createThrottledSignal.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to track isPending changes at hook level (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const throttler = createThrottler(\n * setValue,\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, executionCount } = throttler.state();\n * ```\n */\nexport function createThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as SolidThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,gBACd,IACA,SACA,kBAA6D,EAAE,GAC/B;CAChC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAI,UACzB,IACA,cACD;CAED,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;CAEF,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAEvC,eAAe,QAAQ;IAEzB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"} | ||
| {"version":3,"file":"createThrottler.js","names":[],"sources":["../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\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 { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottlerOptions<\n TFn extends AnyFunction,\n TSelected = {},\n> extends ThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: SolidThrottler<TFn, TSelected>) => void\n}\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<Throttler<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the throttler state.\n *\n * This is useful for tracking specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<ThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates a `Throttler` instance that limits how often the provided function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that\n * integrates directly with Solid's createSignal, see createThrottledSignal.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution when the owning component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const throttler = createThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Subscribe to state changes deep in component tree using Subscribe component\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {(state) => (\n * <div>{state().isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n *\n * // Opt-in to track isPending changes at hook level (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to track executionCount changes (optimized for tracking execution)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Multiple state properties - track when any of these change\n * const throttler = createThrottler(\n * setValue,\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * },\n * (state) => ({\n * isPending: state.isPending,\n * executionCount: state.executionCount,\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, executionCount } = throttler.state();\n * ```\n */\nexport function createThrottler<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: SolidThrottlerOptions<TFn, TSelected>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().throttler,\n ...options,\n } as SolidThrottlerOptions<TFn, TSelected>\n const asyncThrottler = new Throttler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidThrottler<TFn, TSelected>\n\n asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: ThrottlerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useSelector(asyncThrottler.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(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n }\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,SAAgB,gBACd,IACA,SACA,kBAA6D,CAAC,IAC9B;CAChC,MAAM,gBAAgB;EACpB,GAAG,uBAAuB,CAAC,CAAC;EAC5B,GAAG;CACL;CACA,MAAM,iBAAiB,IAAI,UACzB,IACA,aACF;CAEA,eAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,YAAY,eAAe,OAAO,MAAM,UAAU,EACjE,SAAS,QACX,CAAC;EAED,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,QAAQ,IACvB,MAAM;CACZ;CAEA,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,QACX,CAAC;CAED,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,cAAc;QAEtC,eAAe,OAAO;EAE1B,CAAC;CACH,CAAC;CAED,OAAO;EACL,GAAG;EACH;CACF;AACF"} |
| var _tanstack_pacer_types = require("@tanstack/pacer/types"); | ||
@@ -4,0 +3,0 @@ Object.keys(_tanstack_pacer_types).forEach(function (k) { |
| var _tanstack_pacer_utils = require("@tanstack/pacer/utils"); | ||
@@ -4,0 +3,0 @@ Object.keys(_tanstack_pacer_utils).forEach(function (k) { |
+5
-5
| { | ||
| "name": "@tanstack/solid-pacer", | ||
| "version": "0.21.1", | ||
| "version": "0.22.0", | ||
| "description": "Utilities for debouncing and throttling functions in Solid.", | ||
@@ -97,8 +97,8 @@ "author": "Tanner Linsley", | ||
| "dependencies": { | ||
| "@tanstack/solid-store": "^0.11.0", | ||
| "@tanstack/pacer": "0.21.1" | ||
| "@tanstack/solid-store": "^0.11.1", | ||
| "@tanstack/pacer": "0.22.0" | ||
| }, | ||
| "devDependencies": { | ||
| "solid-js": "^1.9.12", | ||
| "vite-plugin-solid": "^2.11.12" | ||
| "solid-js": "^1.9.14", | ||
| "vite-plugin-solid": "^2.11.14" | ||
| }, | ||
@@ -105,0 +105,0 @@ "peerDependencies": { |
+17
-2
| <div align="center"> | ||
| <img src="./media/header_pacer.png" > | ||
| <picture> | ||
| <source | ||
| media="(prefers-color-scheme: dark)" | ||
| srcset="https://tanstack.com/api/readme/pacer.png?theme=dark" | ||
| /> | ||
| <source | ||
| media="(prefers-color-scheme: light)" | ||
| srcset="https://tanstack.com/api/readme/pacer.png" | ||
| /> | ||
| <img | ||
| src="https://tanstack.com/api/readme/pacer.png" | ||
| alt="TanStack Pacer" | ||
| width="900" | ||
| /> | ||
| </picture> | ||
| </div> | ||
@@ -32,4 +46,5 @@ | ||
| <div align="center"> | ||
| ### [Become a Sponsor!](https://github.com/sponsors/tannerlinsley/) | ||
| </div> | ||
@@ -36,0 +51,0 @@ |
823161
0.16%181
9.04%+ Added
+ Added
- Removed
- Removed
Updated