@tanstack/solid-pacer 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/async-debouncer/createAsyncDebouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer/createAsyncDebouncer.d.cts +21 -2
- package/dist/cjs/async-queuer/createAsyncQueuer.cjs +24 -13
- package/dist/cjs/async-queuer/createAsyncQueuer.cjs.map +1 -1
- package/dist/cjs/async-queuer/createAsyncQueuer.d.cts +40 -32
- package/dist/cjs/async-rate-limiter/createAsyncRateLimiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter/createAsyncRateLimiter.d.cts +22 -7
- package/dist/cjs/async-throttler/createAsyncThrottler.cjs.map +1 -1
- package/dist/cjs/async-throttler/createAsyncThrottler.d.cts +15 -1
- package/dist/cjs/rate-limiter/createRateLimiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter/createRateLimiter.d.cts +4 -10
- package/dist/esm/async-debouncer/createAsyncDebouncer.d.ts +21 -2
- package/dist/esm/async-debouncer/createAsyncDebouncer.js.map +1 -1
- package/dist/esm/async-queuer/createAsyncQueuer.d.ts +40 -32
- package/dist/esm/async-queuer/createAsyncQueuer.js +24 -13
- package/dist/esm/async-queuer/createAsyncQueuer.js.map +1 -1
- package/dist/esm/async-rate-limiter/createAsyncRateLimiter.d.ts +22 -7
- package/dist/esm/async-rate-limiter/createAsyncRateLimiter.js.map +1 -1
- package/dist/esm/async-throttler/createAsyncThrottler.d.ts +15 -1
- package/dist/esm/async-throttler/createAsyncThrottler.js.map +1 -1
- package/dist/esm/rate-limiter/createRateLimiter.d.ts +4 -10
- package/dist/esm/rate-limiter/createRateLimiter.js.map +1 -1
- package/package.json +2 -2
- package/src/async-debouncer/createAsyncDebouncer.ts +21 -3
- package/src/async-queuer/createAsyncQueuer.ts +76 -55
- package/src/async-rate-limiter/createAsyncRateLimiter.ts +22 -7
- package/src/async-throttler/createAsyncThrottler.ts +15 -2
- package/src/rate-limiter/createRateLimiter.ts +4 -10
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import { AsyncQueuer, AsyncQueuerOptions } from '@tanstack/pacer/async-queuer';
|
|
1
|
+
import { AsyncQueuer, AsyncQueuerFn, AsyncQueuerOptions } from '@tanstack/pacer/async-queuer';
|
|
2
2
|
import { Accessor } from 'solid-js';
|
|
3
|
-
export interface SolidAsyncQueuer<
|
|
3
|
+
export interface SolidAsyncQueuer<TFn extends AsyncQueuerFn> extends Omit<AsyncQueuer<TFn>, 'getActiveItems' | 'getAllItems' | 'getErrorCount' | 'getIsEmpty' | 'getIsFull' | 'getIsIdle' | 'getIsRunning' | 'getPeek' | 'getPendingItems' | 'getRejectionCount' | 'getSettledCount' | 'getSize' | 'getSuccessCount'> {
|
|
4
4
|
/**
|
|
5
5
|
* Signal version of `getActiveItems`
|
|
6
6
|
*/
|
|
7
|
-
activeItems: Accessor<Array<
|
|
7
|
+
activeItems: Accessor<Array<TFn>>;
|
|
8
8
|
/**
|
|
9
9
|
* Signal version of `getAllItems`
|
|
10
10
|
*/
|
|
11
|
-
allItems: Accessor<Array<
|
|
11
|
+
allItems: Accessor<Array<TFn>>;
|
|
12
12
|
/**
|
|
13
|
-
* Signal version of `
|
|
13
|
+
* Signal version of `getErrorCount`
|
|
14
14
|
*/
|
|
15
|
-
|
|
15
|
+
errorCount: Accessor<number>;
|
|
16
16
|
/**
|
|
17
17
|
* Signal version of `getIsEmpty`
|
|
18
18
|
*/
|
|
@@ -32,38 +32,49 @@ export interface SolidAsyncQueuer<TValue> extends Omit<AsyncQueuer<TValue>, 'get
|
|
|
32
32
|
/**
|
|
33
33
|
* Signal version of `getPeek`
|
|
34
34
|
*/
|
|
35
|
-
peek: Accessor<
|
|
35
|
+
peek: Accessor<TFn | undefined>;
|
|
36
36
|
/**
|
|
37
37
|
* Signal version of `getPendingItems`
|
|
38
38
|
*/
|
|
39
|
-
pendingItems: Accessor<Array<
|
|
39
|
+
pendingItems: Accessor<Array<TFn>>;
|
|
40
40
|
/**
|
|
41
41
|
* Signal version of `getRejectionCount`
|
|
42
42
|
*/
|
|
43
43
|
rejectionCount: Accessor<number>;
|
|
44
|
+
/**
|
|
45
|
+
* Signal version of `getSettledCount`
|
|
46
|
+
*/
|
|
47
|
+
settledCount: Accessor<number>;
|
|
44
48
|
/**
|
|
45
49
|
* Signal version of `getSize`
|
|
46
50
|
*/
|
|
47
51
|
size: Accessor<number>;
|
|
52
|
+
/**
|
|
53
|
+
* Signal version of `getSuccessCount`
|
|
54
|
+
*/
|
|
55
|
+
successCount: Accessor<number>;
|
|
48
56
|
}
|
|
49
57
|
/**
|
|
50
|
-
* A lower-level
|
|
58
|
+
* A lower-level Solid hook that creates an `AsyncQueuer` instance for managing an async queue of items.
|
|
51
59
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
60
|
+
* Features:
|
|
61
|
+
* - Priority queue support via getPriority option
|
|
62
|
+
* - Configurable concurrency limit
|
|
63
|
+
* - Task success/error/completion callbacks
|
|
64
|
+
* - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
|
|
65
|
+
* - Pause/resume task processing
|
|
66
|
+
* - Task cancellation
|
|
67
|
+
* - Item expiration to clear stale items from the queue
|
|
54
68
|
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
* - Maximum queue size
|
|
58
|
-
* - Processing function for queue items
|
|
59
|
-
* - Various lifecycle callbacks
|
|
69
|
+
* Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
|
|
70
|
+
* the next pending task is processed if below the concurrency limit.
|
|
60
71
|
*
|
|
61
|
-
*
|
|
62
|
-
* -
|
|
63
|
-
* -
|
|
64
|
-
* -
|
|
65
|
-
* -
|
|
66
|
-
* -
|
|
72
|
+
* Error Handling:
|
|
73
|
+
* - If an `onError` handler is provided, it will be called with the error and queuer instance
|
|
74
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
75
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
76
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
77
|
+
* - The error state can be checked using the underlying AsyncQueuer instance
|
|
67
78
|
*
|
|
68
79
|
* @example
|
|
69
80
|
* ```tsx
|
|
@@ -73,6 +84,12 @@ export interface SolidAsyncQueuer<TValue> extends Omit<AsyncQueuer<TValue>, 'get
|
|
|
73
84
|
* concurrency: 2,
|
|
74
85
|
* maxSize: 100,
|
|
75
86
|
* started: false,
|
|
87
|
+
* onSuccess: (result) => {
|
|
88
|
+
* console.log('Item processed:', result);
|
|
89
|
+
* },
|
|
90
|
+
* onError: (error) => {
|
|
91
|
+
* console.error('Processing failed:', error);
|
|
92
|
+
* }
|
|
76
93
|
* });
|
|
77
94
|
*
|
|
78
95
|
* // Add items to queue
|
|
@@ -80,15 +97,6 @@ export interface SolidAsyncQueuer<TValue> extends Omit<AsyncQueuer<TValue>, 'get
|
|
|
80
97
|
*
|
|
81
98
|
* // Start processing
|
|
82
99
|
* asyncQueuer.start();
|
|
83
|
-
*
|
|
84
|
-
* // Handle results
|
|
85
|
-
* asyncQueuer.onSuccess((result) => {
|
|
86
|
-
* console.log('Item processed:', result);
|
|
87
|
-
* });
|
|
88
|
-
*
|
|
89
|
-
* asyncQueuer.onError((error) => {
|
|
90
|
-
* console.error('Processing failed:', error);
|
|
91
|
-
* });
|
|
92
100
|
* ```
|
|
93
101
|
*/
|
|
94
|
-
export declare function createAsyncQueuer<
|
|
102
|
+
export declare function createAsyncQueuer<TFn extends AsyncQueuerFn>(initialOptions?: AsyncQueuerOptions<TFn>): SolidAsyncQueuer<TFn>;
|
|
@@ -3,8 +3,12 @@ import { createSignal } from "solid-js";
|
|
|
3
3
|
import { bindInstanceMethods } from "@tanstack/pacer/utils";
|
|
4
4
|
function createAsyncQueuer(initialOptions = {}) {
|
|
5
5
|
const asyncQueuer = new AsyncQueuer(initialOptions);
|
|
6
|
-
const [
|
|
7
|
-
asyncQueuer.
|
|
6
|
+
const [successCount, setSuccessCount] = createSignal(
|
|
7
|
+
asyncQueuer.getSuccessCount()
|
|
8
|
+
);
|
|
9
|
+
const [errorCount, setErrorCount] = createSignal(asyncQueuer.getErrorCount());
|
|
10
|
+
const [settledCount, setSettledCount] = createSignal(
|
|
11
|
+
asyncQueuer.getSettledCount()
|
|
8
12
|
);
|
|
9
13
|
const [rejectionCount, setRejectionCount] = createSignal(
|
|
10
14
|
asyncQueuer.getRejectionCount()
|
|
@@ -16,24 +20,29 @@ function createAsyncQueuer(initialOptions = {}) {
|
|
|
16
20
|
const [allItems, setAllItems] = createSignal(
|
|
17
21
|
asyncQueuer.getAllItems()
|
|
18
22
|
);
|
|
19
|
-
const [activeItems, setActiveItems] = createSignal(
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
+
const [activeItems, setActiveItems] = createSignal(
|
|
24
|
+
asyncQueuer.getActiveItems()
|
|
25
|
+
);
|
|
26
|
+
const [pendingItems, setPendingItems] = createSignal(
|
|
27
|
+
asyncQueuer.getPendingItems()
|
|
23
28
|
);
|
|
29
|
+
const [peek, setPeek] = createSignal(asyncQueuer.getPeek());
|
|
24
30
|
const [size, setSize] = createSignal(asyncQueuer.getSize());
|
|
25
31
|
asyncQueuer.setOptions({
|
|
26
32
|
onItemsChange: (queuer) => {
|
|
27
33
|
var _a;
|
|
28
|
-
|
|
34
|
+
setActiveItems(queuer.getActiveItems());
|
|
35
|
+
setAllItems(queuer.getAllItems());
|
|
36
|
+
setErrorCount(queuer.getErrorCount());
|
|
29
37
|
setIsEmpty(queuer.getIsEmpty());
|
|
30
38
|
setIsFull(queuer.getIsFull());
|
|
31
39
|
setIsIdle(queuer.getIsIdle());
|
|
32
|
-
setAllItems(queuer.getAllItems());
|
|
33
|
-
setActiveItems(queuer.getActiveItems());
|
|
34
|
-
setPendingItems(queuer.getPendingItems());
|
|
35
40
|
setPeek(() => queuer.getPeek());
|
|
41
|
+
setPendingItems(queuer.getPendingItems());
|
|
42
|
+
setRejectionCount(queuer.getRejectionCount());
|
|
43
|
+
setSettledCount(queuer.getSettledCount());
|
|
36
44
|
setSize(queuer.getSize());
|
|
45
|
+
setSuccessCount(queuer.getSuccessCount());
|
|
37
46
|
(_a = initialOptions.onItemsChange) == null ? void 0 : _a.call(initialOptions, queuer);
|
|
38
47
|
},
|
|
39
48
|
onIsRunningChange: (queuer) => {
|
|
@@ -51,16 +60,18 @@ function createAsyncQueuer(initialOptions = {}) {
|
|
|
51
60
|
return {
|
|
52
61
|
...bindInstanceMethods(asyncQueuer),
|
|
53
62
|
activeItems,
|
|
54
|
-
|
|
63
|
+
allItems,
|
|
64
|
+
errorCount,
|
|
55
65
|
isEmpty,
|
|
56
66
|
isFull,
|
|
57
67
|
isIdle,
|
|
58
68
|
isRunning,
|
|
59
|
-
allItems,
|
|
60
69
|
peek,
|
|
61
70
|
pendingItems,
|
|
62
71
|
rejectionCount,
|
|
63
|
-
|
|
72
|
+
settledCount,
|
|
73
|
+
size,
|
|
74
|
+
successCount
|
|
64
75
|
};
|
|
65
76
|
}
|
|
66
77
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncQueuer.js","sources":["../../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type {
|
|
1
|
+
{"version":3,"file":"createAsyncQueuer.js","sources":["../../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type {\n AsyncQueuerFn,\n AsyncQueuerOptions,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TFn extends AsyncQueuerFn>\n extends Omit<\n AsyncQueuer<TFn>,\n | 'getActiveItems'\n | 'getAllItems'\n | 'getErrorCount'\n | 'getIsEmpty'\n | 'getIsFull'\n | 'getIsIdle'\n | 'getIsRunning'\n | 'getPeek'\n | 'getPendingItems'\n | 'getRejectionCount'\n | 'getSettledCount'\n | 'getSize'\n | 'getSuccessCount'\n > {\n /**\n * Signal version of `getActiveItems`\n */\n activeItems: Accessor<Array<TFn>>\n /**\n * Signal version of `getAllItems`\n */\n allItems: Accessor<Array<TFn>>\n /**\n * Signal version of `getErrorCount`\n */\n errorCount: Accessor<number>\n /**\n * Signal version of `getIsEmpty`\n */\n isEmpty: Accessor<boolean>\n /**\n * Signal version of `getIsFull`\n */\n isFull: Accessor<boolean>\n /**\n * Signal version of `getIsIdle`\n */\n isIdle: Accessor<boolean>\n /**\n * Signal version of `getIsRunning`\n */\n isRunning: Accessor<boolean>\n /**\n * Signal version of `getPeek`\n */\n peek: Accessor<TFn | undefined>\n /**\n * Signal version of `getPendingItems`\n */\n pendingItems: Accessor<Array<TFn>>\n /**\n * Signal version of `getRejectionCount`\n */\n rejectionCount: Accessor<number>\n /**\n * Signal version of `getSettledCount`\n */\n settledCount: Accessor<number>\n /**\n * Signal version of `getSize`\n */\n size: Accessor<number>\n /**\n * Signal version of `getSuccessCount`\n */\n successCount: Accessor<number>\n}\n\n/**\n * A lower-level Solid hook that creates an `AsyncQueuer` instance for managing an async queue of items.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\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\n * ```tsx\n * // Basic async queuer for API requests\n * const asyncQueuer = createAsyncQueuer({\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 */\nexport function createAsyncQueuer<TFn extends AsyncQueuerFn>(\n initialOptions: AsyncQueuerOptions<TFn> = {},\n): SolidAsyncQueuer<TFn> {\n const asyncQueuer = new AsyncQueuer<TFn>(initialOptions)\n\n const [successCount, setSuccessCount] = createSignal(\n asyncQueuer.getSuccessCount(),\n )\n const [errorCount, setErrorCount] = createSignal(asyncQueuer.getErrorCount())\n const [settledCount, setSettledCount] = createSignal(\n asyncQueuer.getSettledCount(),\n )\n const [rejectionCount, setRejectionCount] = createSignal(\n asyncQueuer.getRejectionCount(),\n )\n const [isEmpty, setIsEmpty] = createSignal(asyncQueuer.getIsEmpty())\n const [isFull, setIsFull] = createSignal(asyncQueuer.getIsFull())\n const [isIdle, setIsIdle] = createSignal(asyncQueuer.getIsIdle())\n const [isRunning, setIsRunning] = createSignal(asyncQueuer.getIsRunning())\n const [allItems, setAllItems] = createSignal<Array<TFn>>(\n asyncQueuer.getAllItems(),\n )\n const [activeItems, setActiveItems] = createSignal<Array<TFn>>(\n asyncQueuer.getActiveItems(),\n )\n const [pendingItems, setPendingItems] = createSignal<Array<TFn>>(\n asyncQueuer.getPendingItems(),\n )\n const [peek, setPeek] = createSignal<TFn | undefined>(asyncQueuer.getPeek())\n const [size, setSize] = createSignal(asyncQueuer.getSize())\n\n asyncQueuer.setOptions({\n onItemsChange: (queuer) => {\n setActiveItems(queuer.getActiveItems())\n setAllItems(queuer.getAllItems())\n setErrorCount(queuer.getErrorCount())\n setIsEmpty(queuer.getIsEmpty())\n setIsFull(queuer.getIsFull())\n setIsIdle(queuer.getIsIdle())\n setPeek(() => queuer.getPeek())\n setPendingItems(queuer.getPendingItems())\n setRejectionCount(queuer.getRejectionCount())\n setSettledCount(queuer.getSettledCount())\n setSize(queuer.getSize())\n setSuccessCount(queuer.getSuccessCount())\n initialOptions.onItemsChange?.(queuer)\n },\n onIsRunningChange: (queuer) => {\n setIsRunning(queuer.getIsRunning())\n setIsIdle(queuer.getIsIdle())\n initialOptions.onIsRunningChange?.(queuer)\n },\n onReject: (item, queuer) => {\n setRejectionCount(queuer.getRejectionCount())\n initialOptions.onReject?.(item, queuer)\n },\n })\n\n return {\n ...bindInstanceMethods(asyncQueuer),\n activeItems,\n allItems,\n errorCount,\n isEmpty,\n isFull,\n isIdle,\n isRunning,\n peek,\n pendingItems,\n rejectionCount,\n settledCount,\n size,\n successCount,\n } as SolidAsyncQueuer<TFn>\n}\n"],"names":[],"mappings":";;;AA6HgB,SAAA,kBACd,iBAA0C,IACnB;AACjB,QAAA,cAAc,IAAI,YAAiB,cAAc;AAEjD,QAAA,CAAC,cAAc,eAAe,IAAI;AAAA,IACtC,YAAY,gBAAgB;AAAA,EAC9B;AACA,QAAM,CAAC,YAAY,aAAa,IAAI,aAAa,YAAY,eAAe;AACtE,QAAA,CAAC,cAAc,eAAe,IAAI;AAAA,IACtC,YAAY,gBAAgB;AAAA,EAC9B;AACM,QAAA,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C,YAAY,kBAAkB;AAAA,EAChC;AACA,QAAM,CAAC,SAAS,UAAU,IAAI,aAAa,YAAY,YAAY;AACnE,QAAM,CAAC,QAAQ,SAAS,IAAI,aAAa,YAAY,WAAW;AAChE,QAAM,CAAC,QAAQ,SAAS,IAAI,aAAa,YAAY,WAAW;AAChE,QAAM,CAAC,WAAW,YAAY,IAAI,aAAa,YAAY,cAAc;AACnE,QAAA,CAAC,UAAU,WAAW,IAAI;AAAA,IAC9B,YAAY,YAAY;AAAA,EAC1B;AACM,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC,YAAY,eAAe;AAAA,EAC7B;AACM,QAAA,CAAC,cAAc,eAAe,IAAI;AAAA,IACtC,YAAY,gBAAgB;AAAA,EAC9B;AACA,QAAM,CAAC,MAAM,OAAO,IAAI,aAA8B,YAAY,SAAS;AAC3E,QAAM,CAAC,MAAM,OAAO,IAAI,aAAa,YAAY,SAAS;AAE1D,cAAY,WAAW;AAAA,IACrB,eAAe,CAAC,WAAW;;AACV,qBAAA,OAAO,gBAAgB;AAC1B,kBAAA,OAAO,aAAa;AAClB,oBAAA,OAAO,eAAe;AACzB,iBAAA,OAAO,YAAY;AACpB,gBAAA,OAAO,WAAW;AAClB,gBAAA,OAAO,WAAW;AACpB,cAAA,MAAM,OAAO,SAAS;AACd,sBAAA,OAAO,iBAAiB;AACtB,wBAAA,OAAO,mBAAmB;AAC5B,sBAAA,OAAO,iBAAiB;AAChC,cAAA,OAAO,SAAS;AACR,sBAAA,OAAO,iBAAiB;AACxC,2BAAe,kBAAf,wCAA+B;AAAA,IACjC;AAAA,IACA,mBAAmB,CAAC,WAAW;;AAChB,mBAAA,OAAO,cAAc;AACxB,gBAAA,OAAO,WAAW;AAC5B,2BAAe,sBAAf,wCAAmC;AAAA,IACrC;AAAA,IACA,UAAU,CAAC,MAAM,WAAW;;AACR,wBAAA,OAAO,mBAAmB;AAC7B,2BAAA,aAAA,wCAAW,MAAM;AAAA,IAAM;AAAA,EACxC,CACD;AAEM,SAAA;AAAA,IACL,GAAG,oBAAoB,WAAW;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;"}
|
|
@@ -15,13 +15,9 @@ export interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction> extends Omi
|
|
|
15
15
|
* This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
|
|
16
16
|
* you can integrate with any state management solution (createSignal, etc).
|
|
17
17
|
*
|
|
18
|
-
* Rate limiting allows
|
|
19
|
-
* then blocks subsequent calls until the window passes. This
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
|
|
23
|
-
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
24
|
-
* instead of setting the result on a state variable from within the rate-limited function.
|
|
18
|
+
* Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
|
|
19
|
+
* then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
|
|
20
|
+
* all executions happen immediately, followed by a complete block.
|
|
25
21
|
*
|
|
26
22
|
* The rate limiter supports two types of windows:
|
|
27
23
|
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
@@ -29,6 +25,25 @@ export interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction> extends Omi
|
|
|
29
25
|
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
30
26
|
* consistent rate of execution over time.
|
|
31
27
|
*
|
|
28
|
+
* Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
|
|
29
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
30
|
+
* instead of setting the result on a state variable from within the rate-limited function.
|
|
31
|
+
*
|
|
32
|
+
* For smoother execution patterns, consider using:
|
|
33
|
+
* - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
|
|
34
|
+
* - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
|
|
35
|
+
*
|
|
36
|
+
* Rate limiting is best used for hard API limits or resource constraints. For UI updates or
|
|
37
|
+
* smoothing out frequent events, throttling or debouncing usually provide better user experience.
|
|
38
|
+
*
|
|
39
|
+
* Error Handling:
|
|
40
|
+
* - If an `onError` handler is provided, it will be called with the error and rate limiter instance
|
|
41
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
42
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
43
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
44
|
+
* - The error state can be checked using the underlying AsyncRateLimiter instance
|
|
45
|
+
* - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
|
|
46
|
+
*
|
|
32
47
|
* @example
|
|
33
48
|
* ```tsx
|
|
34
49
|
* // Basic API call rate limiting with return value
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncRateLimiter.js","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type { AsyncRateLimiterOptions } from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction>\n extends Omit<\n AsyncRateLimiter<TFn>,\n | 'getSuccessCount'\n | 'getSettleCount'\n | 'getErrorCount'\n | 'getRejectionCount'\n | 'getRemainingInWindow'\n | 'getMsUntilNextWindow'\n > {\n successCount: Accessor<number>\n settleCount: Accessor<number>\n errorCount: Accessor<number>\n rejectionCount: Accessor<number>\n remainingInWindow: Accessor<number>\n msUntilNextWindow: Accessor<number>\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 allows
|
|
1
|
+
{"version":3,"file":"createAsyncRateLimiter.js","sources":["../../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type { AsyncRateLimiterOptions } from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction>\n extends Omit<\n AsyncRateLimiter<TFn>,\n | 'getSuccessCount'\n | 'getSettleCount'\n | 'getErrorCount'\n | 'getRejectionCount'\n | 'getRemainingInWindow'\n | 'getMsUntilNextWindow'\n > {\n successCount: Accessor<number>\n settleCount: Accessor<number>\n errorCount: Accessor<number>\n rejectionCount: Accessor<number>\n remainingInWindow: Accessor<number>\n msUntilNextWindow: Accessor<number>\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<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n): SolidAsyncRateLimiter<TFn> {\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(fn, initialOptions)\n\n const [successCount, setSuccessCount] = createSignal(\n asyncRateLimiter.getSuccessCount(),\n )\n const [rejectionCount, setRejectionCount] = createSignal(\n asyncRateLimiter.getRejectionCount(),\n )\n const [errorCount, setErrorCount] = createSignal(\n asyncRateLimiter.getErrorCount(),\n )\n const [settleCount, setSettleCount] = createSignal(\n asyncRateLimiter.getSettleCount(),\n )\n const [remainingInWindow, setRemainingInWindow] = createSignal(\n asyncRateLimiter.getRemainingInWindow(),\n )\n const [msUntilNextWindow, setMsUntilNextWindow] = createSignal(\n asyncRateLimiter.getMsUntilNextWindow(),\n )\n\n function setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>) {\n asyncRateLimiter.setOptions({\n ...newOptions,\n onSettled: (rateLimiter) => {\n setSuccessCount(rateLimiter.getSuccessCount())\n setSettleCount(rateLimiter.getSettleCount())\n setErrorCount(rateLimiter.getErrorCount())\n setRejectionCount(rateLimiter.getRejectionCount())\n setRemainingInWindow(rateLimiter.getRemainingInWindow())\n setMsUntilNextWindow(rateLimiter.getMsUntilNextWindow())\n\n const onSettled = newOptions.onSettled ?? initialOptions.onSettled\n onSettled?.(rateLimiter)\n },\n onReject: (rateLimiter) => {\n setRejectionCount(rateLimiter.getRejectionCount())\n setRemainingInWindow(rateLimiter.getRemainingInWindow())\n setMsUntilNextWindow(rateLimiter.getMsUntilNextWindow())\n\n const onReject = newOptions.onReject ?? initialOptions.onReject\n onReject?.(rateLimiter)\n },\n })\n }\n\n setOptions(initialOptions)\n\n return {\n ...bindInstanceMethods(asyncRateLimiter),\n errorCount,\n remainingInWindow,\n msUntilNextWindow,\n rejectionCount,\n setOptions,\n settleCount,\n successCount,\n } as SolidAsyncRateLimiter<TFn>\n}\n"],"names":[],"mappings":";;;AAuFgB,SAAA,uBACd,IACA,gBAC4B;AAC5B,QAAM,mBAAmB,IAAI,iBAAsB,IAAI,cAAc;AAE/D,QAAA,CAAC,cAAc,eAAe,IAAI;AAAA,IACtC,iBAAiB,gBAAgB;AAAA,EACnC;AACM,QAAA,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C,iBAAiB,kBAAkB;AAAA,EACrC;AACM,QAAA,CAAC,YAAY,aAAa,IAAI;AAAA,IAClC,iBAAiB,cAAc;AAAA,EACjC;AACM,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC,iBAAiB,eAAe;AAAA,EAClC;AACM,QAAA,CAAC,mBAAmB,oBAAoB,IAAI;AAAA,IAChD,iBAAiB,qBAAqB;AAAA,EACxC;AACM,QAAA,CAAC,mBAAmB,oBAAoB,IAAI;AAAA,IAChD,iBAAiB,qBAAqB;AAAA,EACxC;AAEA,WAAS,WAAW,YAAmD;AACrE,qBAAiB,WAAW;AAAA,MAC1B,GAAG;AAAA,MACH,WAAW,CAAC,gBAAgB;AACV,wBAAA,YAAY,iBAAiB;AAC9B,uBAAA,YAAY,gBAAgB;AAC7B,sBAAA,YAAY,eAAe;AACvB,0BAAA,YAAY,mBAAmB;AAC5B,6BAAA,YAAY,sBAAsB;AAClC,6BAAA,YAAY,sBAAsB;AAEjD,cAAA,YAAY,WAAW,aAAa,eAAe;AACzD,+CAAY;AAAA,MACd;AAAA,MACA,UAAU,CAAC,gBAAgB;AACP,0BAAA,YAAY,mBAAmB;AAC5B,6BAAA,YAAY,sBAAsB;AAClC,6BAAA,YAAY,sBAAsB;AAEjD,cAAA,WAAW,WAAW,YAAY,eAAe;AACvD,6CAAW;AAAA,MAAW;AAAA,IACxB,CACD;AAAA,EAAA;AAGH,aAAW,cAAc;AAElB,SAAA;AAAA,IACL,GAAG,oBAAoB,gBAAgB;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;"}
|
|
@@ -21,6 +21,17 @@ export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction> extends Omit<
|
|
|
21
21
|
* regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
|
|
22
22
|
* database operations, or other async tasks.
|
|
23
23
|
*
|
|
24
|
+
* Unlike the non-async Throttler, this async version supports returning values from the throttled function,
|
|
25
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
26
|
+
* instead of setting the result on a state variable from within the throttled function.
|
|
27
|
+
*
|
|
28
|
+
* Error Handling:
|
|
29
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
30
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
31
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
32
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
33
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
34
|
+
*
|
|
24
35
|
* @example
|
|
25
36
|
* ```tsx
|
|
26
37
|
* // Basic API call throttling
|
|
@@ -42,7 +53,10 @@ export interface SolidAsyncThrottler<TFn extends AnyAsyncFunction> extends Omit<
|
|
|
42
53
|
* {
|
|
43
54
|
* wait: 2000,
|
|
44
55
|
* leading: true, // Execute immediately on first call
|
|
45
|
-
* trailing: false
|
|
56
|
+
* trailing: false, // Skip trailing edge updates
|
|
57
|
+
* onError: (error) => {
|
|
58
|
+
* console.error('API call failed:', error);
|
|
59
|
+
* }
|
|
46
60
|
* }
|
|
47
61
|
* );
|
|
48
62
|
* ```
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncThrottler.js","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type { AsyncThrottlerOptions } from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<TFn extends AnyAsyncFunction>\n extends Omit<\n AsyncThrottler<TFn>,\n | 'getSuccessCount'\n | 'getSettleCount'\n | 'getErrorCount'\n | 'getIsPending'\n | 'getIsExecuting'\n | 'getLastResult'\n | 'getLastExecutionTime'\n | 'getNextExecutionTime'\n > {\n successCount: Accessor<number>\n settleCount: Accessor<number>\n errorCount: Accessor<number>\n isPending: Accessor<boolean>\n isExecuting: Accessor<boolean>\n lastResult: Accessor<ReturnType<TFn> | undefined>\n lastExecutionTime: Accessor<number>\n nextExecutionTime: Accessor<number>\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 * @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
|
|
1
|
+
{"version":3,"file":"createAsyncThrottler.js","sources":["../../../src/async-throttler/createAsyncThrottler.ts"],"sourcesContent":["import { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type { AsyncThrottlerOptions } from '@tanstack/pacer/async-throttler'\n\nexport interface SolidAsyncThrottler<TFn extends AnyAsyncFunction>\n extends Omit<\n AsyncThrottler<TFn>,\n | 'getSuccessCount'\n | 'getSettleCount'\n | 'getErrorCount'\n | 'getIsPending'\n | 'getIsExecuting'\n | 'getLastResult'\n | 'getLastExecutionTime'\n | 'getNextExecutionTime'\n > {\n successCount: Accessor<number>\n settleCount: Accessor<number>\n errorCount: Accessor<number>\n isPending: Accessor<boolean>\n isExecuting: Accessor<boolean>\n lastResult: Accessor<ReturnType<TFn> | undefined>\n lastExecutionTime: Accessor<number>\n nextExecutionTime: Accessor<number>\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<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n): SolidAsyncThrottler<TFn> {\n const asyncThrottler = bindInstanceMethods(\n new AsyncThrottler<TFn>(fn, initialOptions),\n )\n\n const [successCount, setSuccessCount] = createSignal(\n asyncThrottler.getSuccessCount(),\n )\n const [settleCount, setSettleCount] = createSignal(\n asyncThrottler.getSettleCount(),\n )\n const [errorCount, setErrorCount] = createSignal(\n asyncThrottler.getErrorCount(),\n )\n const [isPending, setIsPending] = createSignal(asyncThrottler.getIsPending())\n const [isExecuting, setIsExecuting] = createSignal(\n asyncThrottler.getIsExecuting(),\n )\n const [lastResult, setLastResult] = createSignal(\n asyncThrottler.getLastResult(),\n )\n const [lastExecutionTime, setLastExecutionTime] = createSignal(\n asyncThrottler.getLastExecutionTime(),\n )\n const [nextExecutionTime, setNextExecutionTime] = createSignal(\n asyncThrottler.getNextExecutionTime(),\n )\n\n function setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>) {\n asyncThrottler.setOptions({\n ...newOptions,\n onSettled: (throttler) => {\n setSuccessCount(throttler.getSuccessCount())\n setSettleCount(throttler.getSettleCount())\n setErrorCount(throttler.getErrorCount())\n setIsPending(throttler.getIsPending())\n setIsExecuting(throttler.getIsExecuting())\n setLastExecutionTime(throttler.getLastExecutionTime())\n setNextExecutionTime(throttler.getNextExecutionTime())\n setLastResult(throttler.getLastResult())\n\n const onSettled = newOptions.onSettled ?? initialOptions.onSettled\n onSettled?.(throttler)\n },\n })\n }\n\n setOptions(initialOptions)\n\n return {\n ...asyncThrottler,\n errorCount,\n isExecuting,\n isPending,\n lastExecutionTime,\n lastResult,\n nextExecutionTime,\n setOptions,\n settleCount,\n successCount,\n } as SolidAsyncThrottler<TFn>\n}\n"],"names":[],"mappings":";;;AA+EgB,SAAA,qBACd,IACA,gBAC0B;AAC1B,QAAM,iBAAiB;AAAA,IACrB,IAAI,eAAoB,IAAI,cAAc;AAAA,EAC5C;AAEM,QAAA,CAAC,cAAc,eAAe,IAAI;AAAA,IACtC,eAAe,gBAAgB;AAAA,EACjC;AACM,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC,eAAe,eAAe;AAAA,EAChC;AACM,QAAA,CAAC,YAAY,aAAa,IAAI;AAAA,IAClC,eAAe,cAAc;AAAA,EAC/B;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,aAAa,eAAe,cAAc;AACtE,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC,eAAe,eAAe;AAAA,EAChC;AACM,QAAA,CAAC,YAAY,aAAa,IAAI;AAAA,IAClC,eAAe,cAAc;AAAA,EAC/B;AACM,QAAA,CAAC,mBAAmB,oBAAoB,IAAI;AAAA,IAChD,eAAe,qBAAqB;AAAA,EACtC;AACM,QAAA,CAAC,mBAAmB,oBAAoB,IAAI;AAAA,IAChD,eAAe,qBAAqB;AAAA,EACtC;AAEA,WAAS,WAAW,YAAiD;AACnE,mBAAe,WAAW;AAAA,MACxB,GAAG;AAAA,MACH,WAAW,CAAC,cAAc;AACR,wBAAA,UAAU,iBAAiB;AAC5B,uBAAA,UAAU,gBAAgB;AAC3B,sBAAA,UAAU,eAAe;AAC1B,qBAAA,UAAU,cAAc;AACtB,uBAAA,UAAU,gBAAgB;AACpB,6BAAA,UAAU,sBAAsB;AAChC,6BAAA,UAAU,sBAAsB;AACvC,sBAAA,UAAU,eAAe;AAEjC,cAAA,YAAY,WAAW,aAAa,eAAe;AACzD,+CAAY;AAAA,MAAS;AAAA,IACvB,CACD;AAAA,EAAA;AAGH,aAAW,cAAc;AAElB,SAAA;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;"}
|
|
@@ -34,17 +34,11 @@ export interface SolidRateLimiter<TFn extends AnyFunction> extends Omit<RateLimi
|
|
|
34
34
|
* const rateLimiter = createRateLimiter(apiCall, {
|
|
35
35
|
* limit: 5,
|
|
36
36
|
* window: 60000,
|
|
37
|
-
* windowType: 'sliding'
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* // Monitor rate limit status
|
|
41
|
-
* const handleClick = () => {
|
|
42
|
-
* if (rateLimiter.remainingInWindow() > 0) {
|
|
43
|
-
* rateLimiter.maybeExecute(data);
|
|
44
|
-
* } else {
|
|
45
|
-
* showRateLimitWarning();
|
|
37
|
+
* windowType: 'sliding',
|
|
38
|
+
* onReject: (rateLimiter) => {
|
|
39
|
+
* console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
|
|
46
40
|
* }
|
|
47
|
-
* };
|
|
41
|
+
* });
|
|
48
42
|
*
|
|
49
43
|
* // Access rate limiter state via signals
|
|
50
44
|
* console.log('Executions:', rateLimiter.executionCount());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRateLimiter.js","sources":["../../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { RateLimiterOptions } from '@tanstack/pacer/rate-limiter'\n\nexport interface SolidRateLimiter<TFn extends AnyFunction>\n extends Omit<\n RateLimiter<TFn>,\n | 'getExecutionCount'\n | 'getMsUntilNextWindow'\n | 'getRejectionCount'\n | 'getRemainingInWindow'\n > {\n executionCount: Accessor<number>\n msUntilNextWindow: Accessor<number>\n rejectionCount: Accessor<number>\n remainingInWindow: Accessor<number>\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'
|
|
1
|
+
{"version":3,"file":"createRateLimiter.js","sources":["../../../src/rate-limiter/createRateLimiter.ts"],"sourcesContent":["import { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { createSignal } from 'solid-js'\nimport { bindInstanceMethods } from '@tanstack/pacer/utils'\nimport type { Accessor } from 'solid-js'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { RateLimiterOptions } from '@tanstack/pacer/rate-limiter'\n\nexport interface SolidRateLimiter<TFn extends AnyFunction>\n extends Omit<\n RateLimiter<TFn>,\n | 'getExecutionCount'\n | 'getMsUntilNextWindow'\n | 'getRejectionCount'\n | 'getRemainingInWindow'\n > {\n executionCount: Accessor<number>\n msUntilNextWindow: Accessor<number>\n rejectionCount: Accessor<number>\n remainingInWindow: Accessor<number>\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<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n): SolidRateLimiter<TFn> {\n const rateLimiter = bindInstanceMethods(\n new RateLimiter<TFn>(fn, initialOptions),\n )\n\n const [executionCount, setExecutionCount] = createSignal(\n rateLimiter.getExecutionCount(),\n )\n const [rejectionCount, setRejectionCount] = createSignal(\n rateLimiter.getRejectionCount(),\n )\n const [remainingInWindow, setRemainingInWindow] = createSignal(\n rateLimiter.getRemainingInWindow(),\n )\n const [msUntilNextWindow, setMsUntilNextWindow] = createSignal(\n rateLimiter.getMsUntilNextWindow(),\n )\n\n function setOptions(newOptions: Partial<RateLimiterOptions<TFn>>) {\n rateLimiter.setOptions({\n ...newOptions,\n onExecute: (rateLimiter) => {\n setExecutionCount(rateLimiter.getExecutionCount())\n setRemainingInWindow(rateLimiter.getRemainingInWindow())\n setMsUntilNextWindow(rateLimiter.getMsUntilNextWindow())\n\n const onExecute = newOptions.onExecute ?? initialOptions.onExecute\n onExecute?.(rateLimiter)\n },\n onReject: (rateLimiter) => {\n setRejectionCount(rateLimiter.getRejectionCount())\n setRemainingInWindow(rateLimiter.getRemainingInWindow())\n setMsUntilNextWindow(rateLimiter.getMsUntilNextWindow())\n\n const onReject = newOptions.onReject ?? initialOptions.onReject\n onReject?.(rateLimiter)\n },\n })\n }\n\n setOptions(initialOptions)\n\n return {\n ...rateLimiter,\n executionCount,\n rejectionCount,\n remainingInWindow,\n msUntilNextWindow,\n setOptions,\n } as SolidRateLimiter<TFn>\n}\n"],"names":["rateLimiter"],"mappings":";;;AA6DgB,SAAA,kBACd,IACA,gBACuB;AACvB,QAAM,cAAc;AAAA,IAClB,IAAI,YAAiB,IAAI,cAAc;AAAA,EACzC;AAEM,QAAA,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C,YAAY,kBAAkB;AAAA,EAChC;AACM,QAAA,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C,YAAY,kBAAkB;AAAA,EAChC;AACM,QAAA,CAAC,mBAAmB,oBAAoB,IAAI;AAAA,IAChD,YAAY,qBAAqB;AAAA,EACnC;AACM,QAAA,CAAC,mBAAmB,oBAAoB,IAAI;AAAA,IAChD,YAAY,qBAAqB;AAAA,EACnC;AAEA,WAAS,WAAW,YAA8C;AAChE,gBAAY,WAAW;AAAA,MACrB,GAAG;AAAA,MACH,WAAW,CAACA,iBAAgB;AACRA,0BAAAA,aAAY,mBAAmB;AAC5BA,6BAAAA,aAAY,sBAAsB;AAClCA,6BAAAA,aAAY,sBAAsB;AAEjD,cAAA,YAAY,WAAW,aAAa,eAAe;AACzD,+CAAYA;AAAAA,MACd;AAAA,MACA,UAAU,CAACA,iBAAgB;AACPA,0BAAAA,aAAY,mBAAmB;AAC5BA,6BAAAA,aAAY,sBAAsB;AAClCA,6BAAAA,aAAY,sBAAsB;AAEjD,cAAA,WAAW,WAAW,YAAY,eAAe;AACvD,6CAAWA;AAAAA,MAAW;AAAA,IACxB,CACD;AAAA,EAAA;AAGH,aAAW,cAAc;AAElB,SAAA;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/solid-pacer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Utilities for debouncing and throttling functions in Solid.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -142,7 +142,7 @@
|
|
|
142
142
|
"src"
|
|
143
143
|
],
|
|
144
144
|
"dependencies": {
|
|
145
|
-
"@tanstack/pacer": "0.
|
|
145
|
+
"@tanstack/pacer": "0.6.0"
|
|
146
146
|
},
|
|
147
147
|
"devDependencies": {
|
|
148
148
|
"solid-js": "^1.9.6",
|
|
@@ -28,8 +28,22 @@ export interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction>
|
|
|
28
28
|
* you can integrate with any state management solution (createSignal, etc).
|
|
29
29
|
*
|
|
30
30
|
* Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.
|
|
31
|
-
*
|
|
32
|
-
*
|
|
31
|
+
* Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
|
|
32
|
+
* or input changes where you only want to execute the handler after the events have stopped occurring.
|
|
33
|
+
*
|
|
34
|
+
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
|
|
35
|
+
* the function stops being called for the specified delay period.
|
|
36
|
+
*
|
|
37
|
+
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
38
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
39
|
+
* instead of setting the result on a state variable from within the debounced function.
|
|
40
|
+
*
|
|
41
|
+
* Error Handling:
|
|
42
|
+
* - If an `onError` handler is provided, it will be called with the error and debouncer instance
|
|
43
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
44
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
45
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
46
|
+
* - The error state can be checked using the underlying AsyncDebouncer instance
|
|
33
47
|
*
|
|
34
48
|
* @example
|
|
35
49
|
* ```tsx
|
|
@@ -51,11 +65,15 @@ export interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction>
|
|
|
51
65
|
* },
|
|
52
66
|
* {
|
|
53
67
|
* wait: 300,
|
|
68
|
+
* leading: true, // Execute immediately on first call
|
|
69
|
+
* trailing: false, // Skip trailing edge updates
|
|
70
|
+
* onError: (error) => {
|
|
71
|
+
* console.error('API call failed:', error);
|
|
72
|
+
* }
|
|
54
73
|
* }
|
|
55
74
|
* );
|
|
56
75
|
* ```
|
|
57
76
|
*/
|
|
58
|
-
|
|
59
77
|
export function createAsyncDebouncer<TFn extends AnyAsyncFunction>(
|
|
60
78
|
fn: TFn,
|
|
61
79
|
initialOptions: AsyncDebouncerOptions<TFn>,
|