@depup/reduxjs__toolkit 2.12.0-depup.28

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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/changes.json +18 -0
  4. package/dist/cjs/index.js +6 -0
  5. package/dist/cjs/redux-toolkit.development.cjs +2406 -0
  6. package/dist/cjs/redux-toolkit.development.cjs.map +1 -0
  7. package/dist/cjs/redux-toolkit.production.min.cjs +3 -0
  8. package/dist/cjs/redux-toolkit.production.min.cjs.map +1 -0
  9. package/dist/index.d.mts +2665 -0
  10. package/dist/index.d.ts +2665 -0
  11. package/dist/query/cjs/index.js +6 -0
  12. package/dist/query/cjs/rtk-query.development.cjs +3092 -0
  13. package/dist/query/cjs/rtk-query.development.cjs.map +1 -0
  14. package/dist/query/cjs/rtk-query.production.min.cjs +2 -0
  15. package/dist/query/cjs/rtk-query.production.min.cjs.map +1 -0
  16. package/dist/query/index.d.mts +3066 -0
  17. package/dist/query/index.d.ts +3066 -0
  18. package/dist/query/react/cjs/index.js +6 -0
  19. package/dist/query/react/cjs/rtk-query-react.development.cjs +748 -0
  20. package/dist/query/react/cjs/rtk-query-react.development.cjs.map +1 -0
  21. package/dist/query/react/cjs/rtk-query-react.production.min.cjs +2 -0
  22. package/dist/query/react/cjs/rtk-query-react.production.min.cjs.map +1 -0
  23. package/dist/query/react/index.d.mts +1009 -0
  24. package/dist/query/react/index.d.ts +1009 -0
  25. package/dist/query/react/rtk-query-react.browser.mjs +2 -0
  26. package/dist/query/react/rtk-query-react.browser.mjs.map +1 -0
  27. package/dist/query/react/rtk-query-react.legacy-esm.js +740 -0
  28. package/dist/query/react/rtk-query-react.legacy-esm.js.map +1 -0
  29. package/dist/query/react/rtk-query-react.modern.mjs +705 -0
  30. package/dist/query/react/rtk-query-react.modern.mjs.map +1 -0
  31. package/dist/query/rtk-query.browser.mjs +2 -0
  32. package/dist/query/rtk-query.browser.mjs.map +1 -0
  33. package/dist/query/rtk-query.legacy-esm.js +3117 -0
  34. package/dist/query/rtk-query.legacy-esm.js.map +1 -0
  35. package/dist/query/rtk-query.modern.mjs +3052 -0
  36. package/dist/query/rtk-query.modern.mjs.map +1 -0
  37. package/dist/react/cjs/index.js +6 -0
  38. package/dist/react/cjs/redux-toolkit-react.development.cjs +55 -0
  39. package/dist/react/cjs/redux-toolkit-react.development.cjs.map +1 -0
  40. package/dist/react/cjs/redux-toolkit-react.production.min.cjs +2 -0
  41. package/dist/react/cjs/redux-toolkit-react.production.min.cjs.map +1 -0
  42. package/dist/react/index.d.mts +22 -0
  43. package/dist/react/index.d.ts +22 -0
  44. package/dist/react/redux-toolkit-react.browser.mjs +2 -0
  45. package/dist/react/redux-toolkit-react.browser.mjs.map +1 -0
  46. package/dist/react/redux-toolkit-react.legacy-esm.js +47 -0
  47. package/dist/react/redux-toolkit-react.legacy-esm.js.map +1 -0
  48. package/dist/react/redux-toolkit-react.modern.mjs +28 -0
  49. package/dist/react/redux-toolkit-react.modern.mjs.map +1 -0
  50. package/dist/redux-toolkit.browser.mjs +3 -0
  51. package/dist/redux-toolkit.browser.mjs.map +1 -0
  52. package/dist/redux-toolkit.legacy-esm.js +2351 -0
  53. package/dist/redux-toolkit.legacy-esm.js.map +1 -0
  54. package/dist/redux-toolkit.modern.mjs +2330 -0
  55. package/dist/redux-toolkit.modern.mjs.map +1 -0
  56. package/dist/uncheckedindexed.ts +16 -0
  57. package/package.json +310 -0
  58. package/query/package.json +13 -0
  59. package/query/react/package.json +13 -0
  60. package/react/package.json +13 -0
  61. package/skills/build-modern-redux-apps/modern-redux/SKILL.md +304 -0
  62. package/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +53 -0
  63. package/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +264 -0
  64. package/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +269 -0
  65. package/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +226 -0
  66. package/skills/manage-server-data/adopt-rtk-query/SKILL.md +385 -0
  67. package/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md +36 -0
  68. package/skills/model-redux-state/build-slices-and-selectors/SKILL.md +364 -0
  69. package/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md +59 -0
  70. package/skills/model-redux-state/design-state-ownership/SKILL.md +322 -0
  71. package/skills/model-redux-state/design-state-ownership/references/state-ownership.md +28 -0
  72. package/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +271 -0
  73. package/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +34 -0
  74. package/src/actionCreatorInvariantMiddleware.ts +34 -0
  75. package/src/autoBatchEnhancer.ts +146 -0
  76. package/src/combineSlices.ts +487 -0
  77. package/src/configureStore.ts +248 -0
  78. package/src/createAction.ts +324 -0
  79. package/src/createAsyncThunk.ts +791 -0
  80. package/src/createDraftSafeSelector.ts +30 -0
  81. package/src/createReducer.ts +217 -0
  82. package/src/createSlice.ts +1079 -0
  83. package/src/devtoolsExtension.ts +241 -0
  84. package/src/dynamicMiddleware/index.ts +93 -0
  85. package/src/dynamicMiddleware/react/index.ts +101 -0
  86. package/src/dynamicMiddleware/types.ts +82 -0
  87. package/src/entities/create_adapter.ts +47 -0
  88. package/src/entities/entity_state.ts +38 -0
  89. package/src/entities/index.ts +8 -0
  90. package/src/entities/models.ts +198 -0
  91. package/src/entities/sorted_state_adapter.ts +266 -0
  92. package/src/entities/state_adapter.ts +58 -0
  93. package/src/entities/state_selectors.ts +73 -0
  94. package/src/entities/unsorted_state_adapter.ts +204 -0
  95. package/src/entities/utils.ts +68 -0
  96. package/src/formatProdErrorMessage.ts +13 -0
  97. package/src/getDefaultEnhancers.ts +31 -0
  98. package/src/getDefaultMiddleware.ts +113 -0
  99. package/src/immerImports.ts +7 -0
  100. package/src/immutableStateInvariantMiddleware.ts +274 -0
  101. package/src/index.ts +213 -0
  102. package/src/listenerMiddleware/exceptions.ts +20 -0
  103. package/src/listenerMiddleware/index.ts +562 -0
  104. package/src/listenerMiddleware/task.ts +100 -0
  105. package/src/listenerMiddleware/types.ts +886 -0
  106. package/src/listenerMiddleware/utils.ts +30 -0
  107. package/src/mapBuilders.ts +298 -0
  108. package/src/matchers.ts +365 -0
  109. package/src/nanoid.ts +20 -0
  110. package/src/query/HandledError.ts +6 -0
  111. package/src/query/apiTypes.ts +120 -0
  112. package/src/query/baseQueryTypes.ts +101 -0
  113. package/src/query/core/apiState.ts +377 -0
  114. package/src/query/core/buildInitiate.ts +596 -0
  115. package/src/query/core/buildMiddleware/batchActions.ts +207 -0
  116. package/src/query/core/buildMiddleware/cacheCollection.ts +204 -0
  117. package/src/query/core/buildMiddleware/cacheLifecycle.ts +379 -0
  118. package/src/query/core/buildMiddleware/devMiddleware.ts +34 -0
  119. package/src/query/core/buildMiddleware/index.ts +162 -0
  120. package/src/query/core/buildMiddleware/invalidationByTags.ts +139 -0
  121. package/src/query/core/buildMiddleware/polling.ts +187 -0
  122. package/src/query/core/buildMiddleware/queryLifecycle.ts +508 -0
  123. package/src/query/core/buildMiddleware/types.ts +173 -0
  124. package/src/query/core/buildMiddleware/windowEventHandling.ts +64 -0
  125. package/src/query/core/buildSelectors.ts +413 -0
  126. package/src/query/core/buildSlice.ts +735 -0
  127. package/src/query/core/buildThunks.ts +1124 -0
  128. package/src/query/core/index.ts +58 -0
  129. package/src/query/core/module.ts +727 -0
  130. package/src/query/core/rtkImports.ts +24 -0
  131. package/src/query/core/setupListeners.ts +118 -0
  132. package/src/query/createApi.ts +506 -0
  133. package/src/query/defaultSerializeQueryArgs.ts +52 -0
  134. package/src/query/endpointDefinitions.ts +1717 -0
  135. package/src/query/fakeBaseQuery.ts +21 -0
  136. package/src/query/fetchBaseQuery.ts +385 -0
  137. package/src/query/index.ts +105 -0
  138. package/src/query/react/ApiProvider.tsx +69 -0
  139. package/src/query/react/buildHooks.ts +2297 -0
  140. package/src/query/react/constants.ts +2 -0
  141. package/src/query/react/index.ts +45 -0
  142. package/src/query/react/module.ts +275 -0
  143. package/src/query/react/namedHooks.ts +59 -0
  144. package/src/query/react/reactImports.ts +10 -0
  145. package/src/query/react/reactReduxImports.ts +1 -0
  146. package/src/query/react/rtkqImports.ts +8 -0
  147. package/src/query/react/useSerializedStableValue.ts +17 -0
  148. package/src/query/react/useShallowStableValue.ts +13 -0
  149. package/src/query/retry.ts +233 -0
  150. package/src/query/standardSchema.ts +35 -0
  151. package/src/query/tsHelpers.ts +48 -0
  152. package/src/query/utils/capitalize.ts +3 -0
  153. package/src/query/utils/copyWithStructuralSharing.ts +27 -0
  154. package/src/query/utils/countObjectKeys.ts +14 -0
  155. package/src/query/utils/filterMap.ts +27 -0
  156. package/src/query/utils/getCurrent.ts +6 -0
  157. package/src/query/utils/getOrInsert.ts +41 -0
  158. package/src/query/utils/immerImports.ts +9 -0
  159. package/src/query/utils/index.ts +11 -0
  160. package/src/query/utils/isAbsoluteUrl.ts +9 -0
  161. package/src/query/utils/isDocumentVisible.ts +12 -0
  162. package/src/query/utils/isNotNullish.ts +7 -0
  163. package/src/query/utils/isOnline.ts +12 -0
  164. package/src/query/utils/isValidUrl.ts +9 -0
  165. package/src/query/utils/joinUrls.ts +26 -0
  166. package/src/query/utils/signals.ts +33 -0
  167. package/src/react/index.ts +7 -0
  168. package/src/reduxImports.ts +8 -0
  169. package/src/reselectImports.ts +1 -0
  170. package/src/serializableStateInvariantMiddleware.ts +285 -0
  171. package/src/tsHelpers.ts +214 -0
  172. package/src/uncheckedindexed.ts +16 -0
  173. package/src/utils.ts +125 -0
