@tanstack/solid-pacer 0.21.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher/createAsyncBatcher.d.ts +5 -10
  3. package/dist/async-batcher/createAsyncBatcher.js +2 -5
  4. package/dist/async-debouncer/createAsyncDebouncer.d.ts +8 -12
  5. package/dist/async-debouncer/createAsyncDebouncer.js +5 -7
  6. package/dist/async-queuer/createAsyncQueuer.d.ts +9 -12
  7. package/dist/async-queuer/createAsyncQueuer.js +4 -5
  8. package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +10 -13
  9. package/dist/async-rate-limiter/createAsyncRateLimiter.js +7 -8
  10. package/dist/async-throttler/createAsyncThrottler.d.ts +8 -14
  11. package/dist/async-throttler/createAsyncThrottler.js +5 -9
  12. package/dist/batcher/createBatcher.d.ts +11 -15
  13. package/dist/batcher/createBatcher.js +6 -8
  14. package/dist/debouncer/createDebouncedSignal.d.ts +2 -5
  15. package/dist/debouncer/createDebouncedSignal.js +1 -2
  16. package/dist/debouncer/createDebouncedValue.d.ts +2 -5
  17. package/dist/debouncer/createDebouncedValue.js +1 -2
  18. package/dist/debouncer/createDebouncer.d.ts +4 -7
  19. package/dist/debouncer/createDebouncer.js +1 -2
  20. package/dist/provider/PacerProvider.d.ts +6 -9
  21. package/dist/provider/PacerProvider.js +1 -2
  22. package/dist/queuer/createQueuedSignal.d.ts +2 -5
  23. package/dist/queuer/createQueuedSignal.js +1 -2
  24. package/dist/queuer/createQueuer.d.ts +4 -7
  25. package/dist/queuer/createQueuer.js +1 -2
  26. package/dist/rate-limiter/createRateLimitedSignal.d.ts +12 -14
  27. package/dist/rate-limiter/createRateLimitedSignal.js +11 -11
  28. package/dist/rate-limiter/createRateLimitedValue.d.ts +2 -5
  29. package/dist/rate-limiter/createRateLimitedValue.js +1 -2
  30. package/dist/rate-limiter/createRateLimiter.d.ts +8 -10
  31. package/dist/rate-limiter/createRateLimiter.js +5 -5
  32. package/dist/throttler/createThrottledSignal.d.ts +2 -7
  33. package/dist/throttler/createThrottledSignal.js +1 -4
  34. package/dist/throttler/createThrottledValue.d.ts +2 -7
  35. package/dist/throttler/createThrottledValue.js +1 -4
  36. package/dist/throttler/createThrottler.d.ts +4 -9
  37. package/dist/throttler/createThrottler.js +1 -4
  38. package/package.json +24 -68
  39. package/dist/async-batcher/createAsyncBatcher.cjs +0 -166
  40. package/dist/async-batcher/createAsyncBatcher.cjs.map +0 -1
  41. package/dist/async-batcher/createAsyncBatcher.d.cts +0 -178
  42. package/dist/async-batcher/createAsyncBatcher.js.map +0 -1
  43. package/dist/async-batcher/index.cjs +0 -11
  44. package/dist/async-batcher/index.d.cts +0 -3
  45. package/dist/async-debouncer/createAsyncDebouncer.cjs +0 -151
  46. package/dist/async-debouncer/createAsyncDebouncer.cjs.map +0 -1
  47. package/dist/async-debouncer/createAsyncDebouncer.d.cts +0 -164
  48. package/dist/async-debouncer/createAsyncDebouncer.js.map +0 -1
  49. package/dist/async-debouncer/index.cjs +0 -11
  50. package/dist/async-debouncer/index.d.cts +0 -3
  51. package/dist/async-queuer/createAsyncQueuer.cjs +0 -158
  52. package/dist/async-queuer/createAsyncQueuer.cjs.map +0 -1
  53. package/dist/async-queuer/createAsyncQueuer.d.cts +0 -170
  54. package/dist/async-queuer/createAsyncQueuer.js.map +0 -1
  55. package/dist/async-queuer/index.cjs +0 -11
  56. package/dist/async-queuer/index.d.cts +0 -3
  57. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +0 -193
  58. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +0 -1
  59. package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +0 -209
  60. package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +0 -1
  61. package/dist/async-rate-limiter/index.cjs +0 -11
  62. package/dist/async-rate-limiter/index.d.cts +0 -3
  63. package/dist/async-throttler/createAsyncThrottler.cjs +0 -151
  64. package/dist/async-throttler/createAsyncThrottler.cjs.map +0 -1
  65. package/dist/async-throttler/createAsyncThrottler.d.cts +0 -164
  66. package/dist/async-throttler/createAsyncThrottler.js.map +0 -1
  67. package/dist/async-throttler/index.cjs +0 -11
  68. package/dist/async-throttler/index.d.cts +0 -3
  69. package/dist/batcher/createBatcher.cjs +0 -132
  70. package/dist/batcher/createBatcher.cjs.map +0 -1
  71. package/dist/batcher/createBatcher.d.cts +0 -147
  72. package/dist/batcher/createBatcher.js.map +0 -1
  73. package/dist/batcher/index.cjs +0 -11
  74. package/dist/batcher/index.d.cts +0 -3
  75. package/dist/debouncer/createDebouncedSignal.cjs +0 -88
  76. package/dist/debouncer/createDebouncedSignal.cjs.map +0 -1
  77. package/dist/debouncer/createDebouncedSignal.d.cts +0 -80
  78. package/dist/debouncer/createDebouncedSignal.js.map +0 -1
  79. package/dist/debouncer/createDebouncedValue.cjs +0 -77
  80. package/dist/debouncer/createDebouncedValue.cjs.map +0 -1
  81. package/dist/debouncer/createDebouncedValue.d.cts +0 -71
  82. package/dist/debouncer/createDebouncedValue.js.map +0 -1
  83. package/dist/debouncer/createDebouncer.cjs +0 -129
  84. package/dist/debouncer/createDebouncer.cjs.map +0 -1
  85. package/dist/debouncer/createDebouncer.d.cts +0 -145
  86. package/dist/debouncer/createDebouncer.js.map +0 -1
  87. package/dist/debouncer/index.cjs +0 -15
  88. package/dist/debouncer/index.d.cts +0 -5
  89. package/dist/index.cjs +0 -47
  90. package/dist/index.d.cts +0 -20
  91. package/dist/provider/PacerProvider.cjs +0 -27
  92. package/dist/provider/PacerProvider.cjs.map +0 -1
  93. package/dist/provider/PacerProvider.d.cts +0 -29
  94. package/dist/provider/PacerProvider.js.map +0 -1
  95. package/dist/provider/index.cjs +0 -6
  96. package/dist/provider/index.d.cts +0 -2
  97. package/dist/queuer/createQueuedSignal.cjs +0 -129
  98. package/dist/queuer/createQueuedSignal.cjs.map +0 -1
  99. package/dist/queuer/createQueuedSignal.d.cts +0 -122
  100. package/dist/queuer/createQueuedSignal.js.map +0 -1
  101. package/dist/queuer/createQueuer.cjs +0 -133
  102. package/dist/queuer/createQueuer.cjs.map +0 -1
  103. package/dist/queuer/createQueuer.d.cts +0 -148
  104. package/dist/queuer/createQueuer.js.map +0 -1
  105. package/dist/queuer/index.cjs +0 -13
  106. package/dist/queuer/index.d.cts +0 -4
  107. package/dist/rate-limiter/createRateLimitedSignal.cjs +0 -102
  108. package/dist/rate-limiter/createRateLimitedSignal.cjs.map +0 -1
  109. package/dist/rate-limiter/createRateLimitedSignal.d.cts +0 -94
  110. package/dist/rate-limiter/createRateLimitedSignal.js.map +0 -1
  111. package/dist/rate-limiter/createRateLimitedValue.cjs +0 -102
  112. package/dist/rate-limiter/createRateLimitedValue.cjs.map +0 -1
  113. package/dist/rate-limiter/createRateLimitedValue.d.cts +0 -96
  114. package/dist/rate-limiter/createRateLimitedValue.js.map +0 -1
  115. package/dist/rate-limiter/createRateLimiter.cjs +0 -157
  116. package/dist/rate-limiter/createRateLimiter.cjs.map +0 -1
  117. package/dist/rate-limiter/createRateLimiter.d.cts +0 -174
  118. package/dist/rate-limiter/createRateLimiter.js.map +0 -1
  119. package/dist/rate-limiter/index.cjs +0 -15
  120. package/dist/rate-limiter/index.d.cts +0 -5
  121. package/dist/throttler/createThrottledSignal.cjs +0 -79
  122. package/dist/throttler/createThrottledSignal.cjs.map +0 -1
  123. package/dist/throttler/createThrottledSignal.d.cts +0 -71
  124. package/dist/throttler/createThrottledSignal.js.map +0 -1
  125. package/dist/throttler/createThrottledValue.cjs +0 -74
  126. package/dist/throttler/createThrottledValue.cjs.map +0 -1
  127. package/dist/throttler/createThrottledValue.d.cts +0 -68
  128. package/dist/throttler/createThrottledValue.js.map +0 -1
  129. package/dist/throttler/createThrottler.cjs +0 -132
  130. package/dist/throttler/createThrottler.cjs.map +0 -1
  131. package/dist/throttler/createThrottler.d.cts +0 -148
  132. package/dist/throttler/createThrottler.js.map +0 -1
  133. package/dist/throttler/index.cjs +0 -15
  134. package/dist/throttler/index.d.cts +0 -5
  135. package/dist/types/index.cjs +0 -9
  136. package/dist/types/index.d.cts +0 -1
  137. package/dist/utils/index.cjs +0 -9
  138. package/dist/utils/index.d.cts +0 -1
  139. package/src/async-batcher/createAsyncBatcher.ts +0 -234
  140. package/src/async-batcher/index.ts +0 -3
  141. package/src/async-debouncer/createAsyncDebouncer.ts +0 -225
  142. package/src/async-debouncer/index.ts +0 -4
  143. package/src/async-queuer/createAsyncQueuer.ts +0 -226
  144. package/src/async-queuer/index.ts +0 -3
  145. package/src/async-rate-limiter/createAsyncRateLimiter.ts +0 -269
  146. package/src/async-rate-limiter/index.ts +0 -4
  147. package/src/async-throttler/createAsyncThrottler.ts +0 -225
  148. package/src/async-throttler/index.ts +0 -4
  149. package/src/batcher/createBatcher.ts +0 -199
  150. package/src/batcher/index.ts +0 -3
  151. package/src/debouncer/createDebouncedSignal.ts +0 -92
  152. package/src/debouncer/createDebouncedValue.ts +0 -85
  153. package/src/debouncer/createDebouncer.ts +0 -201
  154. package/src/debouncer/index.ts +0 -6
  155. package/src/index.ts +0 -46
  156. package/src/provider/PacerProvider.tsx +0 -63
  157. package/src/provider/index.ts +0 -1
  158. package/src/queuer/createQueuedSignal.ts +0 -138
  159. package/src/queuer/createQueuer.ts +0 -199
  160. package/src/queuer/index.ts +0 -4
  161. package/src/rate-limiter/createRateLimitedSignal.ts +0 -117
  162. package/src/rate-limiter/createRateLimitedValue.ts +0 -110
  163. package/src/rate-limiter/createRateLimiter.ts +0 -226
  164. package/src/rate-limiter/index.ts +0 -5
  165. package/src/throttler/createThrottledSignal.ts +0 -81
  166. package/src/throttler/createThrottledValue.ts +0 -82
  167. package/src/throttler/createThrottler.ts +0 -204
  168. package/src/throttler/index.ts +0 -6
  169. package/src/types/index.ts +0 -1
  170. package/src/utils/index.ts +0 -1
