@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,2330 @@
1
+ // src/index.ts
2
+ export * from "redux";
3
+ import { freeze, original as original2 } from "immer";
4
+
5
+ // src/immerImports.ts
6
+ import { current, isDraft, produce, isDraftable, setUseStrictIteration } from "immer";
7
+
8
+ // src/index.ts
9
+ import { createSelector, lruMemoize } from "reselect";
10
+
11
+ // src/reselectImports.ts
12
+ import { createSelectorCreator, weakMapMemoize } from "reselect";
13
+
14
+ // src/createDraftSafeSelector.ts
15
+ var createDraftSafeSelectorCreator = (...args) => {
16
+ const createSelector2 = createSelectorCreator(...args);
17
+ const createDraftSafeSelector2 = Object.assign((...args2) => {
18
+ const selector = createSelector2(...args2);
19
+ const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
20
+ Object.assign(wrappedSelector, selector);
21
+ return wrappedSelector;
22
+ }, {
23
+ withTypes: () => createDraftSafeSelector2
24
+ });
25
+ return createDraftSafeSelector2;
26
+ };
27
+ var createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(weakMapMemoize);
28
+
29
+ // src/reduxImports.ts
30
+ import { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from "redux";
31
+
32
+ // src/devtoolsExtension.ts
33
+ var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
34
+ if (arguments.length === 0) return void 0;
35
+ if (typeof arguments[0] === "object") return compose;
36
+ return compose.apply(null, arguments);
37
+ };
38
+ var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
39
+ return function(noop3) {
40
+ return noop3;
41
+ };
42
+ };
43
+
44
+ // src/getDefaultMiddleware.ts
45
+ import { thunk as thunkMiddleware, withExtraArgument } from "redux-thunk";
46
+
47
+ // src/tsHelpers.ts
48
+ var hasMatchFunction = (v) => {
49
+ return v && typeof v.match === "function";
50
+ };
51
+
52
+ // src/createAction.ts
53
+ function createAction(type, prepareAction) {
54
+ function actionCreator(...args) {
55
+ if (prepareAction) {
56
+ let prepared = prepareAction(...args);
57
+ if (!prepared) {
58
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
59
+ }
60
+ return {
61
+ type,
62
+ payload: prepared.payload,
63
+ ..."meta" in prepared && {
64
+ meta: prepared.meta
65
+ },
66
+ ..."error" in prepared && {
67
+ error: prepared.error
68
+ }
69
+ };
70
+ }
71
+ return {
72
+ type,
73
+ payload: args[0]
74
+ };
75
+ }
76
+ actionCreator.toString = () => `${type}`;
77
+ actionCreator.type = type;
78
+ actionCreator.match = (action) => isAction(action) && action.type === type;
79
+ return actionCreator;
80
+ }
81
+ function isActionCreator(action) {
82
+ return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
83
+ hasMatchFunction(action);
84
+ }
85
+ function isFSA(action) {
86
+ return isAction(action) && Object.keys(action).every(isValidKey);
87
+ }
88
+ function isValidKey(key) {
89
+ return ["type", "payload", "error", "meta"].indexOf(key) > -1;
90
+ }
91
+
92
+ // src/actionCreatorInvariantMiddleware.ts
93
+ function getMessage(type) {
94
+ const splitType = type ? `${type}`.split("/") : [];
95
+ const actionName = splitType[splitType.length - 1] || "actionCreator";
96
+ return `Detected an action creator with type "${type || "unknown"}" being dispatched.
97
+ Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`;
98
+ }
99
+ function createActionCreatorInvariantMiddleware(options = {}) {
100
+ if (process.env.NODE_ENV === "production") {
101
+ return () => (next) => (action) => next(action);
102
+ }
103
+ const {
104
+ isActionCreator: isActionCreator2 = isActionCreator
105
+ } = options;
106
+ return () => (next) => (action) => {
107
+ if (isActionCreator2(action)) {
108
+ console.warn(getMessage(action.type));
109
+ }
110
+ return next(action);
111
+ };
112
+ }
113
+
114
+ // src/utils.ts
115
+ function getTimeMeasureUtils(maxDelay, fnName) {
116
+ let elapsed = 0;
117
+ return {
118
+ measureTime(fn) {
119
+ const started = Date.now();
120
+ try {
121
+ return fn();
122
+ } finally {
123
+ const finished = Date.now();
124
+ elapsed += finished - started;
125
+ }
126
+ },
127
+ warnIfExceeded() {
128
+ if (elapsed > maxDelay) {
129
+ console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
130
+ If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
131
+ It is disabled in production builds, so you don't need to worry about that.`);
132
+ }
133
+ }
134
+ };
135
+ }
136
+ var Tuple = class _Tuple extends Array {
137
+ constructor(...items) {
138
+ super(...items);
139
+ Object.setPrototypeOf(this, _Tuple.prototype);
140
+ }
141
+ static get [Symbol.species]() {
142
+ return _Tuple;
143
+ }
144
+ concat(...arr) {
145
+ return super.concat.apply(this, arr);
146
+ }
147
+ prepend(...arr) {
148
+ if (arr.length === 1 && Array.isArray(arr[0])) {
149
+ return new _Tuple(...arr[0].concat(this));
150
+ }
151
+ return new _Tuple(...arr.concat(this));
152
+ }
153
+ };
154
+ function freezeDraftable(val) {
155
+ return isDraftable(val) ? produce(val, () => {
156
+ }) : val;
157
+ }
158
+ function getOrInsertComputed(map, key, compute) {
159
+ if (map.has(key)) return map.get(key);
160
+ return map.set(key, compute(key)).get(key);
161
+ }
162
+
163
+ // src/immutableStateInvariantMiddleware.ts
164
+ function isImmutableDefault(value) {
165
+ return typeof value !== "object" || value == null || Object.isFrozen(value);
166
+ }
167
+ function trackForMutations(isImmutable, ignoredPaths, obj) {
168
+ const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);
169
+ return {
170
+ detectMutations() {
171
+ return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);
172
+ }
173
+ };
174
+ }
175
+ function trackProperties(isImmutable, ignoredPaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
176
+ const tracked = {
177
+ value: obj
178
+ };
179
+ if (!isImmutable(obj) && !checkedObjects.has(obj)) {
180
+ checkedObjects.add(obj);
181
+ tracked.children = {};
182
+ const hasIgnoredPaths = ignoredPaths.length > 0;
183
+ for (const key in obj) {
184
+ const nestedPath = path ? path + "." + key : key;
185
+ if (hasIgnoredPaths) {
186
+ const hasMatches = ignoredPaths.some((ignored) => {
187
+ if (ignored instanceof RegExp) {
188
+ return ignored.test(nestedPath);
189
+ }
190
+ return nestedPath === ignored;
191
+ });
192
+ if (hasMatches) {
193
+ continue;
194
+ }
195
+ }
196
+ tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);
197
+ }
198
+ }
199
+ return tracked;
200
+ }
201
+ function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
202
+ const prevObj = trackedProperty ? trackedProperty.value : void 0;
203
+ const sameRef = prevObj === obj;
204
+ if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
205
+ return {
206
+ wasMutated: true,
207
+ path
208
+ };
209
+ }
210
+ if (isImmutable(prevObj) || isImmutable(obj)) {
211
+ return {
212
+ wasMutated: false
213
+ };
214
+ }
215
+ const keysToDetect = {};
216
+ for (let key in trackedProperty.children) {
217
+ keysToDetect[key] = true;
218
+ }
219
+ for (let key in obj) {
220
+ keysToDetect[key] = true;
221
+ }
222
+ const hasIgnoredPaths = ignoredPaths.length > 0;
223
+ for (let key in keysToDetect) {
224
+ const nestedPath = path ? path + "." + key : key;
225
+ if (hasIgnoredPaths) {
226
+ const hasMatches = ignoredPaths.some((ignored) => {
227
+ if (ignored instanceof RegExp) {
228
+ return ignored.test(nestedPath);
229
+ }
230
+ return nestedPath === ignored;
231
+ });
232
+ if (hasMatches) {
233
+ continue;
234
+ }
235
+ }
236
+ const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
237
+ if (result.wasMutated) {
238
+ return result;
239
+ }
240
+ }
241
+ return {
242
+ wasMutated: false
243
+ };
244
+ }
245
+ function createImmutableStateInvariantMiddleware(options = {}) {
246
+ if (process.env.NODE_ENV === "production") {
247
+ return () => (next) => (action) => next(action);
248
+ } else {
249
+ let stringify2 = function(obj, serializer, indent, decycler) {
250
+ return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
251
+ }, getSerialize2 = function(serializer, decycler) {
252
+ let stack = [], keys = [];
253
+ if (!decycler) decycler = function(_, value) {
254
+ if (stack[0] === value) return "[Circular ~]";
255
+ return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
256
+ };
257
+ return function(key, value) {
258
+ if (stack.length > 0) {
259
+ var thisPos = stack.indexOf(this);
260
+ ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
261
+ ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
262
+ if (~stack.indexOf(value)) value = decycler.call(this, key, value);
263
+ } else stack.push(value);
264
+ return serializer == null ? value : serializer.call(this, key, value);
265
+ };
266
+ };
267
+ var stringify = stringify2, getSerialize = getSerialize2;
268
+ let {
269
+ isImmutable = isImmutableDefault,
270
+ ignoredPaths,
271
+ warnAfter = 32
272
+ } = options;
273
+ const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
274
+ return ({
275
+ getState
276
+ }) => {
277
+ let state = getState();
278
+ let tracker = track(state);
279
+ let result;
280
+ return (next) => (action) => {
281
+ const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
282
+ measureUtils.measureTime(() => {
283
+ state = getState();
284
+ result = tracker.detectMutations();
285
+ tracker = track(state);
286
+ if (result.wasMutated) {
287
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
288
+ }
289
+ });
290
+ const dispatchedAction = next(action);
291
+ measureUtils.measureTime(() => {
292
+ state = getState();
293
+ result = tracker.detectMutations();
294
+ tracker = track(state);
295
+ if (result.wasMutated) {
296
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
297
+ }
298
+ });
299
+ measureUtils.warnIfExceeded();
300
+ return dispatchedAction;
301
+ };
302
+ };
303
+ }
304
+ }
305
+
306
+ // src/serializableStateInvariantMiddleware.ts
307
+ function isPlain(val) {
308
+ const type = typeof val;
309
+ return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
310
+ }
311
+ function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
312
+ let foundNestedSerializable;
313
+ if (!isSerializable(value)) {
314
+ return {
315
+ keyPath: path || "<root>",
316
+ value
317
+ };
318
+ }
319
+ if (typeof value !== "object" || value === null) {
320
+ return false;
321
+ }
322
+ if (cache?.has(value)) return false;
323
+ const entries = getEntries != null ? getEntries(value) : Object.entries(value);
324
+ const hasIgnoredPaths = ignoredPaths.length > 0;
325
+ for (const [key, nestedValue] of entries) {
326
+ const nestedPath = path ? path + "." + key : key;
327
+ if (hasIgnoredPaths) {
328
+ const hasMatches = ignoredPaths.some((ignored) => {
329
+ if (ignored instanceof RegExp) {
330
+ return ignored.test(nestedPath);
331
+ }
332
+ return nestedPath === ignored;
333
+ });
334
+ if (hasMatches) {
335
+ continue;
336
+ }
337
+ }
338
+ if (!isSerializable(nestedValue)) {
339
+ return {
340
+ keyPath: nestedPath,
341
+ value: nestedValue
342
+ };
343
+ }
344
+ if (typeof nestedValue === "object") {
345
+ foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
346
+ if (foundNestedSerializable) {
347
+ return foundNestedSerializable;
348
+ }
349
+ }
350
+ }
351
+ if (cache && isNestedFrozen(value)) cache.add(value);
352
+ return false;
353
+ }
354
+ function isNestedFrozen(value) {
355
+ if (!Object.isFrozen(value)) return false;
356
+ for (const nestedValue of Object.values(value)) {
357
+ if (typeof nestedValue !== "object" || nestedValue === null) continue;
358
+ if (!isNestedFrozen(nestedValue)) return false;
359
+ }
360
+ return true;
361
+ }
362
+ function createSerializableStateInvariantMiddleware(options = {}) {
363
+ if (process.env.NODE_ENV === "production") {
364
+ return () => (next) => (action) => next(action);
365
+ } else {
366
+ const {
367
+ isSerializable = isPlain,
368
+ getEntries,
369
+ ignoredActions = [],
370
+ ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
371
+ ignoredPaths = [],
372
+ warnAfter = 32,
373
+ ignoreState = false,
374
+ ignoreActions = false,
375
+ disableCache = false
376
+ } = options;
377
+ const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
378
+ return (storeAPI) => (next) => (action) => {
379
+ if (!isAction(action)) {
380
+ return next(action);
381
+ }
382
+ const result = next(action);
383
+ const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
384
+ if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
385
+ measureUtils.measureTime(() => {
386
+ const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
387
+ if (foundActionNonSerializableValue) {
388
+ const {
389
+ keyPath,
390
+ value
391
+ } = foundActionNonSerializableValue;
392
+ console.error(`A non-serializable value was detected in an action, in the path: \`${keyPath}\`. Value:`, value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
393
+ }
394
+ });
395
+ }
396
+ if (!ignoreState) {
397
+ measureUtils.measureTime(() => {
398
+ const state = storeAPI.getState();
399
+ const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
400
+ if (foundStateNonSerializableValue) {
401
+ const {
402
+ keyPath,
403
+ value
404
+ } = foundStateNonSerializableValue;
405
+ console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
406
+ Take a look at the reducer(s) handling this action type: ${action.type}.
407
+ (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
408
+ }
409
+ });
410
+ measureUtils.warnIfExceeded();
411
+ }
412
+ return result;
413
+ };
414
+ }
415
+ }
416
+
417
+ // src/getDefaultMiddleware.ts
418
+ function isBoolean(x) {
419
+ return typeof x === "boolean";
420
+ }
421
+ var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
422
+ const {
423
+ thunk = true,
424
+ immutableCheck = true,
425
+ serializableCheck = true,
426
+ actionCreatorCheck = true
427
+ } = options ?? {};
428
+ let middlewareArray = new Tuple();
429
+ if (thunk) {
430
+ if (isBoolean(thunk)) {
431
+ middlewareArray.push(thunkMiddleware);
432
+ } else {
433
+ middlewareArray.push(withExtraArgument(thunk.extraArgument));
434
+ }
435
+ }
436
+ if (process.env.NODE_ENV !== "production") {
437
+ if (immutableCheck) {
438
+ let immutableOptions = {};
439
+ if (!isBoolean(immutableCheck)) {
440
+ immutableOptions = immutableCheck;
441
+ }
442
+ middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
443
+ }
444
+ if (serializableCheck) {
445
+ let serializableOptions = {};
446
+ if (!isBoolean(serializableCheck)) {
447
+ serializableOptions = serializableCheck;
448
+ }
449
+ middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
450
+ }
451
+ if (actionCreatorCheck) {
452
+ let actionCreatorOptions = {};
453
+ if (!isBoolean(actionCreatorCheck)) {
454
+ actionCreatorOptions = actionCreatorCheck;
455
+ }
456
+ middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
457
+ }
458
+ }
459
+ return middlewareArray;
460
+ };
461
+
462
+ // src/autoBatchEnhancer.ts
463
+ var SHOULD_AUTOBATCH = "RTK_autoBatch";
464
+ var prepareAutoBatched = () => (payload) => ({
465
+ payload,
466
+ meta: {
467
+ [SHOULD_AUTOBATCH]: true
468
+ }
469
+ });
470
+ var createQueueWithTimer = (timeout) => {
471
+ return (notify) => {
472
+ setTimeout(notify, timeout);
473
+ };
474
+ };
475
+ var createRafWithFallbackTimer = (raf, timeout) => {
476
+ return (notify) => {
477
+ let called = false;
478
+ const callback = () => {
479
+ if (called) return;
480
+ called = true;
481
+ cancelAnimationFrame(rafId);
482
+ clearTimeout(timerId);
483
+ notify();
484
+ };
485
+ const rafId = raf(callback);
486
+ const timerId = setTimeout(callback, timeout);
487
+ };
488
+ };
489
+ var autoBatchEnhancer = (options = {
490
+ type: "raf"
491
+ }) => (next) => (...args) => {
492
+ const store = next(...args);
493
+ let notifying = true;
494
+ let shouldNotifyAtEndOfTick = false;
495
+ let notificationQueued = false;
496
+ const listeners = /* @__PURE__ */ new Set();
497
+ const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? (
498
+ // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
499
+ typeof window !== "undefined" && window.requestAnimationFrame ? createRafWithFallbackTimer(window.requestAnimationFrame, 100) : createQueueWithTimer(10)
500
+ ) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
501
+ const notifyListeners = () => {
502
+ notificationQueued = false;
503
+ if (shouldNotifyAtEndOfTick) {
504
+ shouldNotifyAtEndOfTick = false;
505
+ listeners.forEach((l) => l());
506
+ }
507
+ };
508
+ return Object.assign({}, store, {
509
+ // Override the base `store.subscribe` method to keep original listeners
510
+ // from running if we're delaying notifications
511
+ subscribe(listener2) {
512
+ const wrappedListener = () => notifying && listener2();
513
+ const unsubscribe = store.subscribe(wrappedListener);
514
+ listeners.add(listener2);
515
+ return () => {
516
+ unsubscribe();
517
+ listeners.delete(listener2);
518
+ };
519
+ },
520
+ // Override the base `store.dispatch` method so that we can check actions
521
+ // for the `shouldAutoBatch` flag and determine if batching is active
522
+ dispatch(action) {
523
+ try {
524
+ notifying = !action?.meta?.[SHOULD_AUTOBATCH];
525
+ shouldNotifyAtEndOfTick = !notifying;
526
+ if (shouldNotifyAtEndOfTick) {
527
+ if (!notificationQueued) {
528
+ notificationQueued = true;
529
+ queueCallback(notifyListeners);
530
+ }
531
+ }
532
+ return store.dispatch(action);
533
+ } finally {
534
+ notifying = true;
535
+ }
536
+ }
537
+ });
538
+ };
539
+
540
+ // src/getDefaultEnhancers.ts
541
+ var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
542
+ const {
543
+ autoBatch = true
544
+ } = options ?? {};
545
+ let enhancerArray = new Tuple(middlewareEnhancer);
546
+ if (autoBatch) {
547
+ enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
548
+ }
549
+ return enhancerArray;
550
+ };
551
+
552
+ // src/configureStore.ts
553
+ function configureStore(options) {
554
+ const getDefaultMiddleware = buildGetDefaultMiddleware();
555
+ const {
556
+ reducer = void 0,
557
+ middleware,
558
+ devTools = true,
559
+ duplicateMiddlewareCheck = true,
560
+ preloadedState = void 0,
561
+ enhancers = void 0
562
+ } = options || {};
563
+ let rootReducer;
564
+ if (typeof reducer === "function") {
565
+ rootReducer = reducer;
566
+ } else if (isPlainObject(reducer)) {
567
+ rootReducer = combineReducers(reducer);
568
+ } else {
569
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
570
+ }
571
+ if (process.env.NODE_ENV !== "production" && middleware && typeof middleware !== "function") {
572
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
573
+ }
574
+ let finalMiddleware;
575
+ if (typeof middleware === "function") {
576
+ finalMiddleware = middleware(getDefaultMiddleware);
577
+ if (process.env.NODE_ENV !== "production" && !Array.isArray(finalMiddleware)) {
578
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
579
+ }
580
+ } else {
581
+ finalMiddleware = getDefaultMiddleware();
582
+ }
583
+ if (process.env.NODE_ENV !== "production" && finalMiddleware.some((item) => typeof item !== "function")) {
584
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
585
+ }
586
+ if (process.env.NODE_ENV !== "production" && duplicateMiddlewareCheck) {
587
+ let middlewareReferences = /* @__PURE__ */ new Set();
588
+ finalMiddleware.forEach((middleware2) => {
589
+ if (middlewareReferences.has(middleware2)) {
590
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(42) : "Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");
591
+ }
592
+ middlewareReferences.add(middleware2);
593
+ });
594
+ }
595
+ let finalCompose = compose;
596
+ if (devTools) {
597
+ finalCompose = composeWithDevTools({
598
+ // Enable capture of stack traces for dispatched Redux actions
599
+ trace: process.env.NODE_ENV !== "production",
600
+ ...typeof devTools === "object" && devTools
601
+ });
602
+ }
603
+ const middlewareEnhancer = applyMiddleware(...finalMiddleware);
604
+ const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
605
+ if (process.env.NODE_ENV !== "production" && enhancers && typeof enhancers !== "function") {
606
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
607
+ }
608
+ let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
609
+ if (process.env.NODE_ENV !== "production" && !Array.isArray(storeEnhancers)) {
610
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
611
+ }
612
+ if (process.env.NODE_ENV !== "production" && storeEnhancers.some((item) => typeof item !== "function")) {
613
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
614
+ }
615
+ if (process.env.NODE_ENV !== "production" && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
616
+ console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
617
+ }
618
+ const composedEnhancer = finalCompose(...storeEnhancers);
619
+ return createStore(rootReducer, preloadedState, composedEnhancer);
620
+ }
621
+
622
+ // src/mapBuilders.ts
623
+ function executeReducerBuilderCallback(builderCallback) {
624
+ const actionsMap = {};
625
+ const actionMatchers = [];
626
+ let defaultCaseReducer;
627
+ const builder = {
628
+ addCase(typeOrActionCreator, reducer) {
629
+ if (process.env.NODE_ENV !== "production") {
630
+ if (actionMatchers.length > 0) {
631
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
632
+ }
633
+ if (defaultCaseReducer) {
634
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
635
+ }
636
+ }
637
+ const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
638
+ if (!type) {
639
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
640
+ }
641
+ if (type in actionsMap) {
642
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
643
+ }
644
+ actionsMap[type] = reducer;
645
+ return builder;
646
+ },
647
+ addAsyncThunk(asyncThunk, reducers) {
648
+ if (process.env.NODE_ENV !== "production") {
649
+ if (defaultCaseReducer) {
650
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(43) : "`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");
651
+ }
652
+ }
653
+ if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
654
+ if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
655
+ if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
656
+ if (reducers.settled) actionMatchers.push({
657
+ matcher: asyncThunk.settled,
658
+ reducer: reducers.settled
659
+ });
660
+ return builder;
661
+ },
662
+ addMatcher(matcher, reducer) {
663
+ if (process.env.NODE_ENV !== "production") {
664
+ if (defaultCaseReducer) {
665
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
666
+ }
667
+ }
668
+ actionMatchers.push({
669
+ matcher,
670
+ reducer
671
+ });
672
+ return builder;
673
+ },
674
+ addDefaultCase(reducer) {
675
+ if (process.env.NODE_ENV !== "production") {
676
+ if (defaultCaseReducer) {
677
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
678
+ }
679
+ }
680
+ defaultCaseReducer = reducer;
681
+ return builder;
682
+ }
683
+ };
684
+ builderCallback(builder);
685
+ return [actionsMap, actionMatchers, defaultCaseReducer];
686
+ }
687
+
688
+ // src/createReducer.ts
689
+ function isStateFunction(x) {
690
+ return typeof x === "function";
691
+ }
692
+ function createReducer(initialState, mapOrBuilderCallback) {
693
+ if (process.env.NODE_ENV !== "production") {
694
+ if (typeof mapOrBuilderCallback === "object") {
695
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
696
+ }
697
+ }
698
+ let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
699
+ let getInitialState;
700
+ if (isStateFunction(initialState)) {
701
+ getInitialState = () => freezeDraftable(initialState());
702
+ } else {
703
+ const frozenInitialState = freezeDraftable(initialState);
704
+ getInitialState = () => frozenInitialState;
705
+ }
706
+ function reducer(state = getInitialState(), action) {
707
+ let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
708
+ matcher
709
+ }) => matcher(action)).map(({
710
+ reducer: reducer2
711
+ }) => reducer2)];
712
+ if (caseReducers.filter((cr) => !!cr).length === 0) {
713
+ caseReducers = [finalDefaultCaseReducer];
714
+ }
715
+ return caseReducers.reduce((previousState, caseReducer) => {
716
+ if (caseReducer) {
717
+ if (isDraft(previousState)) {
718
+ const draft = previousState;
719
+ const result = caseReducer(draft, action);
720
+ if (result === void 0) {
721
+ return previousState;
722
+ }
723
+ return result;
724
+ } else if (!isDraftable(previousState)) {
725
+ const result = caseReducer(previousState, action);
726
+ if (result === void 0) {
727
+ if (previousState === null) {
728
+ return previousState;
729
+ }
730
+ throw Error("A case reducer on a non-draftable value must not return undefined");
731
+ }
732
+ return result;
733
+ } else {
734
+ return produce(previousState, (draft) => {
735
+ return caseReducer(draft, action);
736
+ });
737
+ }
738
+ }
739
+ return previousState;
740
+ }, state);
741
+ }
742
+ reducer.getInitialState = getInitialState;
743
+ return reducer;
744
+ }
745
+
746
+ // src/matchers.ts
747
+ var matches = (matcher, action) => {
748
+ if (hasMatchFunction(matcher)) {
749
+ return matcher.match(action);
750
+ } else {
751
+ return matcher(action);
752
+ }
753
+ };
754
+ function isAnyOf(...matchers) {
755
+ return (action) => {
756
+ return matchers.some((matcher) => matches(matcher, action));
757
+ };
758
+ }
759
+ function isAllOf(...matchers) {
760
+ return (action) => {
761
+ return matchers.every((matcher) => matches(matcher, action));
762
+ };
763
+ }
764
+ function hasExpectedRequestMetadata(action, validStatus) {
765
+ if (!action || !action.meta) return false;
766
+ const hasValidRequestId = typeof action.meta.requestId === "string";
767
+ const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
768
+ return hasValidRequestId && hasValidRequestStatus;
769
+ }
770
+ function isAsyncThunkArray(a) {
771
+ return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
772
+ }
773
+ function isPending(...asyncThunks) {
774
+ if (asyncThunks.length === 0) {
775
+ return (action) => hasExpectedRequestMetadata(action, ["pending"]);
776
+ }
777
+ if (!isAsyncThunkArray(asyncThunks)) {
778
+ return isPending()(asyncThunks[0]);
779
+ }
780
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
781
+ }
782
+ function isRejected(...asyncThunks) {
783
+ if (asyncThunks.length === 0) {
784
+ return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
785
+ }
786
+ if (!isAsyncThunkArray(asyncThunks)) {
787
+ return isRejected()(asyncThunks[0]);
788
+ }
789
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
790
+ }
791
+ function isRejectedWithValue(...asyncThunks) {
792
+ const hasFlag = (action) => {
793
+ return action && action.meta && action.meta.rejectedWithValue;
794
+ };
795
+ if (asyncThunks.length === 0) {
796
+ return isAllOf(isRejected(...asyncThunks), hasFlag);
797
+ }
798
+ if (!isAsyncThunkArray(asyncThunks)) {
799
+ return isRejectedWithValue()(asyncThunks[0]);
800
+ }
801
+ return isAllOf(isRejected(...asyncThunks), hasFlag);
802
+ }
803
+ function isFulfilled(...asyncThunks) {
804
+ if (asyncThunks.length === 0) {
805
+ return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
806
+ }
807
+ if (!isAsyncThunkArray(asyncThunks)) {
808
+ return isFulfilled()(asyncThunks[0]);
809
+ }
810
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
811
+ }
812
+ function isAsyncThunkAction(...asyncThunks) {
813
+ if (asyncThunks.length === 0) {
814
+ return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
815
+ }
816
+ if (!isAsyncThunkArray(asyncThunks)) {
817
+ return isAsyncThunkAction()(asyncThunks[0]);
818
+ }
819
+ return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));
820
+ }
821
+
822
+ // src/nanoid.ts
823
+ var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
824
+ var nanoid = (size = 21) => {
825
+ let id = "";
826
+ let i = size;
827
+ while (i--) {
828
+ id += urlAlphabet[Math.random() * 64 | 0];
829
+ }
830
+ return id;
831
+ };
832
+
833
+ // src/createAsyncThunk.ts
834
+ var commonProperties = ["name", "message", "stack", "code"];
835
+ var RejectWithValue = class {
836
+ constructor(payload, meta) {
837
+ this.payload = payload;
838
+ this.meta = meta;
839
+ }
840
+ payload;
841
+ meta;
842
+ /*
843
+ type-only property to distinguish between RejectWithValue and FulfillWithMeta
844
+ does not exist at runtime
845
+ */
846
+ _type;
847
+ };
848
+ var FulfillWithMeta = class {
849
+ constructor(payload, meta) {
850
+ this.payload = payload;
851
+ this.meta = meta;
852
+ }
853
+ payload;
854
+ meta;
855
+ /*
856
+ type-only property to distinguish between RejectWithValue and FulfillWithMeta
857
+ does not exist at runtime
858
+ */
859
+ _type;
860
+ };
861
+ var miniSerializeError = (value) => {
862
+ if (typeof value === "object" && value !== null) {
863
+ const simpleError = {};
864
+ for (const property of commonProperties) {
865
+ if (typeof value[property] === "string") {
866
+ simpleError[property] = value[property];
867
+ }
868
+ }
869
+ return simpleError;
870
+ }
871
+ return {
872
+ message: String(value)
873
+ };
874
+ };
875
+ var externalAbortMessage = "External signal was aborted";
876
+ var createAsyncThunk = /* @__PURE__ */ (() => {
877
+ function createAsyncThunk2(typePrefix, payloadCreator, options) {
878
+ const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
879
+ payload,
880
+ meta: {
881
+ ...meta || {},
882
+ arg,
883
+ requestId,
884
+ requestStatus: "fulfilled"
885
+ }
886
+ }));
887
+ const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
888
+ payload: void 0,
889
+ meta: {
890
+ ...meta || {},
891
+ arg,
892
+ requestId,
893
+ requestStatus: "pending"
894
+ }
895
+ }));
896
+ const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
897
+ payload,
898
+ error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
899
+ meta: {
900
+ ...meta || {},
901
+ arg,
902
+ requestId,
903
+ rejectedWithValue: !!payload,
904
+ requestStatus: "rejected",
905
+ aborted: error?.name === "AbortError",
906
+ condition: error?.name === "ConditionError"
907
+ }
908
+ }));
909
+ function actionCreator(arg, {
910
+ signal
911
+ } = {}) {
912
+ return (dispatch, getState, extra) => {
913
+ const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();
914
+ const abortController = new AbortController();
915
+ let abortHandler;
916
+ let abortReason;
917
+ function abort(reason) {
918
+ abortReason = reason;
919
+ abortController.abort();
920
+ }
921
+ if (signal) {
922
+ if (signal.aborted) {
923
+ abort(externalAbortMessage);
924
+ } else {
925
+ signal.addEventListener("abort", () => abort(externalAbortMessage), {
926
+ once: true
927
+ });
928
+ }
929
+ }
930
+ const promise = (async function() {
931
+ let finalAction;
932
+ try {
933
+ let conditionResult = options?.condition?.(arg, {
934
+ getState,
935
+ extra
936
+ });
937
+ if (isThenable(conditionResult)) {
938
+ conditionResult = await conditionResult;
939
+ }
940
+ if (conditionResult === false || abortController.signal.aborted) {
941
+ throw {
942
+ name: "ConditionError",
943
+ message: "Aborted due to condition callback returning false."
944
+ };
945
+ }
946
+ const abortedPromise = new Promise((_, reject) => {
947
+ abortHandler = () => {
948
+ reject({
949
+ name: "AbortError",
950
+ message: abortReason || "Aborted"
951
+ });
952
+ };
953
+ abortController.signal.addEventListener("abort", abortHandler, {
954
+ once: true
955
+ });
956
+ });
957
+ dispatch(pending(requestId, arg, options?.getPendingMeta?.({
958
+ requestId,
959
+ arg
960
+ }, {
961
+ getState,
962
+ extra
963
+ })));
964
+ finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
965
+ dispatch,
966
+ getState,
967
+ extra,
968
+ requestId,
969
+ signal: abortController.signal,
970
+ abort,
971
+ rejectWithValue: ((value, meta) => {
972
+ return new RejectWithValue(value, meta);
973
+ }),
974
+ fulfillWithValue: ((value, meta) => {
975
+ return new FulfillWithMeta(value, meta);
976
+ })
977
+ })).then((result) => {
978
+ if (result instanceof RejectWithValue) {
979
+ throw result;
980
+ }
981
+ if (result instanceof FulfillWithMeta) {
982
+ return fulfilled(result.payload, requestId, arg, result.meta);
983
+ }
984
+ return fulfilled(result, requestId, arg);
985
+ })]);
986
+ } catch (err) {
987
+ finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
988
+ } finally {
989
+ if (abortHandler) {
990
+ abortController.signal.removeEventListener("abort", abortHandler);
991
+ }
992
+ }
993
+ const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
994
+ if (!skipDispatch) {
995
+ dispatch(finalAction);
996
+ }
997
+ return finalAction;
998
+ })();
999
+ return Object.assign(promise, {
1000
+ abort,
1001
+ requestId,
1002
+ arg,
1003
+ unwrap() {
1004
+ return promise.then(unwrapResult);
1005
+ }
1006
+ });
1007
+ };
1008
+ }
1009
+ return Object.assign(actionCreator, {
1010
+ pending,
1011
+ rejected,
1012
+ fulfilled,
1013
+ settled: isAnyOf(rejected, fulfilled),
1014
+ typePrefix
1015
+ });
1016
+ }
1017
+ createAsyncThunk2.withTypes = () => createAsyncThunk2;
1018
+ return createAsyncThunk2;
1019
+ })();
1020
+ function unwrapResult(action) {
1021
+ if (action.meta && action.meta.rejectedWithValue) {
1022
+ throw action.payload;
1023
+ }
1024
+ if (action.error) {
1025
+ throw action.error;
1026
+ }
1027
+ return action.payload;
1028
+ }
1029
+ function isThenable(value) {
1030
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1031
+ }
1032
+
1033
+ // src/createSlice.ts
1034
+ var asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
1035
+ var asyncThunkCreator = {
1036
+ [asyncThunkSymbol]: createAsyncThunk
1037
+ };
1038
+ var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
1039
+ ReducerType2["reducer"] = "reducer";
1040
+ ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
1041
+ ReducerType2["asyncThunk"] = "asyncThunk";
1042
+ return ReducerType2;
1043
+ })(ReducerType || {});
1044
+ function getType(slice, actionKey) {
1045
+ return `${slice}/${actionKey}`;
1046
+ }
1047
+ function buildCreateSlice({
1048
+ creators
1049
+ } = {}) {
1050
+ const cAT = creators?.asyncThunk?.[asyncThunkSymbol];
1051
+ return function createSlice2(options) {
1052
+ const {
1053
+ name,
1054
+ reducerPath = name
1055
+ } = options;
1056
+ if (!name) {
1057
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
1058
+ }
1059
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1060
+ if (options.initialState === void 0) {
1061
+ console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
1062
+ }
1063
+ }
1064
+ const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
1065
+ const reducerNames = Object.keys(reducers);
1066
+ const context = {
1067
+ sliceCaseReducersByName: {},
1068
+ sliceCaseReducersByType: {},
1069
+ actionCreators: {},
1070
+ sliceMatchers: []
1071
+ };
1072
+ const contextMethods = {
1073
+ addCase(typeOrActionCreator, reducer2) {
1074
+ const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
1075
+ if (!type) {
1076
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
1077
+ }
1078
+ if (type in context.sliceCaseReducersByType) {
1079
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
1080
+ }
1081
+ context.sliceCaseReducersByType[type] = reducer2;
1082
+ return contextMethods;
1083
+ },
1084
+ addMatcher(matcher, reducer2) {
1085
+ context.sliceMatchers.push({
1086
+ matcher,
1087
+ reducer: reducer2
1088
+ });
1089
+ return contextMethods;
1090
+ },
1091
+ exposeAction(name2, actionCreator) {
1092
+ context.actionCreators[name2] = actionCreator;
1093
+ return contextMethods;
1094
+ },
1095
+ exposeCaseReducer(name2, reducer2) {
1096
+ context.sliceCaseReducersByName[name2] = reducer2;
1097
+ return contextMethods;
1098
+ }
1099
+ };
1100
+ reducerNames.forEach((reducerName) => {
1101
+ const reducerDefinition = reducers[reducerName];
1102
+ const reducerDetails = {
1103
+ reducerName,
1104
+ type: getType(name, reducerName),
1105
+ createNotation: typeof options.reducers === "function"
1106
+ };
1107
+ if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
1108
+ handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
1109
+ } else {
1110
+ handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
1111
+ }
1112
+ });
1113
+ function buildReducer() {
1114
+ if (process.env.NODE_ENV !== "production") {
1115
+ if (typeof options.extraReducers === "object") {
1116
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
1117
+ }
1118
+ }
1119
+ const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
1120
+ const finalCaseReducers = {
1121
+ ...extraReducers,
1122
+ ...context.sliceCaseReducersByType
1123
+ };
1124
+ return createReducer(options.initialState, (builder) => {
1125
+ for (let key in finalCaseReducers) {
1126
+ builder.addCase(key, finalCaseReducers[key]);
1127
+ }
1128
+ for (let sM of context.sliceMatchers) {
1129
+ builder.addMatcher(sM.matcher, sM.reducer);
1130
+ }
1131
+ for (let m of actionMatchers) {
1132
+ builder.addMatcher(m.matcher, m.reducer);
1133
+ }
1134
+ if (defaultCaseReducer) {
1135
+ builder.addDefaultCase(defaultCaseReducer);
1136
+ }
1137
+ });
1138
+ }
1139
+ const selectSelf = (state) => state;
1140
+ const injectedSelectorCache = /* @__PURE__ */ new Map();
1141
+ const injectedStateCache = /* @__PURE__ */ new WeakMap();
1142
+ let _reducer;
1143
+ function reducer(state, action) {
1144
+ if (!_reducer) _reducer = buildReducer();
1145
+ return _reducer(state, action);
1146
+ }
1147
+ function getInitialState() {
1148
+ if (!_reducer) _reducer = buildReducer();
1149
+ return _reducer.getInitialState();
1150
+ }
1151
+ function makeSelectorProps(reducerPath2, injected = false) {
1152
+ function selectSlice(state) {
1153
+ let sliceState = state[reducerPath2];
1154
+ if (typeof sliceState === "undefined") {
1155
+ if (injected) {
1156
+ sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);
1157
+ } else if (process.env.NODE_ENV !== "production") {
1158
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
1159
+ }
1160
+ }
1161
+ return sliceState;
1162
+ }
1163
+ function getSelectors(selectState = selectSelf) {
1164
+ const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => /* @__PURE__ */ new WeakMap());
1165
+ return getOrInsertComputed(selectorCache, selectState, () => {
1166
+ const map = {};
1167
+ for (const [name2, selector] of Object.entries(options.selectors ?? {})) {
1168
+ map[name2] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);
1169
+ }
1170
+ return map;
1171
+ });
1172
+ }
1173
+ return {
1174
+ reducerPath: reducerPath2,
1175
+ getSelectors,
1176
+ get selectors() {
1177
+ return getSelectors(selectSlice);
1178
+ },
1179
+ selectSlice
1180
+ };
1181
+ }
1182
+ const slice = {
1183
+ name,
1184
+ reducer,
1185
+ actions: context.actionCreators,
1186
+ caseReducers: context.sliceCaseReducersByName,
1187
+ getInitialState,
1188
+ ...makeSelectorProps(reducerPath),
1189
+ injectInto(injectable, {
1190
+ reducerPath: pathOpt,
1191
+ ...config
1192
+ } = {}) {
1193
+ const newReducerPath = pathOpt ?? reducerPath;
1194
+ injectable.inject({
1195
+ reducerPath: newReducerPath,
1196
+ reducer
1197
+ }, config);
1198
+ return {
1199
+ ...slice,
1200
+ ...makeSelectorProps(newReducerPath, true)
1201
+ };
1202
+ }
1203
+ };
1204
+ return slice;
1205
+ };
1206
+ }
1207
+ function wrapSelector(selector, selectState, getInitialState, injected) {
1208
+ function wrapper(rootState, ...args) {
1209
+ let sliceState = selectState(rootState);
1210
+ if (typeof sliceState === "undefined") {
1211
+ if (injected) {
1212
+ sliceState = getInitialState();
1213
+ } else if (process.env.NODE_ENV !== "production") {
1214
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
1215
+ }
1216
+ }
1217
+ return selector(sliceState, ...args);
1218
+ }
1219
+ wrapper.unwrapped = selector;
1220
+ return wrapper;
1221
+ }
1222
+ var createSlice = /* @__PURE__ */ buildCreateSlice();
1223
+ function buildReducerCreators() {
1224
+ function asyncThunk(payloadCreator, config) {
1225
+ return {
1226
+ _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
1227
+ payloadCreator,
1228
+ ...config
1229
+ };
1230
+ }
1231
+ asyncThunk.withTypes = () => asyncThunk;
1232
+ return {
1233
+ reducer(caseReducer) {
1234
+ return Object.assign({
1235
+ // hack so the wrapping function has the same name as the original
1236
+ // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
1237
+ [caseReducer.name](...args) {
1238
+ return caseReducer(...args);
1239
+ }
1240
+ }[caseReducer.name], {
1241
+ _reducerDefinitionType: "reducer" /* reducer */
1242
+ });
1243
+ },
1244
+ preparedReducer(prepare, reducer) {
1245
+ return {
1246
+ _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
1247
+ prepare,
1248
+ reducer
1249
+ };
1250
+ },
1251
+ asyncThunk
1252
+ };
1253
+ }
1254
+ function handleNormalReducerDefinition({
1255
+ type,
1256
+ reducerName,
1257
+ createNotation
1258
+ }, maybeReducerWithPrepare, context) {
1259
+ let caseReducer;
1260
+ let prepareCallback;
1261
+ if ("reducer" in maybeReducerWithPrepare) {
1262
+ if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
1263
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
1264
+ }
1265
+ caseReducer = maybeReducerWithPrepare.reducer;
1266
+ prepareCallback = maybeReducerWithPrepare.prepare;
1267
+ } else {
1268
+ caseReducer = maybeReducerWithPrepare;
1269
+ }
1270
+ context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
1271
+ }
1272
+ function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
1273
+ return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
1274
+ }
1275
+ function isCaseReducerWithPrepareDefinition(reducerDefinition) {
1276
+ return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
1277
+ }
1278
+ function handleThunkCaseReducerDefinition({
1279
+ type,
1280
+ reducerName
1281
+ }, reducerDefinition, context, cAT) {
1282
+ if (!cAT) {
1283
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
1284
+ }
1285
+ const {
1286
+ payloadCreator,
1287
+ fulfilled,
1288
+ pending,
1289
+ rejected,
1290
+ settled,
1291
+ options
1292
+ } = reducerDefinition;
1293
+ const thunk = cAT(type, payloadCreator, options);
1294
+ context.exposeAction(reducerName, thunk);
1295
+ if (fulfilled) {
1296
+ context.addCase(thunk.fulfilled, fulfilled);
1297
+ }
1298
+ if (pending) {
1299
+ context.addCase(thunk.pending, pending);
1300
+ }
1301
+ if (rejected) {
1302
+ context.addCase(thunk.rejected, rejected);
1303
+ }
1304
+ if (settled) {
1305
+ context.addMatcher(thunk.settled, settled);
1306
+ }
1307
+ context.exposeCaseReducer(reducerName, {
1308
+ fulfilled: fulfilled || noop,
1309
+ pending: pending || noop,
1310
+ rejected: rejected || noop,
1311
+ settled: settled || noop
1312
+ });
1313
+ }
1314
+ function noop() {
1315
+ }
1316
+
1317
+ // src/entities/entity_state.ts
1318
+ function getInitialEntityState() {
1319
+ return {
1320
+ ids: [],
1321
+ entities: {}
1322
+ };
1323
+ }
1324
+ function createInitialStateFactory(stateAdapter) {
1325
+ function getInitialState(additionalState = {}, entities) {
1326
+ const state = Object.assign(getInitialEntityState(), additionalState);
1327
+ return entities ? stateAdapter.setAll(state, entities) : state;
1328
+ }
1329
+ return {
1330
+ getInitialState
1331
+ };
1332
+ }
1333
+
1334
+ // src/entities/state_selectors.ts
1335
+ function createSelectorsFactory() {
1336
+ function getSelectors(selectState, options = {}) {
1337
+ const {
1338
+ createSelector: createSelector2 = createDraftSafeSelector
1339
+ } = options;
1340
+ const selectIds = (state) => state.ids;
1341
+ const selectEntities = (state) => state.entities;
1342
+ const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
1343
+ const selectId = (_, id) => id;
1344
+ const selectById = (entities, id) => entities[id];
1345
+ const selectTotal = createSelector2(selectIds, (ids) => ids.length);
1346
+ if (!selectState) {
1347
+ return {
1348
+ selectIds,
1349
+ selectEntities,
1350
+ selectAll,
1351
+ selectTotal,
1352
+ selectById: createSelector2(selectEntities, selectId, selectById)
1353
+ };
1354
+ }
1355
+ const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
1356
+ return {
1357
+ selectIds: createSelector2(selectState, selectIds),
1358
+ selectEntities: selectGlobalizedEntities,
1359
+ selectAll: createSelector2(selectState, selectAll),
1360
+ selectTotal: createSelector2(selectState, selectTotal),
1361
+ selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
1362
+ };
1363
+ }
1364
+ return {
1365
+ getSelectors
1366
+ };
1367
+ }
1368
+
1369
+ // src/entities/state_adapter.ts
1370
+ var isDraftTyped = isDraft;
1371
+ function createSingleArgumentStateOperator(mutator) {
1372
+ const operator = createStateOperator((_, state) => mutator(state));
1373
+ return function operation(state) {
1374
+ return operator(state, void 0);
1375
+ };
1376
+ }
1377
+ function createStateOperator(mutator) {
1378
+ return function operation(state, arg) {
1379
+ function isPayloadActionArgument(arg2) {
1380
+ return isFSA(arg2);
1381
+ }
1382
+ const runMutator = (draft) => {
1383
+ if (isPayloadActionArgument(arg)) {
1384
+ mutator(arg.payload, draft);
1385
+ } else {
1386
+ mutator(arg, draft);
1387
+ }
1388
+ };
1389
+ if (isDraftTyped(state)) {
1390
+ runMutator(state);
1391
+ return state;
1392
+ }
1393
+ return produce(state, runMutator);
1394
+ };
1395
+ }
1396
+
1397
+ // src/entities/utils.ts
1398
+ function selectIdValue(entity, selectId) {
1399
+ const key = selectId(entity);
1400
+ if (process.env.NODE_ENV !== "production" && key === void 0) {
1401
+ console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
1402
+ }
1403
+ return key;
1404
+ }
1405
+ function ensureEntitiesArray(entities) {
1406
+ if (!Array.isArray(entities)) {
1407
+ entities = Object.values(entities);
1408
+ }
1409
+ return entities;
1410
+ }
1411
+ function getCurrent(value) {
1412
+ return isDraft(value) ? current(value) : value;
1413
+ }
1414
+ function splitAddedUpdatedEntities(newEntities, selectId, state) {
1415
+ newEntities = ensureEntitiesArray(newEntities);
1416
+ const existingIdsArray = getCurrent(state.ids);
1417
+ const existingIds = new Set(existingIdsArray);
1418
+ const added = [];
1419
+ const addedIds = /* @__PURE__ */ new Set([]);
1420
+ const updated = [];
1421
+ for (const entity of newEntities) {
1422
+ const id = selectIdValue(entity, selectId);
1423
+ if (existingIds.has(id) || addedIds.has(id)) {
1424
+ updated.push({
1425
+ id,
1426
+ changes: entity
1427
+ });
1428
+ } else {
1429
+ addedIds.add(id);
1430
+ added.push(entity);
1431
+ }
1432
+ }
1433
+ return [added, updated, existingIdsArray];
1434
+ }
1435
+
1436
+ // src/entities/unsorted_state_adapter.ts
1437
+ function createUnsortedStateAdapter(selectId) {
1438
+ function addOneMutably(entity, state) {
1439
+ const key = selectIdValue(entity, selectId);
1440
+ if (key in state.entities) {
1441
+ return;
1442
+ }
1443
+ state.ids.push(key);
1444
+ state.entities[key] = entity;
1445
+ }
1446
+ function addManyMutably(newEntities, state) {
1447
+ newEntities = ensureEntitiesArray(newEntities);
1448
+ for (const entity of newEntities) {
1449
+ addOneMutably(entity, state);
1450
+ }
1451
+ }
1452
+ function setOneMutably(entity, state) {
1453
+ const key = selectIdValue(entity, selectId);
1454
+ if (!(key in state.entities)) {
1455
+ state.ids.push(key);
1456
+ }
1457
+ ;
1458
+ state.entities[key] = entity;
1459
+ }
1460
+ function setManyMutably(newEntities, state) {
1461
+ newEntities = ensureEntitiesArray(newEntities);
1462
+ for (const entity of newEntities) {
1463
+ setOneMutably(entity, state);
1464
+ }
1465
+ }
1466
+ function setAllMutably(newEntities, state) {
1467
+ newEntities = ensureEntitiesArray(newEntities);
1468
+ state.ids = [];
1469
+ state.entities = {};
1470
+ addManyMutably(newEntities, state);
1471
+ }
1472
+ function removeOneMutably(key, state) {
1473
+ return removeManyMutably([key], state);
1474
+ }
1475
+ function removeManyMutably(keys, state) {
1476
+ let didMutate = false;
1477
+ keys.forEach((key) => {
1478
+ if (key in state.entities) {
1479
+ delete state.entities[key];
1480
+ didMutate = true;
1481
+ }
1482
+ });
1483
+ if (didMutate) {
1484
+ state.ids = state.ids.filter((id) => id in state.entities);
1485
+ }
1486
+ }
1487
+ function removeAllMutably(state) {
1488
+ Object.assign(state, {
1489
+ ids: [],
1490
+ entities: {}
1491
+ });
1492
+ }
1493
+ function takeNewKey(keys, update, state) {
1494
+ const original3 = state.entities[update.id];
1495
+ if (original3 === void 0) {
1496
+ return false;
1497
+ }
1498
+ const updated = Object.assign({}, original3, update.changes);
1499
+ const newKey = selectIdValue(updated, selectId);
1500
+ const hasNewKey = newKey !== update.id;
1501
+ if (hasNewKey) {
1502
+ keys[update.id] = newKey;
1503
+ delete state.entities[update.id];
1504
+ }
1505
+ ;
1506
+ state.entities[newKey] = updated;
1507
+ return hasNewKey;
1508
+ }
1509
+ function updateOneMutably(update, state) {
1510
+ return updateManyMutably([update], state);
1511
+ }
1512
+ function updateManyMutably(updates, state) {
1513
+ const newKeys = {};
1514
+ const updatesPerEntity = {};
1515
+ updates.forEach((update) => {
1516
+ if (update.id in state.entities) {
1517
+ updatesPerEntity[update.id] = {
1518
+ id: update.id,
1519
+ // Spreads ignore falsy values, so this works even if there isn't
1520
+ // an existing update already at this key
1521
+ changes: {
1522
+ ...updatesPerEntity[update.id]?.changes,
1523
+ ...update.changes
1524
+ }
1525
+ };
1526
+ }
1527
+ });
1528
+ updates = Object.values(updatesPerEntity);
1529
+ const didMutateEntities = updates.length > 0;
1530
+ if (didMutateEntities) {
1531
+ const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
1532
+ if (didMutateIds) {
1533
+ state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
1534
+ }
1535
+ }
1536
+ }
1537
+ function upsertOneMutably(entity, state) {
1538
+ return upsertManyMutably([entity], state);
1539
+ }
1540
+ function upsertManyMutably(newEntities, state) {
1541
+ const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
1542
+ addManyMutably(added, state);
1543
+ updateManyMutably(updated, state);
1544
+ }
1545
+ return {
1546
+ removeAll: createSingleArgumentStateOperator(removeAllMutably),
1547
+ addOne: createStateOperator(addOneMutably),
1548
+ addMany: createStateOperator(addManyMutably),
1549
+ setOne: createStateOperator(setOneMutably),
1550
+ setMany: createStateOperator(setManyMutably),
1551
+ setAll: createStateOperator(setAllMutably),
1552
+ updateOne: createStateOperator(updateOneMutably),
1553
+ updateMany: createStateOperator(updateManyMutably),
1554
+ upsertOne: createStateOperator(upsertOneMutably),
1555
+ upsertMany: createStateOperator(upsertManyMutably),
1556
+ removeOne: createStateOperator(removeOneMutably),
1557
+ removeMany: createStateOperator(removeManyMutably)
1558
+ };
1559
+ }
1560
+
1561
+ // src/entities/sorted_state_adapter.ts
1562
+ function findInsertIndex(sortedItems, item, comparisonFunction) {
1563
+ let lowIndex = 0;
1564
+ let highIndex = sortedItems.length;
1565
+ while (lowIndex < highIndex) {
1566
+ let middleIndex = lowIndex + highIndex >>> 1;
1567
+ const currentItem = sortedItems[middleIndex];
1568
+ const res = comparisonFunction(item, currentItem);
1569
+ if (res >= 0) {
1570
+ lowIndex = middleIndex + 1;
1571
+ } else {
1572
+ highIndex = middleIndex;
1573
+ }
1574
+ }
1575
+ return lowIndex;
1576
+ }
1577
+ function insert(sortedItems, item, comparisonFunction) {
1578
+ const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
1579
+ sortedItems.splice(insertAtIndex, 0, item);
1580
+ return sortedItems;
1581
+ }
1582
+ function createSortedStateAdapter(selectId, comparer) {
1583
+ const {
1584
+ removeOne,
1585
+ removeMany,
1586
+ removeAll
1587
+ } = createUnsortedStateAdapter(selectId);
1588
+ function addOneMutably(entity, state) {
1589
+ return addManyMutably([entity], state);
1590
+ }
1591
+ function addManyMutably(newEntities, state, existingIds) {
1592
+ newEntities = ensureEntitiesArray(newEntities);
1593
+ const existingKeys = new Set(existingIds ?? getCurrent(state.ids));
1594
+ const addedKeys = /* @__PURE__ */ new Set();
1595
+ const models = newEntities.filter((model) => {
1596
+ const modelId = selectIdValue(model, selectId);
1597
+ const notAdded = !addedKeys.has(modelId);
1598
+ if (notAdded) addedKeys.add(modelId);
1599
+ return !existingKeys.has(modelId) && notAdded;
1600
+ });
1601
+ if (models.length !== 0) {
1602
+ mergeFunction(state, models);
1603
+ }
1604
+ }
1605
+ function setOneMutably(entity, state) {
1606
+ return setManyMutably([entity], state);
1607
+ }
1608
+ function setManyMutably(newEntities, state) {
1609
+ let deduplicatedEntities = {};
1610
+ newEntities = ensureEntitiesArray(newEntities);
1611
+ if (newEntities.length !== 0) {
1612
+ for (const item of newEntities) {
1613
+ const entityId = selectId(item);
1614
+ deduplicatedEntities[entityId] = item;
1615
+ delete state.entities[entityId];
1616
+ }
1617
+ newEntities = ensureEntitiesArray(deduplicatedEntities);
1618
+ mergeFunction(state, newEntities);
1619
+ }
1620
+ }
1621
+ function setAllMutably(newEntities, state) {
1622
+ newEntities = ensureEntitiesArray(newEntities);
1623
+ state.entities = {};
1624
+ state.ids = [];
1625
+ addManyMutably(newEntities, state, []);
1626
+ }
1627
+ function updateOneMutably(update, state) {
1628
+ return updateManyMutably([update], state);
1629
+ }
1630
+ function updateManyMutably(updates, state) {
1631
+ let appliedUpdates = false;
1632
+ let replacedIds = false;
1633
+ for (let update of updates) {
1634
+ const entity = state.entities[update.id];
1635
+ if (!entity) {
1636
+ continue;
1637
+ }
1638
+ appliedUpdates = true;
1639
+ Object.assign(entity, update.changes);
1640
+ const newId = selectId(entity);
1641
+ if (update.id !== newId) {
1642
+ replacedIds = true;
1643
+ delete state.entities[update.id];
1644
+ const oldIndex = state.ids.indexOf(update.id);
1645
+ state.ids[oldIndex] = newId;
1646
+ state.entities[newId] = entity;
1647
+ }
1648
+ }
1649
+ if (appliedUpdates) {
1650
+ mergeFunction(state, [], appliedUpdates, replacedIds);
1651
+ }
1652
+ }
1653
+ function upsertOneMutably(entity, state) {
1654
+ return upsertManyMutably([entity], state);
1655
+ }
1656
+ function upsertManyMutably(newEntities, state) {
1657
+ const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
1658
+ if (added.length) {
1659
+ addManyMutably(added, state, existingIdsArray);
1660
+ }
1661
+ if (updated.length) {
1662
+ updateManyMutably(updated, state);
1663
+ }
1664
+ }
1665
+ function areArraysEqual(a, b) {
1666
+ if (a.length !== b.length) {
1667
+ return false;
1668
+ }
1669
+ for (let i = 0; i < a.length; i++) {
1670
+ if (a[i] === b[i]) {
1671
+ continue;
1672
+ }
1673
+ return false;
1674
+ }
1675
+ return true;
1676
+ }
1677
+ const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {
1678
+ const currentEntities = getCurrent(state.entities);
1679
+ const currentIds = getCurrent(state.ids);
1680
+ const stateEntities = state.entities;
1681
+ let ids = currentIds;
1682
+ if (replacedIds) {
1683
+ ids = new Set(currentIds);
1684
+ }
1685
+ let sortedEntities = [];
1686
+ for (const id of ids) {
1687
+ const entity = currentEntities[id];
1688
+ if (entity) {
1689
+ sortedEntities.push(entity);
1690
+ }
1691
+ }
1692
+ const wasPreviouslyEmpty = sortedEntities.length === 0;
1693
+ for (const item of addedItems) {
1694
+ stateEntities[selectId(item)] = item;
1695
+ if (!wasPreviouslyEmpty) {
1696
+ insert(sortedEntities, item, comparer);
1697
+ }
1698
+ }
1699
+ if (wasPreviouslyEmpty) {
1700
+ sortedEntities = addedItems.slice().sort(comparer);
1701
+ } else if (appliedUpdates) {
1702
+ sortedEntities.sort(comparer);
1703
+ }
1704
+ const newSortedIds = sortedEntities.map(selectId);
1705
+ if (!areArraysEqual(currentIds, newSortedIds)) {
1706
+ state.ids = newSortedIds;
1707
+ }
1708
+ };
1709
+ return {
1710
+ removeOne,
1711
+ removeMany,
1712
+ removeAll,
1713
+ addOne: createStateOperator(addOneMutably),
1714
+ updateOne: createStateOperator(updateOneMutably),
1715
+ upsertOne: createStateOperator(upsertOneMutably),
1716
+ setOne: createStateOperator(setOneMutably),
1717
+ setMany: createStateOperator(setManyMutably),
1718
+ setAll: createStateOperator(setAllMutably),
1719
+ addMany: createStateOperator(addManyMutably),
1720
+ updateMany: createStateOperator(updateManyMutably),
1721
+ upsertMany: createStateOperator(upsertManyMutably)
1722
+ };
1723
+ }
1724
+
1725
+ // src/entities/create_adapter.ts
1726
+ function createEntityAdapter(options = {}) {
1727
+ const {
1728
+ selectId,
1729
+ sortComparer
1730
+ } = {
1731
+ sortComparer: false,
1732
+ selectId: (instance) => instance.id,
1733
+ ...options
1734
+ };
1735
+ const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
1736
+ const stateFactory = createInitialStateFactory(stateAdapter);
1737
+ const selectorsFactory = createSelectorsFactory();
1738
+ return {
1739
+ selectId,
1740
+ sortComparer,
1741
+ ...stateFactory,
1742
+ ...selectorsFactory,
1743
+ ...stateAdapter
1744
+ };
1745
+ }
1746
+
1747
+ // src/listenerMiddleware/exceptions.ts
1748
+ var task = "task";
1749
+ var listener = "listener";
1750
+ var completed = "completed";
1751
+ var cancelled = "cancelled";
1752
+ var taskCancelled = `task-${cancelled}`;
1753
+ var taskCompleted = `task-${completed}`;
1754
+ var listenerCancelled = `${listener}-${cancelled}`;
1755
+ var listenerCompleted = `${listener}-${completed}`;
1756
+ var TaskAbortError = class {
1757
+ constructor(code) {
1758
+ this.code = code;
1759
+ this.message = `${task} ${cancelled} (reason: ${code})`;
1760
+ }
1761
+ code;
1762
+ name = "TaskAbortError";
1763
+ message;
1764
+ };
1765
+
1766
+ // src/listenerMiddleware/utils.ts
1767
+ var assertFunction = (func, expected) => {
1768
+ if (typeof func !== "function") {
1769
+ throw new TypeError(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
1770
+ }
1771
+ };
1772
+ var noop2 = () => {
1773
+ };
1774
+ var catchRejection = (promise, onError = noop2) => {
1775
+ promise.catch(onError);
1776
+ return promise;
1777
+ };
1778
+ var addAbortSignalListener = (abortSignal, callback) => {
1779
+ abortSignal.addEventListener("abort", callback, {
1780
+ once: true
1781
+ });
1782
+ return () => abortSignal.removeEventListener("abort", callback);
1783
+ };
1784
+
1785
+ // src/listenerMiddleware/task.ts
1786
+ var validateActive = (signal) => {
1787
+ if (signal.aborted) {
1788
+ throw new TaskAbortError(signal.reason);
1789
+ }
1790
+ };
1791
+ function raceWithSignal(signal, promise) {
1792
+ let cleanup = noop2;
1793
+ return new Promise((resolve, reject) => {
1794
+ const notifyRejection = () => reject(new TaskAbortError(signal.reason));
1795
+ if (signal.aborted) {
1796
+ notifyRejection();
1797
+ return;
1798
+ }
1799
+ cleanup = addAbortSignalListener(signal, notifyRejection);
1800
+ promise.finally(() => cleanup()).then(resolve, reject);
1801
+ }).finally(() => {
1802
+ cleanup = noop2;
1803
+ });
1804
+ }
1805
+ var runTask = async (task2, cleanUp) => {
1806
+ try {
1807
+ await Promise.resolve();
1808
+ const value = await task2();
1809
+ return {
1810
+ status: "ok",
1811
+ value
1812
+ };
1813
+ } catch (error) {
1814
+ return {
1815
+ status: error instanceof TaskAbortError ? "cancelled" : "rejected",
1816
+ error
1817
+ };
1818
+ } finally {
1819
+ cleanUp?.();
1820
+ }
1821
+ };
1822
+ var createPause = (signal) => {
1823
+ return (promise) => {
1824
+ return catchRejection(raceWithSignal(signal, promise).then((output) => {
1825
+ validateActive(signal);
1826
+ return output;
1827
+ }));
1828
+ };
1829
+ };
1830
+ var createDelay = (signal) => {
1831
+ const pause = createPause(signal);
1832
+ return (timeoutMs) => {
1833
+ return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
1834
+ };
1835
+ };
1836
+
1837
+ // src/listenerMiddleware/index.ts
1838
+ var {
1839
+ assign
1840
+ } = Object;
1841
+ var INTERNAL_NIL_TOKEN = {};
1842
+ var alm = "listenerMiddleware";
1843
+ var createFork = (parentAbortSignal, parentBlockingPromises) => {
1844
+ const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));
1845
+ return (taskExecutor, opts) => {
1846
+ assertFunction(taskExecutor, "taskExecutor");
1847
+ const childAbortController = new AbortController();
1848
+ linkControllers(childAbortController);
1849
+ const result = runTask(async () => {
1850
+ validateActive(parentAbortSignal);
1851
+ validateActive(childAbortController.signal);
1852
+ const result2 = await taskExecutor({
1853
+ pause: createPause(childAbortController.signal),
1854
+ delay: createDelay(childAbortController.signal),
1855
+ signal: childAbortController.signal
1856
+ });
1857
+ validateActive(childAbortController.signal);
1858
+ return result2;
1859
+ }, () => childAbortController.abort(taskCompleted));
1860
+ if (opts?.autoJoin) {
1861
+ parentBlockingPromises.push(result.catch(noop2));
1862
+ }
1863
+ return {
1864
+ result: createPause(parentAbortSignal)(result),
1865
+ cancel() {
1866
+ childAbortController.abort(taskCancelled);
1867
+ }
1868
+ };
1869
+ };
1870
+ };
1871
+ var createTakePattern = (startListening, signal) => {
1872
+ const take = async (predicate, timeout) => {
1873
+ validateActive(signal);
1874
+ let unsubscribe = () => {
1875
+ };
1876
+ const tuplePromise = new Promise((resolve, reject) => {
1877
+ let stopListening = startListening({
1878
+ predicate,
1879
+ effect: (action, listenerApi) => {
1880
+ listenerApi.unsubscribe();
1881
+ resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
1882
+ }
1883
+ });
1884
+ unsubscribe = () => {
1885
+ stopListening();
1886
+ reject();
1887
+ };
1888
+ });
1889
+ const promises = [tuplePromise];
1890
+ if (timeout != null) {
1891
+ promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
1892
+ }
1893
+ try {
1894
+ const output = await raceWithSignal(signal, Promise.race(promises));
1895
+ validateActive(signal);
1896
+ return output;
1897
+ } finally {
1898
+ unsubscribe();
1899
+ }
1900
+ };
1901
+ return ((predicate, timeout) => catchRejection(take(predicate, timeout)));
1902
+ };
1903
+ var getListenerEntryPropsFrom = (options) => {
1904
+ let {
1905
+ type,
1906
+ actionCreator,
1907
+ matcher,
1908
+ predicate,
1909
+ effect
1910
+ } = options;
1911
+ if (type) {
1912
+ predicate = createAction(type).match;
1913
+ } else if (actionCreator) {
1914
+ type = actionCreator.type;
1915
+ predicate = actionCreator.match;
1916
+ } else if (matcher) {
1917
+ predicate = matcher;
1918
+ } else if (predicate) {
1919
+ } else {
1920
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
1921
+ }
1922
+ assertFunction(effect, "options.listener");
1923
+ return {
1924
+ predicate,
1925
+ type,
1926
+ effect
1927
+ };
1928
+ };
1929
+ var createListenerEntry = /* @__PURE__ */ assign((options) => {
1930
+ const {
1931
+ type,
1932
+ predicate,
1933
+ effect
1934
+ } = getListenerEntryPropsFrom(options);
1935
+ const entry = {
1936
+ id: nanoid(),
1937
+ effect,
1938
+ type,
1939
+ predicate,
1940
+ pending: /* @__PURE__ */ new Set(),
1941
+ unsubscribe: () => {
1942
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
1943
+ }
1944
+ };
1945
+ return entry;
1946
+ }, {
1947
+ withTypes: () => createListenerEntry
1948
+ });
1949
+ var findListenerEntry = (listenerMap, options) => {
1950
+ const {
1951
+ type,
1952
+ effect,
1953
+ predicate
1954
+ } = getListenerEntryPropsFrom(options);
1955
+ return Array.from(listenerMap.values()).find((entry) => {
1956
+ const matchPredicateOrType = typeof type === "string" ? entry.type === type : entry.predicate === predicate;
1957
+ return matchPredicateOrType && entry.effect === effect;
1958
+ });
1959
+ };
1960
+ var cancelActiveListeners = (entry) => {
1961
+ entry.pending.forEach((controller) => {
1962
+ controller.abort(listenerCancelled);
1963
+ });
1964
+ };
1965
+ var createClearListenerMiddleware = (listenerMap, executingListeners) => {
1966
+ return () => {
1967
+ for (const listener2 of executingListeners.keys()) {
1968
+ cancelActiveListeners(listener2);
1969
+ }
1970
+ listenerMap.clear();
1971
+ };
1972
+ };
1973
+ var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
1974
+ try {
1975
+ errorHandler(errorToNotify, errorInfo);
1976
+ } catch (errorHandlerError) {
1977
+ setTimeout(() => {
1978
+ throw errorHandlerError;
1979
+ }, 0);
1980
+ }
1981
+ };
1982
+ var addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), {
1983
+ withTypes: () => addListener
1984
+ });
1985
+ var clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
1986
+ var removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), {
1987
+ withTypes: () => removeListener
1988
+ });
1989
+ var defaultErrorHandler = (...args) => {
1990
+ console.error(`${alm}/error`, ...args);
1991
+ };
1992
+ var createListenerMiddleware = (middlewareOptions = {}) => {
1993
+ const listenerMap = /* @__PURE__ */ new Map();
1994
+ const executingListeners = /* @__PURE__ */ new Map();
1995
+ const trackExecutingListener = (entry) => {
1996
+ const count = executingListeners.get(entry) ?? 0;
1997
+ executingListeners.set(entry, count + 1);
1998
+ };
1999
+ const untrackExecutingListener = (entry) => {
2000
+ const count = executingListeners.get(entry) ?? 1;
2001
+ if (count === 1) {
2002
+ executingListeners.delete(entry);
2003
+ } else {
2004
+ executingListeners.set(entry, count - 1);
2005
+ }
2006
+ };
2007
+ const {
2008
+ extra,
2009
+ onError = defaultErrorHandler
2010
+ } = middlewareOptions;
2011
+ assertFunction(onError, "onError");
2012
+ const insertEntry = (entry) => {
2013
+ entry.unsubscribe = () => listenerMap.delete(entry.id);
2014
+ listenerMap.set(entry.id, entry);
2015
+ return (cancelOptions) => {
2016
+ entry.unsubscribe();
2017
+ if (cancelOptions?.cancelActive) {
2018
+ cancelActiveListeners(entry);
2019
+ }
2020
+ };
2021
+ };
2022
+ const startListening = ((options) => {
2023
+ const entry = findListenerEntry(listenerMap, options) ?? createListenerEntry(options);
2024
+ return insertEntry(entry);
2025
+ });
2026
+ assign(startListening, {
2027
+ withTypes: () => startListening
2028
+ });
2029
+ const stopListening = (options) => {
2030
+ const entry = findListenerEntry(listenerMap, options);
2031
+ if (entry) {
2032
+ entry.unsubscribe();
2033
+ if (options.cancelActive) {
2034
+ cancelActiveListeners(entry);
2035
+ }
2036
+ }
2037
+ return !!entry;
2038
+ };
2039
+ assign(stopListening, {
2040
+ withTypes: () => stopListening
2041
+ });
2042
+ const notifyListener = async (entry, action, api, getOriginalState) => {
2043
+ const internalTaskController = new AbortController();
2044
+ const take = createTakePattern(startListening, internalTaskController.signal);
2045
+ const autoJoinPromises = [];
2046
+ try {
2047
+ entry.pending.add(internalTaskController);
2048
+ trackExecutingListener(entry);
2049
+ await Promise.resolve(entry.effect(
2050
+ action,
2051
+ // Use assign() rather than ... to avoid extra helper functions added to bundle
2052
+ assign({}, api, {
2053
+ getOriginalState,
2054
+ condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
2055
+ take,
2056
+ delay: createDelay(internalTaskController.signal),
2057
+ pause: createPause(internalTaskController.signal),
2058
+ extra,
2059
+ signal: internalTaskController.signal,
2060
+ fork: createFork(internalTaskController.signal, autoJoinPromises),
2061
+ unsubscribe: entry.unsubscribe,
2062
+ subscribe: () => {
2063
+ listenerMap.set(entry.id, entry);
2064
+ },
2065
+ cancelActiveListeners: () => {
2066
+ entry.pending.forEach((controller, _, set) => {
2067
+ if (controller !== internalTaskController) {
2068
+ controller.abort(listenerCancelled);
2069
+ set.delete(controller);
2070
+ }
2071
+ });
2072
+ },
2073
+ cancel: () => {
2074
+ internalTaskController.abort(listenerCancelled);
2075
+ entry.pending.delete(internalTaskController);
2076
+ },
2077
+ throwIfCancelled: () => {
2078
+ validateActive(internalTaskController.signal);
2079
+ }
2080
+ })
2081
+ ));
2082
+ } catch (listenerError) {
2083
+ if (!(listenerError instanceof TaskAbortError)) {
2084
+ safelyNotifyError(onError, listenerError, {
2085
+ raisedBy: "effect"
2086
+ });
2087
+ }
2088
+ } finally {
2089
+ await Promise.all(autoJoinPromises);
2090
+ internalTaskController.abort(listenerCompleted);
2091
+ untrackExecutingListener(entry);
2092
+ entry.pending.delete(internalTaskController);
2093
+ }
2094
+ };
2095
+ const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);
2096
+ const middleware = (api) => (next) => (action) => {
2097
+ if (!isAction(action)) {
2098
+ return next(action);
2099
+ }
2100
+ if (addListener.match(action)) {
2101
+ return startListening(action.payload);
2102
+ }
2103
+ if (clearAllListeners.match(action)) {
2104
+ clearListenerMiddleware();
2105
+ return;
2106
+ }
2107
+ if (removeListener.match(action)) {
2108
+ return stopListening(action.payload);
2109
+ }
2110
+ let originalState = api.getState();
2111
+ const getOriginalState = () => {
2112
+ if (originalState === INTERNAL_NIL_TOKEN) {
2113
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
2114
+ }
2115
+ return originalState;
2116
+ };
2117
+ let result;
2118
+ try {
2119
+ result = next(action);
2120
+ if (listenerMap.size > 0) {
2121
+ const currentState = api.getState();
2122
+ const listenerEntries = Array.from(listenerMap.values());
2123
+ for (const entry of listenerEntries) {
2124
+ let runListener = false;
2125
+ try {
2126
+ runListener = entry.predicate(action, currentState, originalState);
2127
+ } catch (predicateError) {
2128
+ runListener = false;
2129
+ safelyNotifyError(onError, predicateError, {
2130
+ raisedBy: "predicate"
2131
+ });
2132
+ }
2133
+ if (!runListener) {
2134
+ continue;
2135
+ }
2136
+ notifyListener(entry, action, api, getOriginalState);
2137
+ }
2138
+ }
2139
+ } finally {
2140
+ originalState = INTERNAL_NIL_TOKEN;
2141
+ }
2142
+ return result;
2143
+ };
2144
+ return {
2145
+ middleware,
2146
+ startListening,
2147
+ stopListening,
2148
+ clearListeners: clearListenerMiddleware
2149
+ };
2150
+ };
2151
+
2152
+ // src/dynamicMiddleware/index.ts
2153
+ var createMiddlewareEntry = (middleware) => ({
2154
+ middleware,
2155
+ applied: /* @__PURE__ */ new Map()
2156
+ });
2157
+ var matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;
2158
+ var createDynamicMiddleware = () => {
2159
+ const instanceId = nanoid();
2160
+ const middlewareMap = /* @__PURE__ */ new Map();
2161
+ const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
2162
+ payload: middlewares,
2163
+ meta: {
2164
+ instanceId
2165
+ }
2166
+ })), {
2167
+ withTypes: () => withMiddleware
2168
+ });
2169
+ const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
2170
+ middlewares.forEach((middleware2) => {
2171
+ getOrInsertComputed(middlewareMap, middleware2, createMiddlewareEntry);
2172
+ });
2173
+ }, {
2174
+ withTypes: () => addMiddleware
2175
+ });
2176
+ const getFinalMiddleware = (api) => {
2177
+ const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => getOrInsertComputed(entry.applied, api, entry.middleware));
2178
+ return compose(...appliedMiddleware);
2179
+ };
2180
+ const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
2181
+ const middleware = (api) => (next) => (action) => {
2182
+ if (isWithMiddleware(action)) {
2183
+ addMiddleware(...action.payload);
2184
+ return api.dispatch;
2185
+ }
2186
+ return getFinalMiddleware(api)(next)(action);
2187
+ };
2188
+ return {
2189
+ middleware,
2190
+ addMiddleware,
2191
+ withMiddleware,
2192
+ instanceId
2193
+ };
2194
+ };
2195
+
2196
+ // src/combineSlices.ts
2197
+ import { combineReducers as combineReducers2 } from "redux";
2198
+ var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
2199
+ var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
2200
+ var ORIGINAL_STATE = /* @__PURE__ */ Symbol.for("rtk-state-proxy-original");
2201
+ var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
2202
+ var stateProxyMap = /* @__PURE__ */ new WeakMap();
2203
+ var createStateProxy = (state, reducerMap, initialStateCache) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {
2204
+ get: (target, prop, receiver) => {
2205
+ if (prop === ORIGINAL_STATE) return target;
2206
+ const result = Reflect.get(target, prop, receiver);
2207
+ if (typeof result === "undefined") {
2208
+ const cached = initialStateCache[prop];
2209
+ if (typeof cached !== "undefined") return cached;
2210
+ const reducer = reducerMap[prop];
2211
+ if (reducer) {
2212
+ const reducerResult = reducer(void 0, {
2213
+ type: nanoid()
2214
+ });
2215
+ if (typeof reducerResult === "undefined") {
2216
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
2217
+ }
2218
+ initialStateCache[prop] = reducerResult;
2219
+ return reducerResult;
2220
+ }
2221
+ }
2222
+ return result;
2223
+ }
2224
+ }));
2225
+ var original = (state) => {
2226
+ if (!isStateProxy(state)) {
2227
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
2228
+ }
2229
+ return state[ORIGINAL_STATE];
2230
+ };
2231
+ var emptyObject = {};
2232
+ var noopReducer = (state = emptyObject) => state;
2233
+ function combineSlices(...slices) {
2234
+ const reducerMap = Object.fromEntries(getReducers(slices));
2235
+ const getReducer = () => Object.keys(reducerMap).length ? combineReducers2(reducerMap) : noopReducer;
2236
+ let reducer = getReducer();
2237
+ function combinedReducer(state, action) {
2238
+ return reducer(state, action);
2239
+ }
2240
+ combinedReducer.withLazyLoadedSlices = () => combinedReducer;
2241
+ const initialStateCache = {};
2242
+ const inject = (slice, config = {}) => {
2243
+ const {
2244
+ reducerPath,
2245
+ reducer: reducerToInject
2246
+ } = slice;
2247
+ const currentReducer = reducerMap[reducerPath];
2248
+ if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
2249
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
2250
+ console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
2251
+ }
2252
+ return combinedReducer;
2253
+ }
2254
+ if (config.overrideExisting && currentReducer !== reducerToInject) {
2255
+ delete initialStateCache[reducerPath];
2256
+ }
2257
+ reducerMap[reducerPath] = reducerToInject;
2258
+ reducer = getReducer();
2259
+ return combinedReducer;
2260
+ };
2261
+ const selector = Object.assign(function makeSelector(selectorFn, selectState) {
2262
+ return function selector2(state, ...args) {
2263
+ return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap, initialStateCache), ...args);
2264
+ };
2265
+ }, {
2266
+ original
2267
+ });
2268
+ return Object.assign(combinedReducer, {
2269
+ inject,
2270
+ selector
2271
+ });
2272
+ }
2273
+
2274
+ // src/formatProdErrorMessage.ts
2275
+ function formatProdErrorMessage(code) {
2276
+ return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
2277
+ }
2278
+ export {
2279
+ ReducerType,
2280
+ SHOULD_AUTOBATCH,
2281
+ TaskAbortError,
2282
+ Tuple,
2283
+ addListener,
2284
+ asyncThunkCreator,
2285
+ autoBatchEnhancer,
2286
+ buildCreateSlice,
2287
+ clearAllListeners,
2288
+ combineSlices,
2289
+ configureStore,
2290
+ createAction,
2291
+ createActionCreatorInvariantMiddleware,
2292
+ createAsyncThunk,
2293
+ createDraftSafeSelector,
2294
+ createDraftSafeSelectorCreator,
2295
+ createDynamicMiddleware,
2296
+ createEntityAdapter,
2297
+ createImmutableStateInvariantMiddleware,
2298
+ createListenerMiddleware,
2299
+ produce as createNextState,
2300
+ createReducer,
2301
+ createSelector,
2302
+ createSelectorCreator,
2303
+ createSerializableStateInvariantMiddleware,
2304
+ createSlice,
2305
+ current,
2306
+ findNonSerializableValue,
2307
+ formatProdErrorMessage,
2308
+ freeze,
2309
+ isActionCreator,
2310
+ isAllOf,
2311
+ isAnyOf,
2312
+ isAsyncThunkAction,
2313
+ isDraft,
2314
+ isFSA as isFluxStandardAction,
2315
+ isFulfilled,
2316
+ isImmutableDefault,
2317
+ isPending,
2318
+ isPlain,
2319
+ isRejected,
2320
+ isRejectedWithValue,
2321
+ lruMemoize,
2322
+ miniSerializeError,
2323
+ nanoid,
2324
+ original2 as original,
2325
+ prepareAutoBatched,
2326
+ removeListener,
2327
+ unwrapResult,
2328
+ weakMapMemoize
2329
+ };
2330
+ //# sourceMappingURL=redux-toolkit.modern.mjs.map