@tanstack/solid-pacer
Advanced tools
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createAsyncBatcher(fn, initialOptions = {}, selector) { | ||
| function createAsyncBatcher(fn, initialOptions = {}, selector = () => ({})) { | ||
| const asyncBatcher$1 = new asyncBatcher.AsyncBatcher(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(asyncBatcher$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncBatcher.cjs","sources":["../../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcher<\n TValue,\n TSelected = AsyncBatcherState<TValue>,\n> extends Omit<AsyncBatcher<TValue>, 'store'> {\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\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 * Example usage:\n * ```tsx\n * // Basic async batcher for API requests\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 * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Use Solid signals in your UI\n * const items = asyncBatcher.state().items;\n * const isExecuting = asyncBatcher.state().isExecuting;\n * ```\n */\nexport function createAsyncBatcher<\n TValue,\n TSelected = AsyncBatcherState<TValue>,\n>(\n fn: (items: Array<TValue>) => Promise<any>,\n initialOptions: AsyncBatcherOptions<TValue> = {},\n selector?: (state: AsyncBatcherState<TValue>) => TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const asyncBatcher = new AsyncBatcher<TValue>(fn, initialOptions)\n\n const state = useStore(asyncBatcher.store, selector)\n\n return {\n ...asyncBatcher,\n state,\n } as unknown as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["asyncBatcher","AsyncBatcher","useStore"],"mappings":";;;;AAiFO,SAAS,mBAId,IACA,iBAA8C,CAAA,GAC9C,UACsC;AACtC,QAAMA,iBAAe,IAAIC,0BAAqB,IAAI,cAAc;AAEhE,QAAM,QAAQC,WAAAA,SAASF,eAAa,OAAO,QAAQ;AAEnD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createAsyncBatcher.cjs","sources":["../../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}>\n extends Omit<AsyncBatcher<TValue>, 'store'> {\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * 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 re-render when 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 re-render when 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 initialOptions: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const asyncBatcher = new AsyncBatcher<TValue>(fn, initialOptions)\n\n const state = useStore(asyncBatcher.store, selector)\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["asyncBatcher","AsyncBatcher","useStore"],"mappings":";;;;AA+HO,SAAS,mBACd,IACA,iBAA8C,CAAA,GAC9C,WAA4D,OACzD,CAAA,IACmC;AACtC,QAAMA,iBAAe,IAAIC,0BAAqB,IAAI,cAAc;AAEhE,QAAM,QAAQC,WAAAA,SAASF,eAAa,OAAO,QAAQ;AAEnD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from '@tanstack/pacer/async-batcher'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidAsyncBatcher<TValue, TSelected = AsyncBatcherState<TValue>> extends Omit<AsyncBatcher<TValue>, 'store'> { | ||
| export interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> { | ||
| /** | ||
@@ -10,2 +11,8 @@ * Reactive state that will be updated when the batcher state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncBatcherState<TValue>>>; | ||
| } | ||
@@ -42,5 +49,27 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `errorCount`: Number of failed batch executions | ||
| * - `executionCount`: Total number of batch execution attempts (successful + failed) | ||
| * - `hasError`: Whether the last batch execution resulted in an error | ||
| * - `isExecuting`: Whether a batch execution is currently in progress | ||
| * - `items`: Array of items currently queued for batching | ||
| * - `lastError`: The error from the most recent failed batch execution (if any) | ||
| * - `lastResult`: The result from the most recent successful batch execution | ||
| * - `settleCount`: Number of batch executions that have completed (successful or failed) | ||
| * - `successCount`: Number of successful batch executions | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Basic async batcher for API requests | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const asyncBatcher = createAsyncBatcher( | ||
@@ -63,2 +92,22 @@ * async (items) => { | ||
| * | ||
| * // Opt-in to re-render when items or isExecuting changes (optimized for UI updates) | ||
| * const asyncBatcher = createAsyncBatcher( | ||
| * async (items) => { | ||
| * const results = await Promise.all(items.map(item => processItem(item))); | ||
| * return results; | ||
| * }, | ||
| * { maxSize: 10, wait: 2000 }, | ||
| * (state) => ({ items: state.items, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const asyncBatcher = createAsyncBatcher( | ||
| * async (items) => { | ||
| * const results = await Promise.all(items.map(item => processItem(item))); | ||
| * return results; | ||
| * }, | ||
| * { maxSize: 10, wait: 2000 }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Add items to batch | ||
@@ -70,7 +119,6 @@ * asyncBatcher.addItem(newItem); | ||
| * | ||
| * // Use Solid signals in your UI | ||
| * const items = asyncBatcher.state().items; | ||
| * const isExecuting = asyncBatcher.state().isExecuting; | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isExecuting } = asyncBatcher.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncBatcher<TValue, TSelected = AsyncBatcherState<TValue>>(fn: (items: Array<TValue>) => Promise<any>, initialOptions?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): SolidAsyncBatcher<TValue, TSelected>; | ||
| export declare function createAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, initialOptions?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): SolidAsyncBatcher<TValue, TSelected>; |
@@ -6,3 +6,3 @@ "use strict"; | ||
| const solidJs = require("solid-js"); | ||
| function createAsyncDebouncer(fn, initialOptions, selector) { | ||
| function createAsyncDebouncer(fn, initialOptions, selector = () => ({})) { | ||
| const asyncDebouncer$1 = new asyncDebouncer.AsyncDebouncer(fn, initialOptions); | ||
@@ -9,0 +9,0 @@ const state = solidStore.useStore(asyncDebouncer$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncDebouncer.cjs","sources":["../../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport type { Accessor } 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 SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncDebouncerState<TFn>,\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Basic API call debouncing\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 * // With state management\n * const [results, setResults] = createSignal([]);\n * const { maybeExecute } = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(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 * );\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncDebouncerState<TFn>,\n>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n selector?: (state: AsyncDebouncerState<TFn>) => TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const asyncDebouncer = new AsyncDebouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as unknown as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["asyncDebouncer","AsyncDebouncer","useStore","createEffect","onCleanup"],"mappings":";;;;;AA2EO,SAAS,qBAId,IACA,gBACA,UACqC;AACrC,QAAMA,mBAAiB,IAAIC,8BAAoB,IAAI,cAAc;AAEjE,QAAM,QAAQC,WAAAA,SAASF,iBAAe,OAAO,QAAQ;AAErDG,UAAAA,aAAa,MAAM;AACjBC,YAAAA,UAAU,MAAM;AACdJ,uBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createAsyncDebouncer.cjs","sources":["../../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } 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 SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * @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 re-render when 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 re-render when 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 initialOptions: AsyncDebouncerOptions<TFn>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const asyncDebouncer = new AsyncDebouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["asyncDebouncer","AsyncDebouncer","useStore","createEffect","onCleanup"],"mappings":";;;;;AAqHO,SAAS,qBAId,IACA,gBACA,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAMA,mBAAiB,IAAIC,8BAAoB,IAAI,cAAc;AAEjE,QAAM,QAAQC,WAAAA,SAASF,iBAAe,OAAO,QAAQ;AAErDG,UAAAA,aAAa,MAAM;AACjBC,YAAAA,UAAU,MAAM;AACdJ,uBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { AsyncDebouncer, AsyncDebouncerOptions, AsyncDebouncerState } from '@tanstack/pacer/async-debouncer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyAsyncFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = AsyncDebouncerState<TFn>> extends Omit<AsyncDebouncer<TFn>, 'store'> { | ||
| export interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncDebouncer<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the debouncer state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>; | ||
| } | ||
@@ -37,5 +44,27 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call debouncing | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncDebouncer( | ||
@@ -49,8 +78,17 @@ * async (query: string) => { | ||
| * | ||
| * // With state management | ||
| * const [results, setResults] = createSignal([]); | ||
| * const { maybeExecute } = createAsyncDebouncer( | ||
| * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states) | ||
| * const debouncer = createAsyncDebouncer( | ||
| * async (query: string) => { | ||
| * const results = await api.search(query); | ||
| * return results; | ||
| * }, | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const debouncer = createAsyncDebouncer( | ||
| * async (searchTerm) => { | ||
| * const data = await searchAPI(searchTerm); | ||
| * setResults(data); | ||
| * return data; | ||
| * }, | ||
@@ -64,6 +102,10 @@ * { | ||
| * } | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, isExecuting } = debouncer.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = AsyncDebouncerState<TFn>>(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): SolidAsyncDebouncer<TFn, TSelected>; | ||
| export declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): SolidAsyncDebouncer<TFn, TSelected>; |
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createAsyncQueuer(fn, initialOptions = {}, selector) { | ||
| function createAsyncQueuer(fn, initialOptions = {}, selector = () => ({})) { | ||
| const asyncQueuer$1 = new asyncQueuer.AsyncQueuer(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(asyncQueuer$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncQueuer.cjs","sources":["../../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>\n extends Omit<AsyncQueuer<TValue>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\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 * Example usage:\n * ```tsx\n * // Basic async queuer for API requests\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 * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Use Solid signals in your UI\n * const pending = asyncQueuer.pendingItems();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>(\n fn: (value: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue> = {},\n selector?: (state: AsyncQueuerState<TValue>) => TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n\n const state = useStore(asyncQueuer.store, selector)\n\n return {\n ...asyncQueuer,\n state,\n } as unknown as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["asyncQueuer","AsyncQueuer","useStore"],"mappings":";;;;AAsEO,SAAS,kBACd,IACA,iBAA6C,CAAA,GAC7C,UACqC;AACrC,QAAMA,gBAAc,IAAIC,wBAAoB,IAAI,cAAc;AAE9D,QAAM,QAAQC,WAAAA,SAASF,cAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createAsyncQueuer.cjs","sources":["../../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}>\n extends Omit<AsyncQueuer<TValue>, 'store'> {\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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * 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 re-render when 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 re-render when processing metrics change (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 initialOptions: AsyncQueuerOptions<TValue> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n\n const state = useStore(asyncQueuer.store, selector)\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["asyncQueuer","AsyncQueuer","useStore"],"mappings":";;;;AAuHO,SAAS,kBACd,IACA,iBAA6C,CAAA,GAC7C,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAMA,gBAAc,IAAIC,wBAAoB,IAAI,cAAc;AAE9D,QAAM,QAAQC,WAAAA,SAASF,cAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from '@tanstack/pacer/async-queuer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>> extends Omit<AsyncQueuer<TValue>, 'store'> { | ||
| export interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TValue>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated and re-rendered when the queuer state changes | ||
| * Reactive state that will be updated when the queuer state changes | ||
| * | ||
@@ -10,2 +11,8 @@ * Use this instead of `queuer.store.state` | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncQueuerState<TValue>>>; | ||
| } | ||
@@ -35,5 +42,25 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `activeItems`: Array of items currently being processed | ||
| * - `errorCount`: Number of items that failed processing | ||
| * - `isRunning`: Whether the queuer is currently running (not stopped) | ||
| * - `pendingItems`: Array of items waiting to be processed | ||
| * - `rejectionCount`: Number of items that were rejected (expired or failed validation) | ||
| * - `settleCount`: Number of items that have completed processing (successful or failed) | ||
| * - `successCount`: Number of items that were processed successfully | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Basic async queuer for API requests | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const asyncQueuer = createAsyncQueuer(async (item) => { | ||
@@ -55,2 +82,24 @@ * // process item | ||
| * | ||
| * // Opt-in to re-render when queue state changes (optimized for UI updates) | ||
| * const asyncQueuer = createAsyncQueuer( | ||
| * async (item) => await fetchData(item), | ||
| * { concurrency: 2, started: true }, | ||
| * (state) => ({ | ||
| * pendingItems: state.pendingItems, | ||
| * activeItems: state.activeItems, | ||
| * isRunning: state.isRunning | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when processing metrics change (optimized for tracking progress) | ||
| * const asyncQueuer = createAsyncQueuer( | ||
| * async (item) => await fetchData(item), | ||
| * { concurrency: 2, started: true }, | ||
| * (state) => ({ | ||
| * successCount: state.successCount, | ||
| * errorCount: state.errorCount, | ||
| * settleCount: state.settleCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to queue | ||
@@ -62,6 +111,6 @@ * asyncQueuer.addItem(newItem); | ||
| * | ||
| * // Use Solid signals in your UI | ||
| * const pending = asyncQueuer.pendingItems(); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { pendingItems, activeItems } = asyncQueuer.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>(fn: (value: TValue) => Promise<any>, initialOptions?: AsyncQueuerOptions<TValue>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>; | ||
| export declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, initialOptions?: AsyncQueuerOptions<TValue>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>; |
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createAsyncRateLimiter(fn, initialOptions, selector) { | ||
| function createAsyncRateLimiter(fn, initialOptions, selector = () => ({})) { | ||
| const asyncRateLimiter$1 = new asyncRateLimiter.AsyncRateLimiter(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(asyncRateLimiter$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncRateLimiter.cjs","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncRateLimiterState<TFn>,\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n readonly state: Accessor<Readonly<TSelected>>\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 * @example\n * ```tsx\n * // Basic API call rate limiting with return value\n * const { maybeExecute } = 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 * // With state management and return value\n * const [data, setData] = createSignal(null);\n * const { maybeExecute } = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`)\n * }\n * );\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncRateLimiterState<TFn>,\n>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n selector?: (state: AsyncRateLimiterState<TFn>) => TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"names":["asyncRateLimiter","AsyncRateLimiter","useStore"],"mappings":";;;;AA8EO,SAAS,uBAId,IACA,gBACA,UACuC;AACvC,QAAMA,qBAAmB,IAAIC,kCAAsB,IAAI,cAAc;AAErE,QAAM,QAAQC,WAAAA,SAASF,mBAAiB,OAAO,QAAQ;AAEvD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createAsyncRateLimiter.cjs","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = 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 * // Opt-in to re-render when rate limit and execution state changes (optimized for UI feedback)\n * const rateLimiter = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { limit: 10, window: 60000 },\n * (state) => ({\n * remainingInWindow: state.remainingInWindow,\n * isExecuting: state.isExecuting,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const rateLimiter = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`)\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 { remainingInWindow, isExecuting } = rateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"names":["asyncRateLimiter","AsyncRateLimiter","useStore"],"mappings":";;;;AAgIO,SAAS,uBAId,IACA,gBACA,WAA6D,OAC1D,CAAA,IACoC;AACvC,QAAMA,qBAAmB,IAAIC,kCAAsB,IAAI,cAAc;AAErE,QAAM,QAAQC,WAAAA,SAASF,mBAAiB,OAAO,QAAQ;AAEvD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState } from '@tanstack/pacer/async-rate-limiter'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyAsyncFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = AsyncRateLimiterState<TFn>> extends Omit<AsyncRateLimiter<TFn>, 'store'> { | ||
| export interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncRateLimiter<TFn>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated when the rate limiter state changes | ||
| * | ||
| * Use this instead of `rateLimiter.store.state` | ||
| */ | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>; | ||
| } | ||
@@ -42,5 +54,27 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `currentWindowStart`: Timestamp when the current window started | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `nextWindowTime`: Timestamp when the next window begins | ||
| * - `rejectionCount`: Number of function calls that were rejected due to rate limiting | ||
| * - `remainingInWindow`: Number of executions remaining in the current window | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call rate limiting with return value | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncRateLimiter( | ||
@@ -54,10 +88,22 @@ * async (id: string) => { | ||
| * | ||
| * // With state management and return value | ||
| * const [data, setData] = createSignal(null); | ||
| * const { maybeExecute } = createAsyncRateLimiter( | ||
| * // Opt-in to re-render when rate limit and execution state changes (optimized for UI feedback) | ||
| * const rateLimiter = createAsyncRateLimiter( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * setData(result); | ||
| * return result; // Return value can be used by the caller | ||
| * return result; | ||
| * }, | ||
| * { limit: 10, window: 60000 }, | ||
| * (state) => ({ | ||
| * remainingInWindow: state.remainingInWindow, | ||
| * isExecuting: state.isExecuting, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const rateLimiter = createAsyncRateLimiter( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * return result; | ||
| * }, | ||
| * { | ||
@@ -67,6 +113,10 @@ * limit: 10, | ||
| * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`) | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { remainingInWindow, isExecuting } = rateLimiter.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = AsyncRateLimiterState<TFn>>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>; | ||
| export declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>; |
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createAsyncThrottler(fn, initialOptions, selector) { | ||
| function createAsyncThrottler(fn, initialOptions, selector = () => ({})) { | ||
| const asyncThrottler$1 = new asyncThrottler.AsyncThrottler(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(asyncThrottler$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncThrottler.cjs","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncThrottlerState<TFn>,\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\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 * @example\n * ```tsx\n * // Basic API call throttling\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 * // With state management\n * const [data, setData] = createSignal(null);\n * const { maybeExecute } = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(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 * );\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncThrottlerState<TFn>,\n>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n selector?: (state: AsyncThrottlerState<TFn>) => TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"names":["asyncThrottler","AsyncThrottler","useStore"],"mappings":";;;;AAuEO,SAAS,qBAId,IACA,gBACA,UACqC;AACrC,QAAMA,mBAAiB,IAAIC,8BAAe,IAAI,cAAc;AAE5D,QAAM,QAAQC,WAAAA,SAASF,iBAAe,OAAO,QAAQ;AAErD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createAsyncThrottler.cjs","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to re-render when 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 re-render when 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 initialOptions: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"names":["asyncThrottler","AsyncThrottler","useStore"],"mappings":";;;;AAoHO,SAAS,qBAId,IACA,gBACA,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAMA,mBAAiB,IAAIC,8BAAe,IAAI,cAAc;AAE5D,QAAM,QAAQC,WAAAA,SAASF,iBAAe,OAAO,QAAQ;AAErD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from '@tanstack/pacer/async-throttler'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyAsyncFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = AsyncThrottlerState<TFn>> extends Omit<AsyncThrottler<TFn>, 'store'> { | ||
| export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated and re-rendered when the throttler state changes | ||
| * Reactive state that will be updated when the throttler state changes | ||
| * | ||
@@ -11,2 +12,8 @@ * Use this instead of `throttler.store.state` | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>; | ||
| } | ||
@@ -34,5 +41,30 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastExecutionTime`: Timestamp of the last execution | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `nextExecutionTime`: Timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call throttling | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncThrottler( | ||
@@ -46,9 +78,18 @@ * async (id: string) => { | ||
| * | ||
| * // With state management | ||
| * const [data, setData] = createSignal(null); | ||
| * const { maybeExecute } = createAsyncThrottler( | ||
| * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states) | ||
| * const throttler = createAsyncThrottler( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * setData(result); | ||
| * return result; | ||
| * }, | ||
| * { wait: 2000 }, | ||
| * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const throttler = createAsyncThrottler( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * return result; | ||
| * }, | ||
| * { | ||
@@ -61,6 +102,10 @@ * wait: 2000, | ||
| * } | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, isExecuting } = throttler.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = AsyncThrottlerState<TFn>>(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>; | ||
| export declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>; |
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createBatcher(fn, initialOptions = {}, selector) { | ||
| function createBatcher(fn, initialOptions = {}, selector = () => ({})) { | ||
| const batcher$1 = new batcher.Batcher(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(batcher$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createBatcher.cjs","sources":["../../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected = BatcherState<TValue>>\n extends Omit<Batcher<TValue>, 'store'> {\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\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 * Example usage:\n * ```tsx\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 * // 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 batcher state via signals\n * console.log('Items:', batcher.allItems());\n * console.log('Size:', batcher.size());\n * console.log('Is empty:', batcher.isEmpty());\n * console.log('Is running:', batcher.isRunning());\n * console.log('Batch count:', batcher.executionCount());\n * console.log('Item count:', batcher.totalItemsProcessed());\n * ```\n */\nexport function createBatcher<TValue, TSelected = BatcherState<TValue>>(\n fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue> = {},\n selector?: (state: BatcherState<TValue>) => TSelected,\n): SolidBatcher<TValue, TSelected> {\n const batcher = new Batcher(fn, initialOptions)\n\n const state = useStore(batcher.store, selector)\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"names":["batcher","Batcher","useStore"],"mappings":";;;;AA8DO,SAAS,cACd,IACA,iBAAyC,CAAA,GACzC,UACiC;AACjC,QAAMA,YAAU,IAAIC,gBAAQ,IAAI,cAAc;AAE9C,QAAM,QAAQC,WAAAA,SAASF,UAAQ,OAAO,QAAQ;AAC9C,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createBatcher.cjs","sources":["../../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected = {}>\n extends Omit<Batcher<TValue>, 'store'> {\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to re-render when 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 re-render when execution metrics change (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 initialOptions: BatcherOptions<TValue> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const batcher = new Batcher(fn, initialOptions)\n\n const state = useStore(batcher.store, selector)\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"names":["batcher","Batcher","useStore"],"mappings":";;;;AAmGO,SAAS,cACd,IACA,iBAAyC,CAAA,GACzC,WAAuD,OACpD,CAAA,IAC8B;AACjC,QAAMA,YAAU,IAAIC,gBAAQ,IAAI,cAAc;AAE9C,QAAM,QAAQC,WAAAA,SAASF,UAAQ,OAAO,QAAQ;AAC9C,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { Batcher, BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidBatcher<TValue, TSelected = BatcherState<TValue>> extends Omit<Batcher<TValue>, 'store'> { | ||
| export interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'store'> { | ||
| /** | ||
@@ -10,2 +11,8 @@ * Reactive state that will be updated when the batcher state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<BatcherState<TValue>>>; | ||
| } | ||
@@ -27,4 +34,22 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of batch executions that have been completed | ||
| * - `isRunning`: Whether the batcher is currently running (not stopped) | ||
| * - `items`: Array of items currently queued for batching | ||
| * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const batcher = createBatcher( | ||
@@ -43,2 +68,19 @@ * (items) => { | ||
| * | ||
| * // Opt-in to re-render when items or isRunning changes (optimized for UI updates) | ||
| * const batcher = createBatcher( | ||
| * (items) => console.log('Processing batch:', items), | ||
| * { maxSize: 5, wait: 2000 }, | ||
| * (state) => ({ items: state.items, isRunning: state.isRunning }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const batcher = createBatcher( | ||
| * (items) => console.log('Processing batch:', items), | ||
| * { maxSize: 5, wait: 2000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * totalItemsProcessed: state.totalItemsProcessed | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to batch | ||
@@ -52,11 +94,6 @@ * batcher.addItem('task1'); | ||
| * | ||
| * // Access batcher state via signals | ||
| * console.log('Items:', batcher.allItems()); | ||
| * console.log('Size:', batcher.size()); | ||
| * console.log('Is empty:', batcher.isEmpty()); | ||
| * console.log('Is running:', batcher.isRunning()); | ||
| * console.log('Batch count:', batcher.executionCount()); | ||
| * console.log('Item count:', batcher.totalItemsProcessed()); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isRunning } = batcher.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createBatcher<TValue, TSelected = BatcherState<TValue>>(fn: (items: Array<TValue>) => void, initialOptions?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>; | ||
| export declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, initialOptions?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedSignal.cjs","sources":["../../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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 * @example\n * ```tsx\n * // Debounced search input\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\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.executionCount());\n * console.log('Is pending:', debouncer.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<\n TValue,\n TSelected = DebouncerState<Setter<TValue>>,\n>(\n value: TValue,\n initialOptions: DebouncerOptions<Setter<TValue>>,\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"],"names":["createSignal","createDebouncer"],"mappings":";;;;AAgDO,SAAS,sBAId,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAIA,QAAAA,aAAqB,KAAK;AAEtE,QAAM,YAAYC,gBAAAA,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAE7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;;"} | ||
| {"version":3,"file":"createDebouncedSignal.cjs","sources":["../../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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: DebouncerOptions<Setter<TValue>>,\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"],"names":["createSignal","createDebouncer"],"mappings":";;;;AAgFO,SAAS,sBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAIA,QAAAA,aAAqB,KAAK;AAEtE,QAAM,YAAYC,gBAAAA,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAE7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;;"} |
@@ -18,5 +18,23 @@ import { SolidDebouncer } from './createDebouncer.cjs'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying debouncer instance. | ||
| * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available debouncer state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounced search input | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', { | ||
@@ -26,2 +44,16 @@ * wait: 500 // Wait 500ms after last keystroke | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal( | ||
| * '', | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to reactive updates when execution count changes (optimized for tracking executions) | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal( | ||
| * '', | ||
| * { wait: 500 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Update value - will be debounced | ||
@@ -33,4 +65,4 @@ * const handleChange = (e) => { | ||
| * // Access debouncer state via signals | ||
| * console.log('Executions:', debouncer.executionCount()); | ||
| * console.log('Is pending:', debouncer.isPending()); | ||
| * console.log('Executions:', debouncer.state().executionCount); | ||
| * console.log('Is pending:', debouncer.state().isPending); | ||
| * | ||
@@ -46,3 +78,3 @@ * // In onExecute callback, use get* methods | ||
| */ | ||
| export declare function createDebouncedSignal<TValue, TSelected = DebouncerState<Setter<TValue>>>(value: TValue, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [ | ||
| export declare function createDebouncedSignal<TValue, TSelected = {}>(value: TValue, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [ | ||
| Accessor<TValue>, | ||
@@ -49,0 +81,0 @@ Setter<TValue>, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedValue.cjs","sources":["../../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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 * @example\n * ```tsx\n * // Debounce a search query\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<\n TValue,\n TSelected = DebouncerState<Setter<TValue>>,\n>(\n value: Accessor<TValue>,\n initialOptions: DebouncerOptions<Setter<TValue>>,\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"],"names":["createDebouncedSignal","createEffect"],"mappings":";;;;AA2CO,SAAS,qBAId,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAIA,sBAAAA;AAAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGFC,UAAAA,aAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;;"} | ||
| {"version":3,"file":"createDebouncedValue.cjs","sources":["../../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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: DebouncerOptions<Setter<TValue>>,\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"],"names":["createDebouncedSignal","createEffect"],"mappings":";;;;AAuEO,SAAS,qBACd,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAIA,sBAAAA;AAAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGFC,UAAAA,aAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;;"} |
@@ -21,5 +21,23 @@ import { SolidDebouncer } from './createDebouncer.cjs'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying debouncer instance. | ||
| * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available debouncer state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounce a search query | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [searchQuery, setSearchQuery] = createSignal(''); | ||
@@ -30,2 +48,9 @@ * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, { | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [debouncedQuery, debouncer] = createDebouncedValue( | ||
| * searchQuery, | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // debouncedQuery will update 500ms after searchQuery stops changing | ||
@@ -36,2 +61,5 @@ * createEffect(() => { | ||
| * | ||
| * // Access debouncer state via signals | ||
| * console.log('Is pending:', debouncer.state().isPending); | ||
| * | ||
| * // Control the debouncer | ||
@@ -41,2 +69,2 @@ * debouncer.cancel(); // Cancel any pending updates | ||
| */ | ||
| export declare function createDebouncedValue<TValue, TSelected = DebouncerState<Setter<TValue>>>(value: Accessor<TValue>, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>]; | ||
| export declare function createDebouncedValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>]; |
@@ -6,3 +6,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createDebouncer(fn, initialOptions, selector) { | ||
| function createDebouncer(fn, initialOptions, selector = () => ({})) { | ||
| const asyncDebouncer = new debouncer.Debouncer(fn, initialOptions); | ||
@@ -9,0 +9,0 @@ const state = solidStore.useStore(asyncDebouncer.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncer.cjs","sources":["../../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncer<\n TFn extends AnyFunction,\n TSelected = DebouncerState<TFn>,\n> extends Omit<Debouncer<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Debounce a search function to limit API calls\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 } // Wait 500ms after last keystroke\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.executionCount());\n * console.log('Is pending:', debouncer.isPending());\n *\n * // Update options\n * debouncer.setOptions({ wait: 1000 });\n * ```\n */\nexport function createDebouncer<\n TFn extends AnyFunction,\n TSelected = DebouncerState<TFn>,\n>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n selector?: (state: DebouncerState<TFn>) => TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const asyncDebouncer = new Debouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["Debouncer","useStore","createEffect","onCleanup"],"mappings":";;;;;AA0DO,SAAS,gBAId,IACA,gBACA,UACgC;AAChC,QAAM,iBAAiB,IAAIA,oBAAe,IAAI,cAAc;AAE5D,QAAM,QAAQC,WAAAA,SAAS,eAAe,OAAO,QAAQ;AAErDC,UAAAA,aAAa,MAAM;AACjBC,YAAAA,UAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createDebouncer.cjs","sources":["../../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}>\n extends Omit<Debouncer<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * @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 re-render when 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 re-render when 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 - re-render 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 initialOptions: DebouncerOptions<TFn>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const asyncDebouncer = new Debouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["Debouncer","useStore","createEffect","onCleanup"],"mappings":";;;;;AAsGO,SAAS,gBACd,IACA,gBACA,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAM,iBAAiB,IAAIA,oBAAe,IAAI,cAAc;AAE5D,QAAM,QAAQC,WAAAA,SAAS,eAAe,OAAO,QAAQ;AAErDC,UAAAA,aAAa,MAAM;AACjBC,YAAAA,UAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { Debouncer, DebouncerOptions, DebouncerState } from '@tanstack/pacer/debouncer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidDebouncer<TFn extends AnyFunction, TSelected = DebouncerState<TFn>> extends Omit<Debouncer<TFn>, 'store'> { | ||
| export interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}> extends Omit<Debouncer<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the debouncer state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<DebouncerState<TFn>>>; | ||
| } | ||
@@ -28,10 +35,53 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounce a search function to limit API calls | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 } // Wait 500ms after last keystroke | ||
| * { wait: 500 } | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when isPending changes (optimized for loading states) | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when executionCount changes (optimized for tracking execution) | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Multiple state properties - re-render when any of these change | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ | ||
| * isPending: state.isPending, | ||
| * executionCount: state.executionCount, | ||
| * status: state.status | ||
| * }) | ||
| * ); | ||
| * | ||
| * // In an event handler | ||
@@ -42,10 +92,6 @@ * const handleChange = (e) => { | ||
| * | ||
| * // Access debouncer state via signals | ||
| * console.log('Executions:', debouncer.executionCount()); | ||
| * console.log('Is pending:', debouncer.isPending()); | ||
| * | ||
| * // Update options | ||
| * debouncer.setOptions({ wait: 1000 }); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending } = debouncer.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createDebouncer<TFn extends AnyFunction, TSelected = DebouncerState<TFn>>(fn: TFn, initialOptions: DebouncerOptions<TFn>, selector?: (state: DebouncerState<TFn>) => TSelected): SolidDebouncer<TFn, TSelected>; | ||
| export declare function createDebouncer<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: DebouncerOptions<TFn>, selector?: (state: DebouncerState<TFn>) => TSelected): SolidDebouncer<TFn, TSelected>; |
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createQueuer(fn, initialOptions = {}, selector) { | ||
| function createQueuer(fn, initialOptions = {}, selector = () => ({})) { | ||
| const queuer$1 = new queuer.Queuer(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(queuer$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createQueuer.cjs","sources":["../../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuer<TValue, TSelected = QueuerState<TValue>>\n extends Omit<Queuer<TValue>, 'store'> {\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\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 * Example usage:\n * ```tsx\n * // Example with Solid signals and scheduling\n * const [items, setItems] = createSignal([]);\n *\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 * onItemsChange: (queue) => setItems(queue.peekAllItems()),\n * getPriority: (item) => item.priority // Process higher priority items first\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 queue state via signals\n * console.log('Items:', queue.allItems());\n * console.log('Size:', queue.size());\n * console.log('Is empty:', queue.isEmpty());\n * console.log('Is running:', queue.isRunning());\n * console.log('Next item:', queue.nextItem());\n * ```\n */\nexport function createQueuer<TValue, TSelected = QueuerState<TValue>>(\n fn: (item: TValue) => void,\n initialOptions: QueuerOptions<TValue> = {},\n selector?: (state: QueuerState<TValue>) => TSelected,\n): SolidQueuer<TValue, TSelected> {\n const queuer = new Queuer(fn, initialOptions)\n\n const state = useStore(queuer.store, selector)\n\n return {\n ...queuer,\n state,\n } as unknown as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["queuer","Queuer","useStore"],"mappings":";;;;AAkEO,SAAS,aACd,IACA,iBAAwC,CAAA,GACxC,UACgC;AAChC,QAAMA,WAAS,IAAIC,cAAO,IAAI,cAAc;AAE5C,QAAM,QAAQC,WAAAA,SAASF,SAAO,OAAO,QAAQ;AAE7C,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createQueuer.cjs","sources":["../../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuer<TValue, TSelected = {}>\n extends Omit<Queuer<TValue>, 'store'> {\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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * 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 re-render when 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 re-render when execution metrics change (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 initialOptions: QueuerOptions<TValue> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): SolidQueuer<TValue, TSelected> {\n const queuer = new Queuer(fn, initialOptions)\n\n const state = useStore(queuer.store, selector)\n\n return {\n ...queuer,\n state,\n } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["queuer","Queuer","useStore"],"mappings":";;;;AAoGO,SAAS,aACd,IACA,iBAAwC,CAAA,GACxC,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAMA,WAAS,IAAIC,cAAO,IAAI,cAAc;AAE5C,QAAM,QAAQC,WAAAA,SAASF,SAAO,OAAO,QAAQ;AAE7C,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { Queuer, QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidQueuer<TValue, TSelected = QueuerState<TValue>> extends Omit<Queuer<TValue>, 'store'> { | ||
| export interface SolidQueuer<TValue, TSelected = {}> extends Omit<Queuer<TValue>, 'store'> { | ||
| /** | ||
@@ -10,2 +11,8 @@ * Reactive state that will be updated when the queuer state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<QueuerState<TValue>>>; | ||
| } | ||
@@ -29,7 +36,22 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of items that have been processed | ||
| * - `isRunning`: Whether the queuer is currently running (not stopped) | ||
| * - `items`: Array of items currently queued for processing | ||
| * - `rejectionCount`: Number of items that were rejected (expired or failed validation) | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Example with Solid signals and scheduling | ||
| * const [items, setItems] = createSignal([]); | ||
| * | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const queue = createQueuer( | ||
@@ -43,3 +65,2 @@ * (item) => { | ||
| * wait: 1000, // Process one item every second | ||
| * onItemsChange: (queue) => setItems(queue.peekAllItems()), | ||
| * getPriority: (item) => item.priority // Process higher priority items first | ||
@@ -49,2 +70,19 @@ * } | ||
| * | ||
| * // Opt-in to re-render when items or isRunning changes (optimized for UI updates) | ||
| * const queue = createQueuer( | ||
| * (item) => console.log('Processing', item), | ||
| * { started: true, wait: 1000 }, | ||
| * (state) => ({ items: state.items, isRunning: state.isRunning }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const queue = createQueuer( | ||
| * (item) => console.log('Processing', item), | ||
| * { started: true, wait: 1000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to process - they'll be handled automatically | ||
@@ -58,10 +96,6 @@ * queue.addItem('task1'); | ||
| * | ||
| * // Access queue state via signals | ||
| * console.log('Items:', queue.allItems()); | ||
| * console.log('Size:', queue.size()); | ||
| * console.log('Is empty:', queue.isEmpty()); | ||
| * console.log('Is running:', queue.isRunning()); | ||
| * console.log('Next item:', queue.nextItem()); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isRunning } = queue.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createQueuer<TValue, TSelected = QueuerState<TValue>>(fn: (item: TValue) => void, initialOptions?: QueuerOptions<TValue>, selector?: (state: QueuerState<TValue>) => TSelected): SolidQueuer<TValue, TSelected>; | ||
| export declare function createQueuer<TValue, TSelected = {}>(fn: (item: TValue) => void, initialOptions?: QueuerOptions<TValue>, selector?: (state: QueuerState<TValue>) => TSelected): SolidQueuer<TValue, TSelected>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedSignal.cjs","sources":["../../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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 * @example\n * ```tsx\n * // Basic rate limiting - update state at most 5 times per minute with a sliding window\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\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.remainingInWindow();\n * if (remaining > 0) {\n * setValue(newValue);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n * ```\n */\nexport function createRateLimitedSignal<TValue, TSelected = RateLimiterState>(\n value: TValue,\n initialOptions: RateLimiterOptions<Setter<TValue>>,\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"],"names":["createSignal","createRateLimiter"],"mappings":";;;;AAmEO,SAAS,wBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,kBAAkB,mBAAmB,IAAIA,QAAAA,aAAqB,KAAK;AAE1E,QAAM,cAAcC,kBAAAA;AAAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AAAA,IACL;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createRateLimitedSignal.cjs","sources":["../../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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: RateLimiterOptions<Setter<TValue>>,\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"],"names":["createSignal","createRateLimiter"],"mappings":";;;;AA8FO,SAAS,wBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,kBAAkB,mBAAmB,IAAIA,QAAAA,aAAqB,KAAK;AAE1E,QAAM,cAAcC,kBAAAA;AAAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AAAA,IACL;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,EAAA;AAEJ;;"} |
@@ -32,5 +32,25 @@ import { SolidRateLimiter } from './createRateLimiter.cjs'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance. | ||
| * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available rate limiter state properties: | ||
| * - `callsInWindow`: Number of calls made in the current window | ||
| * - `remainingInWindow`: Number of calls remaining in the current window | ||
| * - `windowStart`: Unix timestamp when the current window started | ||
| * - `nextWindowStart`: Unix timestamp when the next window will start | ||
| * - `msUntilNextWindow`: Milliseconds until the next window starts | ||
| * - `isAtLimit`: Whether the call limit for the current window has been reached | ||
| * - `status`: Current status ('disabled' | 'idle' | 'at-limit') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - update state at most 5 times per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, { | ||
@@ -42,2 +62,9 @@ * limit: 5, | ||
| * | ||
| * // Opt-in to reactive updates when limit state changes (optimized for UI feedback) | ||
| * const [value, setValue, rateLimiter] = createRateLimitedSignal( | ||
| * 0, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow }) | ||
| * ); | ||
| * | ||
| * // With rejection callback and fixed window | ||
@@ -55,3 +82,3 @@ * const [value, setValue] = createRateLimitedSignal(0, { | ||
| * const handleSubmit = () => { | ||
| * const remaining = rateLimiter.remainingInWindow(); | ||
| * const remaining = rateLimiter.state().remainingInWindow; | ||
| * if (remaining > 0) { | ||
@@ -65,3 +92,3 @@ * setValue(newValue); | ||
| */ | ||
| export declare function createRateLimitedSignal<TValue, TSelected = RateLimiterState>(value: TValue, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [ | ||
| export declare function createRateLimitedSignal<TValue, TSelected = {}>(value: TValue, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [ | ||
| Accessor<TValue>, | ||
@@ -68,0 +95,0 @@ Setter<TValue>, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedValue.cjs","sources":["../../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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 * @example\n * ```tsx\n * // Basic rate limiting - update at most 5 times per minute with a sliding window\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Use the rate-limited value\n * console.log(rateLimitedValue()); // Access the current rate-limited value\n *\n * // Control the rate limiter\n * rateLimiter.reset(); // Reset the rate limit window\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = RateLimiterState>(\n value: Accessor<TValue>,\n initialOptions: RateLimiterOptions<Setter<TValue>>,\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"],"names":["createRateLimitedSignal","createEffect"],"mappings":";;;;AAoDO,SAAS,uBACd,OACA,gBACA,UACiE;AACjE,QAAM,CAAC,kBAAkB,qBAAqB,WAAW,IACvDA,wBAAAA,wBAAwB,MAAA,GAAS,gBAAgB,QAAQ;AAE3DC,UAAAA,aAAa,MAAM;AACjB,wBAAoB,OAAc;AAAA,EAAA,CACnC;AAED,SAAO,CAAC,kBAAkB,WAAW;AACvC;;"} | ||
| {"version":3,"file":"createRateLimitedValue.cjs","sources":["../../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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 * - `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 [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\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 [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000 },\n * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow })\n * );\n *\n * // Use the rate-limited value\n * console.log(rateLimitedValue()); // Access the current rate-limited value\n *\n * // Access rate limiter state via signals\n * console.log('Is at limit:', rateLimiter.state().isAtLimit);\n *\n * // Control the rate limiter\n * rateLimiter.reset(); // Reset the rate limit window\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: RateLimiterOptions<Setter<TValue>>,\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"],"names":["createRateLimitedSignal","createEffect"],"mappings":";;;;AAkFO,SAAS,uBACd,OACA,gBACA,UACiE;AACjE,QAAM,CAAC,kBAAkB,qBAAqB,WAAW,IACvDA,wBAAAA,wBAAwB,MAAA,GAAS,gBAAgB,QAAQ;AAE3DC,UAAAA,aAAa,MAAM;AACjB,wBAAoB,OAAc;AAAA,EAAA,CACnC;AAED,SAAO,CAAC,kBAAkB,WAAW;AACvC;;"} |
@@ -31,5 +31,25 @@ import { SolidRateLimiter } from './createRateLimiter.cjs'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance. | ||
| * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available rate limiter state properties: | ||
| * - `callsInWindow`: Number of calls made in the current window | ||
| * - `remainingInWindow`: Number of calls remaining in the current window | ||
| * - `windowStart`: Unix timestamp when the current window started | ||
| * - `nextWindowStart`: Unix timestamp when the next window will start | ||
| * - `msUntilNextWindow`: Milliseconds until the next window starts | ||
| * - `isAtLimit`: Whether the call limit for the current window has been reached | ||
| * - `status`: Current status ('disabled' | 'idle' | 'at-limit') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - update at most 5 times per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, { | ||
@@ -41,5 +61,15 @@ * limit: 5, | ||
| * | ||
| * // Opt-in to reactive updates when limit state changes (optimized for UI feedback) | ||
| * const [rateLimitedValue, rateLimiter] = createRateLimitedValue( | ||
| * rawValue, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow }) | ||
| * ); | ||
| * | ||
| * // Use the rate-limited value | ||
| * console.log(rateLimitedValue()); // Access the current rate-limited value | ||
| * | ||
| * // Access rate limiter state via signals | ||
| * console.log('Is at limit:', rateLimiter.state().isAtLimit); | ||
| * | ||
| * // Control the rate limiter | ||
@@ -49,2 +79,2 @@ * rateLimiter.reset(); // Reset the rate limit window | ||
| */ | ||
| export declare function createRateLimitedValue<TValue, TSelected = RateLimiterState>(value: Accessor<TValue>, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>]; | ||
| export declare function createRateLimitedValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>]; |
@@ -5,3 +5,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createRateLimiter(fn, initialOptions, selector) { | ||
| function createRateLimiter(fn, initialOptions, selector = () => ({})) { | ||
| const rateLimiter$1 = new rateLimiter.RateLimiter(fn, initialOptions); | ||
@@ -8,0 +8,0 @@ const state = solidStore.useStore(rateLimiter$1.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimiter.cjs","sources":["../../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } 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 SolidRateLimiter<\n TFn extends AnyFunction,\n TSelected = RateLimiterState,\n> extends Omit<RateLimiter<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Basic rate limiting - max 5 calls per minute with a sliding window\n * const rateLimiter = createRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access rate limiter state via signals\n * console.log('Executions:', rateLimiter.executionCount());\n * console.log('Rejections:', rateLimiter.rejectionCount());\n * console.log('Remaining:', rateLimiter.remainingInWindow());\n * console.log('Next window in:', rateLimiter.msUntilNextWindow());\n * ```\n */\nexport function createRateLimiter<\n TFn extends AnyFunction,\n TSelected = RateLimiterState,\n>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n selector?: (state: RateLimiterState) => TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const rateLimiter = new RateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return {\n ...rateLimiter,\n state,\n } as unknown as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["rateLimiter","RateLimiter","useStore"],"mappings":";;;;AA6DO,SAAS,kBAId,IACA,gBACA,UACkC;AAClC,QAAMA,gBAAc,IAAIC,wBAAiB,IAAI,cAAc;AAE3D,QAAM,QAAQC,WAAAA,SAASF,cAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createRateLimiter.cjs","sources":["../../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } 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 SolidRateLimiter<TFn extends AnyFunction, TSelected = {}>\n extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Opt-in to re-render when rate limit state changes (optimized for UI feedback)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * { limit: 5, window: 60000 },\n * (state) => ({\n * remainingInWindow: state.remainingInWindow,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for tracking progress)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * { limit: 5, window: 60000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * nextWindowTime: state.nextWindowTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { remainingInWindow, rejectionCount } = rateLimiter.state();\n * ```\n */\nexport function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const rateLimiter = new RateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return {\n ...rateLimiter,\n state,\n } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["rateLimiter","RateLimiter","useStore"],"mappings":";;;;AAqGO,SAAS,kBACd,IACA,gBACA,WAAmD,OAAO,CAAA,IACxB;AAClC,QAAMA,gBAAc,IAAIC,wBAAiB,IAAI,cAAc;AAE3D,QAAM,QAAQC,WAAAA,SAASF,cAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAGA;AAAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { RateLimiter, RateLimiterOptions, RateLimiterState } from '@tanstack/pacer/rate-limiter'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidRateLimiter<TFn extends AnyFunction, TSelected = RateLimiterState> extends Omit<RateLimiter<TFn>, 'store'> { | ||
| export interface SolidRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omit<RateLimiter<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the rate limiter state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<RateLimiterState>>; | ||
| } | ||
@@ -34,5 +41,23 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `rejectionCount`: Number of function calls that were rejected due to rate limiting | ||
| * - `remainingInWindow`: Number of executions remaining in the current window | ||
| * - `nextWindowTime`: Timestamp when the next window begins | ||
| * - `currentWindowStart`: Timestamp when the current window started | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - max 5 calls per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const rateLimiter = createRateLimiter(apiCall, { | ||
@@ -47,9 +72,26 @@ * limit: 5, | ||
| * | ||
| * // Access rate limiter state via signals | ||
| * console.log('Executions:', rateLimiter.executionCount()); | ||
| * console.log('Rejections:', rateLimiter.rejectionCount()); | ||
| * console.log('Remaining:', rateLimiter.remainingInWindow()); | ||
| * console.log('Next window in:', rateLimiter.msUntilNextWindow()); | ||
| * // Opt-in to re-render when rate limit state changes (optimized for UI feedback) | ||
| * const rateLimiter = createRateLimiter( | ||
| * apiCall, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ | ||
| * remainingInWindow: state.remainingInWindow, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const rateLimiter = createRateLimiter( | ||
| * apiCall, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * nextWindowTime: state.nextWindowTime | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { remainingInWindow, rejectionCount } = rateLimiter.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createRateLimiter<TFn extends AnyFunction, TSelected = RateLimiterState>(fn: TFn, initialOptions: RateLimiterOptions<TFn>, selector?: (state: RateLimiterState) => TSelected): SolidRateLimiter<TFn, TSelected>; | ||
| export declare function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: RateLimiterOptions<TFn>, selector?: (state: RateLimiterState) => TSelected): SolidRateLimiter<TFn, TSelected>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledSignal.cjs","sources":["../../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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 * @example\n * ```tsx\n * // Basic throttling - update state at most once per second\n * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 });\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.executionCount());\n * console.log('Is pending:', throttler.isPending());\n * console.log('Last execution:', throttler.lastExecutionTime());\n * console.log('Next execution:', throttler.nextExecutionTime());\n * ```\n */\nexport function createThrottledSignal<\n TValue,\n TSelected = ThrottlerState<Setter<TValue>>,\n>(\n value: TValue,\n initialOptions: ThrottlerOptions<Setter<TValue>>,\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"],"names":["createSignal","createThrottler"],"mappings":";;;;AA2CO,SAAS,sBAId,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAIA,QAAAA,aAAqB,KAAK;AACtE,QAAM,YAAYC,gBAAAA,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAC7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;;"} | ||
| {"version":3,"file":"createThrottledSignal.cjs","sources":["../../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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: ThrottlerOptions<Setter<TValue>>,\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"],"names":["createSignal","createThrottler"],"mappings":";;;;AAuEO,SAAS,sBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAIA,QAAAA,aAAqB,KAAK;AACtE,QAAM,YAAYC,gBAAAA,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAC7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;;"} |
@@ -19,7 +19,35 @@ import { SolidThrottler } from './createThrottler.cjs'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying throttler instance. | ||
| * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available throttler state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Unix timestamp of the last execution | ||
| * - `nextExecutionTime`: Unix timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling - update state at most once per second | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 }); | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [value, setValue, throttler] = createThrottledSignal( | ||
| * 0, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // With custom leading/trailing behavior | ||
@@ -33,9 +61,9 @@ * const [value, setValue] = createThrottledSignal(0, { | ||
| * // Access throttler state via signals | ||
| * console.log('Executions:', throttler.executionCount()); | ||
| * console.log('Is pending:', throttler.isPending()); | ||
| * console.log('Last execution:', throttler.lastExecutionTime()); | ||
| * console.log('Next execution:', throttler.nextExecutionTime()); | ||
| * console.log('Executions:', throttler.state().executionCount); | ||
| * console.log('Is pending:', throttler.state().isPending); | ||
| * console.log('Last execution:', throttler.state().lastExecutionTime); | ||
| * console.log('Next execution:', throttler.state().nextExecutionTime); | ||
| * ``` | ||
| */ | ||
| export declare function createThrottledSignal<TValue, TSelected = ThrottlerState<Setter<TValue>>>(value: TValue, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [ | ||
| export declare function createThrottledSignal<TValue, TSelected = {}>(value: TValue, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [ | ||
| Accessor<TValue>, | ||
@@ -42,0 +70,0 @@ Setter<TValue>, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledValue.cjs","sources":["../../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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 * @example\n * ```tsx\n * // Basic throttling - update at most once per second\n * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 });\n *\n * // Use the throttled value\n * console.log(throttledValue()); // Access the current throttled value\n *\n * // Control the throttler\n * throttler.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createThrottledValue<\n TValue,\n TSelected = ThrottlerState<Setter<TValue>>,\n>(\n value: Accessor<TValue>,\n initialOptions: ThrottlerOptions<Setter<TValue>>,\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"],"names":["createThrottledSignal","createEffect"],"mappings":";;;;AAqCO,SAAS,qBAId,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAIA,sBAAAA;AAAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGFC,UAAAA,aAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;;"} | ||
| {"version":3,"file":"createThrottledValue.cjs","sources":["../../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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: ThrottlerOptions<Setter<TValue>>,\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"],"names":["createThrottledSignal","createEffect"],"mappings":";;;;AAoEO,SAAS,qBACd,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAIA,sBAAAA;AAAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGFC,UAAAA,aAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;;"} |
@@ -20,10 +20,41 @@ import { SolidThrottler } from './createThrottler.cjs'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying throttler instance. | ||
| * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available throttler state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Unix timestamp of the last execution | ||
| * - `nextExecutionTime`: Unix timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling - update at most once per second | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 }); | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [throttledValue, throttler] = createThrottledValue( | ||
| * rawValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Use the throttled value | ||
| * console.log(throttledValue()); // Access the current throttled value | ||
| * | ||
| * // Access throttler state via signals | ||
| * console.log('Is pending:', throttler.state().isPending); | ||
| * | ||
| * // Control the throttler | ||
@@ -33,2 +64,2 @@ * throttler.cancel(); // Cancel any pending updates | ||
| */ | ||
| export declare function createThrottledValue<TValue, TSelected = ThrottlerState<Setter<TValue>>>(value: Accessor<TValue>, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>]; | ||
| export declare function createThrottledValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>]; |
@@ -6,3 +6,3 @@ "use strict"; | ||
| const solidStore = require("@tanstack/solid-store"); | ||
| function createThrottler(fn, initialOptions, selector) { | ||
| function createThrottler(fn, initialOptions, selector = () => ({})) { | ||
| const asyncThrottler = new throttler.Throttler(fn, initialOptions); | ||
@@ -9,0 +9,0 @@ const state = solidStore.useStore(asyncThrottler.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottler.cjs","sources":["../../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = ThrottlerState<TFn>,\n> extends Omit<Throttler<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Basic throttling with custom state\n * const [value, setValue] = createSignal(0);\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // With any state manager\n * const throttler = createThrottler(\n * (value) => stateManager.setState(value),\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access throttler state via signals\n * console.log(throttler.executionCount()); // number of times executed\n * console.log(throttler.isPending()); // whether throttled function is pending\n * console.log(throttler.lastExecutionTime()); // timestamp of last execution\n * console.log(throttler.nextExecutionTime()); // timestamp of next allowed execution\n * ```\n */\nexport function createThrottler<\n TFn extends AnyFunction,\n TSelected = ThrottlerState<TFn>,\n>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n selector?: (state: ThrottlerState<TFn>) => TSelected,\n): SolidThrottler<TFn, TSelected> {\n const asyncThrottler = new Throttler<TFn>(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncThrottler.cancel()\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["Throttler","useStore","createEffect","onCleanup"],"mappings":";;;;;AAwDO,SAAS,gBAId,IACA,gBACA,UACgC;AAChC,QAAM,iBAAiB,IAAIA,oBAAe,IAAI,cAAc;AAE5D,QAAM,QAAQC,WAAAA,SAAS,eAAe,OAAO,QAAQ;AAErDC,UAAAA,aAAa,MAAM;AACjBC,YAAAA,UAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;;"} | ||
| {"version":3,"file":"createThrottler.cjs","sources":["../../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottler<TFn extends AnyFunction, TSelected = {}>\n extends Omit<Throttler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Opt-in to re-render when isPending changes (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to re-render when 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 - re-render 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 initialOptions: ThrottlerOptions<TFn>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const asyncThrottler = new Throttler<TFn>(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncThrottler.cancel()\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":["Throttler","useStore","createEffect","onCleanup"],"mappings":";;;;;AAkGO,SAAS,gBACd,IACA,gBACA,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAM,iBAAiB,IAAIA,oBAAe,IAAI,cAAc;AAE5D,QAAM,QAAQC,WAAAA,SAAS,eAAe,OAAO,QAAQ;AAErDC,UAAAA,aAAa,MAAM;AACjBC,YAAAA,UAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;;"} |
| import { Throttler, ThrottlerOptions, ThrottlerState } from '@tanstack/pacer/throttler'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidThrottler<TFn extends AnyFunction, TSelected = ThrottlerState<TFn>> extends Omit<Throttler<TFn>, 'store'> { | ||
| export interface SolidThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<Throttler<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the throttler state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<ThrottlerState<TFn>>>; | ||
| } | ||
@@ -24,11 +31,45 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Timestamp of the last execution | ||
| * - `nextExecutionTime`: Timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling with custom state | ||
| * const [value, setValue] = createSignal(0); | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const throttler = createThrottler(setValue, { wait: 1000 }); | ||
| * | ||
| * // With any state manager | ||
| * // Opt-in to re-render when isPending changes (optimized for loading states) | ||
| * const throttler = createThrottler( | ||
| * (value) => stateManager.setState(value), | ||
| * setValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when executionCount changes (optimized for tracking execution) | ||
| * const throttler = createThrottler( | ||
| * setValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Multiple state properties - re-render when any of these change | ||
| * const throttler = createThrottler( | ||
| * setValue, | ||
| * { | ||
@@ -38,12 +79,15 @@ * wait: 2000, | ||
| * trailing: false // Skip trailing edge updates | ||
| * } | ||
| * }, | ||
| * (state) => ({ | ||
| * isPending: state.isPending, | ||
| * executionCount: state.executionCount, | ||
| * lastExecutionTime: state.lastExecutionTime, | ||
| * nextExecutionTime: state.nextExecutionTime | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Access throttler state via signals | ||
| * console.log(throttler.executionCount()); // number of times executed | ||
| * console.log(throttler.isPending()); // whether throttled function is pending | ||
| * console.log(throttler.lastExecutionTime()); // timestamp of last execution | ||
| * console.log(throttler.nextExecutionTime()); // timestamp of next allowed execution | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, executionCount } = throttler.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createThrottler<TFn extends AnyFunction, TSelected = ThrottlerState<TFn>>(fn: TFn, initialOptions: ThrottlerOptions<TFn>, selector?: (state: ThrottlerState<TFn>) => TSelected): SolidThrottler<TFn, TSelected>; | ||
| export declare function createThrottler<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: ThrottlerOptions<TFn>, selector?: (state: ThrottlerState<TFn>) => TSelected): SolidThrottler<TFn, TSelected>; |
| import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from '@tanstack/pacer/async-batcher'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidAsyncBatcher<TValue, TSelected = AsyncBatcherState<TValue>> extends Omit<AsyncBatcher<TValue>, 'store'> { | ||
| export interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> { | ||
| /** | ||
@@ -10,2 +11,8 @@ * Reactive state that will be updated when the batcher state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncBatcherState<TValue>>>; | ||
| } | ||
@@ -42,5 +49,27 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `errorCount`: Number of failed batch executions | ||
| * - `executionCount`: Total number of batch execution attempts (successful + failed) | ||
| * - `hasError`: Whether the last batch execution resulted in an error | ||
| * - `isExecuting`: Whether a batch execution is currently in progress | ||
| * - `items`: Array of items currently queued for batching | ||
| * - `lastError`: The error from the most recent failed batch execution (if any) | ||
| * - `lastResult`: The result from the most recent successful batch execution | ||
| * - `settleCount`: Number of batch executions that have completed (successful or failed) | ||
| * - `successCount`: Number of successful batch executions | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Basic async batcher for API requests | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const asyncBatcher = createAsyncBatcher( | ||
@@ -63,2 +92,22 @@ * async (items) => { | ||
| * | ||
| * // Opt-in to re-render when items or isExecuting changes (optimized for UI updates) | ||
| * const asyncBatcher = createAsyncBatcher( | ||
| * async (items) => { | ||
| * const results = await Promise.all(items.map(item => processItem(item))); | ||
| * return results; | ||
| * }, | ||
| * { maxSize: 10, wait: 2000 }, | ||
| * (state) => ({ items: state.items, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const asyncBatcher = createAsyncBatcher( | ||
| * async (items) => { | ||
| * const results = await Promise.all(items.map(item => processItem(item))); | ||
| * return results; | ||
| * }, | ||
| * { maxSize: 10, wait: 2000 }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Add items to batch | ||
@@ -70,7 +119,6 @@ * asyncBatcher.addItem(newItem); | ||
| * | ||
| * // Use Solid signals in your UI | ||
| * const items = asyncBatcher.state().items; | ||
| * const isExecuting = asyncBatcher.state().isExecuting; | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isExecuting } = asyncBatcher.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncBatcher<TValue, TSelected = AsyncBatcherState<TValue>>(fn: (items: Array<TValue>) => Promise<any>, initialOptions?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): SolidAsyncBatcher<TValue, TSelected>; | ||
| export declare function createAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, initialOptions?: AsyncBatcherOptions<TValue>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): SolidAsyncBatcher<TValue, TSelected>; |
| import { AsyncBatcher } from "@tanstack/pacer/async-batcher"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createAsyncBatcher(fn, initialOptions = {}, selector) { | ||
| function createAsyncBatcher(fn, initialOptions = {}, selector = () => ({})) { | ||
| const asyncBatcher = new AsyncBatcher(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(asyncBatcher.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncBatcher.js","sources":["../../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcher<\n TValue,\n TSelected = AsyncBatcherState<TValue>,\n> extends Omit<AsyncBatcher<TValue>, 'store'> {\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\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 * Example usage:\n * ```tsx\n * // Basic async batcher for API requests\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 * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Use Solid signals in your UI\n * const items = asyncBatcher.state().items;\n * const isExecuting = asyncBatcher.state().isExecuting;\n * ```\n */\nexport function createAsyncBatcher<\n TValue,\n TSelected = AsyncBatcherState<TValue>,\n>(\n fn: (items: Array<TValue>) => Promise<any>,\n initialOptions: AsyncBatcherOptions<TValue> = {},\n selector?: (state: AsyncBatcherState<TValue>) => TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const asyncBatcher = new AsyncBatcher<TValue>(fn, initialOptions)\n\n const state = useStore(asyncBatcher.store, selector)\n\n return {\n ...asyncBatcher,\n state,\n } as unknown as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AAiFO,SAAS,mBAId,IACA,iBAA8C,CAAA,GAC9C,UACsC;AACtC,QAAM,eAAe,IAAI,aAAqB,IAAI,cAAc;AAEhE,QAAM,QAAQ,SAAS,aAAa,OAAO,QAAQ;AAEnD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createAsyncBatcher.js","sources":["../../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}>\n extends Omit<AsyncBatcher<TValue>, 'store'> {\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * 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 re-render when 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 re-render when 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 initialOptions: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const asyncBatcher = new AsyncBatcher<TValue>(fn, initialOptions)\n\n const state = useStore(asyncBatcher.store, selector)\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AA+HO,SAAS,mBACd,IACA,iBAA8C,CAAA,GAC9C,WAA4D,OACzD,CAAA,IACmC;AACtC,QAAM,eAAe,IAAI,aAAqB,IAAI,cAAc;AAEhE,QAAM,QAAQ,SAAS,aAAa,OAAO,QAAQ;AAEnD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
| import { AsyncDebouncer, AsyncDebouncerOptions, AsyncDebouncerState } from '@tanstack/pacer/async-debouncer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyAsyncFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = AsyncDebouncerState<TFn>> extends Omit<AsyncDebouncer<TFn>, 'store'> { | ||
| export interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncDebouncer<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the debouncer state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>; | ||
| } | ||
@@ -37,5 +44,27 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call debouncing | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncDebouncer( | ||
@@ -49,8 +78,17 @@ * async (query: string) => { | ||
| * | ||
| * // With state management | ||
| * const [results, setResults] = createSignal([]); | ||
| * const { maybeExecute } = createAsyncDebouncer( | ||
| * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states) | ||
| * const debouncer = createAsyncDebouncer( | ||
| * async (query: string) => { | ||
| * const results = await api.search(query); | ||
| * return results; | ||
| * }, | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const debouncer = createAsyncDebouncer( | ||
| * async (searchTerm) => { | ||
| * const data = await searchAPI(searchTerm); | ||
| * setResults(data); | ||
| * return data; | ||
| * }, | ||
@@ -64,6 +102,10 @@ * { | ||
| * } | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, isExecuting } = debouncer.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = AsyncDebouncerState<TFn>>(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): SolidAsyncDebouncer<TFn, TSelected>; | ||
| export declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): SolidAsyncDebouncer<TFn, TSelected>; |
| import { AsyncDebouncer } from "@tanstack/pacer/async-debouncer"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| import { createEffect, onCleanup } from "solid-js"; | ||
| function createAsyncDebouncer(fn, initialOptions, selector) { | ||
| function createAsyncDebouncer(fn, initialOptions, selector = () => ({})) { | ||
| const asyncDebouncer = new AsyncDebouncer(fn, initialOptions); | ||
@@ -6,0 +6,0 @@ const state = useStore(asyncDebouncer.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncDebouncer.js","sources":["../../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport type { Accessor } 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 SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncDebouncerState<TFn>,\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Basic API call debouncing\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 * // With state management\n * const [results, setResults] = createSignal([]);\n * const { maybeExecute } = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(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 * );\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncDebouncerState<TFn>,\n>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n selector?: (state: AsyncDebouncerState<TFn>) => TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const asyncDebouncer = new AsyncDebouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as unknown as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AA2EO,SAAS,qBAId,IACA,gBACA,UACqC;AACrC,QAAM,iBAAiB,IAAI,eAAoB,IAAI,cAAc;AAEjE,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createAsyncDebouncer.js","sources":["../../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } 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 SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * @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 re-render when 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 re-render when 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 initialOptions: AsyncDebouncerOptions<TFn>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const asyncDebouncer = new AsyncDebouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AAqHO,SAAS,qBAId,IACA,gBACA,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAM,iBAAiB,IAAI,eAAoB,IAAI,cAAc;AAEjE,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
| import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from '@tanstack/pacer/async-queuer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>> extends Omit<AsyncQueuer<TValue>, 'store'> { | ||
| export interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TValue>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated and re-rendered when the queuer state changes | ||
| * Reactive state that will be updated when the queuer state changes | ||
| * | ||
@@ -10,2 +11,8 @@ * Use this instead of `queuer.store.state` | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncQueuerState<TValue>>>; | ||
| } | ||
@@ -35,5 +42,25 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `activeItems`: Array of items currently being processed | ||
| * - `errorCount`: Number of items that failed processing | ||
| * - `isRunning`: Whether the queuer is currently running (not stopped) | ||
| * - `pendingItems`: Array of items waiting to be processed | ||
| * - `rejectionCount`: Number of items that were rejected (expired or failed validation) | ||
| * - `settleCount`: Number of items that have completed processing (successful or failed) | ||
| * - `successCount`: Number of items that were processed successfully | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Basic async queuer for API requests | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const asyncQueuer = createAsyncQueuer(async (item) => { | ||
@@ -55,2 +82,24 @@ * // process item | ||
| * | ||
| * // Opt-in to re-render when queue state changes (optimized for UI updates) | ||
| * const asyncQueuer = createAsyncQueuer( | ||
| * async (item) => await fetchData(item), | ||
| * { concurrency: 2, started: true }, | ||
| * (state) => ({ | ||
| * pendingItems: state.pendingItems, | ||
| * activeItems: state.activeItems, | ||
| * isRunning: state.isRunning | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when processing metrics change (optimized for tracking progress) | ||
| * const asyncQueuer = createAsyncQueuer( | ||
| * async (item) => await fetchData(item), | ||
| * { concurrency: 2, started: true }, | ||
| * (state) => ({ | ||
| * successCount: state.successCount, | ||
| * errorCount: state.errorCount, | ||
| * settleCount: state.settleCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to queue | ||
@@ -62,6 +111,6 @@ * asyncQueuer.addItem(newItem); | ||
| * | ||
| * // Use Solid signals in your UI | ||
| * const pending = asyncQueuer.pendingItems(); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { pendingItems, activeItems } = asyncQueuer.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>(fn: (value: TValue) => Promise<any>, initialOptions?: AsyncQueuerOptions<TValue>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>; | ||
| export declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, initialOptions?: AsyncQueuerOptions<TValue>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>; |
| import { AsyncQueuer } from "@tanstack/pacer/async-queuer"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createAsyncQueuer(fn, initialOptions = {}, selector) { | ||
| function createAsyncQueuer(fn, initialOptions = {}, selector = () => ({})) { | ||
| const asyncQueuer = new AsyncQueuer(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(asyncQueuer.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncQueuer.js","sources":["../../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>\n extends Omit<AsyncQueuer<TValue>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\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 * Example usage:\n * ```tsx\n * // Basic async queuer for API requests\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 * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Use Solid signals in your UI\n * const pending = asyncQueuer.pendingItems();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>(\n fn: (value: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue> = {},\n selector?: (state: AsyncQueuerState<TValue>) => TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n\n const state = useStore(asyncQueuer.store, selector)\n\n return {\n ...asyncQueuer,\n state,\n } as unknown as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AAsEO,SAAS,kBACd,IACA,iBAA6C,CAAA,GAC7C,UACqC;AACrC,QAAM,cAAc,IAAI,YAAoB,IAAI,cAAc;AAE9D,QAAM,QAAQ,SAAS,YAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createAsyncQueuer.js","sources":["../../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}>\n extends Omit<AsyncQueuer<TValue>, 'store'> {\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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * 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 re-render when 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 re-render when processing metrics change (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 initialOptions: AsyncQueuerOptions<TValue> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n\n const state = useStore(asyncQueuer.store, selector)\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AAuHO,SAAS,kBACd,IACA,iBAA6C,CAAA,GAC7C,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAM,cAAc,IAAI,YAAoB,IAAI,cAAc;AAE9D,QAAM,QAAQ,SAAS,YAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
| import { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState } from '@tanstack/pacer/async-rate-limiter'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyAsyncFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = AsyncRateLimiterState<TFn>> extends Omit<AsyncRateLimiter<TFn>, 'store'> { | ||
| export interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncRateLimiter<TFn>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated when the rate limiter state changes | ||
| * | ||
| * Use this instead of `rateLimiter.store.state` | ||
| */ | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>; | ||
| } | ||
@@ -42,5 +54,27 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `currentWindowStart`: Timestamp when the current window started | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `nextWindowTime`: Timestamp when the next window begins | ||
| * - `rejectionCount`: Number of function calls that were rejected due to rate limiting | ||
| * - `remainingInWindow`: Number of executions remaining in the current window | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call rate limiting with return value | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncRateLimiter( | ||
@@ -54,10 +88,22 @@ * async (id: string) => { | ||
| * | ||
| * // With state management and return value | ||
| * const [data, setData] = createSignal(null); | ||
| * const { maybeExecute } = createAsyncRateLimiter( | ||
| * // Opt-in to re-render when rate limit and execution state changes (optimized for UI feedback) | ||
| * const rateLimiter = createAsyncRateLimiter( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * setData(result); | ||
| * return result; // Return value can be used by the caller | ||
| * return result; | ||
| * }, | ||
| * { limit: 10, window: 60000 }, | ||
| * (state) => ({ | ||
| * remainingInWindow: state.remainingInWindow, | ||
| * isExecuting: state.isExecuting, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const rateLimiter = createAsyncRateLimiter( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * return result; | ||
| * }, | ||
| * { | ||
@@ -67,6 +113,10 @@ * limit: 10, | ||
| * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`) | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { remainingInWindow, isExecuting } = rateLimiter.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = AsyncRateLimiterState<TFn>>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>; | ||
| export declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>; |
| import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createAsyncRateLimiter(fn, initialOptions, selector) { | ||
| function createAsyncRateLimiter(fn, initialOptions, selector = () => ({})) { | ||
| const asyncRateLimiter = new AsyncRateLimiter(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(asyncRateLimiter.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncRateLimiter.js","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncRateLimiterState<TFn>,\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n readonly state: Accessor<Readonly<TSelected>>\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 * @example\n * ```tsx\n * // Basic API call rate limiting with return value\n * const { maybeExecute } = 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 * // With state management and return value\n * const [data, setData] = createSignal(null);\n * const { maybeExecute } = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`)\n * }\n * );\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncRateLimiterState<TFn>,\n>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n selector?: (state: AsyncRateLimiterState<TFn>) => TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"names":[],"mappings":";;AA8EO,SAAS,uBAId,IACA,gBACA,UACuC;AACvC,QAAM,mBAAmB,IAAI,iBAAsB,IAAI,cAAc;AAErE,QAAM,QAAQ,SAAS,iBAAiB,OAAO,QAAQ;AAEvD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createAsyncRateLimiter.js","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = 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 * // Opt-in to re-render when rate limit and execution state changes (optimized for UI feedback)\n * const rateLimiter = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * { limit: 10, window: 60000 },\n * (state) => ({\n * remainingInWindow: state.remainingInWindow,\n * isExecuting: state.isExecuting,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const rateLimiter = createAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * return result;\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`)\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 { remainingInWindow, isExecuting } = rateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"names":[],"mappings":";;AAgIO,SAAS,uBAId,IACA,gBACA,WAA6D,OAC1D,CAAA,IACoC;AACvC,QAAM,mBAAmB,IAAI,iBAAsB,IAAI,cAAc;AAErE,QAAM,QAAQ,SAAS,iBAAiB,OAAO,QAAQ;AAEvD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
| import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from '@tanstack/pacer/async-throttler'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyAsyncFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = AsyncThrottlerState<TFn>> extends Omit<AsyncThrottler<TFn>, 'store'> { | ||
| export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated and re-rendered when the throttler state changes | ||
| * Reactive state that will be updated when the throttler state changes | ||
| * | ||
@@ -11,2 +12,8 @@ * Use this instead of `throttler.store.state` | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>; | ||
| } | ||
@@ -34,5 +41,30 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastExecutionTime`: Timestamp of the last execution | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `nextExecutionTime`: Timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call throttling | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncThrottler( | ||
@@ -46,9 +78,18 @@ * async (id: string) => { | ||
| * | ||
| * // With state management | ||
| * const [data, setData] = createSignal(null); | ||
| * const { maybeExecute } = createAsyncThrottler( | ||
| * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states) | ||
| * const throttler = createAsyncThrottler( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * setData(result); | ||
| * return result; | ||
| * }, | ||
| * { wait: 2000 }, | ||
| * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const throttler = createAsyncThrottler( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * return result; | ||
| * }, | ||
| * { | ||
@@ -61,6 +102,10 @@ * wait: 2000, | ||
| * } | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, isExecuting } = throttler.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = AsyncThrottlerState<TFn>>(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>; | ||
| export declare function createAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): SolidAsyncThrottler<TFn, TSelected>; |
| import { AsyncThrottler } from "@tanstack/pacer/async-throttler"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createAsyncThrottler(fn, initialOptions, selector) { | ||
| function createAsyncThrottler(fn, initialOptions, selector = () => ({})) { | ||
| const asyncThrottler = new AsyncThrottler(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(asyncThrottler.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createAsyncThrottler.js","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncThrottlerState<TFn>,\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\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 * @example\n * ```tsx\n * // Basic API call throttling\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 * // With state management\n * const [data, setData] = createSignal(null);\n * const { maybeExecute } = createAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(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 * );\n * ```\n */\nexport function createAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = AsyncThrottlerState<TFn>,\n>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n selector?: (state: AsyncThrottlerState<TFn>) => TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"names":[],"mappings":";;AAuEO,SAAS,qBAId,IACA,gBACA,UACqC;AACrC,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createAsyncThrottler.js","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the throttler can execute on the leading edge\n * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastExecutionTime`: Timestamp of the last execution\n * - `lastResult`: The result from the most recent successful execution\n * - `nextExecutionTime`: Timestamp of the next allowed execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to re-render when 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 re-render when 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 initialOptions: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncThrottler<TFn, TSelected> {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n return {\n ...asyncThrottler,\n state,\n } as SolidAsyncThrottler<TFn, TSelected>\n}\n"],"names":[],"mappings":";;AAoHO,SAAS,qBAId,IACA,gBACA,WAA2D,OACxD,CAAA,IACkC;AACrC,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
| import { Batcher, BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidBatcher<TValue, TSelected = BatcherState<TValue>> extends Omit<Batcher<TValue>, 'store'> { | ||
| export interface SolidBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 'store'> { | ||
| /** | ||
@@ -10,2 +11,8 @@ * Reactive state that will be updated when the batcher state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<BatcherState<TValue>>>; | ||
| } | ||
@@ -27,4 +34,22 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of batch executions that have been completed | ||
| * - `isRunning`: Whether the batcher is currently running (not stopped) | ||
| * - `items`: Array of items currently queued for batching | ||
| * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const batcher = createBatcher( | ||
@@ -43,2 +68,19 @@ * (items) => { | ||
| * | ||
| * // Opt-in to re-render when items or isRunning changes (optimized for UI updates) | ||
| * const batcher = createBatcher( | ||
| * (items) => console.log('Processing batch:', items), | ||
| * { maxSize: 5, wait: 2000 }, | ||
| * (state) => ({ items: state.items, isRunning: state.isRunning }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const batcher = createBatcher( | ||
| * (items) => console.log('Processing batch:', items), | ||
| * { maxSize: 5, wait: 2000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * totalItemsProcessed: state.totalItemsProcessed | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to batch | ||
@@ -52,11 +94,6 @@ * batcher.addItem('task1'); | ||
| * | ||
| * // Access batcher state via signals | ||
| * console.log('Items:', batcher.allItems()); | ||
| * console.log('Size:', batcher.size()); | ||
| * console.log('Is empty:', batcher.isEmpty()); | ||
| * console.log('Is running:', batcher.isRunning()); | ||
| * console.log('Batch count:', batcher.executionCount()); | ||
| * console.log('Item count:', batcher.totalItemsProcessed()); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isRunning } = batcher.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createBatcher<TValue, TSelected = BatcherState<TValue>>(fn: (items: Array<TValue>) => void, initialOptions?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>; | ||
| export declare function createBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => void, initialOptions?: BatcherOptions<TValue>, selector?: (state: BatcherState<TValue>) => TSelected): SolidBatcher<TValue, TSelected>; |
| import { Batcher } from "@tanstack/pacer/batcher"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createBatcher(fn, initialOptions = {}, selector) { | ||
| function createBatcher(fn, initialOptions = {}, selector = () => ({})) { | ||
| const batcher = new Batcher(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(batcher.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createBatcher.js","sources":["../../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected = BatcherState<TValue>>\n extends Omit<Batcher<TValue>, 'store'> {\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\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 * Example usage:\n * ```tsx\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 * // 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 batcher state via signals\n * console.log('Items:', batcher.allItems());\n * console.log('Size:', batcher.size());\n * console.log('Is empty:', batcher.isEmpty());\n * console.log('Is running:', batcher.isRunning());\n * console.log('Batch count:', batcher.executionCount());\n * console.log('Item count:', batcher.totalItemsProcessed());\n * ```\n */\nexport function createBatcher<TValue, TSelected = BatcherState<TValue>>(\n fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue> = {},\n selector?: (state: BatcherState<TValue>) => TSelected,\n): SolidBatcher<TValue, TSelected> {\n const batcher = new Batcher(fn, initialOptions)\n\n const state = useStore(batcher.store, selector)\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"names":[],"mappings":";;AA8DO,SAAS,cACd,IACA,iBAAyC,CAAA,GACzC,UACiC;AACjC,QAAM,UAAU,IAAI,QAAQ,IAAI,cAAc;AAE9C,QAAM,QAAQ,SAAS,QAAQ,OAAO,QAAQ;AAC9C,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createBatcher.js","sources":["../../../src/batcher/createBatcher.ts"],"sourcesContent":["import { Batcher } from '@tanstack/pacer/batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\n\nexport interface SolidBatcher<TValue, TSelected = {}>\n extends Omit<Batcher<TValue>, 'store'> {\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible Batcher instance for managing batches of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Batch processing of items using the provided `fn` function\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `executionCount`: Number of batch executions that have been completed\n * - `isRunning`: Whether the batcher is currently running (not stopped)\n * - `items`: Array of items currently queued for batching\n * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = createBatcher(\n * (items) => {\n * // Process batch of items\n * console.log('Processing batch:', items);\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed'),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Opt-in to re-render when 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 re-render when execution metrics change (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 initialOptions: BatcherOptions<TValue> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidBatcher<TValue, TSelected> {\n const batcher = new Batcher(fn, initialOptions)\n\n const state = useStore(batcher.store, selector)\n return {\n ...batcher,\n state,\n } as SolidBatcher<TValue, TSelected>\n}\n"],"names":[],"mappings":";;AAmGO,SAAS,cACd,IACA,iBAAyC,CAAA,GACzC,WAAuD,OACpD,CAAA,IAC8B;AACjC,QAAM,UAAU,IAAI,QAAQ,IAAI,cAAc;AAE9C,QAAM,QAAQ,SAAS,QAAQ,OAAO,QAAQ;AAC9C,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
@@ -18,5 +18,23 @@ import { SolidDebouncer } from './createDebouncer.js'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying debouncer instance. | ||
| * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available debouncer state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounced search input | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', { | ||
@@ -26,2 +44,16 @@ * wait: 500 // Wait 500ms after last keystroke | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal( | ||
| * '', | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to reactive updates when execution count changes (optimized for tracking executions) | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal( | ||
| * '', | ||
| * { wait: 500 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Update value - will be debounced | ||
@@ -33,4 +65,4 @@ * const handleChange = (e) => { | ||
| * // Access debouncer state via signals | ||
| * console.log('Executions:', debouncer.executionCount()); | ||
| * console.log('Is pending:', debouncer.isPending()); | ||
| * console.log('Executions:', debouncer.state().executionCount); | ||
| * console.log('Is pending:', debouncer.state().isPending); | ||
| * | ||
@@ -46,3 +78,3 @@ * // In onExecute callback, use get* methods | ||
| */ | ||
| export declare function createDebouncedSignal<TValue, TSelected = DebouncerState<Setter<TValue>>>(value: TValue, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [ | ||
| export declare function createDebouncedSignal<TValue, TSelected = {}>(value: TValue, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [ | ||
| Accessor<TValue>, | ||
@@ -49,0 +81,0 @@ Setter<TValue>, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedSignal.js","sources":["../../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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 * @example\n * ```tsx\n * // Debounced search input\n * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', {\n * wait: 500 // Wait 500ms after last keystroke\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.executionCount());\n * console.log('Is pending:', debouncer.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<\n TValue,\n TSelected = DebouncerState<Setter<TValue>>,\n>(\n value: TValue,\n initialOptions: DebouncerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAgDO,SAAS,sBAId,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,aAAqB,KAAK;AAEtE,QAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAE7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;"} | ||
| {"version":3,"file":"createDebouncedSignal.js","sources":["../../../src/debouncer/createDebouncedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createDebouncer } from './createDebouncer'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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: DebouncerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAgFO,SAAS,sBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,aAAqB,KAAK;AAEtE,QAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAE7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;"} |
@@ -21,5 +21,23 @@ import { SolidDebouncer } from './createDebouncer.js'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying debouncer instance. | ||
| * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available debouncer state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounce a search query | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [searchQuery, setSearchQuery] = createSignal(''); | ||
@@ -30,2 +48,9 @@ * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, { | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [debouncedQuery, debouncer] = createDebouncedValue( | ||
| * searchQuery, | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // debouncedQuery will update 500ms after searchQuery stops changing | ||
@@ -36,2 +61,5 @@ * createEffect(() => { | ||
| * | ||
| * // Access debouncer state via signals | ||
| * console.log('Is pending:', debouncer.state().isPending); | ||
| * | ||
| * // Control the debouncer | ||
@@ -41,2 +69,2 @@ * debouncer.cancel(); // Cancel any pending updates | ||
| */ | ||
| export declare function createDebouncedValue<TValue, TSelected = DebouncerState<Setter<TValue>>>(value: Accessor<TValue>, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>]; | ||
| export declare function createDebouncedValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: DebouncerOptions<Setter<TValue>>, selector?: (state: DebouncerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidDebouncer<Setter<TValue>, TSelected>]; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncedValue.js","sources":["../../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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 * @example\n * ```tsx\n * // Debounce a search query\n * const [searchQuery, setSearchQuery] = createSignal('');\n * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, {\n * wait: 500 // Wait 500ms after last change\n * });\n *\n * // debouncedQuery will update 500ms after searchQuery stops changing\n * createEffect(() => {\n * fetchSearchResults(debouncedQuery());\n * });\n *\n * // Control the debouncer\n * debouncer.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createDebouncedValue<\n TValue,\n TSelected = DebouncerState<Setter<TValue>>,\n>(\n value: Accessor<TValue>,\n initialOptions: DebouncerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AA2CO,SAAS,qBAId,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAI;AAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,eAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;"} | ||
| {"version":3,"file":"createDebouncedValue.js","sources":["../../../src/debouncer/createDebouncedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createDebouncedSignal } from './createDebouncedSignal'\nimport type { SolidDebouncer } from './createDebouncer'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} 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: DebouncerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAuEO,SAAS,qBACd,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAI;AAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,eAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;"} |
| import { Debouncer, DebouncerOptions, DebouncerState } from '@tanstack/pacer/debouncer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidDebouncer<TFn extends AnyFunction, TSelected = DebouncerState<TFn>> extends Omit<Debouncer<TFn>, 'store'> { | ||
| export interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}> extends Omit<Debouncer<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the debouncer state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<DebouncerState<TFn>>>; | ||
| } | ||
@@ -28,10 +35,53 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounce a search function to limit API calls | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 } // Wait 500ms after last keystroke | ||
| * { wait: 500 } | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when isPending changes (optimized for loading states) | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when executionCount changes (optimized for tracking execution) | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Multiple state properties - re-render when any of these change | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ | ||
| * isPending: state.isPending, | ||
| * executionCount: state.executionCount, | ||
| * status: state.status | ||
| * }) | ||
| * ); | ||
| * | ||
| * // In an event handler | ||
@@ -42,10 +92,6 @@ * const handleChange = (e) => { | ||
| * | ||
| * // Access debouncer state via signals | ||
| * console.log('Executions:', debouncer.executionCount()); | ||
| * console.log('Is pending:', debouncer.isPending()); | ||
| * | ||
| * // Update options | ||
| * debouncer.setOptions({ wait: 1000 }); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending } = debouncer.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createDebouncer<TFn extends AnyFunction, TSelected = DebouncerState<TFn>>(fn: TFn, initialOptions: DebouncerOptions<TFn>, selector?: (state: DebouncerState<TFn>) => TSelected): SolidDebouncer<TFn, TSelected>; | ||
| export declare function createDebouncer<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: DebouncerOptions<TFn>, selector?: (state: DebouncerState<TFn>) => TSelected): SolidDebouncer<TFn, TSelected>; |
| import { Debouncer } from "@tanstack/pacer/debouncer"; | ||
| import { createEffect, onCleanup } from "solid-js"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createDebouncer(fn, initialOptions, selector) { | ||
| function createDebouncer(fn, initialOptions, selector = () => ({})) { | ||
| const asyncDebouncer = new Debouncer(fn, initialOptions); | ||
@@ -6,0 +6,0 @@ const state = useStore(asyncDebouncer.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createDebouncer.js","sources":["../../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncer<\n TFn extends AnyFunction,\n TSelected = DebouncerState<TFn>,\n> extends Omit<Debouncer<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Debounce a search function to limit API calls\n * const debouncer = createDebouncer(\n * (query: string) => fetchSearchResults(query),\n * { wait: 500 } // Wait 500ms after last keystroke\n * );\n *\n * // In an event handler\n * const handleChange = (e) => {\n * debouncer.maybeExecute(e.target.value);\n * };\n *\n * // Access debouncer state via signals\n * console.log('Executions:', debouncer.executionCount());\n * console.log('Is pending:', debouncer.isPending());\n *\n * // Update options\n * debouncer.setOptions({ wait: 1000 });\n * ```\n */\nexport function createDebouncer<\n TFn extends AnyFunction,\n TSelected = DebouncerState<TFn>,\n>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n selector?: (state: DebouncerState<TFn>) => TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const asyncDebouncer = new Debouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AA0DO,SAAS,gBAId,IACA,gBACA,UACgC;AAChC,QAAM,iBAAiB,IAAI,UAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createDebouncer.js","sources":["../../../src/debouncer/createDebouncer.ts"],"sourcesContent":["import { Debouncer } from '@tanstack/pacer/debouncer'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n DebouncerOptions,\n DebouncerState,\n} from '@tanstack/pacer/debouncer'\n\nexport interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}>\n extends Omit<Debouncer<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * @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 re-render when 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 re-render when 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 - re-render 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 initialOptions: DebouncerOptions<TFn>,\n selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidDebouncer<TFn, TSelected> {\n const asyncDebouncer = new Debouncer<TFn>(fn, initialOptions)\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AAsGO,SAAS,gBACd,IACA,gBACA,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAM,iBAAiB,IAAI,UAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
| import { Queuer, QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| export interface SolidQueuer<TValue, TSelected = QueuerState<TValue>> extends Omit<Queuer<TValue>, 'store'> { | ||
| export interface SolidQueuer<TValue, TSelected = {}> extends Omit<Queuer<TValue>, 'store'> { | ||
| /** | ||
@@ -10,2 +11,8 @@ * Reactive state that will be updated when the queuer state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<QueuerState<TValue>>>; | ||
| } | ||
@@ -29,7 +36,22 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of items that have been processed | ||
| * - `isRunning`: Whether the queuer is currently running (not stopped) | ||
| * - `items`: Array of items currently queued for processing | ||
| * - `rejectionCount`: Number of items that were rejected (expired or failed validation) | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Example with Solid signals and scheduling | ||
| * const [items, setItems] = createSignal([]); | ||
| * | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const queue = createQueuer( | ||
@@ -43,3 +65,2 @@ * (item) => { | ||
| * wait: 1000, // Process one item every second | ||
| * onItemsChange: (queue) => setItems(queue.peekAllItems()), | ||
| * getPriority: (item) => item.priority // Process higher priority items first | ||
@@ -49,2 +70,19 @@ * } | ||
| * | ||
| * // Opt-in to re-render when items or isRunning changes (optimized for UI updates) | ||
| * const queue = createQueuer( | ||
| * (item) => console.log('Processing', item), | ||
| * { started: true, wait: 1000 }, | ||
| * (state) => ({ items: state.items, isRunning: state.isRunning }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const queue = createQueuer( | ||
| * (item) => console.log('Processing', item), | ||
| * { started: true, wait: 1000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to process - they'll be handled automatically | ||
@@ -58,10 +96,6 @@ * queue.addItem('task1'); | ||
| * | ||
| * // Access queue state via signals | ||
| * console.log('Items:', queue.allItems()); | ||
| * console.log('Size:', queue.size()); | ||
| * console.log('Is empty:', queue.isEmpty()); | ||
| * console.log('Is running:', queue.isRunning()); | ||
| * console.log('Next item:', queue.nextItem()); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isRunning } = queue.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createQueuer<TValue, TSelected = QueuerState<TValue>>(fn: (item: TValue) => void, initialOptions?: QueuerOptions<TValue>, selector?: (state: QueuerState<TValue>) => TSelected): SolidQueuer<TValue, TSelected>; | ||
| export declare function createQueuer<TValue, TSelected = {}>(fn: (item: TValue) => void, initialOptions?: QueuerOptions<TValue>, selector?: (state: QueuerState<TValue>) => TSelected): SolidQueuer<TValue, TSelected>; |
| import { Queuer } from "@tanstack/pacer/queuer"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createQueuer(fn, initialOptions = {}, selector) { | ||
| function createQueuer(fn, initialOptions = {}, selector = () => ({})) { | ||
| const queuer = new Queuer(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(queuer.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createQueuer.js","sources":["../../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuer<TValue, TSelected = QueuerState<TValue>>\n extends Omit<Queuer<TValue>, 'store'> {\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\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 * Example usage:\n * ```tsx\n * // Example with Solid signals and scheduling\n * const [items, setItems] = createSignal([]);\n *\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 * onItemsChange: (queue) => setItems(queue.peekAllItems()),\n * getPriority: (item) => item.priority // Process higher priority items first\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 queue state via signals\n * console.log('Items:', queue.allItems());\n * console.log('Size:', queue.size());\n * console.log('Is empty:', queue.isEmpty());\n * console.log('Is running:', queue.isRunning());\n * console.log('Next item:', queue.nextItem());\n * ```\n */\nexport function createQueuer<TValue, TSelected = QueuerState<TValue>>(\n fn: (item: TValue) => void,\n initialOptions: QueuerOptions<TValue> = {},\n selector?: (state: QueuerState<TValue>) => TSelected,\n): SolidQueuer<TValue, TSelected> {\n const queuer = new Queuer(fn, initialOptions)\n\n const state = useStore(queuer.store, selector)\n\n return {\n ...queuer,\n state,\n } as unknown as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AAkEO,SAAS,aACd,IACA,iBAAwC,CAAA,GACxC,UACgC;AAChC,QAAM,SAAS,IAAI,OAAO,IAAI,cAAc;AAE5C,QAAM,QAAQ,SAAS,OAAO,OAAO,QAAQ;AAE7C,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createQueuer.js","sources":["../../../src/queuer/createQueuer.ts"],"sourcesContent":["import { Queuer } from '@tanstack/pacer/queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer'\n\nexport interface SolidQueuer<TValue, TSelected = {}>\n extends Omit<Queuer<TValue>, 'store'> {\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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * 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 re-render when 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 re-render when execution metrics change (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 initialOptions: QueuerOptions<TValue> = {},\n selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected,\n): SolidQueuer<TValue, TSelected> {\n const queuer = new Queuer(fn, initialOptions)\n\n const state = useStore(queuer.store, selector)\n\n return {\n ...queuer,\n state,\n } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AAoGO,SAAS,aACd,IACA,iBAAwC,CAAA,GACxC,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAM,SAAS,IAAI,OAAO,IAAI,cAAc;AAE5C,QAAM,QAAQ,SAAS,OAAO,OAAO,QAAQ;AAE7C,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
@@ -32,5 +32,25 @@ import { SolidRateLimiter } from './createRateLimiter.js'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance. | ||
| * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available rate limiter state properties: | ||
| * - `callsInWindow`: Number of calls made in the current window | ||
| * - `remainingInWindow`: Number of calls remaining in the current window | ||
| * - `windowStart`: Unix timestamp when the current window started | ||
| * - `nextWindowStart`: Unix timestamp when the next window will start | ||
| * - `msUntilNextWindow`: Milliseconds until the next window starts | ||
| * - `isAtLimit`: Whether the call limit for the current window has been reached | ||
| * - `status`: Current status ('disabled' | 'idle' | 'at-limit') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - update state at most 5 times per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, { | ||
@@ -42,2 +62,9 @@ * limit: 5, | ||
| * | ||
| * // Opt-in to reactive updates when limit state changes (optimized for UI feedback) | ||
| * const [value, setValue, rateLimiter] = createRateLimitedSignal( | ||
| * 0, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow }) | ||
| * ); | ||
| * | ||
| * // With rejection callback and fixed window | ||
@@ -55,3 +82,3 @@ * const [value, setValue] = createRateLimitedSignal(0, { | ||
| * const handleSubmit = () => { | ||
| * const remaining = rateLimiter.remainingInWindow(); | ||
| * const remaining = rateLimiter.state().remainingInWindow; | ||
| * if (remaining > 0) { | ||
@@ -65,3 +92,3 @@ * setValue(newValue); | ||
| */ | ||
| export declare function createRateLimitedSignal<TValue, TSelected = RateLimiterState>(value: TValue, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [ | ||
| export declare function createRateLimitedSignal<TValue, TSelected = {}>(value: TValue, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [ | ||
| Accessor<TValue>, | ||
@@ -68,0 +95,0 @@ Setter<TValue>, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedSignal.js","sources":["../../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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 * @example\n * ```tsx\n * // Basic rate limiting - update state at most 5 times per minute with a sliding window\n * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\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.remainingInWindow();\n * if (remaining > 0) {\n * setValue(newValue);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n * ```\n */\nexport function createRateLimitedSignal<TValue, TSelected = RateLimiterState>(\n value: TValue,\n initialOptions: RateLimiterOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAmEO,SAAS,wBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,aAAqB,KAAK;AAE1E,QAAM,cAAc;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AAAA,IACL;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createRateLimitedSignal.js","sources":["../../../src/rate-limiter/createRateLimitedSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createRateLimiter } from './createRateLimiter'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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: RateLimiterOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AA8FO,SAAS,wBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,aAAqB,KAAK;AAE1E,QAAM,cAAc;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AAAA,IACL;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,EAAA;AAEJ;"} |
@@ -31,5 +31,25 @@ import { SolidRateLimiter } from './createRateLimiter.js'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance. | ||
| * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available rate limiter state properties: | ||
| * - `callsInWindow`: Number of calls made in the current window | ||
| * - `remainingInWindow`: Number of calls remaining in the current window | ||
| * - `windowStart`: Unix timestamp when the current window started | ||
| * - `nextWindowStart`: Unix timestamp when the next window will start | ||
| * - `msUntilNextWindow`: Milliseconds until the next window starts | ||
| * - `isAtLimit`: Whether the call limit for the current window has been reached | ||
| * - `status`: Current status ('disabled' | 'idle' | 'at-limit') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - update at most 5 times per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, { | ||
@@ -41,5 +61,15 @@ * limit: 5, | ||
| * | ||
| * // Opt-in to reactive updates when limit state changes (optimized for UI feedback) | ||
| * const [rateLimitedValue, rateLimiter] = createRateLimitedValue( | ||
| * rawValue, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow }) | ||
| * ); | ||
| * | ||
| * // Use the rate-limited value | ||
| * console.log(rateLimitedValue()); // Access the current rate-limited value | ||
| * | ||
| * // Access rate limiter state via signals | ||
| * console.log('Is at limit:', rateLimiter.state().isAtLimit); | ||
| * | ||
| * // Control the rate limiter | ||
@@ -49,2 +79,2 @@ * rateLimiter.reset(); // Reset the rate limit window | ||
| */ | ||
| export declare function createRateLimitedValue<TValue, TSelected = RateLimiterState>(value: Accessor<TValue>, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>]; | ||
| export declare function createRateLimitedValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: RateLimiterOptions<Setter<TValue>>, selector?: (state: RateLimiterState) => TSelected): [Accessor<TValue>, SolidRateLimiter<Setter<TValue>, TSelected>]; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimitedValue.js","sources":["../../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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 * @example\n * ```tsx\n * // Basic rate limiting - update at most 5 times per minute with a sliding window\n * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Use the rate-limited value\n * console.log(rateLimitedValue()); // Access the current rate-limited value\n *\n * // Control the rate limiter\n * rateLimiter.reset(); // Reset the rate limit window\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = RateLimiterState>(\n value: Accessor<TValue>,\n initialOptions: RateLimiterOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAoDO,SAAS,uBACd,OACA,gBACA,UACiE;AACjE,QAAM,CAAC,kBAAkB,qBAAqB,WAAW,IACvD,wBAAwB,MAAA,GAAS,gBAAgB,QAAQ;AAE3D,eAAa,MAAM;AACjB,wBAAoB,OAAc;AAAA,EAAA,CACnC;AAED,SAAO,CAAC,kBAAkB,WAAW;AACvC;"} | ||
| {"version":3,"file":"createRateLimitedValue.js","sources":["../../../src/rate-limiter/createRateLimitedValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createRateLimitedSignal } from './createRateLimitedSignal'\nimport type { SolidRateLimiter } from './createRateLimiter'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} 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 * - `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 [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, {\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 [rateLimitedValue, rateLimiter] = createRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000 },\n * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow })\n * );\n *\n * // Use the rate-limited value\n * console.log(rateLimitedValue()); // Access the current rate-limited value\n *\n * // Access rate limiter state via signals\n * console.log('Is at limit:', rateLimiter.state().isAtLimit);\n *\n * // Control the rate limiter\n * rateLimiter.reset(); // Reset the rate limit window\n * ```\n */\nexport function createRateLimitedValue<TValue, TSelected = {}>(\n value: Accessor<TValue>,\n initialOptions: RateLimiterOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAkFO,SAAS,uBACd,OACA,gBACA,UACiE;AACjE,QAAM,CAAC,kBAAkB,qBAAqB,WAAW,IACvD,wBAAwB,MAAA,GAAS,gBAAgB,QAAQ;AAE3D,eAAa,MAAM;AACjB,wBAAoB,OAAc;AAAA,EAAA,CACnC;AAED,SAAO,CAAC,kBAAkB,WAAW;AACvC;"} |
| import { RateLimiter, RateLimiterOptions, RateLimiterState } from '@tanstack/pacer/rate-limiter'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidRateLimiter<TFn extends AnyFunction, TSelected = RateLimiterState> extends Omit<RateLimiter<TFn>, 'store'> { | ||
| export interface SolidRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omit<RateLimiter<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the rate limiter state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<RateLimiterState>>; | ||
| } | ||
@@ -34,5 +41,23 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `rejectionCount`: Number of function calls that were rejected due to rate limiting | ||
| * - `remainingInWindow`: Number of executions remaining in the current window | ||
| * - `nextWindowTime`: Timestamp when the next window begins | ||
| * - `currentWindowStart`: Timestamp when the current window started | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - max 5 calls per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const rateLimiter = createRateLimiter(apiCall, { | ||
@@ -47,9 +72,26 @@ * limit: 5, | ||
| * | ||
| * // Access rate limiter state via signals | ||
| * console.log('Executions:', rateLimiter.executionCount()); | ||
| * console.log('Rejections:', rateLimiter.rejectionCount()); | ||
| * console.log('Remaining:', rateLimiter.remainingInWindow()); | ||
| * console.log('Next window in:', rateLimiter.msUntilNextWindow()); | ||
| * // Opt-in to re-render when rate limit state changes (optimized for UI feedback) | ||
| * const rateLimiter = createRateLimiter( | ||
| * apiCall, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ | ||
| * remainingInWindow: state.remainingInWindow, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const rateLimiter = createRateLimiter( | ||
| * apiCall, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * nextWindowTime: state.nextWindowTime | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { remainingInWindow, rejectionCount } = rateLimiter.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createRateLimiter<TFn extends AnyFunction, TSelected = RateLimiterState>(fn: TFn, initialOptions: RateLimiterOptions<TFn>, selector?: (state: RateLimiterState) => TSelected): SolidRateLimiter<TFn, TSelected>; | ||
| export declare function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: RateLimiterOptions<TFn>, selector?: (state: RateLimiterState) => TSelected): SolidRateLimiter<TFn, TSelected>; |
| import { RateLimiter } from "@tanstack/pacer/rate-limiter"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createRateLimiter(fn, initialOptions, selector) { | ||
| function createRateLimiter(fn, initialOptions, selector = () => ({})) { | ||
| const rateLimiter = new RateLimiter(fn, initialOptions); | ||
@@ -5,0 +5,0 @@ const state = useStore(rateLimiter.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createRateLimiter.js","sources":["../../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } 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 SolidRateLimiter<\n TFn extends AnyFunction,\n TSelected = RateLimiterState,\n> extends Omit<RateLimiter<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Basic rate limiting - max 5 calls per minute with a sliding window\n * const rateLimiter = createRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access rate limiter state via signals\n * console.log('Executions:', rateLimiter.executionCount());\n * console.log('Rejections:', rateLimiter.rejectionCount());\n * console.log('Remaining:', rateLimiter.remainingInWindow());\n * console.log('Next window in:', rateLimiter.msUntilNextWindow());\n * ```\n */\nexport function createRateLimiter<\n TFn extends AnyFunction,\n TSelected = RateLimiterState,\n>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n selector?: (state: RateLimiterState) => TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const rateLimiter = new RateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return {\n ...rateLimiter,\n state,\n } as unknown as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AA6DO,SAAS,kBAId,IACA,gBACA,UACkC;AAClC,QAAM,cAAc,IAAI,YAAiB,IAAI,cAAc;AAE3D,QAAM,QAAQ,SAAS,YAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createRateLimiter.js","sources":["../../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } 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 SolidRateLimiter<TFn extends AnyFunction, TSelected = {}>\n extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Opt-in to re-render when rate limit state changes (optimized for UI feedback)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * { limit: 5, window: 60000 },\n * (state) => ({\n * remainingInWindow: state.remainingInWindow,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for tracking progress)\n * const rateLimiter = createRateLimiter(\n * apiCall,\n * { limit: 5, window: 60000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * nextWindowTime: state.nextWindowTime\n * })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { remainingInWindow, rejectionCount } = rateLimiter.state();\n * ```\n */\nexport function createRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): SolidRateLimiter<TFn, TSelected> {\n const rateLimiter = new RateLimiter<TFn>(fn, initialOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return {\n ...rateLimiter,\n state,\n } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;AAqGO,SAAS,kBACd,IACA,gBACA,WAAmD,OAAO,CAAA,IACxB;AAClC,QAAM,cAAc,IAAI,YAAiB,IAAI,cAAc;AAE3D,QAAM,QAAQ,SAAS,YAAY,OAAO,QAAQ;AAElD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
@@ -19,7 +19,35 @@ import { SolidThrottler } from './createThrottler.js'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying throttler instance. | ||
| * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available throttler state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Unix timestamp of the last execution | ||
| * - `nextExecutionTime`: Unix timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling - update state at most once per second | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 }); | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [value, setValue, throttler] = createThrottledSignal( | ||
| * 0, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // With custom leading/trailing behavior | ||
@@ -33,9 +61,9 @@ * const [value, setValue] = createThrottledSignal(0, { | ||
| * // Access throttler state via signals | ||
| * console.log('Executions:', throttler.executionCount()); | ||
| * console.log('Is pending:', throttler.isPending()); | ||
| * console.log('Last execution:', throttler.lastExecutionTime()); | ||
| * console.log('Next execution:', throttler.nextExecutionTime()); | ||
| * console.log('Executions:', throttler.state().executionCount); | ||
| * console.log('Is pending:', throttler.state().isPending); | ||
| * console.log('Last execution:', throttler.state().lastExecutionTime); | ||
| * console.log('Next execution:', throttler.state().nextExecutionTime); | ||
| * ``` | ||
| */ | ||
| export declare function createThrottledSignal<TValue, TSelected = ThrottlerState<Setter<TValue>>>(value: TValue, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [ | ||
| export declare function createThrottledSignal<TValue, TSelected = {}>(value: TValue, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [ | ||
| Accessor<TValue>, | ||
@@ -42,0 +70,0 @@ Setter<TValue>, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledSignal.js","sources":["../../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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 * @example\n * ```tsx\n * // Basic throttling - update state at most once per second\n * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 });\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.executionCount());\n * console.log('Is pending:', throttler.isPending());\n * console.log('Last execution:', throttler.lastExecutionTime());\n * console.log('Next execution:', throttler.nextExecutionTime());\n * ```\n */\nexport function createThrottledSignal<\n TValue,\n TSelected = ThrottlerState<Setter<TValue>>,\n>(\n value: TValue,\n initialOptions: ThrottlerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AA2CO,SAAS,sBAId,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,aAAqB,KAAK;AACtE,QAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAC7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;"} | ||
| {"version":3,"file":"createThrottledSignal.js","sources":["../../../src/throttler/createThrottledSignal.ts"],"sourcesContent":["import { createSignal } from 'solid-js'\nimport { createThrottler } from './createThrottler'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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: ThrottlerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAuEO,SAAS,sBACd,OACA,gBACA,UAKA;AACA,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,aAAqB,KAAK;AACtE,QAAM,YAAY,gBAAgB,mBAAmB,gBAAgB,QAAQ;AAC7E,SAAO,CAAC,gBAAgB,UAAU,cAAgC,SAAS;AAC7E;"} |
@@ -20,10 +20,41 @@ import { SolidThrottler } from './createThrottler.js'; | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying throttler instance. | ||
| * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available throttler state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Unix timestamp of the last execution | ||
| * - `nextExecutionTime`: Unix timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling - update at most once per second | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 }); | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [throttledValue, throttler] = createThrottledValue( | ||
| * rawValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Use the throttled value | ||
| * console.log(throttledValue()); // Access the current throttled value | ||
| * | ||
| * // Access throttler state via signals | ||
| * console.log('Is pending:', throttler.state().isPending); | ||
| * | ||
| * // Control the throttler | ||
@@ -33,2 +64,2 @@ * throttler.cancel(); // Cancel any pending updates | ||
| */ | ||
| export declare function createThrottledValue<TValue, TSelected = ThrottlerState<Setter<TValue>>>(value: Accessor<TValue>, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>]; | ||
| export declare function createThrottledValue<TValue, TSelected = {}>(value: Accessor<TValue>, initialOptions: ThrottlerOptions<Setter<TValue>>, selector?: (state: ThrottlerState<Setter<TValue>>) => TSelected): [Accessor<TValue>, SolidThrottler<Setter<TValue>, TSelected>]; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottledValue.js","sources":["../../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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 * @example\n * ```tsx\n * // Basic throttling - update at most once per second\n * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 });\n *\n * // Use the throttled value\n * console.log(throttledValue()); // Access the current throttled value\n *\n * // Control the throttler\n * throttler.cancel(); // Cancel any pending updates\n * ```\n */\nexport function createThrottledValue<\n TValue,\n TSelected = ThrottlerState<Setter<TValue>>,\n>(\n value: Accessor<TValue>,\n initialOptions: ThrottlerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAqCO,SAAS,qBAId,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAI;AAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,eAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;"} | ||
| {"version":3,"file":"createThrottledValue.js","sources":["../../../src/throttler/createThrottledValue.ts"],"sourcesContent":["import { createEffect } from 'solid-js'\nimport { createThrottledSignal } from './createThrottledSignal'\nimport type { SolidThrottler } from './createThrottler'\nimport type { Accessor, Setter } from 'solid-js'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} 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 re-renders 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: ThrottlerOptions<Setter<TValue>>,\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"],"names":[],"mappings":";;AAoEO,SAAS,qBACd,OACA,gBACA,UAC+D;AAC/D,QAAM,CAAC,gBAAgB,mBAAmB,SAAS,IAAI;AAAA,IACrD,MAAA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,eAAa,MAAM;AACjB,sBAAkB,OAAc;AAAA,EAAA,CACjC;AAED,SAAO,CAAC,gBAAgB,SAAS;AACnC;"} |
| import { Throttler, ThrottlerOptions, ThrottlerState } from '@tanstack/pacer/throttler'; | ||
| import { Store } from '@tanstack/solid-store'; | ||
| import { Accessor } from 'solid-js'; | ||
| import { AnyFunction } from '@tanstack/pacer/types'; | ||
| export interface SolidThrottler<TFn extends AnyFunction, TSelected = ThrottlerState<TFn>> extends Omit<Throttler<TFn>, 'store'> { | ||
| export interface SolidThrottler<TFn extends AnyFunction, TSelected = {}> extends Omit<Throttler<TFn>, 'store'> { | ||
| /** | ||
@@ -11,2 +12,8 @@ * Reactive state that will be updated when the throttler state changes | ||
| readonly state: Accessor<Readonly<TSelected>>; | ||
| /** | ||
| * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<ThrottlerState<TFn>>>; | ||
| } | ||
@@ -24,11 +31,45 @@ /** | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Timestamp of the last execution | ||
| * - `nextExecutionTime`: Timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling with custom state | ||
| * const [value, setValue] = createSignal(0); | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const throttler = createThrottler(setValue, { wait: 1000 }); | ||
| * | ||
| * // With any state manager | ||
| * // Opt-in to re-render when isPending changes (optimized for loading states) | ||
| * const throttler = createThrottler( | ||
| * (value) => stateManager.setState(value), | ||
| * setValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when executionCount changes (optimized for tracking execution) | ||
| * const throttler = createThrottler( | ||
| * setValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Multiple state properties - re-render when any of these change | ||
| * const throttler = createThrottler( | ||
| * setValue, | ||
| * { | ||
@@ -38,12 +79,15 @@ * wait: 2000, | ||
| * trailing: false // Skip trailing edge updates | ||
| * } | ||
| * }, | ||
| * (state) => ({ | ||
| * isPending: state.isPending, | ||
| * executionCount: state.executionCount, | ||
| * lastExecutionTime: state.lastExecutionTime, | ||
| * nextExecutionTime: state.nextExecutionTime | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Access throttler state via signals | ||
| * console.log(throttler.executionCount()); // number of times executed | ||
| * console.log(throttler.isPending()); // whether throttled function is pending | ||
| * console.log(throttler.lastExecutionTime()); // timestamp of last execution | ||
| * console.log(throttler.nextExecutionTime()); // timestamp of next allowed execution | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, executionCount } = throttler.state(); | ||
| * ``` | ||
| */ | ||
| export declare function createThrottler<TFn extends AnyFunction, TSelected = ThrottlerState<TFn>>(fn: TFn, initialOptions: ThrottlerOptions<TFn>, selector?: (state: ThrottlerState<TFn>) => TSelected): SolidThrottler<TFn, TSelected>; | ||
| export declare function createThrottler<TFn extends AnyFunction, TSelected = {}>(fn: TFn, initialOptions: ThrottlerOptions<TFn>, selector?: (state: ThrottlerState<TFn>) => TSelected): SolidThrottler<TFn, TSelected>; |
| import { Throttler } from "@tanstack/pacer/throttler"; | ||
| import { createEffect, onCleanup } from "solid-js"; | ||
| import { useStore } from "@tanstack/solid-store"; | ||
| function createThrottler(fn, initialOptions, selector) { | ||
| function createThrottler(fn, initialOptions, selector = () => ({})) { | ||
| const asyncThrottler = new Throttler(fn, initialOptions); | ||
@@ -6,0 +6,0 @@ const state = useStore(asyncThrottler.store, selector); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"createThrottler.js","sources":["../../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottler<\n TFn extends AnyFunction,\n TSelected = ThrottlerState<TFn>,\n> extends Omit<Throttler<TFn>, 'store'> {\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\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 * @example\n * ```tsx\n * // Basic throttling with custom state\n * const [value, setValue] = createSignal(0);\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // With any state manager\n * const throttler = createThrottler(\n * (value) => stateManager.setState(value),\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access throttler state via signals\n * console.log(throttler.executionCount()); // number of times executed\n * console.log(throttler.isPending()); // whether throttled function is pending\n * console.log(throttler.lastExecutionTime()); // timestamp of last execution\n * console.log(throttler.nextExecutionTime()); // timestamp of next allowed execution\n * ```\n */\nexport function createThrottler<\n TFn extends AnyFunction,\n TSelected = ThrottlerState<TFn>,\n>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n selector?: (state: ThrottlerState<TFn>) => TSelected,\n): SolidThrottler<TFn, TSelected> {\n const asyncThrottler = new Throttler<TFn>(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncThrottler.cancel()\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AAwDO,SAAS,gBAId,IACA,gBACA,UACgC;AAChC,QAAM,iBAAiB,IAAI,UAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} | ||
| {"version":3,"file":"createThrottler.js","sources":["../../../src/throttler/createThrottler.ts"],"sourcesContent":["import { Throttler } from '@tanstack/pacer/throttler'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type {\n ThrottlerOptions,\n ThrottlerState,\n} from '@tanstack/pacer/throttler'\n\nexport interface SolidThrottler<TFn extends AnyFunction, TSelected = {}>\n extends Omit<Throttler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<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. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders 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 re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\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 * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const throttler = createThrottler(setValue, { wait: 1000 });\n *\n * // Opt-in to re-render when isPending changes (optimized for loading states)\n * const throttler = createThrottler(\n * setValue,\n * { wait: 1000 },\n * (state) => ({ isPending: state.isPending })\n * );\n *\n * // Opt-in to re-render when 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 - re-render 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 initialOptions: ThrottlerOptions<TFn>,\n selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected,\n): SolidThrottler<TFn, TSelected> {\n const asyncThrottler = new Throttler<TFn>(fn, initialOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncThrottler.cancel()\n })\n })\n\n return {\n ...asyncThrottler,\n state,\n } as SolidThrottler<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"names":[],"mappings":";;;AAkGO,SAAS,gBACd,IACA,gBACA,WAAsD,OAAO,CAAA,IAC7B;AAChC,QAAM,iBAAiB,IAAI,UAAe,IAAI,cAAc;AAE5D,QAAM,QAAQ,SAAS,eAAe,OAAO,QAAQ;AAErD,eAAa,MAAM;AACjB,cAAU,MAAM;AACd,qBAAe,OAAA;AAAA,IAAO,CACvB;AAAA,EAAA,CACF;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"} |
+2
-2
| { | ||
| "name": "@tanstack/solid-pacer", | ||
| "version": "0.10.0", | ||
| "version": "0.11.0", | ||
| "description": "Utilities for debouncing and throttling functions in Solid.", | ||
@@ -166,3 +166,3 @@ "author": "Tanner Linsley", | ||
| "@tanstack/solid-store": "^0.7.3", | ||
| "@tanstack/pacer": "0.10.0" | ||
| "@tanstack/pacer": "0.11.0" | ||
| }, | ||
@@ -169,0 +169,0 @@ "devDependencies": { |
| import { AsyncBatcher } from '@tanstack/pacer/async-batcher' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -9,6 +10,4 @@ import type { | ||
| export interface SolidAsyncBatcher< | ||
| TValue, | ||
| TSelected = AsyncBatcherState<TValue>, | ||
| > extends Omit<AsyncBatcher<TValue>, 'store'> { | ||
| export interface SolidAsyncBatcher<TValue, TSelected = {}> | ||
| extends Omit<AsyncBatcher<TValue>, 'store'> { | ||
| /** | ||
@@ -20,2 +19,8 @@ * Reactive state that will be updated when the batcher state changes | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncBatcherState<TValue>>> | ||
| } | ||
@@ -53,5 +58,27 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `errorCount`: Number of failed batch executions | ||
| * - `executionCount`: Total number of batch execution attempts (successful + failed) | ||
| * - `hasError`: Whether the last batch execution resulted in an error | ||
| * - `isExecuting`: Whether a batch execution is currently in progress | ||
| * - `items`: Array of items currently queued for batching | ||
| * - `lastError`: The error from the most recent failed batch execution (if any) | ||
| * - `lastResult`: The result from the most recent successful batch execution | ||
| * - `settleCount`: Number of batch executions that have completed (successful or failed) | ||
| * - `successCount`: Number of successful batch executions | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Basic async batcher for API requests | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const asyncBatcher = createAsyncBatcher( | ||
@@ -74,2 +101,22 @@ * async (items) => { | ||
| * | ||
| * // Opt-in to re-render when items or isExecuting changes (optimized for UI updates) | ||
| * const asyncBatcher = createAsyncBatcher( | ||
| * async (items) => { | ||
| * const results = await Promise.all(items.map(item => processItem(item))); | ||
| * return results; | ||
| * }, | ||
| * { maxSize: 10, wait: 2000 }, | ||
| * (state) => ({ items: state.items, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const asyncBatcher = createAsyncBatcher( | ||
| * async (items) => { | ||
| * const results = await Promise.all(items.map(item => processItem(item))); | ||
| * return results; | ||
| * }, | ||
| * { maxSize: 10, wait: 2000 }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Add items to batch | ||
@@ -81,14 +128,11 @@ * asyncBatcher.addItem(newItem); | ||
| * | ||
| * // Use Solid signals in your UI | ||
| * const items = asyncBatcher.state().items; | ||
| * const isExecuting = asyncBatcher.state().isExecuting; | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isExecuting } = asyncBatcher.state(); | ||
| * ``` | ||
| */ | ||
| export function createAsyncBatcher< | ||
| TValue, | ||
| TSelected = AsyncBatcherState<TValue>, | ||
| >( | ||
| export function createAsyncBatcher<TValue, TSelected = {}>( | ||
| fn: (items: Array<TValue>) => Promise<any>, | ||
| initialOptions: AsyncBatcherOptions<TValue> = {}, | ||
| selector?: (state: AsyncBatcherState<TValue>) => TSelected, | ||
| selector: (state: AsyncBatcherState<TValue>) => TSelected = () => | ||
| ({}) as TSelected, | ||
| ): SolidAsyncBatcher<TValue, TSelected> { | ||
@@ -102,3 +146,3 @@ const asyncBatcher = new AsyncBatcher<TValue>(fn, initialOptions) | ||
| state, | ||
| } as unknown as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state` | ||
| } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state` | ||
| } |
| import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import { createEffect, onCleanup } from 'solid-js' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -13,3 +14,3 @@ import type { | ||
| TFn extends AnyAsyncFunction, | ||
| TSelected = AsyncDebouncerState<TFn>, | ||
| TSelected = {}, | ||
| > extends Omit<AsyncDebouncer<TFn>, 'store'> { | ||
@@ -22,2 +23,8 @@ /** | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncDebouncerState<TFn>>> | ||
| } | ||
@@ -49,5 +56,27 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call debouncing | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncDebouncer( | ||
@@ -61,8 +90,17 @@ * async (query: string) => { | ||
| * | ||
| * // With state management | ||
| * const [results, setResults] = createSignal([]); | ||
| * const { maybeExecute } = createAsyncDebouncer( | ||
| * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states) | ||
| * const debouncer = createAsyncDebouncer( | ||
| * async (query: string) => { | ||
| * const results = await api.search(query); | ||
| * return results; | ||
| * }, | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const debouncer = createAsyncDebouncer( | ||
| * async (searchTerm) => { | ||
| * const data = await searchAPI(searchTerm); | ||
| * setResults(data); | ||
| * return data; | ||
| * }, | ||
@@ -76,4 +114,8 @@ * { | ||
| * } | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, isExecuting } = debouncer.state(); | ||
| * ``` | ||
@@ -83,7 +125,8 @@ */ | ||
| TFn extends AnyAsyncFunction, | ||
| TSelected = AsyncDebouncerState<TFn>, | ||
| TSelected = {}, | ||
| >( | ||
| fn: TFn, | ||
| initialOptions: AsyncDebouncerOptions<TFn>, | ||
| selector?: (state: AsyncDebouncerState<TFn>) => TSelected, | ||
| selector: (state: AsyncDebouncerState<TFn>) => TSelected = () => | ||
| ({}) as TSelected, | ||
| ): SolidAsyncDebouncer<TFn, TSelected> { | ||
@@ -103,3 +146,3 @@ const asyncDebouncer = new AsyncDebouncer<TFn>(fn, initialOptions) | ||
| state, | ||
| } as unknown as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state` | ||
| } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state` | ||
| } |
| import { AsyncQueuer } from '@tanstack/pacer/async-queuer' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -9,6 +10,6 @@ import type { | ||
| export interface SolidAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>> | ||
| export interface SolidAsyncQueuer<TValue, TSelected = {}> | ||
| extends Omit<AsyncQueuer<TValue>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated and re-rendered when the queuer state changes | ||
| * Reactive state that will be updated when the queuer state changes | ||
| * | ||
@@ -18,2 +19,8 @@ * Use this instead of `queuer.store.state` | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncQueuerState<TValue>>> | ||
| } | ||
@@ -44,5 +51,25 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `activeItems`: Array of items currently being processed | ||
| * - `errorCount`: Number of items that failed processing | ||
| * - `isRunning`: Whether the queuer is currently running (not stopped) | ||
| * - `pendingItems`: Array of items waiting to be processed | ||
| * - `rejectionCount`: Number of items that were rejected (expired or failed validation) | ||
| * - `settleCount`: Number of items that have completed processing (successful or failed) | ||
| * - `successCount`: Number of items that were processed successfully | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Basic async queuer for API requests | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const asyncQueuer = createAsyncQueuer(async (item) => { | ||
@@ -64,2 +91,24 @@ * // process item | ||
| * | ||
| * // Opt-in to re-render when queue state changes (optimized for UI updates) | ||
| * const asyncQueuer = createAsyncQueuer( | ||
| * async (item) => await fetchData(item), | ||
| * { concurrency: 2, started: true }, | ||
| * (state) => ({ | ||
| * pendingItems: state.pendingItems, | ||
| * activeItems: state.activeItems, | ||
| * isRunning: state.isRunning | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when processing metrics change (optimized for tracking progress) | ||
| * const asyncQueuer = createAsyncQueuer( | ||
| * async (item) => await fetchData(item), | ||
| * { concurrency: 2, started: true }, | ||
| * (state) => ({ | ||
| * successCount: state.successCount, | ||
| * errorCount: state.errorCount, | ||
| * settleCount: state.settleCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to queue | ||
@@ -71,10 +120,11 @@ * asyncQueuer.addItem(newItem); | ||
| * | ||
| * // Use Solid signals in your UI | ||
| * const pending = asyncQueuer.pendingItems(); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { pendingItems, activeItems } = asyncQueuer.state(); | ||
| * ``` | ||
| */ | ||
| export function createAsyncQueuer<TValue, TSelected = AsyncQueuerState<TValue>>( | ||
| export function createAsyncQueuer<TValue, TSelected = {}>( | ||
| fn: (value: TValue) => Promise<any>, | ||
| initialOptions: AsyncQueuerOptions<TValue> = {}, | ||
| selector?: (state: AsyncQueuerState<TValue>) => TSelected, | ||
| selector: (state: AsyncQueuerState<TValue>) => TSelected = () => | ||
| ({}) as TSelected, | ||
| ): SolidAsyncQueuer<TValue, TSelected> { | ||
@@ -88,3 +138,3 @@ const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions) | ||
| state, | ||
| } as unknown as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state` | ||
| } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state` | ||
| } |
| import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -12,5 +13,16 @@ import type { AnyAsyncFunction } from '@tanstack/pacer/types' | ||
| TFn extends AnyAsyncFunction, | ||
| TSelected = AsyncRateLimiterState<TFn>, | ||
| TSelected = {}, | ||
| > extends Omit<AsyncRateLimiter<TFn>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated when the rate limiter state changes | ||
| * | ||
| * Use this instead of `rateLimiter.store.state` | ||
| */ | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>> | ||
| } | ||
@@ -53,5 +65,27 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `currentWindowStart`: Timestamp when the current window started | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `nextWindowTime`: Timestamp when the next window begins | ||
| * - `rejectionCount`: Number of function calls that were rejected due to rate limiting | ||
| * - `remainingInWindow`: Number of executions remaining in the current window | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call rate limiting with return value | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncRateLimiter( | ||
@@ -65,10 +99,22 @@ * async (id: string) => { | ||
| * | ||
| * // With state management and return value | ||
| * const [data, setData] = createSignal(null); | ||
| * const { maybeExecute } = createAsyncRateLimiter( | ||
| * // Opt-in to re-render when rate limit and execution state changes (optimized for UI feedback) | ||
| * const rateLimiter = createAsyncRateLimiter( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * setData(result); | ||
| * return result; // Return value can be used by the caller | ||
| * return result; | ||
| * }, | ||
| * { limit: 10, window: 60000 }, | ||
| * (state) => ({ | ||
| * remainingInWindow: state.remainingInWindow, | ||
| * isExecuting: state.isExecuting, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const rateLimiter = createAsyncRateLimiter( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * return result; | ||
| * }, | ||
| * { | ||
@@ -78,4 +124,8 @@ * limit: 10, | ||
| * onReject: (info) => console.log(`Rate limit exceeded: ${info.nextValidTime - Date.now()}ms until next window`) | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { remainingInWindow, isExecuting } = rateLimiter.state(); | ||
| * ``` | ||
@@ -85,7 +135,8 @@ */ | ||
| TFn extends AnyAsyncFunction, | ||
| TSelected = AsyncRateLimiterState<TFn>, | ||
| TSelected = {}, | ||
| >( | ||
| fn: TFn, | ||
| initialOptions: AsyncRateLimiterOptions<TFn>, | ||
| selector?: (state: AsyncRateLimiterState<TFn>) => TSelected, | ||
| selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () => | ||
| ({}) as TSelected, | ||
| ): SolidAsyncRateLimiter<TFn, TSelected> { | ||
@@ -92,0 +143,0 @@ const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions) |
| import { AsyncThrottler } from '@tanstack/pacer/async-throttler' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -12,6 +13,6 @@ import type { AnyAsyncFunction } from '@tanstack/pacer/types' | ||
| TFn extends AnyAsyncFunction, | ||
| TSelected = AsyncThrottlerState<TFn>, | ||
| TSelected = {}, | ||
| > extends Omit<AsyncThrottler<TFn>, 'store'> { | ||
| /** | ||
| * Reactive state that will be updated and re-rendered when the throttler state changes | ||
| * Reactive state that will be updated when the throttler state changes | ||
| * | ||
@@ -21,2 +22,8 @@ * Use this instead of `throttler.store.state` | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<AsyncThrottlerState<TFn>>> | ||
| } | ||
@@ -45,5 +52,30 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `hasError`: Whether the last execution resulted in an error | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution | ||
| * - `isExecuting`: Whether an async function execution is currently in progress | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastError`: The error from the most recent failed execution (if any) | ||
| * - `lastExecutionTime`: Timestamp of the last execution | ||
| * - `lastResult`: The result from the most recent successful execution | ||
| * - `nextExecutionTime`: Timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic API call throttling | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const { maybeExecute } = createAsyncThrottler( | ||
@@ -57,9 +89,18 @@ * async (id: string) => { | ||
| * | ||
| * // With state management | ||
| * const [data, setData] = createSignal(null); | ||
| * const { maybeExecute } = createAsyncThrottler( | ||
| * // Opt-in to re-render when isPending or isExecuting changes (optimized for loading states) | ||
| * const throttler = createAsyncThrottler( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * setData(result); | ||
| * return result; | ||
| * }, | ||
| * { wait: 2000 }, | ||
| * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when error state changes (optimized for error handling) | ||
| * const throttler = createAsyncThrottler( | ||
| * async (query) => { | ||
| * const result = await searchAPI(query); | ||
| * return result; | ||
| * }, | ||
| * { | ||
@@ -72,4 +113,8 @@ * wait: 2000, | ||
| * } | ||
| * } | ||
| * }, | ||
| * (state) => ({ hasError: state.hasError, lastError: state.lastError }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, isExecuting } = throttler.state(); | ||
| * ``` | ||
@@ -79,7 +124,8 @@ */ | ||
| TFn extends AnyAsyncFunction, | ||
| TSelected = AsyncThrottlerState<TFn>, | ||
| TSelected = {}, | ||
| >( | ||
| fn: TFn, | ||
| initialOptions: AsyncThrottlerOptions<TFn>, | ||
| selector?: (state: AsyncThrottlerState<TFn>) => TSelected, | ||
| selector: (state: AsyncThrottlerState<TFn>) => TSelected = () => | ||
| ({}) as TSelected, | ||
| ): SolidAsyncThrottler<TFn, TSelected> { | ||
@@ -86,0 +132,0 @@ const asyncThrottler = new AsyncThrottler(fn, initialOptions) |
| import { Batcher } from '@tanstack/pacer/batcher' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
| import type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher' | ||
| export interface SolidBatcher<TValue, TSelected = BatcherState<TValue>> | ||
| export interface SolidBatcher<TValue, TSelected = {}> | ||
| extends Omit<Batcher<TValue>, 'store'> { | ||
@@ -14,2 +15,8 @@ /** | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<BatcherState<TValue>>> | ||
| } | ||
@@ -32,4 +39,22 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of batch executions that have been completed | ||
| * - `isRunning`: Whether the batcher is currently running (not stopped) | ||
| * - `items`: Array of items currently queued for batching | ||
| * - `totalItemsProcessed`: Total number of individual items that have been processed across all batches | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const batcher = createBatcher( | ||
@@ -48,2 +73,19 @@ * (items) => { | ||
| * | ||
| * // Opt-in to re-render when items or isRunning changes (optimized for UI updates) | ||
| * const batcher = createBatcher( | ||
| * (items) => console.log('Processing batch:', items), | ||
| * { maxSize: 5, wait: 2000 }, | ||
| * (state) => ({ items: state.items, isRunning: state.isRunning }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const batcher = createBatcher( | ||
| * (items) => console.log('Processing batch:', items), | ||
| * { maxSize: 5, wait: 2000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * totalItemsProcessed: state.totalItemsProcessed | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to batch | ||
@@ -57,15 +99,11 @@ * batcher.addItem('task1'); | ||
| * | ||
| * // Access batcher state via signals | ||
| * console.log('Items:', batcher.allItems()); | ||
| * console.log('Size:', batcher.size()); | ||
| * console.log('Is empty:', batcher.isEmpty()); | ||
| * console.log('Is running:', batcher.isRunning()); | ||
| * console.log('Batch count:', batcher.executionCount()); | ||
| * console.log('Item count:', batcher.totalItemsProcessed()); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isRunning } = batcher.state(); | ||
| * ``` | ||
| */ | ||
| export function createBatcher<TValue, TSelected = BatcherState<TValue>>( | ||
| export function createBatcher<TValue, TSelected = {}>( | ||
| fn: (items: Array<TValue>) => void, | ||
| initialOptions: BatcherOptions<TValue> = {}, | ||
| selector?: (state: BatcherState<TValue>) => TSelected, | ||
| selector: (state: BatcherState<TValue>) => TSelected = () => | ||
| ({}) as TSelected, | ||
| ): SolidBatcher<TValue, TSelected> { | ||
@@ -72,0 +110,0 @@ const batcher = new Batcher(fn, initialOptions) |
@@ -24,5 +24,23 @@ import { createSignal } from 'solid-js' | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying debouncer instance. | ||
| * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available debouncer state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounced search input | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal('', { | ||
@@ -32,2 +50,16 @@ * wait: 500 // Wait 500ms after last keystroke | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal( | ||
| * '', | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to reactive updates when execution count changes (optimized for tracking executions) | ||
| * const [searchTerm, setSearchTerm, debouncer] = createDebouncedSignal( | ||
| * '', | ||
| * { wait: 500 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Update value - will be debounced | ||
@@ -39,4 +71,4 @@ * const handleChange = (e) => { | ||
| * // Access debouncer state via signals | ||
| * console.log('Executions:', debouncer.executionCount()); | ||
| * console.log('Is pending:', debouncer.isPending()); | ||
| * console.log('Executions:', debouncer.state().executionCount); | ||
| * console.log('Is pending:', debouncer.state().isPending); | ||
| * | ||
@@ -52,6 +84,3 @@ * // In onExecute callback, use get* methods | ||
| */ | ||
| export function createDebouncedSignal< | ||
| TValue, | ||
| TSelected = DebouncerState<Setter<TValue>>, | ||
| >( | ||
| export function createDebouncedSignal<TValue, TSelected = {}>( | ||
| value: TValue, | ||
@@ -58,0 +87,0 @@ initialOptions: DebouncerOptions<Setter<TValue>>, |
@@ -27,5 +27,23 @@ import { createEffect } from 'solid-js' | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying debouncer instance. | ||
| * The `selector` parameter allows you to specify which debouncer state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available debouncer state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounce a search query | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [searchQuery, setSearchQuery] = createSignal(''); | ||
@@ -36,2 +54,9 @@ * const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, { | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [debouncedQuery, debouncer] = createDebouncedValue( | ||
| * searchQuery, | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // debouncedQuery will update 500ms after searchQuery stops changing | ||
@@ -42,2 +67,5 @@ * createEffect(() => { | ||
| * | ||
| * // Access debouncer state via signals | ||
| * console.log('Is pending:', debouncer.state().isPending); | ||
| * | ||
| * // Control the debouncer | ||
@@ -47,6 +75,3 @@ * debouncer.cancel(); // Cancel any pending updates | ||
| */ | ||
| export function createDebouncedValue< | ||
| TValue, | ||
| TSelected = DebouncerState<Setter<TValue>>, | ||
| >( | ||
| export function createDebouncedValue<TValue, TSelected = {}>( | ||
| value: Accessor<TValue>, | ||
@@ -53,0 +78,0 @@ initialOptions: DebouncerOptions<Setter<TValue>>, |
| import { Debouncer } from '@tanstack/pacer/debouncer' | ||
| import { createEffect, onCleanup } from 'solid-js' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -11,6 +12,4 @@ import type { AnyFunction } from '@tanstack/pacer/types' | ||
| export interface SolidDebouncer< | ||
| TFn extends AnyFunction, | ||
| TSelected = DebouncerState<TFn>, | ||
| > extends Omit<Debouncer<TFn>, 'store'> { | ||
| export interface SolidDebouncer<TFn extends AnyFunction, TSelected = {}> | ||
| extends Omit<Debouncer<TFn>, 'store'> { | ||
| /** | ||
@@ -22,2 +21,8 @@ * Reactive state that will be updated when the debouncer state changes | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<DebouncerState<TFn>>> | ||
| } | ||
@@ -40,10 +45,53 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Debounce a search function to limit API calls | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 } // Wait 500ms after last keystroke | ||
| * { wait: 500 } | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when isPending changes (optimized for loading states) | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when executionCount changes (optimized for tracking execution) | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Multiple state properties - re-render when any of these change | ||
| * const debouncer = createDebouncer( | ||
| * (query: string) => fetchSearchResults(query), | ||
| * { wait: 500 }, | ||
| * (state) => ({ | ||
| * isPending: state.isPending, | ||
| * executionCount: state.executionCount, | ||
| * status: state.status | ||
| * }) | ||
| * ); | ||
| * | ||
| * // In an event handler | ||
@@ -54,17 +102,10 @@ * const handleChange = (e) => { | ||
| * | ||
| * // Access debouncer state via signals | ||
| * console.log('Executions:', debouncer.executionCount()); | ||
| * console.log('Is pending:', debouncer.isPending()); | ||
| * | ||
| * // Update options | ||
| * debouncer.setOptions({ wait: 1000 }); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending } = debouncer.state(); | ||
| * ``` | ||
| */ | ||
| export function createDebouncer< | ||
| TFn extends AnyFunction, | ||
| TSelected = DebouncerState<TFn>, | ||
| >( | ||
| export function createDebouncer<TFn extends AnyFunction, TSelected = {}>( | ||
| fn: TFn, | ||
| initialOptions: DebouncerOptions<TFn>, | ||
| selector?: (state: DebouncerState<TFn>) => TSelected, | ||
| selector: (state: DebouncerState<TFn>) => TSelected = () => ({}) as TSelected, | ||
| ): SolidDebouncer<TFn, TSelected> { | ||
@@ -71,0 +112,0 @@ const asyncDebouncer = new Debouncer<TFn>(fn, initialOptions) |
| import { Queuer } from '@tanstack/pacer/queuer' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
| import type { QueuerOptions, QueuerState } from '@tanstack/pacer/queuer' | ||
| export interface SolidQueuer<TValue, TSelected = QueuerState<TValue>> | ||
| export interface SolidQueuer<TValue, TSelected = {}> | ||
| extends Omit<Queuer<TValue>, 'store'> { | ||
@@ -14,2 +15,8 @@ /** | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<QueuerState<TValue>>> | ||
| } | ||
@@ -34,7 +41,22 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of items that have been processed | ||
| * - `isRunning`: Whether the queuer is currently running (not stopped) | ||
| * - `items`: Array of items currently queued for processing | ||
| * - `rejectionCount`: Number of items that were rejected (expired or failed validation) | ||
| * | ||
| * Example usage: | ||
| * ```tsx | ||
| * // Example with Solid signals and scheduling | ||
| * const [items, setItems] = createSignal([]); | ||
| * | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const queue = createQueuer( | ||
@@ -48,3 +70,2 @@ * (item) => { | ||
| * wait: 1000, // Process one item every second | ||
| * onItemsChange: (queue) => setItems(queue.peekAllItems()), | ||
| * getPriority: (item) => item.priority // Process higher priority items first | ||
@@ -54,2 +75,19 @@ * } | ||
| * | ||
| * // Opt-in to re-render when items or isRunning changes (optimized for UI updates) | ||
| * const queue = createQueuer( | ||
| * (item) => console.log('Processing', item), | ||
| * { started: true, wait: 1000 }, | ||
| * (state) => ({ items: state.items, isRunning: state.isRunning }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const queue = createQueuer( | ||
| * (item) => console.log('Processing', item), | ||
| * { started: true, wait: 1000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Add items to process - they'll be handled automatically | ||
@@ -63,14 +101,10 @@ * queue.addItem('task1'); | ||
| * | ||
| * // Access queue state via signals | ||
| * console.log('Items:', queue.allItems()); | ||
| * console.log('Size:', queue.size()); | ||
| * console.log('Is empty:', queue.isEmpty()); | ||
| * console.log('Is running:', queue.isRunning()); | ||
| * console.log('Next item:', queue.nextItem()); | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { items, isRunning } = queue.state(); | ||
| * ``` | ||
| */ | ||
| export function createQueuer<TValue, TSelected = QueuerState<TValue>>( | ||
| export function createQueuer<TValue, TSelected = {}>( | ||
| fn: (item: TValue) => void, | ||
| initialOptions: QueuerOptions<TValue> = {}, | ||
| selector?: (state: QueuerState<TValue>) => TSelected, | ||
| selector: (state: QueuerState<TValue>) => TSelected = () => ({}) as TSelected, | ||
| ): SolidQueuer<TValue, TSelected> { | ||
@@ -84,3 +118,3 @@ const queuer = new Queuer(fn, initialOptions) | ||
| state, | ||
| } as unknown as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state` | ||
| } as SolidQueuer<TValue, TSelected> // omit `store` in favor of `state` | ||
| } |
@@ -38,5 +38,25 @@ import { createSignal } from 'solid-js' | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance. | ||
| * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available rate limiter state properties: | ||
| * - `callsInWindow`: Number of calls made in the current window | ||
| * - `remainingInWindow`: Number of calls remaining in the current window | ||
| * - `windowStart`: Unix timestamp when the current window started | ||
| * - `nextWindowStart`: Unix timestamp when the next window will start | ||
| * - `msUntilNextWindow`: Milliseconds until the next window starts | ||
| * - `isAtLimit`: Whether the call limit for the current window has been reached | ||
| * - `status`: Current status ('disabled' | 'idle' | 'at-limit') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - update state at most 5 times per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [value, setValue, rateLimiter] = createRateLimitedSignal(0, { | ||
@@ -48,2 +68,9 @@ * limit: 5, | ||
| * | ||
| * // Opt-in to reactive updates when limit state changes (optimized for UI feedback) | ||
| * const [value, setValue, rateLimiter] = createRateLimitedSignal( | ||
| * 0, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow }) | ||
| * ); | ||
| * | ||
| * // With rejection callback and fixed window | ||
@@ -61,3 +88,3 @@ * const [value, setValue] = createRateLimitedSignal(0, { | ||
| * const handleSubmit = () => { | ||
| * const remaining = rateLimiter.remainingInWindow(); | ||
| * const remaining = rateLimiter.state().remainingInWindow; | ||
| * if (remaining > 0) { | ||
@@ -71,3 +98,3 @@ * setValue(newValue); | ||
| */ | ||
| export function createRateLimitedSignal<TValue, TSelected = RateLimiterState>( | ||
| export function createRateLimitedSignal<TValue, TSelected = {}>( | ||
| value: TValue, | ||
@@ -74,0 +101,0 @@ initialOptions: RateLimiterOptions<Setter<TValue>>, |
@@ -37,5 +37,25 @@ import { createEffect } from 'solid-js' | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance. | ||
| * The `selector` parameter allows you to specify which rate limiter state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available rate limiter state properties: | ||
| * - `callsInWindow`: Number of calls made in the current window | ||
| * - `remainingInWindow`: Number of calls remaining in the current window | ||
| * - `windowStart`: Unix timestamp when the current window started | ||
| * - `nextWindowStart`: Unix timestamp when the next window will start | ||
| * - `msUntilNextWindow`: Milliseconds until the next window starts | ||
| * - `isAtLimit`: Whether the call limit for the current window has been reached | ||
| * - `status`: Current status ('disabled' | 'idle' | 'at-limit') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - update at most 5 times per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [rateLimitedValue, rateLimiter] = createRateLimitedValue(rawValue, { | ||
@@ -47,5 +67,15 @@ * limit: 5, | ||
| * | ||
| * // Opt-in to reactive updates when limit state changes (optimized for UI feedback) | ||
| * const [rateLimitedValue, rateLimiter] = createRateLimitedValue( | ||
| * rawValue, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ isAtLimit: state.isAtLimit, remainingInWindow: state.remainingInWindow }) | ||
| * ); | ||
| * | ||
| * // Use the rate-limited value | ||
| * console.log(rateLimitedValue()); // Access the current rate-limited value | ||
| * | ||
| * // Access rate limiter state via signals | ||
| * console.log('Is at limit:', rateLimiter.state().isAtLimit); | ||
| * | ||
| * // Control the rate limiter | ||
@@ -55,3 +85,3 @@ * rateLimiter.reset(); // Reset the rate limit window | ||
| */ | ||
| export function createRateLimitedValue<TValue, TSelected = RateLimiterState>( | ||
| export function createRateLimitedValue<TValue, TSelected = {}>( | ||
| value: Accessor<TValue>, | ||
@@ -58,0 +88,0 @@ initialOptions: RateLimiterOptions<Setter<TValue>>, |
| import { RateLimiter } from '@tanstack/pacer/rate-limiter' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -10,6 +11,4 @@ import type { AnyFunction } from '@tanstack/pacer/types' | ||
| export interface SolidRateLimiter< | ||
| TFn extends AnyFunction, | ||
| TSelected = RateLimiterState, | ||
| > extends Omit<RateLimiter<TFn>, 'store'> { | ||
| export interface SolidRateLimiter<TFn extends AnyFunction, TSelected = {}> | ||
| extends Omit<RateLimiter<TFn>, 'store'> { | ||
| /** | ||
@@ -21,2 +20,8 @@ * Reactive state that will be updated when the rate limiter state changes | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<RateLimiterState>> | ||
| } | ||
@@ -45,5 +50,23 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `rejectionCount`: Number of function calls that were rejected due to rate limiting | ||
| * - `remainingInWindow`: Number of executions remaining in the current window | ||
| * - `nextWindowTime`: Timestamp when the next window begins | ||
| * - `currentWindowStart`: Timestamp when the current window started | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic rate limiting - max 5 calls per minute with a sliding window | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const rateLimiter = createRateLimiter(apiCall, { | ||
@@ -58,16 +81,30 @@ * limit: 5, | ||
| * | ||
| * // Access rate limiter state via signals | ||
| * console.log('Executions:', rateLimiter.executionCount()); | ||
| * console.log('Rejections:', rateLimiter.rejectionCount()); | ||
| * console.log('Remaining:', rateLimiter.remainingInWindow()); | ||
| * console.log('Next window in:', rateLimiter.msUntilNextWindow()); | ||
| * // Opt-in to re-render when rate limit state changes (optimized for UI feedback) | ||
| * const rateLimiter = createRateLimiter( | ||
| * apiCall, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ | ||
| * remainingInWindow: state.remainingInWindow, | ||
| * rejectionCount: state.rejectionCount | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when execution metrics change (optimized for tracking progress) | ||
| * const rateLimiter = createRateLimiter( | ||
| * apiCall, | ||
| * { limit: 5, window: 60000 }, | ||
| * (state) => ({ | ||
| * executionCount: state.executionCount, | ||
| * nextWindowTime: state.nextWindowTime | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { remainingInWindow, rejectionCount } = rateLimiter.state(); | ||
| * ``` | ||
| */ | ||
| export function createRateLimiter< | ||
| TFn extends AnyFunction, | ||
| TSelected = RateLimiterState, | ||
| >( | ||
| export function createRateLimiter<TFn extends AnyFunction, TSelected = {}>( | ||
| fn: TFn, | ||
| initialOptions: RateLimiterOptions<TFn>, | ||
| selector?: (state: RateLimiterState) => TSelected, | ||
| selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected, | ||
| ): SolidRateLimiter<TFn, TSelected> { | ||
@@ -81,3 +118,3 @@ const rateLimiter = new RateLimiter<TFn>(fn, initialOptions) | ||
| state, | ||
| } as unknown as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state` | ||
| } as SolidRateLimiter<TFn, TSelected> // omit `store` in favor of `state` | ||
| } |
@@ -25,7 +25,35 @@ import { createSignal } from 'solid-js' | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying throttler instance. | ||
| * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available throttler state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Unix timestamp of the last execution | ||
| * - `nextExecutionTime`: Unix timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling - update state at most once per second | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [value, setValue, throttler] = createThrottledSignal(0, { wait: 1000 }); | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [value, setValue, throttler] = createThrottledSignal( | ||
| * 0, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // With custom leading/trailing behavior | ||
@@ -39,12 +67,9 @@ * const [value, setValue] = createThrottledSignal(0, { | ||
| * // Access throttler state via signals | ||
| * console.log('Executions:', throttler.executionCount()); | ||
| * console.log('Is pending:', throttler.isPending()); | ||
| * console.log('Last execution:', throttler.lastExecutionTime()); | ||
| * console.log('Next execution:', throttler.nextExecutionTime()); | ||
| * console.log('Executions:', throttler.state().executionCount); | ||
| * console.log('Is pending:', throttler.state().isPending); | ||
| * console.log('Last execution:', throttler.state().lastExecutionTime); | ||
| * console.log('Next execution:', throttler.state().nextExecutionTime); | ||
| * ``` | ||
| */ | ||
| export function createThrottledSignal< | ||
| TValue, | ||
| TSelected = ThrottlerState<Setter<TValue>>, | ||
| >( | ||
| export function createThrottledSignal<TValue, TSelected = {}>( | ||
| value: TValue, | ||
@@ -51,0 +76,0 @@ initialOptions: ThrottlerOptions<Setter<TValue>>, |
@@ -26,10 +26,41 @@ import { createEffect } from 'solid-js' | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management via the underlying throttler instance. | ||
| * The `selector` parameter allows you to specify which throttler state changes will trigger reactive updates, | ||
| * optimizing performance by preventing unnecessary subscriptions when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary reactive updates and gives you | ||
| * full control over when your component subscribes to state changes. Only when you provide a selector will | ||
| * the reactive system track the selected state values. | ||
| * | ||
| * Available throttler state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger trailing execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Unix timestamp of the last execution | ||
| * - `nextExecutionTime`: Unix timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling - update at most once per second | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const [throttledValue, throttler] = createThrottledValue(rawValue, { wait: 1000 }); | ||
| * | ||
| * // Opt-in to reactive updates when pending state changes (optimized for loading indicators) | ||
| * const [throttledValue, throttler] = createThrottledValue( | ||
| * rawValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Use the throttled value | ||
| * console.log(throttledValue()); // Access the current throttled value | ||
| * | ||
| * // Access throttler state via signals | ||
| * console.log('Is pending:', throttler.state().isPending); | ||
| * | ||
| * // Control the throttler | ||
@@ -39,6 +70,3 @@ * throttler.cancel(); // Cancel any pending updates | ||
| */ | ||
| export function createThrottledValue< | ||
| TValue, | ||
| TSelected = ThrottlerState<Setter<TValue>>, | ||
| >( | ||
| export function createThrottledValue<TValue, TSelected = {}>( | ||
| value: Accessor<TValue>, | ||
@@ -45,0 +73,0 @@ initialOptions: ThrottlerOptions<Setter<TValue>>, |
| import { Throttler } from '@tanstack/pacer/throttler' | ||
| import { createEffect, onCleanup } from 'solid-js' | ||
| import { useStore } from '@tanstack/solid-store' | ||
| import type { Store } from '@tanstack/solid-store' | ||
| import type { Accessor } from 'solid-js' | ||
@@ -11,6 +12,4 @@ import type { AnyFunction } from '@tanstack/pacer/types' | ||
| export interface SolidThrottler< | ||
| TFn extends AnyFunction, | ||
| TSelected = ThrottlerState<TFn>, | ||
| > extends Omit<Throttler<TFn>, 'store'> { | ||
| export interface SolidThrottler<TFn extends AnyFunction, TSelected = {}> | ||
| extends Omit<Throttler<TFn>, 'store'> { | ||
| /** | ||
@@ -22,2 +21,8 @@ * Reactive state that will be updated when the throttler state changes | ||
| readonly state: Accessor<Readonly<TSelected>> | ||
| /** | ||
| * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state. | ||
| * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally. | ||
| * Although, you can make the state reactive by using the `useStore` in your own usage. | ||
| */ | ||
| readonly store: Store<Readonly<ThrottlerState<TFn>>> | ||
| } | ||
@@ -36,11 +41,45 @@ | ||
| * | ||
| * ## State Management and Selector | ||
| * | ||
| * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you | ||
| * to specify which state changes will trigger a re-render, optimizing performance by preventing | ||
| * unnecessary re-renders when irrelevant state changes occur. | ||
| * | ||
| * **By default, there will be no reactive state subscriptions** and you must opt-in to state | ||
| * tracking by providing a selector function. This prevents unnecessary re-renders and gives you | ||
| * full control over when your component updates. Only when you provide a selector will the | ||
| * component re-render when the selected state values change. | ||
| * | ||
| * Available state properties: | ||
| * - `canLeadingExecute`: Whether the throttler can execute on the leading edge | ||
| * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge | ||
| * - `executionCount`: Number of function executions that have been completed | ||
| * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution | ||
| * - `lastArgs`: The arguments from the most recent call to maybeExecute | ||
| * - `lastExecutionTime`: Timestamp of the last execution | ||
| * - `nextExecutionTime`: Timestamp of the next allowed execution | ||
| * - `status`: Current execution status ('disabled' | 'idle' | 'pending') | ||
| * | ||
| * @example | ||
| * ```tsx | ||
| * // Basic throttling with custom state | ||
| * const [value, setValue] = createSignal(0); | ||
| * // Default behavior - no reactive state subscriptions | ||
| * const throttler = createThrottler(setValue, { wait: 1000 }); | ||
| * | ||
| * // With any state manager | ||
| * // Opt-in to re-render when isPending changes (optimized for loading states) | ||
| * const throttler = createThrottler( | ||
| * (value) => stateManager.setState(value), | ||
| * setValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ isPending: state.isPending }) | ||
| * ); | ||
| * | ||
| * // Opt-in to re-render when executionCount changes (optimized for tracking execution) | ||
| * const throttler = createThrottler( | ||
| * setValue, | ||
| * { wait: 1000 }, | ||
| * (state) => ({ executionCount: state.executionCount }) | ||
| * ); | ||
| * | ||
| * // Multiple state properties - re-render when any of these change | ||
| * const throttler = createThrottler( | ||
| * setValue, | ||
| * { | ||
@@ -50,19 +89,19 @@ * wait: 2000, | ||
| * trailing: false // Skip trailing edge updates | ||
| * } | ||
| * }, | ||
| * (state) => ({ | ||
| * isPending: state.isPending, | ||
| * executionCount: state.executionCount, | ||
| * lastExecutionTime: state.lastExecutionTime, | ||
| * nextExecutionTime: state.nextExecutionTime | ||
| * }) | ||
| * ); | ||
| * | ||
| * // Access throttler state via signals | ||
| * console.log(throttler.executionCount()); // number of times executed | ||
| * console.log(throttler.isPending()); // whether throttled function is pending | ||
| * console.log(throttler.lastExecutionTime()); // timestamp of last execution | ||
| * console.log(throttler.nextExecutionTime()); // timestamp of next allowed execution | ||
| * // Access the selected state (will be empty object {} unless selector provided) | ||
| * const { isPending, executionCount } = throttler.state(); | ||
| * ``` | ||
| */ | ||
| export function createThrottler< | ||
| TFn extends AnyFunction, | ||
| TSelected = ThrottlerState<TFn>, | ||
| >( | ||
| export function createThrottler<TFn extends AnyFunction, TSelected = {}>( | ||
| fn: TFn, | ||
| initialOptions: ThrottlerOptions<TFn>, | ||
| selector?: (state: ThrottlerState<TFn>) => TSelected, | ||
| selector: (state: ThrottlerState<TFn>) => TSelected = () => ({}) as TSelected, | ||
| ): SolidThrottler<TFn, TSelected> { | ||
@@ -69,0 +108,0 @@ const asyncThrottler = new Throttler<TFn>(fn, initialOptions) |
446262
56.47%4178
40.11%+ Added
- Removed
Updated