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