@@ -1,269 +0,0 @@
1
- import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'
2
- import { createEffect, onCleanup } from 'solid-js'
3
- import { shallow, useSelector } from '@tanstack/solid-store'
4
- import { useDefaultPacerOptions } from '../provider/PacerProvider'
5
- import type { Store } from '@tanstack/solid-store'
6
- import type { Accessor, JSX } from 'solid-js'
7
- import type { AnyAsyncFunction } from '@tanstack/pacer/types'
8
- import type {
9
- AsyncRateLimiterOptions,
10
- AsyncRateLimiterState,
11
- } from '@tanstack/pacer/async-rate-limiter'
12
-
13
- export interface SolidAsyncRateLimiterOptions<
14
- TFn extends AnyAsyncFunction,
15
- TSelected = {},
16
- > extends AsyncRateLimiterOptions<TFn> {
17
- /**
18
- * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.
19
- * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.
20
- */
21
- onUnmount?: (rateLimiter: SolidAsyncRateLimiter<TFn, TSelected>) => void
22
- }
23
-
24
- export interface SolidAsyncRateLimiter<
25
- TFn extends AnyAsyncFunction,
26
- TSelected = {},
27
- > extends Omit<AsyncRateLimiter<TFn>, 'store'> {
28
- /**
29
- * A Solid component that allows you to subscribe to the rate limiter state.
30
- *
31
- * This is useful for tracking specific parts of the rate limiter state
32
- * deep in your component tree without needing to pass a selector to the hook.
33
- *
34
- * @example
35
- * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>
36
- * {(state) => (
37
- * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>
38
- * )}
39
- * </rateLimiter.Subscribe>
40
- */
41
- Subscribe: <TSelected>(props: {
42
- selector: (state: AsyncRateLimiterState<TFn>) => TSelected
43
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element
44
- }) => JSX.Element
45
- /**
46
- * Reactive state that will be updated when the rate limiter state changes
47
- *
48
- * Use this instead of `rateLimiter.store.state`
49
- */
50
- readonly state: Accessor<Readonly<TSelected>>
51
- /**
52
- * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
53
- * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
54
- * Although, you can make the state reactive by using the `useSelector` in your own usage.
55
- */
56
- readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>
57
- }
58
-
59
- /**
60
- * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.
61
- *
62
- * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
63
- * you can integrate with any state management solution (createSignal, etc).
64
- *
65
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
66
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
67
- * all executions happen immediately, followed by a complete block.
68
- *
69
- * The rate limiter supports two types of windows:
70
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
71
- * towards the limit, and the window resets completely after the period.
72
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
73
- * consistent rate of execution over time.
74
- *
75
- * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
76
- * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
77
- * instead of setting the result on a state variable from within the rate-limited function.
78
- *
79
- * For smoother execution patterns, consider using:
80
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
81
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
82
- *
83
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
84
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
85
- *
86
- * Error Handling:
87
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
88
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
89
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
90
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
91
- * - The error state can be checked using the underlying AsyncRateLimiter instance
92
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
93
- *
94
- * ## State Management and Selector
95
- *
96
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
97
- * in two ways:
98
- *
99
- * **1. Using `rateLimiter.Subscribe` component (Recommended for component tree subscriptions)**
100
- *
101
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
102
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
103
- * in child components.
104
- *
105
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
106
- *
107
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
108
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
109
- * state changes occur.
110
- *
111
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
112
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
113
- * updates and gives you full control over when your component tracks state changes.
114
- *
115
- * Available state properties:
116
- * - `currentWindowStart`: Timestamp when the current window started
117
- * - `executionCount`: Number of function executions that have been completed
118
- * - `hasError`: Whether the last execution resulted in an error
119
- * - `isExecuting`: Whether an async function execution is currently in progress
120
- * - `lastError`: The error from the most recent failed execution (if any)
121
- * - `lastResult`: The result from the most recent successful execution
122
- * - `nextWindowTime`: Timestamp when the next window begins
123
- * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
124
- * - `remainingInWindow`: Number of executions remaining in the current window
125
- *
126
- * ## Unmount behavior
127
- *
128
- * By default, the primitive aborts any in-flight execution when the owning component unmounts.
129
- * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
130
- * Use the `onUnmount` option to customize this.
131
- *
132
- * @example
133
- * ```tsx
134
- * // Default behavior - no reactive state subscriptions
135
- * const asyncRateLimiter = createAsyncRateLimiter(
136
- * async (id: string) => {
137
- * const data = await api.fetchData(id);
138
- * return data; // Return value is preserved
139
- * },
140
- * { limit: 5, window: 1000 } // 5 calls per second
141
- * );
142
- *
143
- * // Subscribe to state changes deep in component tree using Subscribe component
144
- * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>
145
- * {(state) => (
146
- * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>
147
- * )}
148
- * </asyncRateLimiter.Subscribe>
149
- *
150
- * // Opt-in to track execution state changes at hook level (optimized for loading indicators)
151
- * const asyncRateLimiter = createAsyncRateLimiter(
152
- * async (id: string) => {
153
- * const data = await api.fetchData(id);
154
- * return data;
155
- * },
156
- * { limit: 5, window: 1000 },
157
- * (state) => ({ isExecuting: state.isExecuting })
158
- * );
159
- *
160
- * // Opt-in to track results when available (optimized for data display)
161
- * const asyncRateLimiter = createAsyncRateLimiter(
162
- * async (id: string) => {
163
- * const data = await api.fetchData(id);
164
- * return data;
165
- * },
166
- * { limit: 5, window: 1000 },
167
- * (state) => ({
168
- * lastResult: state.lastResult,
169
- * successCount: state.successCount
170
- * })
171
- * );
172
- *
173
- * // Opt-in to track error/rejection state changes (optimized for error handling)
174
- * const asyncRateLimiter = createAsyncRateLimiter(
175
- * async (id: string) => {
176
- * const data = await api.fetchData(id);
177
- * return data;
178
- * },
179
- * {
180
- * limit: 5,
181
- * window: 1000,
182
- * onError: (error) => console.error('API call failed:', error),
183
- * onReject: (rateLimiter) => console.log('Rate limit exceeded')
184
- * },
185
- * (state) => ({
186
- * errorCount: state.errorCount,
187
- * rejectionCount: state.rejectionCount
188
- * })
189
- * );
190
- *
191
- * // Opt-in to track execution metrics changes (optimized for stats display)
192
- * const asyncRateLimiter = createAsyncRateLimiter(
193
- * async (id: string) => {
194
- * const data = await api.fetchData(id);
195
- * return data;
196
- * },
197
- * { limit: 5, window: 1000 },
198
- * (state) => ({
199
- * successCount: state.successCount,
200
- * errorCount: state.errorCount,
201
- * settleCount: state.settleCount,
202
- * rejectionCount: state.rejectionCount
203
- * })
204
- * );
205
- *
206
- * // Opt-in to track execution times changes (optimized for window calculations)
207
- * const asyncRateLimiter = createAsyncRateLimiter(
208
- * async (id: string) => {
209
- * const data = await api.fetchData(id);
210
- * return data;
211
- * },
212
- * { limit: 5, window: 1000 },
213
- * (state) => ({ executionTimes: state.executionTimes })
214
- * );
215
- *
216
- * // Access the selected state (will be empty object {} unless selector provided)
217
- * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();
218
- * ```
219
- */
220
- export function createAsyncRateLimiter<
221
- TFn extends AnyAsyncFunction,
222
- TSelected = {},
223
- >(
224
- fn: TFn,
225
- options: SolidAsyncRateLimiterOptions<TFn, TSelected>,
226
- selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>
227
- ({}) as TSelected,
228
- ): SolidAsyncRateLimiter<TFn, TSelected> {
229
- const mergedOptions = {
230
- ...useDefaultPacerOptions().asyncRateLimiter,
231
- ...options,
232
- } as SolidAsyncRateLimiterOptions<TFn, TSelected>
233
- const asyncRateLimiter = new AsyncRateLimiter<TFn>(
234
- fn,
235
- mergedOptions,
236
- ) as unknown as SolidAsyncRateLimiter<TFn, TSelected>
237
-
238
- asyncRateLimiter.Subscribe = function Subscribe<TSelected>(props: {
239
- selector: (state: AsyncRateLimiterState<TFn>) => TSelected
240
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element
241
- }) {
242
- const selected = useSelector(asyncRateLimiter.store, props.selector, {
243
- compare: shallow,
244
- })
245
-
246
- return typeof props.children === 'function'
247
- ? props.children(selected)
248
- : props.children
249
- }
250
-
251
- const state = useSelector(asyncRateLimiter.store, selector, {
252
- compare: shallow,
253
- })
254
-
255
- createEffect(() => {
256
- onCleanup(() => {
257
- if (mergedOptions.onUnmount) {
258
- mergedOptions.onUnmount(asyncRateLimiter)
259
- } else {
260
- asyncRateLimiter.abort()
261
- }
262
- })
263
- })
264
-
265
- return {
266
- ...asyncRateLimiter,
267
- state,
268
- } as SolidAsyncRateLimiter<TFn, TSelected>
269
- }
@@ -1,4 +0,0 @@
1
- // re-export everything from the core pacer package, BUT ONLY from the async-rate-limiter module
2
- export * from '@tanstack/pacer/async-rate-limiter'
3
-
4
- export * from './createAsyncRateLimiter'
@@ -1,225 +0,0 @@
1
- import { createEffect, onCleanup } from 'solid-js'
2
- import { AsyncThrottler } from '@tanstack/pacer/async-throttler'
3
- import { shallow, useSelector } from '@tanstack/solid-store'
4
- import { useDefaultPacerOptions } from '../provider/PacerProvider'
5
- import type { Store } from '@tanstack/solid-store'
6
- import type { Accessor, JSX } from 'solid-js'
7
- import type { AnyAsyncFunction } from '@tanstack/pacer/types'
8
- import type {
9
- AsyncThrottlerOptions,
10
- AsyncThrottlerState,
11
- } from '@tanstack/pacer/async-throttler'
12
-
13
- export interface SolidAsyncThrottlerOptions<
14
- TFn extends AnyAsyncFunction,
15
- TSelected = {},
16
- > extends AsyncThrottlerOptions<TFn> {
17
- /**
18
- * Optional callback invoked when the owning component unmounts. Receives the throttler instance.
19
- * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
20
- */
21
- onUnmount?: (throttler: SolidAsyncThrottler<TFn, TSelected>) => void
22
- }
23
-
24
- export interface SolidAsyncThrottler<
25
- TFn extends AnyAsyncFunction,
26
- TSelected = {},
27
- > extends Omit<AsyncThrottler<TFn>, 'store'> {
28
- /**
29
- * A Solid component that allows you to subscribe to the throttler state.
30
- *
31
- * This is useful for tracking specific parts of the throttler state
32
- * deep in your component tree without needing to pass a selector to the hook.
33
- *
34
- * @example
35
- * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>
36
- * {(state) => (
37
- * <div>{state().isPending ? 'Pending...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>
38
- * )}
39
- * </throttler.Subscribe>
40
- */
41
- Subscribe: <TSelected>(props: {
42
- selector: (state: AsyncThrottlerState<TFn>) => TSelected
43
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element
44
- }) => JSX.Element
45
- /**
46
- * Reactive state that will be updated when the throttler state changes
47
- *
48
- * Use this instead of `throttler.store.state`
49
- */
50
- readonly state: Accessor<Readonly<TSelected>>
51
- /**
52
- * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
53
- * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
54
- * Although, you can make the state reactive by using the `useSelector` in your own usage.
55
- */
56
- readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>
57
- }
58
-
59
- /**
60
- * A low-level Solid hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
61
- *
62
- * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
63
- * you can integrate with any state management solution (createSignal, etc).
64
- *
65
- * Async throttling ensures an async function executes at most once within a specified time window,
66
- * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
67
- * database operations, or other async tasks.
68
- *
69
- * Unlike the non-async Throttler, this async version supports returning values from the throttled function,
70
- * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
71
- * instead of setting the result on a state variable from within the throttled function.
72
- *
73
- * Error Handling:
74
- * - If an `onError` handler is provided, it will be called with the error and throttler instance
75
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
76
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
77
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
78
- * - The error state can be checked using the underlying AsyncThrottler instance
79
- *
80
- * ## State Management and Selector
81
- *
82
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
83
- * in two ways:
84
- *
85
- * **1. Using `throttler.Subscribe` component (Recommended for component tree subscriptions)**
86
- *
87
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
88
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
89
- * in child components.
90
- *
91
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
92
- *
93
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
94
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
95
- * state changes occur.
96
- *
97
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
98
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
99
- * updates and gives you full control over when your component tracks state changes.
100
- *
101
- * Available state properties:
102
- * - `canLeadingExecute`: Whether the throttler can execute on the leading edge
103
- * - `canTrailingExecute`: Whether the throttler can execute on the trailing edge
104
- * - `executionCount`: Number of function executions that have been completed
105
- * - `hasError`: Whether the last execution resulted in an error
106
- * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
107
- * - `isExecuting`: Whether an async function execution is currently in progress
108
- * - `lastArgs`: The arguments from the most recent call to maybeExecute
109
- * - `lastError`: The error from the most recent failed execution (if any)
110
- * - `lastExecutionTime`: Timestamp of the last execution
111
- * - `lastResult`: The result from the most recent successful execution
112
- * - `nextExecutionTime`: Timestamp of the next allowed execution
113
- * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
114
- *
115
- * ## Unmount behavior
116
- *
117
- * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
118
- * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
119
- * Use the `onUnmount` option to customize this. For example, to flush pending work instead:
120
- *
121
- * ```tsx
122
- * const throttler = createAsyncThrottler(fn, {
123
- * wait: 1000,
124
- * onUnmount: (t) => t.flush()
125
- * });
126
- * ```
127
- *
128
- * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
129
- * If your throttled function updates Solid signals, those updates may run after the component has
130
- * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
131
- * using onUnmount with flush.
132
- *
133
- * @example
134
- * ```tsx
135
- * // Default behavior - no reactive state subscriptions
136
- * const { maybeExecute } = createAsyncThrottler(
137
- * async (id: string) => {
138
- * const data = await api.fetchData(id);
139
- * return data;
140
- * },
141
- * { wait: 1000 }
142
- * );
143
- *
144
- * // Opt-in to track isPending or isExecuting changes (optimized for loading states)
145
- * const throttler = createAsyncThrottler(
146
- * async (query) => {
147
- * const result = await searchAPI(query);
148
- * return result;
149
- * },
150
- * { wait: 2000 },
151
- * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })
152
- * );
153
- *
154
- * // Opt-in to track error state changes (optimized for error handling)
155
- * const throttler = createAsyncThrottler(
156
- * async (query) => {
157
- * const result = await searchAPI(query);
158
- * return result;
159
- * },
160
- * {
161
- * wait: 2000,
162
- * leading: true, // Execute immediately on first call
163
- * trailing: false, // Skip trailing edge updates
164
- * onError: (error) => {
165
- * console.error('API call failed:', error);
166
- * }
167
- * },
168
- * (state) => ({ hasError: state.hasError, lastError: state.lastError })
169
- * );
170
- *
171
- * // Access the selected state (will be empty object {} unless selector provided)
172
- * const { isPending, isExecuting } = throttler.state();
173
- * ```
174
- */
175
- export function createAsyncThrottler<
176
- TFn extends AnyAsyncFunction,
177
- TSelected = {},
178
- >(
179
- fn: TFn,
180
- options: SolidAsyncThrottlerOptions<TFn, TSelected>,
181
- selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>
182
- ({}) as TSelected,
183
- ): SolidAsyncThrottler<TFn, TSelected> {
184
- const mergedOptions = {
185
- ...useDefaultPacerOptions().asyncThrottler,
186
- ...options,
187
- } as SolidAsyncThrottlerOptions<TFn, TSelected>
188
- const asyncThrottler = new AsyncThrottler(
189
- fn,
190
- mergedOptions,
191
- ) as unknown as SolidAsyncThrottler<TFn, TSelected>
192
-
193
- asyncThrottler.Subscribe = function Subscribe<TSelected>(props: {
194
- selector: (state: AsyncThrottlerState<TFn>) => TSelected
195
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element
196
- }) {
197
- const selected = useSelector(asyncThrottler.store, props.selector, {
198
- compare: shallow,
199
- })
200
-
201
- return typeof props.children === 'function'
202
- ? props.children(selected)
203
- : props.children
204
- }
205
-
206
- const state = useSelector(asyncThrottler.store, selector, {
207
- compare: shallow,
208
- })
209
-
210
- createEffect(() => {
211
- onCleanup(() => {
212
- if (mergedOptions.onUnmount) {
213
- mergedOptions.onUnmount(asyncThrottler)
214
- } else {
215
- asyncThrottler.cancel()
216
- asyncThrottler.abort()
217
- }
218
- })
219
- })
220
-
221
- return {
222
- ...asyncThrottler,
223
- state,
224
- } as SolidAsyncThrottler<TFn, TSelected>
225
- }
@@ -1,4 +0,0 @@
1
- // re-export everything from the core pacer package, BUT ONLY from the async-throttler module
2
- export * from '@tanstack/pacer/async-throttler'
3
-
4
- export * from './createAsyncThrottler'