@depup/reduxjs__toolkit 2.12.0-depup.29 → 2.13.0-depup.0

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