@@ -0,0 +1,2665 @@
1
+ import { ActionCreator, Action, Middleware, StoreEnhancer, UnknownAction, Reducer, ReducersMapObject, Store, Dispatch, StateFromReducersMapObject, PreloadedStateShapeFromReducersMapObject, MiddlewareAPI } from 'redux';
2
+ export * from 'redux';
3
+ import { Draft } from 'immer';
4
+ export { Draft, WritableDraft, produce as createNextState, current, freeze, isDraft, original } from 'immer';
5
+ import * as reselect from 'reselect';
6
+ import { weakMapMemoize, createSelectorCreator, Selector, CreateSelectorFunction } from 'reselect';
7
+ export { OutputSelector, Selector, createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from 'reselect';
8
+ import { ThunkMiddleware, ThunkDispatch } from 'redux-thunk';
9
+ export { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';
10
+ import { UncheckedIndexedAccess } from './uncheckedindexed.js';
11
+
12
+ declare const createDraftSafeSelectorCreator: typeof createSelectorCreator;
13
+ /**
14
+ * "Draft-Safe" version of `reselect`'s `createSelector`:
15
+ * If an `immer`-drafted object is passed into the resulting selector's first argument,
16
+ * the selector will act on the current draft value, instead of returning a cached value
17
+ * that might be possibly outdated if the draft has been modified since.
18
+ * @public
19
+ */
20
+ declare const createDraftSafeSelector: reselect.CreateSelectorFunction<typeof weakMapMemoize, typeof weakMapMemoize, any>;
21
+
22
+ /**
23
+ * @public
24
+ */
25
+ interface DevToolsEnhancerOptions {
26
+ /**
27
+ * the instance name to be showed on the monitor page. Default value is `document.title`.
28
+ * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
29
+ */
30
+ name?: string;
31
+ /**
32
+ * action creators functions to be available in the Dispatcher.
33
+ */
34
+ actionCreators?: ActionCreator<any>[] | {
35
+ [key: string]: ActionCreator<any>;
36
+ };
37
+ /**
38
+ * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
39
+ * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
40
+ * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
41
+ *
42
+ * @default 500 ms.
43
+ */
44
+ latency?: number;
45
+ /**
46
+ * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
47
+ *
48
+ * @default 50
49
+ */
50
+ maxAge?: number;
51
+ /**
52
+ * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
53
+ * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
54
+ * functions.
55
+ */
56
+ serialize?: boolean | {
57
+ /**
58
+ * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
59
+ * - `false` - will handle also circular references.
60
+ * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
61
+ * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
62
+ * For each of them you can indicate if to include (by setting as `true`).
63
+ * For `function` key you can also specify a custom function which handles serialization.
64
+ * See [`jsan`](https://github.com/kolodny/jsan) for more details.
65
+ */
66
+ options?: undefined | boolean | {
67
+ date?: true;
68
+ regex?: true;
69
+ undefined?: true;
70
+ error?: true;
71
+ symbol?: true;
72
+ map?: true;
73
+ set?: true;
74
+ function?: true | ((fn: (...args: any[]) => any) => string);
75
+ };
76
+ /**
77
+ * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
78
+ * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
79
+ * key. So you can deserialize it back while importing or persisting data.
80
+ * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
81
+ */
82
+ replacer?: (key: string, value: unknown) => any;
83
+ /**
84
+ * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
85
+ * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
86
+ * as an example on how to serialize special data types and get them back.
87
+ */
88
+ reviver?: (key: string, value: unknown) => any;
89
+ /**
90
+ * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
91
+ * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
92
+ * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
93
+ */
94
+ immutable?: any;
95
+ /**
96
+ * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
97
+ */
98
+ refs?: any;
99
+ };
100
+ /**
101
+ * function which takes `action` object and id number as arguments, and should return `action` object back.
102
+ */
103
+ actionSanitizer?: <A extends Action>(action: A, id: number) => A;
104
+ /**
105
+ * function which takes `state` object and index as arguments, and should return `state` object back.
106
+ */
107
+ stateSanitizer?: <S>(state: S, index: number) => S;
108
+ /**
109
+ * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
110
+ * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
111
+ */
112
+ actionsDenylist?: string | string[];
113
+ /**
114
+ * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
115
+ * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
116
+ */
117
+ actionsAllowlist?: string | string[];
118
+ /**
119
+ * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
120
+ * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
121
+ */
122
+ predicate?: <S, A extends Action>(state: S, action: A) => boolean;
123
+ /**
124
+ * if specified as `false`, it will not record the changes till clicking on `Start recording` button.
125
+ * Available only for Redux enhancer, for others use `autoPause`.
126
+ *
127
+ * @default true
128
+ */
129
+ shouldRecordChanges?: boolean;
130
+ /**
131
+ * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
132
+ * If not specified, will commit when paused. Available only for Redux enhancer.
133
+ *
134
+ * @default "@@PAUSED""
135
+ */
136
+ pauseActionType?: string;
137
+ /**
138
+ * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
139
+ * Not available for Redux enhancer (as it already does it but storing the data to be sent).
140
+ *
141
+ * @default false
142
+ */
143
+ autoPause?: boolean;
144
+ /**
145
+ * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
146
+ * Available only for Redux enhancer.
147
+ *
148
+ * @default false
149
+ */
150
+ shouldStartLocked?: boolean;
151
+ /**
152
+ * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
153
+ *
154
+ * @default true
155
+ */
156
+ shouldHotReload?: boolean;
157
+ /**
158
+ * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
159
+ *
160
+ * @default false
161
+ */
162
+ shouldCatchErrors?: boolean;
163
+ /**
164
+ * If you want to restrict the extension, specify the features you allow.
165
+ * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
166
+ * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
167
+ * Otherwise, you'll get/set the data right from the monitor part.
168
+ */
169
+ features?: {
170
+ /**
171
+ * start/pause recording of dispatched actions
172
+ */
173
+ pause?: boolean;
174
+ /**
175
+ * lock/unlock dispatching actions and side effects
176
+ */
177
+ lock?: boolean;
178
+ /**
179
+ * persist states on page reloading
180
+ */
181
+ persist?: boolean;
182
+ /**
183
+ * export history of actions in a file
184
+ */
185
+ export?: boolean | 'custom';
186
+ /**
187
+ * import history of actions from a file
188
+ */
189
+ import?: boolean | 'custom';
190
+ /**
191
+ * jump back and forth (time traveling)
192
+ */
193
+ jump?: boolean;
194
+ /**
195
+ * skip (cancel) actions
196
+ */
197
+ skip?: boolean;
198
+ /**
199
+ * drag and drop actions in the history list
200
+ */
201
+ reorder?: boolean;
202
+ /**
203
+ * dispatch custom actions or action creators
204
+ */
205
+ dispatch?: boolean;
206
+ /**
207
+ * generate tests for the selected actions
208
+ */
209
+ test?: boolean;
210
+ };
211
+ /**
212
+ * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
213
+ * Defaults to false.
214
+ */
215
+ trace?: boolean | (<A extends Action>(action: A) => string);
216
+ /**
217
+ * The maximum number of stack trace entries to record per action. Defaults to 10.
218
+ */
219
+ traceLimit?: number;
220
+ }
221
+
222
+ interface ActionCreatorInvariantMiddlewareOptions {
223
+ /**
224
+ * The function to identify whether a value is an action creator.
225
+ * The default checks for a function with a static type property and match method.
226
+ */
227
+ isActionCreator?: (action: unknown) => action is Function & {
228
+ type?: unknown;
229
+ };
230
+ }
231
+ declare function createActionCreatorInvariantMiddleware(options?: ActionCreatorInvariantMiddlewareOptions): Middleware;
232
+
233
+ /**
234
+ * Returns true if the passed value is "plain", i.e. a value that is either
235
+ * directly JSON-serializable (boolean, number, string, array, plain object)
236
+ * or `undefined`.
237
+ *
238
+ * @param val The value to check.
239
+ *
240
+ * @public
241
+ */
242
+ declare function isPlain(val: any): boolean;
243
+ interface NonSerializableValue {
244
+ keyPath: string;
245
+ value: unknown;
246
+ }
247
+ type IgnoredPaths = readonly (string | RegExp)[];
248
+ /**
249
+ * @public
250
+ */
251
+ declare function findNonSerializableValue(value: unknown, path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], ignoredPaths?: IgnoredPaths, cache?: WeakSet<object>): NonSerializableValue | false;
252
+ /**
253
+ * Options for `createSerializableStateInvariantMiddleware()`.
254
+ *
255
+ * @public
256
+ */
257
+ interface SerializableStateInvariantMiddlewareOptions {
258
+ /**
259
+ * The function to check if a value is considered serializable. This
260
+ * function is applied recursively to every value contained in the
261
+ * state. Defaults to `isPlain()`.
262
+ */
263
+ isSerializable?: (value: any) => boolean;
264
+ /**
265
+ * The function that will be used to retrieve entries from each
266
+ * value. If unspecified, `Object.entries` will be used. Defaults
267
+ * to `undefined`.
268
+ */
269
+ getEntries?: (value: any) => [string, any][];
270
+ /**
271
+ * An array of action types to ignore when checking for serializability.
272
+ * Defaults to []
273
+ */
274
+ ignoredActions?: string[];
275
+ /**
276
+ * An array of dot-separated path strings or regular expressions to ignore
277
+ * when checking for serializability, Defaults to
278
+ * ['meta.arg', 'meta.baseQueryMeta']
279
+ */
280
+ ignoredActionPaths?: (string | RegExp)[];
281
+ /**
282
+ * An array of dot-separated path strings or regular expressions to ignore
283
+ * when checking for serializability, Defaults to []
284
+ */
285
+ ignoredPaths?: (string | RegExp)[];
286
+ /**
287
+ * Execution time warning threshold. If the middleware takes longer
288
+ * than `warnAfter` ms, a warning will be displayed in the console.
289
+ * Defaults to 32ms.
290
+ */
291
+ warnAfter?: number;
292
+ /**
293
+ * Opt out of checking state. When set to `true`, other state-related params will be ignored.
294
+ */
295
+ ignoreState?: boolean;
296
+ /**
297
+ * Opt out of checking actions. When set to `true`, other action-related params will be ignored.
298
+ */
299
+ ignoreActions?: boolean;
300
+ /**
301
+ * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.
302
+ * The cache is automatically disabled if no browser support for WeakSet is present.
303
+ */
304
+ disableCache?: boolean;
305
+ }
306
+ /**
307
+ * Creates a middleware that, after every state change, checks if the new
308
+ * state is serializable. If a non-serializable value is found within the
309
+ * state, an error is printed to the console.
310
+ *
311
+ * @param options Middleware options.
312
+ *
313
+ * @public
314
+ */
315
+ declare function createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware;
316
+
317
+ /**
318
+ * The default `isImmutable` function.
319
+ *
320
+ * @public
321
+ */
322
+ declare function isImmutableDefault(value: unknown): boolean;
323
+ type IsImmutableFunc = (value: any) => boolean;
324
+ /**
325
+ * Options for `createImmutableStateInvariantMiddleware()`.
326
+ *
327
+ * @public
328
+ */
329
+ interface ImmutableStateInvariantMiddlewareOptions {
330
+ /**
331
+ Callback function to check if a value is considered to be immutable.
332
+ This function is applied recursively to every value contained in the state.
333
+ The default implementation will return true for primitive types
334
+ (like numbers, strings, booleans, null and undefined).
335
+ */
336
+ isImmutable?: IsImmutableFunc;
337
+ /**
338
+ An array of dot-separated path strings that match named nodes from
339
+ the root state to ignore when checking for immutability.
340
+ Defaults to undefined
341
+ */
342
+ ignoredPaths?: IgnoredPaths;
343
+ /** Print a warning if checks take longer than N ms. Default: 32ms */
344
+ warnAfter?: number;
345
+ }
346
+ /**
347
+ * Creates a middleware that checks whether any state was mutated in between
348
+ * dispatches or during a dispatch. If any mutations are detected, an error is
349
+ * thrown.
350
+ *
351
+ * @param options Middleware options.
352
+ *
353
+ * @public
354
+ */
355
+ declare function createImmutableStateInvariantMiddleware(options?: ImmutableStateInvariantMiddlewareOptions): Middleware;
356
+
357
+ declare class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {
358
+ constructor(length: number);
359
+ constructor(...items: Items);
360
+ static get [Symbol.species](): any;
361
+ concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;
362
+ concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
363
+ concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
364
+ prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;
365
+ prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
366
+ prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
367
+ }
368
+
369
+ /**
370
+ * return True if T is `any`, otherwise return False
371
+ * taken from https://github.com/joonhocho/tsdef
372
+ *
373
+ * @internal
374
+ */
375
+ type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
376
+ type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
377
+ /**
378
+ * return True if T is `unknown`, otherwise return False
379
+ * taken from https://github.com/joonhocho/tsdef
380
+ *
381
+ * @internal
382
+ */
383
+ type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;
384
+ type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;
385
+ /**
386
+ * @internal
387
+ */
388
+ type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;
389
+ /**
390
+ * @internal
391
+ */
392
+ type IfVoid<P, True, False> = [void] extends [P] ? True : False;
393
+ /**
394
+ * @internal
395
+ */
396
+ type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;
397
+ /**
398
+ * returns True if TS version is above 3.5, False if below.
399
+ * uses feature detection to detect TS version >= 3.5
400
+ * * versions below 3.5 will return `{}` for unresolvable interference
401
+ * * versions above will return `unknown`
402
+ *
403
+ * @internal
404
+ */
405
+ type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<(<T>() => T)>, 0, 1>];
406
+ /**
407
+ * @internal
408
+ */
409
+ type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;
410
+ /**
411
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
412
+ */
413
+ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
414
+ type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
415
+ infer Head,
416
+ ...infer Tail
417
+ ] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;
418
+ type ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;
419
+ type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;
420
+ type ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;
421
+ type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;
422
+ type ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;
423
+ type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;
424
+ type NonUndefined<T> = T extends undefined ? never : T;
425
+ type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
426
+ type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
427
+ interface TypeGuard<T> {
428
+ (value: any): value is T;
429
+ }
430
+ interface HasMatchFunction<T> {
431
+ match: TypeGuard<T>;
432
+ }
433
+ /** @public */
434
+ type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;
435
+ /** @public */
436
+ type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;
437
+ type Id<T> = {
438
+ [K in keyof T]: T[K];
439
+ } & {};
440
+ type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;
441
+ type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;
442
+ /**
443
+ * A Promise that will never reject.
444
+ * @see https://github.com/reduxjs/redux-toolkit/issues/4101
445
+ */
446
+ type SafePromise<T> = Promise<T> & {
447
+ __linterBrands: 'SafePromise';
448
+ };
449
+
450
+ interface ThunkOptions<E = any> {
451
+ extraArgument: E;
452
+ }
453
+ interface GetDefaultMiddlewareOptions {
454
+ thunk?: boolean | ThunkOptions;
455
+ immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;
456
+ serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;
457
+ actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;
458
+ }
459
+ type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {
460
+ thunk: false;
461
+ } ? never : O extends {
462
+ thunk: {
463
+ extraArgument: infer E;
464
+ };
465
+ } ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;
466
+ type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {
467
+ thunk: true;
468
+ immutableCheck: true;
469
+ serializableCheck: true;
470
+ actionCreatorCheck: true;
471
+ }>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
472
+
473
+ declare const SHOULD_AUTOBATCH = "RTK_autoBatch";
474
+ declare const prepareAutoBatched: <T>() => (payload: T) => {
475
+ payload: T;
476
+ meta: unknown;
477
+ };
478
+ type AutoBatchOptions = {
479
+ type: 'tick';
480
+ } | {
481
+ type: 'timer';
482
+ timeout: number;
483
+ } | {
484
+ type: 'raf';
485
+ } | {
486
+ type: 'callback';
487
+ queueNotification: (notify: () => void) => void;
488
+ };
489
+ /**
490
+ * A Redux store enhancer that watches for "low-priority" actions, and delays
491
+ * notifying subscribers until either the queued callback executes or the
492
+ * next "standard-priority" action is dispatched.
493
+ *
494
+ * This allows dispatching multiple "low-priority" actions in a row with only
495
+ * a single subscriber notification to the UI after the sequence of actions
496
+ * is finished, thus improving UI re-render performance.
497
+ *
498
+ * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
499
+ * This can be added to `action.meta` manually, or by using the
500
+ * `prepareAutoBatched` helper.
501
+ *
502
+ * By default, it will queue a notification for the end of the event loop tick.
503
+ * However, you can pass several other options to configure the behavior:
504
+ * - `{type: 'tick'}`: queues using `queueMicrotask`
505
+ * - `{type: 'timer', timeout: number}`: queues using `setTimeout`
506
+ * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
507
+ * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
508
+ *
509
+ *
510
+ */
511
+ declare const autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;
512
+
513
+ type GetDefaultEnhancersOptions = {
514
+ autoBatch?: boolean | AutoBatchOptions;
515
+ };
516
+ type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{
517
+ dispatch: ExtractDispatchExtensions<M>;
518
+ }>]>;
519
+
520
+ /**
521
+ * Options for `configureStore()`.
522
+ *
523
+ * @public
524
+ */
525
+ interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {
526
+ /**
527
+ * A single reducer function that will be used as the root reducer, or an
528
+ * object of slice reducers that will be passed to `combineReducers()`.
529
+ */
530
+ reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;
531
+ /**
532
+ * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
533
+ * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
534
+ *
535
+ * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
536
+ * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
537
+ */
538
+ middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;
539
+ /**
540
+ * Whether to enable Redux DevTools integration. Defaults to `true`.
541
+ *
542
+ * Additional configuration can be done by passing Redux DevTools options
543
+ */
544
+ devTools?: boolean | DevToolsEnhancerOptions;
545
+ /**
546
+ * Whether to check for duplicate middleware instances. Defaults to `true`.
547
+ */
548
+ duplicateMiddlewareCheck?: boolean;
549
+ /**
550
+ * The initial state, same as Redux's createStore.
551
+ * You may optionally specify it to hydrate the state
552
+ * from the server in universal apps, or to restore a previously serialized
553
+ * user session. If you use `combineReducers()` to produce the root reducer
554
+ * function (either directly or indirectly by passing an object as `reducer`),
555
+ * this must be an object with the same shape as the reducer map keys.
556
+ */
557
+ preloadedState?: P;
558
+ /**
559
+ * The store enhancers to apply. See Redux's `createStore()`.
560
+ * All enhancers will be included before the DevTools Extension enhancer.
561
+ * If you need to customize the order of enhancers, supply a callback
562
+ * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
563
+ * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
564
+ * If you only need to add middleware, you can use the `middleware` parameter instead.
565
+ */
566
+ enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;
567
+ }
568
+ type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;
569
+ type Enhancers = ReadonlyArray<StoreEnhancer>;
570
+ /**
571
+ * A Redux store returned by `configureStore()`. Supports dispatching
572
+ * side-effectful _thunks_ in addition to plain actions.
573
+ *
574
+ * @public
575
+ */
576
+ type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;
577
+ /**
578
+ * A friendly abstraction over the standard Redux `createStore()` function.
579
+ *
580
+ * @param options The store configuration.
581
+ * @returns A configured Redux store.
582
+ *
583
+ * @public
584
+ */
585
+ declare function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[
586
+ StoreEnhancer<{
587
+ dispatch: ExtractDispatchExtensions<M>;
588
+ }>,
589
+ StoreEnhancer
590
+ ]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E>;
591
+
592
+ /**
593
+ * An action with a string type and an associated payload. This is the
594
+ * type of action returned by `createAction()` action creators.
595
+ *
596
+ * @template P The type of the action's payload.
597
+ * @template T the type used for the action type.
598
+ * @template M The type of the action's meta (optional)
599
+ * @template E The type of the action's error (optional)
600
+ *
601
+ * @public
602
+ */
603
+ type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
604
+ payload: P;
605
+ type: T;
606
+ } & ([M] extends [never] ? {} : {
607
+ meta: M;
608
+ }) & ([E] extends [never] ? {} : {
609
+ error: E;
610
+ });
611
+ /**
612
+ * A "prepare" method to be used as the second parameter of `createAction`.
613
+ * Takes any number of arguments and returns a Flux Standard Action without
614
+ * type (will be added later) that *must* contain a payload (might be undefined).
615
+ *
616
+ * @public
617
+ */
618
+ type PrepareAction<P> = ((...args: any[]) => {
619
+ payload: P;
620
+ }) | ((...args: any[]) => {
621
+ payload: P;
622
+ meta: any;
623
+ }) | ((...args: any[]) => {
624
+ payload: P;
625
+ error: any;
626
+ }) | ((...args: any[]) => {
627
+ payload: P;
628
+ meta: any;
629
+ error: any;
630
+ });
631
+ /**
632
+ * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
633
+ *
634
+ * @internal
635
+ */
636
+ type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {
637
+ error: infer E;
638
+ } ? E : never, ReturnType<PA> extends {
639
+ meta: infer M;
640
+ } ? M : never> : void;
641
+ /**
642
+ * Basic type for all action creators.
643
+ *
644
+ * @inheritdoc {redux#ActionCreator}
645
+ */
646
+ type BaseActionCreator<P, T extends string, M = never, E = never> = {
647
+ type: T;
648
+ match: (action: unknown) => action is PayloadAction<P, T, M, E>;
649
+ };
650
+ /**
651
+ * An action creator that takes multiple arguments that are passed
652
+ * to a `PrepareAction` method to create the final Action.
653
+ * @typeParam Args arguments for the action creator function
654
+ * @typeParam P `payload` type
655
+ * @typeParam T `type` name
656
+ * @typeParam E optional `error` type
657
+ * @typeParam M optional `meta` type
658
+ *
659
+ * @inheritdoc {redux#ActionCreator}
660
+ *
661
+ * @public
662
+ */
663
+ interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
664
+ /**
665
+ * Calling this {@link redux#ActionCreator} with `Args` will return
666
+ * an Action with a payload of type `P` and (depending on the `PrepareAction`
667
+ * method used) a `meta`- and `error` property of types `M` and `E` respectively.
668
+ */
669
+ (...args: Args): PayloadAction<P, T, M, E>;
670
+ }
671
+ /**
672
+ * An action creator of type `T` that takes an optional payload of type `P`.
673
+ *
674
+ * @inheritdoc {redux#ActionCreator}
675
+ *
676
+ * @public
677
+ */
678
+ interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
679
+ /**
680
+ * Calling this {@link redux#ActionCreator} with an argument will
681
+ * return a {@link PayloadAction} of type `T` with a payload of `P`.
682
+ * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
683
+ */
684
+ (payload?: P): PayloadAction<P, T>;
685
+ }
686
+ /**
687
+ * An action creator of type `T` that takes no payload.
688
+ *
689
+ * @inheritdoc {redux#ActionCreator}
690
+ *
691
+ * @public
692
+ */
693
+ interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
694
+ /**
695
+ * Calling this {@link redux#ActionCreator} will
696
+ * return a {@link PayloadAction} of type `T` with a payload of `undefined`
697
+ */
698
+ (noArgument: void): PayloadAction<undefined, T>;
699
+ }
700
+ /**
701
+ * An action creator of type `T` that requires a payload of type P.
702
+ *
703
+ * @inheritdoc {redux#ActionCreator}
704
+ *
705
+ * @public
706
+ */
707
+ interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
708
+ /**
709
+ * Calling this {@link redux#ActionCreator} with an argument will
710
+ * return a {@link PayloadAction} of type `T` with a payload of `P`
711
+ */
712
+ (payload: P): PayloadAction<P, T>;
713
+ }
714
+ /**
715
+ * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
716
+ *
717
+ * @inheritdoc {redux#ActionCreator}
718
+ *
719
+ * @public
720
+ */
721
+ interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
722
+ /**
723
+ * Calling this {@link redux#ActionCreator} with an argument will
724
+ * return a {@link PayloadAction} of type `T` with a payload
725
+ * of exactly the type of the argument.
726
+ */
727
+ <PT extends unknown>(payload: PT): PayloadAction<PT, T>;
728
+ }
729
+ /**
730
+ * An action creator that produces actions with a `payload` attribute.
731
+ *
732
+ * @typeParam P the `payload` type
733
+ * @typeParam T the `type` of the resulting action
734
+ * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
735
+ *
736
+ * @public
737
+ */
738
+ type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>, IfVoid<P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T>>>>>>;
739
+ /**
740
+ * A utility function to create an action creator for the given action type
741
+ * string. The action creator accepts a single argument, which will be included
742
+ * in the action object as a field called payload. The action creator function
743
+ * will also have its toString() overridden so that it returns the action type.
744
+ *
745
+ * @param type The action type to use for created actions.
746
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
747
+ * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
748
+ *
749
+ * @public
750
+ */
751
+ declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
752
+ /**
753
+ * A utility function to create an action creator for the given action type
754
+ * string. The action creator accepts a single argument, which will be included
755
+ * in the action object as a field called payload. The action creator function
756
+ * will also have its toString() overridden so that it returns the action type.
757
+ *
758
+ * @param type The action type to use for created actions.
759
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
760
+ * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
761
+ *
762
+ * @public
763
+ */
764
+ declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;
765
+ /**
766
+ * Returns true if value is an RTK-like action creator, with a static type property and match method.
767
+ */
768
+ declare function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function;
769
+ /**
770
+ * Returns true if value is an action with a string type and valid Flux Standard Action keys.
771
+ */
772
+ declare function isFSA(action: unknown): action is {
773
+ type: string;
774
+ payload?: unknown;
775
+ error?: unknown;
776
+ meta?: unknown;
777
+ };
778
+ type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
779
+
780
+ type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {
781
+ dispatch: D;
782
+ getState: () => S;
783
+ extra: E;
784
+ requestId: string;
785
+ signal: AbortSignal;
786
+ abort: (reason?: string) => void;
787
+ rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;
788
+ fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;
789
+ };
790
+ /**
791
+ * @public
792
+ */
793
+ interface SerializedError {
794
+ name?: string;
795
+ message?: string;
796
+ stack?: string;
797
+ code?: string;
798
+ }
799
+ declare class RejectWithValue<Payload, RejectedMeta> {
800
+ readonly payload: Payload;
801
+ readonly meta: RejectedMeta;
802
+ private readonly _type;
803
+ constructor(payload: Payload, meta: RejectedMeta);
804
+ }
805
+ declare class FulfillWithMeta<Payload, FulfilledMeta> {
806
+ readonly payload: Payload;
807
+ readonly meta: FulfilledMeta;
808
+ private readonly _type;
809
+ constructor(payload: Payload, meta: FulfilledMeta);
810
+ }
811
+ /**
812
+ * Serializes an error into a plain object.
813
+ * Reworked from https://github.com/sindresorhus/serialize-error
814
+ *
815
+ * @public
816
+ */
817
+ declare const miniSerializeError: (value: any) => SerializedError;
818
+ type AsyncThunkConfig = {
819
+ state?: unknown;
820
+ dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;
821
+ extra?: unknown;
822
+ rejectValue?: unknown;
823
+ serializedErrorType?: unknown;
824
+ pendingMeta?: unknown;
825
+ fulfilledMeta?: unknown;
826
+ rejectedMeta?: unknown;
827
+ };
828
+ type GetState<ThunkApiConfig> = ThunkApiConfig extends {
829
+ state: infer State;
830
+ } ? State : unknown;
831
+ type GetExtra<ThunkApiConfig> = ThunkApiConfig extends {
832
+ extra: infer Extra;
833
+ } ? Extra : unknown;
834
+ type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
835
+ dispatch: infer Dispatch;
836
+ } ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;
837
+ type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;
838
+ type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
839
+ rejectValue: infer RejectValue;
840
+ } ? RejectValue : unknown;
841
+ type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
842
+ pendingMeta: infer PendingMeta;
843
+ } ? PendingMeta : unknown;
844
+ type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
845
+ fulfilledMeta: infer FulfilledMeta;
846
+ } ? FulfilledMeta : unknown;
847
+ type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
848
+ rejectedMeta: infer RejectedMeta;
849
+ } ? RejectedMeta : unknown;
850
+ type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
851
+ serializedErrorType: infer GetSerializedErrorType;
852
+ } ? GetSerializedErrorType : SerializedError;
853
+ type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);
854
+ /**
855
+ * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
856
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
857
+ *
858
+ * @public
859
+ */
860
+ type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;
861
+ /**
862
+ * A type describing the `payloadCreator` argument to `createAsyncThunk`.
863
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
864
+ *
865
+ * @public
866
+ */
867
+ type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
868
+ /**
869
+ * A ThunkAction created by `createAsyncThunk`.
870
+ * Dispatching it returns a Promise for either a
871
+ * fulfilled or rejected action.
872
+ * Also, the returned value contains an `abort()` method
873
+ * that allows the asyncAction to be cancelled from the outside.
874
+ *
875
+ * @public
876
+ */
877
+ type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {
878
+ abort: (reason?: string) => void;
879
+ requestId: string;
880
+ arg: ThunkArg;
881
+ unwrap: () => Promise<Returned>;
882
+ };
883
+ /**
884
+ * Config provided when calling the async thunk action creator.
885
+ */
886
+ interface AsyncThunkDispatchConfig {
887
+ /**
888
+ * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
889
+ */
890
+ signal?: AbortSignal;
891
+ }
892
+ type AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, unknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [void] extends [ThunkArg] ? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [undefined] extends [ThunkArg] ? WithStrictNullChecks<(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> : (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;
893
+ /**
894
+ * Options object for `createAsyncThunk`.
895
+ *
896
+ * @public
897
+ */
898
+ type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {
899
+ /**
900
+ * A method to control whether the asyncThunk should be executed. Has access to the
901
+ * `arg`, `api.getState()` and `api.extra` arguments.
902
+ *
903
+ * @returns `false` if it should be skipped
904
+ */
905
+ condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;
906
+ /**
907
+ * If `condition` returns `false`, the asyncThunk will be skipped.
908
+ * This option allows you to control whether a `rejected` action with `meta.condition == false`
909
+ * will be dispatched or not.
910
+ *
911
+ * @default `false`
912
+ */
913
+ dispatchConditionRejection?: boolean;
914
+ serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;
915
+ /**
916
+ * A function to use when generating the `requestId` for the request sequence.
917
+ *
918
+ * @default `nanoid`
919
+ */
920
+ idGenerator?: (arg: ThunkArg) => string;
921
+ } & IsUnknown<GetPendingMeta<ThunkApiConfig>, {
922
+ /**
923
+ * A method to generate additional properties to be added to `meta` of the pending action.
924
+ *
925
+ * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
926
+ * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
927
+ */
928
+ getPendingMeta?(base: {
929
+ arg: ThunkArg;
930
+ requestId: string;
931
+ }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
932
+ }, {
933
+ /**
934
+ * A method to generate additional properties to be added to `meta` of the pending action.
935
+ */
936
+ getPendingMeta(base: {
937
+ arg: ThunkArg;
938
+ requestId: string;
939
+ }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
940
+ }>;
941
+ type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
942
+ string,
943
+ ThunkArg,
944
+ GetPendingMeta<ThunkApiConfig>?
945
+ ], undefined, string, never, {
946
+ arg: ThunkArg;
947
+ requestId: string;
948
+ requestStatus: 'pending';
949
+ } & GetPendingMeta<ThunkApiConfig>>;
950
+ type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
951
+ Error | null,
952
+ string,
953
+ ThunkArg,
954
+ GetRejectValue<ThunkApiConfig>?,
955
+ GetRejectedMeta<ThunkApiConfig>?
956
+ ], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {
957
+ arg: ThunkArg;
958
+ requestId: string;
959
+ requestStatus: 'rejected';
960
+ aborted: boolean;
961
+ condition: boolean;
962
+ } & (({
963
+ rejectedWithValue: false;
964
+ } & {
965
+ [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined;
966
+ }) | ({
967
+ rejectedWithValue: true;
968
+ } & GetRejectedMeta<ThunkApiConfig>))>;
969
+ type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
970
+ Returned,
971
+ string,
972
+ ThunkArg,
973
+ GetFulfilledMeta<ThunkApiConfig>?
974
+ ], Returned, string, never, {
975
+ arg: ThunkArg;
976
+ requestId: string;
977
+ requestStatus: 'fulfilled';
978
+ } & GetFulfilledMeta<ThunkApiConfig>>;
979
+ /**
980
+ * A type describing the return value of `createAsyncThunk`.
981
+ * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
982
+ *
983
+ * @public
984
+ */
985
+ type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
986
+ pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;
987
+ rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;
988
+ fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;
989
+ settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;
990
+ typePrefix: string;
991
+ };
992
+ type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;
993
+ type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {
994
+ /**
995
+ *
996
+ * @param typePrefix
997
+ * @param payloadCreator
998
+ * @param options
999
+ *
1000
+ * @public
1001
+ */
1002
+ <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;
1003
+ /**
1004
+ *
1005
+ * @param typePrefix
1006
+ * @param payloadCreator
1007
+ * @param options
1008
+ *
1009
+ * @public
1010
+ */
1011
+ <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1012
+ };
1013
+ type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
1014
+ withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1015
+ };
1016
+ declare const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
1017
+ interface UnwrappableAction {
1018
+ payload: any;
1019
+ meta?: any;
1020
+ error?: any;
1021
+ }
1022
+ type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {
1023
+ error: any;
1024
+ }>['payload'];
1025
+ /**
1026
+ * @public
1027
+ */
1028
+ declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;
1029
+ type WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;
1030
+
1031
+ type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {
1032
+ pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;
1033
+ rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;
1034
+ fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;
1035
+ settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;
1036
+ };
1037
+ type TypedActionCreator<Type extends string> = {
1038
+ (...args: any[]): Action<Type>;
1039
+ type: Type;
1040
+ };
1041
+ /**
1042
+ * A builder for an action <-> reducer map.
1043
+ *
1044
+ * @public
1045
+ */
1046
+ interface ActionReducerMapBuilder<State> {
1047
+ /**
1048
+ * Adds a case reducer to handle a single exact action type.
1049
+ * @remarks
1050
+ * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
1051
+ * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
1052
+ * @param reducer - The actual case reducer function.
1053
+ */
1054
+ addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;
1055
+ /**
1056
+ * Adds a case reducer to handle a single exact action type.
1057
+ * @remarks
1058
+ * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
1059
+ * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
1060
+ * @param reducer - The actual case reducer function.
1061
+ */
1062
+ addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;
1063
+ /**
1064
+ * Adds case reducers to handle actions based on a `AsyncThunk` action creator.
1065
+ * @remarks
1066
+ * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
1067
+ * @param asyncThunk - The async thunk action creator itself.
1068
+ * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
1069
+ * @example
1070
+ * ```ts no-transpile
1071
+ * import { createAsyncThunk, createReducer } from '@reduxjs/toolkit';
1072
+ *
1073
+ * const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
1074
+ * const response = await fetch(`https://reqres.in/api/users/${id}`);
1075
+ * return (await response.json()).data;
1076
+ * });
1077
+ *
1078
+ * const reducer = createReducer(initialState, (builder) => {
1079
+ * builder.addAsyncThunk(fetchUserById, {
1080
+ * pending: (state, action) => {
1081
+ * state.fetchUserById.loading = 'pending';
1082
+ * },
1083
+ * fulfilled: (state, action) => {
1084
+ * state.fetchUserById.data = action.payload;
1085
+ * },
1086
+ * rejected: (state, action) => {
1087
+ * state.fetchUserById.error = action.error;
1088
+ * },
1089
+ * settled: (state, action) => {
1090
+ * state.fetchUserById.loading = action.meta.requestStatus;
1091
+ * },
1092
+ * });
1093
+ * });
1094
+ * ```
1095
+ */
1096
+ addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;
1097
+ /**
1098
+ * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
1099
+ * @remarks
1100
+ * If multiple matcher reducers match, all of them will be executed in the order
1101
+ * they were defined in - even if a case reducer already matched.
1102
+ * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
1103
+ * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
1104
+ * function
1105
+ * @param reducer - The actual case reducer function.
1106
+ *
1107
+ * @example
1108
+ * ```ts
1109
+ * import type { AsyncThunk, UnknownAction } from '@reduxjs/toolkit';
1110
+ * import { createAction, createReducer } from '@reduxjs/toolkit';
1111
+ *
1112
+ * type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
1113
+ *
1114
+ * type PendingAction = ReturnType<GenericAsyncThunk['pending']>;
1115
+ * type RejectedAction = ReturnType<GenericAsyncThunk['rejected']>;
1116
+ * type FulfilledAction = ReturnType<GenericAsyncThunk['fulfilled']>;
1117
+ *
1118
+ * const initialState: Record<string, string> = {};
1119
+ * const resetAction = createAction('reset-tracked-loading-state');
1120
+ *
1121
+ * function isPendingAction(action: UnknownAction): action is PendingAction {
1122
+ * return typeof action.type === 'string' && action.type.endsWith('/pending');
1123
+ * }
1124
+ *
1125
+ * const reducer = createReducer(initialState, (builder) => {
1126
+ * builder
1127
+ * .addCase(resetAction, () => initialState)
1128
+ * // matcher can be defined outside as a type predicate function
1129
+ * .addMatcher(isPendingAction, (state, action) => {
1130
+ * state[action.meta.requestId] = 'pending';
1131
+ * })
1132
+ * .addMatcher(
1133
+ * // matcher can be defined inline as a type predicate function
1134
+ * (action): action is RejectedAction => action.type.endsWith('/rejected'),
1135
+ * (state, action) => {
1136
+ * state[action.meta.requestId] = 'rejected';
1137
+ * },
1138
+ * )
1139
+ * // matcher can just return boolean and the matcher can receive a generic argument
1140
+ * .addMatcher<FulfilledAction>(
1141
+ * (action) => action.type.endsWith('/fulfilled'),
1142
+ * (state, action) => {
1143
+ * state[action.meta.requestId] = 'fulfilled';
1144
+ * },
1145
+ * );
1146
+ * });
1147
+ * ```
1148
+ */
1149
+ addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;
1150
+ /**
1151
+ * Adds a "default case" reducer that is executed if no case reducer and no matcher
1152
+ * reducer was executed for this action.
1153
+ * @param reducer - The fallback "default case" reducer function.
1154
+ *
1155
+ * @example
1156
+ * ```ts
1157
+ * import { createReducer } from '@reduxjs/toolkit';
1158
+ *
1159
+ * const initialState = { otherActions: 0 };
1160
+ *
1161
+ * const reducer = createReducer(initialState, (builder) => {
1162
+ * builder
1163
+ * // .addCase(...)
1164
+ * // .addMatcher(...)
1165
+ * .addDefaultCase((state, action) => {
1166
+ * state.otherActions++;
1167
+ * });
1168
+ * });
1169
+ * ```
1170
+ */
1171
+ addDefaultCase(reducer: CaseReducer<State, Action>): {};
1172
+ }
1173
+
1174
+ /**
1175
+ * Defines a mapping from action types to corresponding action object shapes.
1176
+ *
1177
+ * @deprecated This should not be used manually - it is only used for internal
1178
+ * inference purposes and should not have any further value.
1179
+ * It might be removed in the future.
1180
+ * @public
1181
+ */
1182
+ type Actions<T extends keyof any = string> = Record<T, Action>;
1183
+ /**
1184
+ * A *case reducer* is a reducer function for a specific action type. Case
1185
+ * reducers can be composed to full reducers using `createReducer()`.
1186
+ *
1187
+ * Unlike a normal Redux reducer, a case reducer is never called with an
1188
+ * `undefined` state to determine the initial state. Instead, the initial
1189
+ * state is explicitly specified as an argument to `createReducer()`.
1190
+ *
1191
+ * In addition, a case reducer can choose to mutate the passed-in `state`
1192
+ * value directly instead of returning a new state. This does not actually
1193
+ * cause the store state to be mutated directly; instead, thanks to
1194
+ * [immer](https://github.com/mweststrate/immer), the mutations are
1195
+ * translated to copy operations that result in a new state.
1196
+ *
1197
+ * @public
1198
+ */
1199
+ type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
1200
+ /**
1201
+ * A mapping from action types to case reducers for `createReducer()`.
1202
+ *
1203
+ * @deprecated This should not be used manually - it is only used
1204
+ * for internal inference purposes and using it manually
1205
+ * would lead to type erasure.
1206
+ * It might be removed in the future.
1207
+ * @public
1208
+ */
1209
+ type CaseReducers<S, AS extends Actions> = {
1210
+ [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;
1211
+ };
1212
+ type NotFunction<T> = T extends Function ? never : T;
1213
+ type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
1214
+ getInitialState: () => S;
1215
+ };
1216
+ /**
1217
+ * A utility function that allows defining a reducer as a mapping from action
1218
+ * type to *case reducer* functions that handle these action types. The
1219
+ * reducer's initial state is passed as the first argument.
1220
+ *
1221
+ * @remarks
1222
+ * The body of every case reducer is implicitly wrapped with a call to
1223
+ * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
1224
+ * This means that rather than returning a new state object, you can also
1225
+ * mutate the passed-in state object directly; these mutations will then be
1226
+ * automatically and efficiently translated into copies, giving you both
1227
+ * convenience and immutability.
1228
+ *
1229
+ * @overloadSummary
1230
+ * This function accepts a callback that receives a `builder` object as its argument.
1231
+ * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
1232
+ * called to define what actions this reducer will handle.
1233
+ *
1234
+ * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
1235
+ * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
1236
+ * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
1237
+ * @example
1238
+ * ```ts
1239
+ * import type { PayloadAction, UnknownAction } from '@reduxjs/toolkit';
1240
+ * import { createAction, createReducer } from '@reduxjs/toolkit';
1241
+ *
1242
+ * const increment = createAction<number>('increment');
1243
+ * const decrement = createAction<number>('decrement');
1244
+ *
1245
+ * function isActionWithNumberPayload(
1246
+ * action: UnknownAction,
1247
+ * ): action is PayloadAction<number> {
1248
+ * return typeof action.payload === 'number';
1249
+ * }
1250
+ *
1251
+ * const reducer = createReducer(
1252
+ * {
1253
+ * counter: 0,
1254
+ * sumOfNumberPayloads: 0,
1255
+ * unhandledActions: 0,
1256
+ * },
1257
+ * (builder) => {
1258
+ * builder
1259
+ * .addCase(increment, (state, action) => {
1260
+ * // action is inferred correctly here
1261
+ * state.counter += action.payload;
1262
+ * })
1263
+ * // You can chain calls, or have separate `builder.addCase()` lines each time
1264
+ * .addCase(decrement, (state, action) => {
1265
+ * state.counter -= action.payload;
1266
+ * })
1267
+ * // You can apply a "matcher function" to incoming actions
1268
+ * .addMatcher(isActionWithNumberPayload, (state, action) => {})
1269
+ * // and provide a default case if no other handlers matched
1270
+ * .addDefaultCase((state, action) => {});
1271
+ * },
1272
+ * );
1273
+ * ```
1274
+ * @public
1275
+ */
1276
+ declare function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>;
1277
+
1278
+ type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
1279
+ reducerPath: ReducerPath;
1280
+ reducer: Reducer<State, any, PreloadedState>;
1281
+ };
1282
+ type AnySliceLike = SliceLike<string, any>;
1283
+ type SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;
1284
+ type SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;
1285
+ type SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;
1286
+ type WithSlice<A extends AnySliceLike> = {
1287
+ [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>;
1288
+ };
1289
+ type WithSlicePreloadedState<A extends AnySliceLike> = {
1290
+ [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>;
1291
+ };
1292
+ type ReducerMap = Record<string, Reducer>;
1293
+ type ExistingSliceLike<DeclaredState, PreloadedState> = {
1294
+ [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>>;
1295
+ }[keyof DeclaredState];
1296
+ type InjectConfig = {
1297
+ /**
1298
+ * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
1299
+ */
1300
+ overrideExisting?: boolean;
1301
+ };
1302
+ /**
1303
+ * A reducer that allows for slices/reducers to be injected after initialisation.
1304
+ */
1305
+ interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
1306
+ /**
1307
+ * Provide a type for slices that will be injected lazily.
1308
+ *
1309
+ * One way to do this would be with interface merging:
1310
+ * ```ts
1311
+ *
1312
+ * export interface LazyLoadedSlices {}
1313
+ *
1314
+ * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1315
+ *
1316
+ * // elsewhere
1317
+ *
1318
+ * declare module './reducer' {
1319
+ * export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1320
+ * }
1321
+ *
1322
+ * const withBoolean = rootReducer.inject(booleanSlice);
1323
+ *
1324
+ * // elsewhere again
1325
+ *
1326
+ * declare module './reducer' {
1327
+ * export interface LazyLoadedSlices {
1328
+ * customName: CustomState
1329
+ * }
1330
+ * }
1331
+ *
1332
+ * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
1333
+ * ```
1334
+ */
1335
+ withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;
1336
+ /**
1337
+ * Inject a slice.
1338
+ *
1339
+ * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
1340
+ *
1341
+ * ```ts
1342
+ * rootReducer.inject(booleanSlice)
1343
+ * rootReducer.inject(baseApi)
1344
+ * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
1345
+ * ```
1346
+ *
1347
+ */
1348
+ inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;
1349
+ /**
1350
+ * Inject a slice.
1351
+ *
1352
+ * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
1353
+ *
1354
+ * ```ts
1355
+ * rootReducer.inject(booleanSlice)
1356
+ * rootReducer.inject(baseApi)
1357
+ * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
1358
+ * ```
1359
+ *
1360
+ */
1361
+ inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;
1362
+ /**
1363
+ * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1364
+ *
1365
+ * ```ts
1366
+ * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1367
+ * // ^? boolean | undefined
1368
+ *
1369
+ * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1370
+ * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1371
+ * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1372
+ * return state.boolean;
1373
+ * // ^? boolean
1374
+ * })
1375
+ * ```
1376
+ *
1377
+ * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
1378
+ *
1379
+ * ```ts
1380
+ *
1381
+ * export interface LazyLoadedSlices {};
1382
+ *
1383
+ * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1384
+ *
1385
+ * export const rootReducer = combineSlices({ inner: innerReducer });
1386
+ *
1387
+ * export type RootState = ReturnType<typeof rootReducer>;
1388
+ *
1389
+ * // elsewhere
1390
+ *
1391
+ * declare module "./reducer.ts" {
1392
+ * export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1393
+ * }
1394
+ *
1395
+ * const withBool = innerReducer.inject(booleanSlice);
1396
+ *
1397
+ * const selectBoolean = withBool.selector(
1398
+ * (state) => state.boolean,
1399
+ * (rootState: RootState) => state.inner
1400
+ * );
1401
+ * // now expects to be passed RootState instead of innerReducer state
1402
+ *
1403
+ * ```
1404
+ *
1405
+ * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1406
+ *
1407
+ * ```ts
1408
+ * const injectedReducer = rootReducer.inject(booleanSlice);
1409
+ * const selectBoolean = injectedReducer.selector((state) => {
1410
+ * console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
1411
+ * return state.boolean
1412
+ * })
1413
+ * ```
1414
+ */
1415
+ selector: {
1416
+ /**
1417
+ * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1418
+ *
1419
+ * ```ts
1420
+ * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1421
+ * // ^? boolean | undefined
1422
+ *
1423
+ * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1424
+ * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1425
+ * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1426
+ * return state.boolean;
1427
+ * // ^? boolean
1428
+ * })
1429
+ * ```
1430
+ *
1431
+ * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1432
+ *
1433
+ * ```ts
1434
+ * const injectedReducer = rootReducer.inject(booleanSlice);
1435
+ * const selectBoolean = injectedReducer.selector((state) => {
1436
+ * console.log(injectedReducer.selector.original(state).boolean) // undefined
1437
+ * return state.boolean
1438
+ * })
1439
+ * ```
1440
+ */
1441
+ <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
1442
+ /**
1443
+ * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1444
+ *
1445
+ * ```ts
1446
+ * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1447
+ * // ^? boolean | undefined
1448
+ *
1449
+ * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1450
+ * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1451
+ * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1452
+ * return state.boolean;
1453
+ * // ^? boolean
1454
+ * })
1455
+ * ```
1456
+ *
1457
+ * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
1458
+ *
1459
+ * ```ts
1460
+ *
1461
+ * interface LazyLoadedSlices {};
1462
+ *
1463
+ * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1464
+ *
1465
+ * const rootReducer = combineSlices({ inner: innerReducer });
1466
+ *
1467
+ * type RootState = ReturnType<typeof rootReducer>;
1468
+ *
1469
+ * // elsewhere
1470
+ *
1471
+ * declare module "./reducer.ts" {
1472
+ * interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1473
+ * }
1474
+ *
1475
+ * const withBool = innerReducer.inject(booleanSlice);
1476
+ *
1477
+ * const selectBoolean = withBool.selector(
1478
+ * (state) => state.boolean,
1479
+ * (rootState: RootState) => state.inner
1480
+ * );
1481
+ * // now expects to be passed RootState instead of innerReducer state
1482
+ *
1483
+ * ```
1484
+ *
1485
+ * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1486
+ *
1487
+ * ```ts
1488
+ * const injectedReducer = rootReducer.inject(booleanSlice);
1489
+ * const selectBoolean = injectedReducer.selector((state) => {
1490
+ * console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
1491
+ * return state.boolean
1492
+ * })
1493
+ * ```
1494
+ */
1495
+ <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
1496
+ /**
1497
+ * Returns the unproxied state. Useful for debugging.
1498
+ * @param state state Proxy, that ensures injected reducers have value
1499
+ * @returns original, unproxied state
1500
+ * @throws if value passed is not a state Proxy
1501
+ */
1502
+ original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;
1503
+ };
1504
+ }
1505
+ type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;
1506
+ type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;
1507
+ declare function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>>;
1508
+
1509
+ declare const asyncThunkSymbol: unique symbol;
1510
+ declare const asyncThunkCreator: {
1511
+ [asyncThunkSymbol]: typeof createAsyncThunk;
1512
+ };
1513
+ type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
1514
+ reducerPath?: NewReducerPath;
1515
+ };
1516
+ /**
1517
+ * The return value of `createSlice`
1518
+ *
1519
+ * @public
1520
+ */
1521
+ interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
1522
+ /**
1523
+ * The slice name.
1524
+ */
1525
+ name: Name;
1526
+ /**
1527
+ * The slice reducer path.
1528
+ */
1529
+ reducerPath: ReducerPath;
1530
+ /**
1531
+ * The slice's reducer.
1532
+ */
1533
+ reducer: Reducer<State>;
1534
+ /**
1535
+ * Action creators for the types of actions that are handled by the slice
1536
+ * reducer.
1537
+ */
1538
+ actions: CaseReducerActions<CaseReducers, Name>;
1539
+ /**
1540
+ * The individual case reducer functions that were passed in the `reducers` parameter.
1541
+ * This enables reuse and testing if they were defined inline when calling `createSlice`.
1542
+ */
1543
+ caseReducers: SliceDefinedCaseReducers<CaseReducers>;
1544
+ /**
1545
+ * Provides access to the initial state value given to the slice.
1546
+ * If a lazy state initializer was provided, it will be called and a fresh value returned.
1547
+ */
1548
+ getInitialState: () => State;
1549
+ /**
1550
+ * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
1551
+ */
1552
+ getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;
1553
+ /**
1554
+ * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
1555
+ */
1556
+ getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
1557
+ /**
1558
+ * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
1559
+ *
1560
+ * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
1561
+ */
1562
+ get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
1563
+ [K in ReducerPath]: State;
1564
+ }>>;
1565
+ /**
1566
+ * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
1567
+ */
1568
+ injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {
1569
+ inject: (slice: {
1570
+ reducerPath: string;
1571
+ reducer: Reducer;
1572
+ }, config?: InjectConfig) => void;
1573
+ }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;
1574
+ /**
1575
+ * Select the slice state, using the slice's current reducerPath.
1576
+ *
1577
+ * Will throw an error if slice is not found.
1578
+ */
1579
+ selectSlice(state: {
1580
+ [K in ReducerPath]: State;
1581
+ }): State;
1582
+ }
1583
+ /**
1584
+ * A slice after being called with `injectInto(reducer)`.
1585
+ *
1586
+ * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
1587
+ */
1588
+ type InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {
1589
+ /**
1590
+ * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
1591
+ */
1592
+ getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;
1593
+ /**
1594
+ * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
1595
+ */
1596
+ getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
1597
+ /**
1598
+ * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
1599
+ *
1600
+ * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
1601
+ */
1602
+ get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
1603
+ [K in ReducerPath]?: State | undefined;
1604
+ }>>;
1605
+ /**
1606
+ * Select the slice state, using the slice's current reducerPath.
1607
+ *
1608
+ * Returns initial state if slice is not found.
1609
+ */
1610
+ selectSlice(state: {
1611
+ [K in ReducerPath]?: State | undefined;
1612
+ }): State;
1613
+ };
1614
+ /**
1615
+ * Options for `createSlice()`.
1616
+ *
1617
+ * @public
1618
+ */
1619
+ interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
1620
+ /**
1621
+ * The slice's name. Used to namespace the generated action types.
1622
+ */
1623
+ name: Name;
1624
+ /**
1625
+ * The slice's reducer path. Used when injecting into a combined slice reducer.
1626
+ */
1627
+ reducerPath?: ReducerPath;
1628
+ /**
1629
+ * The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
1630
+ */
1631
+ initialState: State | (() => State);
1632
+ /**
1633
+ * A mapping from action types to action-type-specific *case reducer*
1634
+ * functions. For every action type, a matching action creator will be
1635
+ * generated using `createAction()`.
1636
+ */
1637
+ reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);
1638
+ /**
1639
+ * A callback that receives a *builder* object to define
1640
+ * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
1641
+ *
1642
+ *
1643
+ * @example
1644
+ * ```ts
1645
+ * import type { Action } from '@reduxjs/toolkit';
1646
+ * import { createAction, createSlice } from '@reduxjs/toolkit';
1647
+ *
1648
+ * const incrementBy = createAction<number>('incrementBy');
1649
+ * const decrement = createAction('decrement');
1650
+ *
1651
+ * interface RejectedAction extends Action {
1652
+ * error: Error;
1653
+ * }
1654
+ *
1655
+ * function isRejectedAction(action: Action): action is RejectedAction {
1656
+ * return action.type.endsWith('rejected');
1657
+ * }
1658
+ *
1659
+ * createSlice({
1660
+ * name: 'counter',
1661
+ * initialState: 0,
1662
+ * reducers: {},
1663
+ * extraReducers: (builder) => {
1664
+ * builder
1665
+ * .addCase(incrementBy, (state, action) => {
1666
+ * // action is inferred correctly here if using TS
1667
+ * })
1668
+ * // You can chain calls, or have separate `builder.addCase()` lines each time
1669
+ * .addCase(decrement, (state, action) => {})
1670
+ * // You can match a range of action types
1671
+ * .addMatcher(
1672
+ * isRejectedAction,
1673
+ * // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
1674
+ * (state, action) => {},
1675
+ * )
1676
+ * // and provide a default case if no other handlers matched
1677
+ * .addDefaultCase((state, action) => {});
1678
+ * },
1679
+ * });
1680
+ * ```
1681
+ */
1682
+ extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;
1683
+ /**
1684
+ * A map of selectors that receive the slice's state and any additional arguments, and return a result.
1685
+ */
1686
+ selectors?: Selectors;
1687
+ }
1688
+ declare enum ReducerType {
1689
+ reducer = "reducer",
1690
+ reducerWithPrepare = "reducerWithPrepare",
1691
+ asyncThunk = "asyncThunk"
1692
+ }
1693
+ type ReducerDefinition<T extends ReducerType = ReducerType> = {
1694
+ _reducerDefinitionType: T;
1695
+ };
1696
+ type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;
1697
+ /**
1698
+ * A CaseReducer with a `prepare` method.
1699
+ *
1700
+ * @public
1701
+ */
1702
+ type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
1703
+ reducer: CaseReducer<State, Action>;
1704
+ prepare: PrepareAction<Action['payload']>;
1705
+ };
1706
+ type AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
1707
+ options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;
1708
+ };
1709
+ type AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {
1710
+ payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;
1711
+ };
1712
+ /**
1713
+ * Providing these as part of the config would cause circular types, so we disallow passing them
1714
+ */
1715
+ type PreventCircular<ThunkApiConfig> = {
1716
+ [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K];
1717
+ };
1718
+ interface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {
1719
+ <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;
1720
+ <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;
1721
+ withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1722
+ }
1723
+ interface ReducerCreators<State> {
1724
+ reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;
1725
+ reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;
1726
+ asyncThunk: AsyncThunkCreator<State>;
1727
+ preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {
1728
+ _reducerDefinitionType: ReducerType.reducerWithPrepare;
1729
+ prepare: Prepare;
1730
+ reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;
1731
+ };
1732
+ }
1733
+ /**
1734
+ * The type describing a slice's `reducers` option.
1735
+ *
1736
+ * @public
1737
+ */
1738
+ type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;
1739
+ /**
1740
+ * The type describing a slice's `selectors` option.
1741
+ */
1742
+ type SliceSelectors<State> = {
1743
+ [K: string]: (sliceState: State, ...args: any[]) => any;
1744
+ };
1745
+ type SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;
1746
+ /**
1747
+ * Derives the slice's `actions` property from the `reducers` options
1748
+ *
1749
+ * @public
1750
+ */
1751
+ type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = {
1752
+ [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {
1753
+ prepare: any;
1754
+ } ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {
1755
+ reducer: any;
1756
+ } ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never;
1757
+ };
1758
+ /**
1759
+ * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
1760
+ *
1761
+ * @internal
1762
+ */
1763
+ type ActionCreatorForCaseReducerWithPrepare<CR extends {
1764
+ prepare: any;
1765
+ }, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;
1766
+ /**
1767
+ * Get a `PayloadActionCreator` type for a passed `CaseReducer`
1768
+ *
1769
+ * @internal
1770
+ */
1771
+ type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (state: any, action: infer Action) => any ? Action extends {
1772
+ payload: infer P;
1773
+ } ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;
1774
+ /**
1775
+ * Extracts the CaseReducers out of a `reducers` object, even if they are
1776
+ * tested into a `CaseReducerWithPrepare`.
1777
+ *
1778
+ * @internal
1779
+ */
1780
+ type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
1781
+ [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {
1782
+ reducer: infer Reducer;
1783
+ } ? Reducer : Definition : never;
1784
+ };
1785
+ type RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {
1786
+ unwrapped: S;
1787
+ } : never;
1788
+ /**
1789
+ * Extracts the final selector type from the `selectors` object.
1790
+ *
1791
+ * Removes the `string` index signature from the default value.
1792
+ */
1793
+ type SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = {
1794
+ [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState>;
1795
+ };
1796
+ /**
1797
+ * Used on a SliceCaseReducers object.
1798
+ * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
1799
+ * the `reducer` and the `prepare` function use the same type of `payload`.
1800
+ *
1801
+ * Might do additional such checks in the future.
1802
+ *
1803
+ * This type is only ever useful if you want to write your own wrapper around
1804
+ * `createSlice`. Please don't use it otherwise!
1805
+ *
1806
+ * @public
1807
+ */
1808
+ type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
1809
+ [T in keyof ACR]: ACR[T] extends {
1810
+ reducer(s: S, action?: infer A): any;
1811
+ } ? {
1812
+ prepare(...a: never[]): Omit<A, 'type'>;
1813
+ } : {};
1814
+ };
1815
+ interface BuildCreateSliceConfig {
1816
+ creators?: {
1817
+ asyncThunk?: typeof asyncThunkCreator;
1818
+ };
1819
+ }
1820
+ declare function buildCreateSlice({ creators }?: BuildCreateSliceConfig): <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
1821
+ /**
1822
+ * A function that accepts an initial state, an object full of reducer
1823
+ * functions, and a "slice name", and automatically generates
1824
+ * action creators and action types that correspond to the
1825
+ * reducers and state.
1826
+ *
1827
+ * @public
1828
+ */
1829
+ declare const createSlice: <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
1830
+
1831
+ type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;
1832
+ type GetSelectorsOptions = {
1833
+ createSelector?: AnyCreateSelectorFunction;
1834
+ };
1835
+
1836
+ /**
1837
+ * @public
1838
+ */
1839
+ type EntityId = number | string;
1840
+ /**
1841
+ * @public
1842
+ */
1843
+ type Comparer<T> = (a: T, b: T) => number;
1844
+ /**
1845
+ * @public
1846
+ */
1847
+ type IdSelector<T, Id extends EntityId> = (model: T) => Id;
1848
+ /**
1849
+ * @public
1850
+ */
1851
+ type Update<T, Id extends EntityId> = {
1852
+ id: Id;
1853
+ changes: Partial<T>;
1854
+ };
1855
+ /**
1856
+ * @public
1857
+ */
1858
+ interface EntityState<T, Id extends EntityId> {
1859
+ ids: Id[];
1860
+ entities: Record<Id, T>;
1861
+ }
1862
+ /**
1863
+ * @public
1864
+ */
1865
+ interface EntityAdapterOptions<T, Id extends EntityId> {
1866
+ selectId?: IdSelector<T, Id>;
1867
+ sortComparer?: false | Comparer<T>;
1868
+ }
1869
+ type PreventAny<S, T, Id extends EntityId> = CastAny<S, EntityState<T, Id>>;
1870
+ type DraftableEntityState<T, Id extends EntityId> = EntityState<T, Id> | Draft<EntityState<T, Id>>;
1871
+ /**
1872
+ * @public
1873
+ */
1874
+ interface EntityStateAdapter<T, Id extends EntityId> {
1875
+ addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1876
+ addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
1877
+ addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1878
+ addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1879
+ setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1880
+ setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
1881
+ setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1882
+ setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1883
+ setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1884
+ setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1885
+ removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: Id): S;
1886
+ removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: PayloadAction<Id>): S;
1887
+ removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: readonly Id[]): S;
1888
+ removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: PayloadAction<readonly Id[]>): S;
1889
+ removeAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S;
1890
+ updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: Update<T, Id>): S;
1891
+ updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: PayloadAction<Update<T, Id>>): S;
1892
+ updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: ReadonlyArray<Update<T, Id>>): S;
1893
+ updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: PayloadAction<ReadonlyArray<Update<T, Id>>>): S;
1894
+ upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1895
+ upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: PayloadAction<T>): S;
1896
+ upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1897
+ upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1898
+ }
1899
+ /**
1900
+ * @public
1901
+ */
1902
+ interface EntitySelectors<T, V, IdType extends EntityId> {
1903
+ selectIds: (state: V) => IdType[];
1904
+ selectEntities: (state: V) => Record<IdType, T>;
1905
+ selectAll: (state: V) => T[];
1906
+ selectTotal: (state: V) => number;
1907
+ selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>;
1908
+ }
1909
+ /**
1910
+ * @public
1911
+ */
1912
+ interface EntityStateFactory<T, Id extends EntityId> {
1913
+ getInitialState(state?: undefined, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id>;
1914
+ getInitialState<S extends object>(state: S, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id> & S;
1915
+ }
1916
+ /**
1917
+ * @public
1918
+ */
1919
+ interface EntityAdapter<T, Id extends EntityId> extends EntityStateAdapter<T, Id>, EntityStateFactory<T, Id>, Required<EntityAdapterOptions<T, Id>> {
1920
+ getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;
1921
+ getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;
1922
+ }
1923
+
1924
+ declare function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;
1925
+ declare function createEntityAdapter<T extends {
1926
+ id: EntityId;
1927
+ }>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;
1928
+
1929
+ /** @public */
1930
+ type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;
1931
+ /** @public */
1932
+ type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;
1933
+ /**
1934
+ * A higher-order function that returns a function that may be used to check
1935
+ * whether an action matches any one of the supplied type guards or action
1936
+ * creators.
1937
+ *
1938
+ * @param matchers The type guards or action creators to match against.
1939
+ *
1940
+ * @public
1941
+ */
1942
+ declare function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAnyOf<Matchers>;
1943
+ /**
1944
+ * A higher-order function that returns a function that may be used to check
1945
+ * whether an action matches all of the supplied type guards or action
1946
+ * creators.
1947
+ *
1948
+ * @param matchers The type guards or action creators to match against.
1949
+ *
1950
+ * @public
1951
+ */
1952
+ declare function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAllOf<Matchers>;
1953
+ type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;
1954
+ type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;
1955
+ /**
1956
+ * A higher-order function that returns a function that may be used to check
1957
+ * whether an action was created by an async thunk action creator, and that
1958
+ * the action is pending.
1959
+ *
1960
+ * @public
1961
+ */
1962
+ declare function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;
1963
+ /**
1964
+ * A higher-order function that returns a function that may be used to check
1965
+ * whether an action belongs to one of the provided async thunk action creators,
1966
+ * and that the action is pending.
1967
+ *
1968
+ * @param asyncThunks (optional) The async thunk action creators to match against.
1969
+ *
1970
+ * @public
1971
+ */
1972
+ declare function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;
1973
+ /**
1974
+ * Tests if `action` is a pending thunk action
1975
+ * @public
1976
+ */
1977
+ declare function isPending(action: any): action is UnknownAsyncThunkPendingAction;
1978
+ type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
1979
+ type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;
1980
+ /**
1981
+ * A higher-order function that returns a function that may be used to check
1982
+ * whether an action was created by an async thunk action creator, and that
1983
+ * the action is rejected.
1984
+ *
1985
+ * @public
1986
+ */
1987
+ declare function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;
1988
+ /**
1989
+ * A higher-order function that returns a function that may be used to check
1990
+ * whether an action belongs to one of the provided async thunk action creators,
1991
+ * and that the action is rejected.
1992
+ *
1993
+ * @param asyncThunks (optional) The async thunk action creators to match against.
1994
+ *
1995
+ * @public
1996
+ */
1997
+ declare function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;
1998
+ /**
1999
+ * Tests if `action` is a rejected thunk action
2000
+ * @public
2001
+ */
2002
+ declare function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;
2003
+ type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {
2004
+ rejectValue: infer RejectedValue;
2005
+ }> ? {
2006
+ payload: RejectedValue;
2007
+ } : unknown);
2008
+ /**
2009
+ * A higher-order function that returns a function that may be used to check
2010
+ * whether an action was created by an async thunk action creator, and that
2011
+ * the action is rejected with value.
2012
+ *
2013
+ * @public
2014
+ */
2015
+ declare function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;
2016
+ /**
2017
+ * A higher-order function that returns a function that may be used to check
2018
+ * whether an action belongs to one of the provided async thunk action creators,
2019
+ * and that the action is rejected with value.
2020
+ *
2021
+ * @param asyncThunks (optional) The async thunk action creators to match against.
2022
+ *
2023
+ * @public
2024
+ */
2025
+ declare function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;
2026
+ /**
2027
+ * Tests if `action` is a rejected thunk action with value
2028
+ * @public
2029
+ */
2030
+ declare function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;
2031
+ type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;
2032
+ type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;
2033
+ /**
2034
+ * A higher-order function that returns a function that may be used to check
2035
+ * whether an action was created by an async thunk action creator, and that
2036
+ * the action is fulfilled.
2037
+ *
2038
+ * @public
2039
+ */
2040
+ declare function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;
2041
+ /**
2042
+ * A higher-order function that returns a function that may be used to check
2043
+ * whether an action belongs to one of the provided async thunk action creators,
2044
+ * and that the action is fulfilled.
2045
+ *
2046
+ * @param asyncThunks (optional) The async thunk action creators to match against.
2047
+ *
2048
+ * @public
2049
+ */
2050
+ declare function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;
2051
+ /**
2052
+ * Tests if `action` is a fulfilled thunk action
2053
+ * @public
2054
+ */
2055
+ declare function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;
2056
+ type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;
2057
+ type AnyAsyncThunk = {
2058
+ pending: {
2059
+ match: (action: any) => action is any;
2060
+ };
2061
+ fulfilled: {
2062
+ match: (action: any) => action is any;
2063
+ };
2064
+ rejected: {
2065
+ match: (action: any) => action is any;
2066
+ };
2067
+ };
2068
+ type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;
2069
+ /**
2070
+ * A higher-order function that returns a function that may be used to check
2071
+ * whether an action was created by an async thunk action creator.
2072
+ *
2073
+ * @public
2074
+ */
2075
+ declare function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;
2076
+ /**
2077
+ * A higher-order function that returns a function that may be used to check
2078
+ * whether an action belongs to one of the provided async thunk action creators.
2079
+ *
2080
+ * @param asyncThunks (optional) The async thunk action creators to match against.
2081
+ *
2082
+ * @public
2083
+ */
2084
+ declare function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;
2085
+ /**
2086
+ * Tests if `action` is a thunk action
2087
+ * @public
2088
+ */
2089
+ declare function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;
2090
+
2091
+ /**
2092
+ *
2093
+ * @public
2094
+ */
2095
+ declare let nanoid: (size?: number) => string;
2096
+
2097
+ declare class TaskAbortError implements SerializedError {
2098
+ code: string | undefined;
2099
+ name: string;
2100
+ message: string;
2101
+ constructor(code: string | undefined);
2102
+ }
2103
+
2104
+ /**
2105
+ * Types copied from RTK
2106
+ */
2107
+ /** @internal */
2108
+ type TypedActionCreatorWithMatchFunction<Type extends string> = TypedActionCreator<Type> & {
2109
+ match: MatchFunction<any>;
2110
+ };
2111
+ /** @internal */
2112
+ type AnyListenerPredicate<State> = (action: UnknownAction, currentState: State, originalState: State) => boolean;
2113
+ /** @public */
2114
+ type ListenerPredicate<ActionType extends Action, State> = (action: UnknownAction, currentState: State, originalState: State) => action is ActionType;
2115
+ /** @public */
2116
+ interface ConditionFunction<State> {
2117
+ (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
2118
+ (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
2119
+ (predicate: () => boolean, timeout?: number): Promise<boolean>;
2120
+ }
2121
+ /** @internal */
2122
+ type MatchFunction<T> = (v: any) => v is T;
2123
+ /** @public */
2124
+ interface ForkedTaskAPI {
2125
+ /**
2126
+ * Returns a promise that resolves when `waitFor` resolves or
2127
+ * rejects if the task or the parent listener has been cancelled or is completed.
2128
+ */
2129
+ pause<W>(waitFor: Promise<W>): Promise<W>;
2130
+ /**
2131
+ * Returns a promise that resolves after `timeoutMs` or
2132
+ * rejects if the task or the parent listener has been cancelled or is completed.
2133
+ * @param timeoutMs
2134
+ */
2135
+ delay(timeoutMs: number): Promise<void>;
2136
+ /**
2137
+ * An abort signal whose `aborted` property is set to `true`
2138
+ * if the task execution is either aborted or completed.
2139
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
2140
+ */
2141
+ signal: AbortSignal;
2142
+ }
2143
+ /** @public */
2144
+ interface AsyncTaskExecutor<T> {
2145
+ (forkApi: ForkedTaskAPI): Promise<T>;
2146
+ }
2147
+ /** @public */
2148
+ interface SyncTaskExecutor<T> {
2149
+ (forkApi: ForkedTaskAPI): T;
2150
+ }
2151
+ /** @public */
2152
+ type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
2153
+ /** @public */
2154
+ type TaskResolved<T> = {
2155
+ readonly status: 'ok';
2156
+ readonly value: T;
2157
+ };
2158
+ /** @public */
2159
+ type TaskRejected = {
2160
+ readonly status: 'rejected';
2161
+ readonly error: unknown;
2162
+ };
2163
+ /** @public */
2164
+ type TaskCancelled = {
2165
+ readonly status: 'cancelled';
2166
+ readonly error: TaskAbortError;
2167
+ };
2168
+ /** @public */
2169
+ type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
2170
+ /** @public */
2171
+ interface ForkedTask<T> {
2172
+ /**
2173
+ * A promise that resolves when the task is either completed or cancelled or rejects
2174
+ * if parent listener execution is cancelled or completed.
2175
+ *
2176
+ * ### Example
2177
+ * ```ts
2178
+ * const result = await fork(async (forkApi) => Promise.resolve(4)).result;
2179
+ *
2180
+ * if (result.status === 'ok') {
2181
+ * console.log(result.value); // logs 4
2182
+ * }
2183
+ * ```
2184
+ */
2185
+ result: Promise<TaskResult<T>>;
2186
+ /**
2187
+ * Cancel task if it is in progress or not yet started,
2188
+ * it is noop otherwise.
2189
+ */
2190
+ cancel(): void;
2191
+ }
2192
+ /** @public */
2193
+ interface ForkOptions {
2194
+ /**
2195
+ * If true, causes the parent task to not be marked as complete until
2196
+ * all autoJoined forks have completed or failed.
2197
+ */
2198
+ autoJoin: boolean;
2199
+ }
2200
+ /** @public */
2201
+ interface ListenerEffectAPI<State, DispatchType extends Dispatch, ExtraArgument = unknown> extends MiddlewareAPI<DispatchType, State> {
2202
+ /**
2203
+ * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
2204
+ *
2205
+ * ### Synchronous invocation
2206
+ *
2207
+ * This function can **only** be invoked **synchronously**, it throws error otherwise.
2208
+ *
2209
+ * @example
2210
+ *
2211
+ * ```ts
2212
+ * middleware.startListening({
2213
+ * predicate: () => true,
2214
+ * async effect(_, { getOriginalState }) {
2215
+ * getOriginalState(); // sync: OK!
2216
+ *
2217
+ * setTimeout(getOriginalState, 0); // async: throws Error
2218
+ *
2219
+ * await Promise().resolve();
2220
+ *
2221
+ * getOriginalState(); // async: throws Error
2222
+ * },
2223
+ * });
2224
+ * ```
2225
+ */
2226
+ getOriginalState: () => State;
2227
+ /**
2228
+ * Removes the listener entry from the middleware and prevent future instances of the listener from running.
2229
+ *
2230
+ * It does **not** cancel any active instances.
2231
+ */
2232
+ unsubscribe(): void;
2233
+ /**
2234
+ * It will subscribe a listener if it was previously removed, noop otherwise.
2235
+ */
2236
+ subscribe(): void;
2237
+ /**
2238
+ * Returns a promise that resolves when the input predicate returns `true` or
2239
+ * rejects if the listener has been cancelled or is completed.
2240
+ *
2241
+ * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
2242
+ *
2243
+ * ### Example
2244
+ *
2245
+ * ```ts
2246
+ * import { createAction } from '@reduxjs/toolkit';
2247
+ *
2248
+ * const updateBy = createAction<number>('counter/updateBy');
2249
+ *
2250
+ * middleware.startListening({
2251
+ * actionCreator: updateBy,
2252
+ * async effect(_, { condition }) {
2253
+ * // wait at most 3s for `updateBy` actions.
2254
+ * if (await condition(updateBy.match, 3_000)) {
2255
+ * // `updateBy` has been dispatched twice in less than 3s.
2256
+ * }
2257
+ * },
2258
+ * });
2259
+ * ```
2260
+ */
2261
+ condition: ConditionFunction<State>;
2262
+ /**
2263
+ * Returns a promise that resolves when the input predicate returns `true` or
2264
+ * rejects if the listener has been cancelled or is completed.
2265
+ *
2266
+ * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
2267
+ *
2268
+ * The promise resolves to null if a timeout is provided and expires first,
2269
+ *
2270
+ * ### Example
2271
+ *
2272
+ * ```ts
2273
+ * const updateBy = createAction<number>('counter/updateBy');
2274
+ *
2275
+ * middleware.startListening({
2276
+ * actionCreator: updateBy,
2277
+ * async effect(_, { take }) {
2278
+ * const [{ payload }] = await take(updateBy.match);
2279
+ * console.log(payload); // logs 5;
2280
+ * }
2281
+ * })
2282
+ *
2283
+ * store.dispatch(updateBy(5));
2284
+ * ```
2285
+ */
2286
+ take: TakePattern<State>;
2287
+ /**
2288
+ * Cancels all other running instances of this same listener except for the one that made this call.
2289
+ */
2290
+ cancelActiveListeners: () => void;
2291
+ /**
2292
+ * Cancels the instance of this listener that made this call.
2293
+ */
2294
+ cancel: () => void;
2295
+ /**
2296
+ * Throws a `TaskAbortError` if this listener has been cancelled
2297
+ */
2298
+ throwIfCancelled: () => void;
2299
+ /**
2300
+ * An abort signal whose `aborted` property is set to `true`
2301
+ * if the listener execution is either aborted or completed.
2302
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
2303
+ */
2304
+ signal: AbortSignal;
2305
+ /**
2306
+ * Returns a promise that resolves after `timeoutMs` or
2307
+ * rejects if the listener has been cancelled or is completed.
2308
+ */
2309
+ delay(timeoutMs: number): Promise<void>;
2310
+ /**
2311
+ * Queues in the next microtask the execution of a task.
2312
+ * @param executor
2313
+ * @param options
2314
+ */
2315
+ fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>;
2316
+ /**
2317
+ * Returns a promise that resolves when `waitFor` resolves or
2318
+ * rejects if the listener has been cancelled or is completed.
2319
+ * @param promise
2320
+ */
2321
+ pause<M>(promise: Promise<M>): Promise<M>;
2322
+ extra: ExtraArgument;
2323
+ }
2324
+ /** @public */
2325
+ type ListenerEffect<ActionType extends Action, State, DispatchType extends Dispatch, ExtraArgument = unknown> = (action: ActionType, api: ListenerEffectAPI<State, DispatchType, ExtraArgument>) => void | Promise<void>;
2326
+ /**
2327
+ * Additional infos regarding the error raised.
2328
+ * @public
2329
+ */
2330
+ interface ListenerErrorInfo {
2331
+ /**
2332
+ * Which function has generated the exception.
2333
+ */
2334
+ raisedBy: 'effect' | 'predicate';
2335
+ }
2336
+ /**
2337
+ * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
2338
+ * @param error The thrown error.
2339
+ * @param errorInfo Additional information regarding the thrown error.
2340
+ * @public
2341
+ */
2342
+ interface ListenerErrorHandler {
2343
+ (error: unknown, errorInfo: ListenerErrorInfo): void;
2344
+ }
2345
+ /** @public */
2346
+ interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
2347
+ extra?: ExtraArgument;
2348
+ /**
2349
+ * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
2350
+ */
2351
+ onError?: ListenerErrorHandler;
2352
+ }
2353
+ /** @public */
2354
+ type ListenerMiddleware<State = unknown, DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<State, unknown, UnknownAction>, ExtraArgument = unknown> = Middleware<{
2355
+ (action: Action<'listenerMiddleware/add'>): UnsubscribeListener;
2356
+ }, State, DispatchType>;
2357
+ /** @public */
2358
+ interface ListenerMiddlewareInstance<StateType = unknown, DispatchType extends ThunkDispatch<StateType, unknown, Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> {
2359
+ middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>;
2360
+ startListening: AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & TypedStartListening<StateType, DispatchType, ExtraArgument>;
2361
+ stopListening: RemoveListenerOverloads<StateType, DispatchType> & TypedStopListening<StateType, DispatchType>;
2362
+ /**
2363
+ * Unsubscribes all listeners, cancels running listeners and tasks.
2364
+ */
2365
+ clearListeners: () => void;
2366
+ }
2367
+ /**
2368
+ * API Function Overloads
2369
+ */
2370
+ /** @public */
2371
+ type TakePatternOutputWithoutTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State]> : Promise<[UnknownAction, State, State]>;
2372
+ /** @public */
2373
+ type TakePatternOutputWithTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State] | null> : Promise<[UnknownAction, State, State] | null>;
2374
+ /** @public */
2375
+ interface TakePattern<State> {
2376
+ <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate): TakePatternOutputWithoutTimeout<State, Predicate>;
2377
+ <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout: number): TakePatternOutputWithTimeout<State, Predicate>;
2378
+ <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout?: number | undefined): TakePatternOutputWithTimeout<State, Predicate>;
2379
+ }
2380
+ /** @public */
2381
+ interface UnsubscribeListenerOptions {
2382
+ cancelActive?: true;
2383
+ }
2384
+ /** @public */
2385
+ type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
2386
+ /**
2387
+ * The possible overloads and options for defining a listener.
2388
+ * The return type of each function is specified as a generic arg,
2389
+ * so the overloads can be reused for multiple different functions.
2390
+ *
2391
+ * @public
2392
+ */
2393
+ type AddListenerOverloads<Return, StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, AdditionalOptions = unknown> = {
2394
+ /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
2395
+ <MiddlewareActionType extends UnknownAction, ListenerPredicateType extends ListenerPredicate<MiddlewareActionType, StateType>>(options: {
2396
+ actionCreator?: never;
2397
+ type?: never;
2398
+ matcher?: never;
2399
+ predicate: ListenerPredicateType;
2400
+ effect: ListenerEffect<ListenerPredicateGuardedActionType<ListenerPredicateType>, StateType, DispatchType, ExtraArgument>;
2401
+ } & AdditionalOptions): Return;
2402
+ /** Accepts an RTK action creator, like `incrementByAmount` */
2403
+ <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(options: {
2404
+ actionCreator: ActionCreatorType;
2405
+ type?: never;
2406
+ matcher?: never;
2407
+ predicate?: never;
2408
+ effect: ListenerEffect<ReturnType<ActionCreatorType>, StateType, DispatchType, ExtraArgument>;
2409
+ } & AdditionalOptions): Return;
2410
+ /** Accepts a specific action type string */
2411
+ <T extends string>(options: {
2412
+ actionCreator?: never;
2413
+ type: T;
2414
+ matcher?: never;
2415
+ predicate?: never;
2416
+ effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>;
2417
+ } & AdditionalOptions): Return;
2418
+ /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
2419
+ <MatchFunctionType extends MatchFunction<Action>>(options: {
2420
+ actionCreator?: never;
2421
+ type?: never;
2422
+ matcher: MatchFunctionType;
2423
+ predicate?: never;
2424
+ effect: ListenerEffect<GuardedType<MatchFunctionType>, StateType, DispatchType, ExtraArgument>;
2425
+ } & AdditionalOptions): Return;
2426
+ /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
2427
+ <ListenerPredicateType extends AnyListenerPredicate<StateType>>(options: {
2428
+ actionCreator?: never;
2429
+ type?: never;
2430
+ matcher?: never;
2431
+ predicate: ListenerPredicateType;
2432
+ effect: ListenerEffect<UnknownAction, StateType, DispatchType, ExtraArgument>;
2433
+ } & AdditionalOptions): Return;
2434
+ };
2435
+ /** @public */
2436
+ type RemoveListenerOverloads<StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<boolean, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions>;
2437
+ /**
2438
+ * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
2439
+ *
2440
+ * @public
2441
+ */
2442
+ type TypedAddListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/add'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument> & {
2443
+ /**
2444
+ * Creates a "pre-typed" version of `addListener`
2445
+ * where the `state`, `dispatch` and `extra` types are predefined.
2446
+ *
2447
+ * This allows you to set the `state`, `dispatch` and `extra` types once,
2448
+ * eliminating the need to specify them with every `addListener` call.
2449
+ *
2450
+ * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
2451
+ *
2452
+ * @example
2453
+ * ```ts
2454
+ * import { addListener } from '@reduxjs/toolkit';
2455
+ *
2456
+ * export const addAppListener = addListener.withTypes<
2457
+ * RootState,
2458
+ * AppDispatch,
2459
+ * ExtraArguments
2460
+ * >();
2461
+ * ```
2462
+ *
2463
+ * @template OverrideStateType - The specific type of state the middleware listener operates on.
2464
+ * @template OverrideDispatchType - The specific type of the dispatch function.
2465
+ * @template OverrideExtraArgument - The specific type of the extra object.
2466
+ *
2467
+ * @since 2.1.0
2468
+ */
2469
+ withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedAddListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2470
+ };
2471
+ /**
2472
+ * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
2473
+ *
2474
+ * @public
2475
+ */
2476
+ type TypedRemoveListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/remove'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions> & {
2477
+ /**
2478
+ * Creates a "pre-typed" version of `removeListener`
2479
+ * where the `state`, `dispatch` and `extra` types are predefined.
2480
+ *
2481
+ * This allows you to set the `state`, `dispatch` and `extra` types once,
2482
+ * eliminating the need to specify them with every `removeListener` call.
2483
+ *
2484
+ * @returns A pre-typed `removeListener` with the state, dispatch and extra
2485
+ * types already defined.
2486
+ *
2487
+ * @example
2488
+ * ```ts
2489
+ * import { removeListener } from '@reduxjs/toolkit'
2490
+ *
2491
+ * export const removeAppListener = removeListener.withTypes<
2492
+ * RootState,
2493
+ * AppDispatch,
2494
+ * ExtraArguments
2495
+ * >()
2496
+ * ```
2497
+ *
2498
+ * @template OverrideStateType - The specific type of state the middleware listener operates on.
2499
+ * @template OverrideDispatchType - The specific type of the dispatch function.
2500
+ * @template OverrideExtraArgument - The specific type of the extra object.
2501
+ *
2502
+ * @since 2.1.0
2503
+ */
2504
+ withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedRemoveListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2505
+ };
2506
+ /**
2507
+ * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
2508
+ *
2509
+ * @public
2510
+ */
2511
+ type TypedStartListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & {
2512
+ /**
2513
+ * Creates a "pre-typed" version of
2514
+ * {@linkcode ListenerMiddlewareInstance.startListening | startListening}
2515
+ * where the `state`, `dispatch` and `extra` types are predefined.
2516
+ *
2517
+ * This allows you to set the `state`, `dispatch` and `extra` types once,
2518
+ * eliminating the need to specify them with every
2519
+ * {@linkcode ListenerMiddlewareInstance.startListening | startListening}
2520
+ * call.
2521
+ *
2522
+ * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
2523
+ *
2524
+ * @example
2525
+ * ```ts
2526
+ * import { createListenerMiddleware } from '@reduxjs/toolkit'
2527
+ *
2528
+ * const listenerMiddleware = createListenerMiddleware()
2529
+ *
2530
+ * export const startAppListening = listenerMiddleware.startListening.withTypes<
2531
+ * RootState,
2532
+ * AppDispatch,
2533
+ * ExtraArguments
2534
+ * >()
2535
+ * ```
2536
+ *
2537
+ * @template OverrideStateType - The specific type of state the middleware listener operates on.
2538
+ * @template OverrideDispatchType - The specific type of the dispatch function.
2539
+ * @template OverrideExtraArgument - The specific type of the extra object.
2540
+ *
2541
+ * @since 2.1.0
2542
+ */
2543
+ withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStartListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2544
+ };
2545
+ /**
2546
+ * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
2547
+ *
2548
+ * @public
2549
+ */
2550
+ type TypedStopListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
2551
+ /**
2552
+ * Creates a "pre-typed" version of
2553
+ * {@linkcode ListenerMiddlewareInstance.stopListening | stopListening}
2554
+ * where the `state`, `dispatch` and `extra` types are predefined.
2555
+ *
2556
+ * This allows you to set the `state`, `dispatch` and `extra` types once,
2557
+ * eliminating the need to specify them with every
2558
+ * {@linkcode ListenerMiddlewareInstance.stopListening | stopListening} call.
2559
+ *
2560
+ * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
2561
+ *
2562
+ * @example
2563
+ * ```ts
2564
+ * import { createListenerMiddleware } from '@reduxjs/toolkit'
2565
+ *
2566
+ * const listenerMiddleware = createListenerMiddleware()
2567
+ *
2568
+ * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
2569
+ * RootState,
2570
+ * AppDispatch,
2571
+ * ExtraArguments
2572
+ * >()
2573
+ * ```
2574
+ *
2575
+ * @template OverrideStateType - The specific type of state the middleware listener operates on.
2576
+ * @template OverrideDispatchType - The specific type of the dispatch function.
2577
+ * @template OverrideExtraArgument - The specific type of the extra object.
2578
+ *
2579
+ * @since 2.1.0
2580
+ */
2581
+ withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2582
+ };
2583
+ /**
2584
+ * Internal Types
2585
+ */
2586
+ /**
2587
+ * An single listener entry
2588
+ *
2589
+ * @internal
2590
+ */
2591
+ type ListenerEntry<State = unknown, DispatchType extends Dispatch = Dispatch> = {
2592
+ id: string;
2593
+ effect: ListenerEffect<any, State, DispatchType>;
2594
+ unsubscribe: () => void;
2595
+ pending: Set<AbortController>;
2596
+ type?: string;
2597
+ predicate: ListenerPredicate<UnknownAction, State>;
2598
+ };
2599
+ /**
2600
+ * Utility Types
2601
+ */
2602
+ /** @public */
2603
+ type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T ? T : never;
2604
+ /** @public */
2605
+ type ListenerPredicateGuardedActionType<T> = T extends ListenerPredicate<infer ActionType, any> ? ActionType : never;
2606
+
2607
+ /**
2608
+ * @public
2609
+ */
2610
+ declare const addListener: TypedAddListener<unknown>;
2611
+ /**
2612
+ * @public
2613
+ */
2614
+ declare const clearAllListeners: ActionCreatorWithoutPayload<"listenerMiddleware/removeAll">;
2615
+ /**
2616
+ * @public
2617
+ */
2618
+ declare const removeListener: TypedRemoveListener<unknown>;
2619
+ /**
2620
+ * @public
2621
+ */
2622
+ declare const createListenerMiddleware: <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>) => ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;
2623
+
2624
+ type MiddlewareApiConfig = {
2625
+ state?: unknown;
2626
+ dispatch?: Dispatch;
2627
+ };
2628
+ type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
2629
+ dispatch: infer DispatchType;
2630
+ } ? FallbackIfUnknown<DispatchType, Dispatch> : Dispatch;
2631
+ type AddMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
2632
+ (...middlewares: Middleware<any, State, DispatchType>[]): void;
2633
+ withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
2634
+ };
2635
+ type WithMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = BaseActionCreator<Middleware<any, State, DispatchType>[], 'dynamicMiddleware/add', {
2636
+ instanceId: string;
2637
+ }> & {
2638
+ <Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares): PayloadAction<Middlewares, 'dynamicMiddleware/add', {
2639
+ instanceId: string;
2640
+ }>;
2641
+ withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
2642
+ };
2643
+ interface DynamicDispatch {
2644
+ <Middlewares extends Middleware<any>[]>(action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>): ExtractDispatchExtensions<Middlewares> & this;
2645
+ }
2646
+ type DynamicMiddleware<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = Middleware<DynamicDispatch, State, DispatchType>;
2647
+ type DynamicMiddlewareInstance<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
2648
+ middleware: DynamicMiddleware<State, DispatchType>;
2649
+ addMiddleware: AddMiddleware<State, DispatchType>;
2650
+ withMiddleware: WithMiddleware<State, DispatchType>;
2651
+ instanceId: string;
2652
+ };
2653
+
2654
+ declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => DynamicMiddlewareInstance<State, DispatchType>;
2655
+
2656
+ /**
2657
+ * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
2658
+ *
2659
+ * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
2660
+ * during build.
2661
+ * @param {number} code
2662
+ */
2663
+ declare function formatProdErrorMessage(code: number): string;
2664
+
2665
+ export { type ActionCreatorInvariantMiddlewareOptions, type ActionCreatorWithNonInferrablePayload, type ActionCreatorWithOptionalPayload, type ActionCreatorWithPayload, type ActionCreatorWithPreparedPayload, type ActionCreatorWithoutPayload, type ActionMatchingAllOf, type ActionMatchingAnyOf, type ActionReducerMapBuilder, type Actions, type AddMiddleware, type AnyListenerPredicate, type AsyncTaskExecutor, type AsyncThunk, type AsyncThunkAction, type AsyncThunkConfig, type AsyncThunkDispatchConfig, type AsyncThunkOptions, type AsyncThunkPayloadCreator, type AsyncThunkPayloadCreatorReturnValue, type AsyncThunkReducers, type AutoBatchOptions, type CaseReducer, type CaseReducerActions, type CaseReducerWithPrepare, type CaseReducers, type CombinedSliceReducer, type Comparer, type ConfigureStoreOptions, type CreateAsyncThunkFunction, type CreateListenerMiddlewareOptions, type CreateSliceOptions, type DevToolsEnhancerOptions, type DynamicDispatch, type DynamicMiddlewareInstance, type EnhancedStore, type EntityAdapter, type EntityId, type EntitySelectors, type EntityState, type EntityStateAdapter, type ForkedTask, type ForkedTaskAPI, type ForkedTaskExecutor, type GetDispatchType as GetDispatch, type GetState, type GetThunkAPI, type IdSelector, type ImmutableStateInvariantMiddlewareOptions, type ListenerEffect, type ListenerEffectAPI, type ListenerErrorHandler, type ListenerMiddleware, type ListenerMiddlewareInstance, type MiddlewareApiConfig, type PayloadAction, type PayloadActionCreator, type PrepareAction, type ReducerCreators, ReducerType, SHOULD_AUTOBATCH, type SafePromise, type SerializableStateInvariantMiddlewareOptions, type SerializedError, type Slice, type SliceCaseReducers, type SliceSelectors, type SyncTaskExecutor, type ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, TaskAbortError, type TaskCancelled, type TaskRejected, type TaskResolved, type TaskResult, Tuple, type TypedAddListener, type TypedRemoveListener, type TypedStartListening, type TypedStopListening, type UnsubscribeListener, type UnsubscribeListenerOptions, type Update, type ValidateSliceCaseReducers, type WithSlice, type WithSlicePreloadedState, addListener, asyncThunkCreator, autoBatchEnhancer, buildCreateSlice, clearAllListeners, combineSlices, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, createReducer, createSerializableStateInvariantMiddleware, createSlice, findNonSerializableValue, formatProdErrorMessage, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isRejected, isRejectedWithValue, miniSerializeError, nanoid, prepareAutoBatched, removeListener, unwrapResult };