UNPKG

70.6 kBJavaScriptView Raw
1var __defProp = Object.defineProperty;
2var __defProps = Object.defineProperties;
3var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5var __hasOwnProp = Object.prototype.hasOwnProperty;
6var __propIsEnum = Object.prototype.propertyIsEnumerable;
7var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8var __spreadValues = (a, b) => {
9 for (var prop in b || (b = {}))
10 if (__hasOwnProp.call(b, prop))
11 __defNormalProp(a, prop, b[prop]);
12 if (__getOwnPropSymbols)
13 for (var prop of __getOwnPropSymbols(b)) {
14 if (__propIsEnum.call(b, prop))
15 __defNormalProp(a, prop, b[prop]);
16 }
17 return a;
18};
19var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20// src/index.ts
21import { enableES5 } from "immer";
22export * from "redux";
23import { default as default2, current as current2, freeze, original, isDraft as isDraft4 } from "immer";
24import { createSelector as createSelector2 } from "reselect";
25// src/createDraftSafeSelector.ts
26import { current, isDraft } from "immer";
27import { createSelector } from "reselect";
28var createDraftSafeSelector = (...args) => {
29 const selector = createSelector(...args);
30 const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
31 return wrappedSelector;
32};
33// src/configureStore.ts
34import { createStore, compose as compose2, applyMiddleware, combineReducers } from "redux";
35// src/devtoolsExtension.ts
36import { compose } from "redux";
37var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {
38 if (arguments.length === 0)
39 return void 0;
40 if (typeof arguments[0] === "object")
41 return compose;
42 return compose.apply(null, arguments);
43};
44var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {
45 return function (noop2) {
46 return noop2;
47 };
48};
49// src/isPlainObject.ts
50function isPlainObject(value) {
51 if (typeof value !== "object" || value === null)
52 return false;
53 let proto = Object.getPrototypeOf(value);
54 if (proto === null)
55 return true;
56 let baseProto = proto;
57 while (Object.getPrototypeOf(baseProto) !== null) {
58 baseProto = Object.getPrototypeOf(baseProto);
59 }
60 return proto === baseProto;
61}
62// src/getDefaultMiddleware.ts
63import thunkMiddleware from "redux-thunk";
64// src/tsHelpers.ts
65var hasMatchFunction = (v) => {
66 return v && typeof v.match === "function";
67};
68// src/createAction.ts
69function createAction(type, prepareAction) {
70 function actionCreator(...args) {
71 if (prepareAction) {
72 let prepared = prepareAction(...args);
73 if (!prepared) {
74 throw new Error("prepareAction did not return an object");
75 }
76 return __spreadValues(__spreadValues({
77 type,
78 payload: prepared.payload
79 }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error });
80 }
81 return { type, payload: args[0] };
82 }
83 actionCreator.toString = () => `${type}`;
84 actionCreator.type = type;
85 actionCreator.match = (action) => action.type === type;
86 return actionCreator;
87}
88function isAction(action) {
89 return isPlainObject(action) && "type" in action;
90}
91function isActionCreator(action) {
92 return typeof action === "function" && "type" in action && hasMatchFunction(action);
93}
94function isFSA(action) {
95 return isAction(action) && typeof action.type === "string" && Object.keys(action).every(isValidKey);
96}
97function isValidKey(key) {
98 return ["type", "payload", "error", "meta"].indexOf(key) > -1;
99}
100function getType(actionCreator) {
101 return `${actionCreator}`;
102}
103// src/actionCreatorInvariantMiddleware.ts
104function getMessage(type) {
105 const splitType = type ? `${type}`.split("/") : [];
106 const actionName = splitType[splitType.length - 1] || "actionCreator";
107 return `Detected an action creator with type "${type || "unknown"}" being dispatched.
108Make 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.`;
109}
110function createActionCreatorInvariantMiddleware(options = {}) {
111 if (process.env.NODE_ENV === "production") {
112 return () => (next) => (action) => next(action);
113 }
114 const { isActionCreator: isActionCreator2 = isActionCreator } = options;
115 return () => (next) => (action) => {
116 if (isActionCreator2(action)) {
117 console.warn(getMessage(action.type));
118 }
119 return next(action);
120 };
121}
122// src/utils.ts
123import createNextState, { isDraftable } from "immer";
124function getTimeMeasureUtils(maxDelay, fnName) {
125 let elapsed = 0;
126 return {
127 measureTime(fn) {
128 const started = Date.now();
129 try {
130 return fn();
131 }
132 finally {
133 const finished = Date.now();
134 elapsed += finished - started;
135 }
136 },
137 warnIfExceeded() {
138 if (elapsed > maxDelay) {
139 console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
140If 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.
141It is disabled in production builds, so you don't need to worry about that.`);
142 }
143 }
144 };
145}
146var MiddlewareArray = class extends Array {
147 constructor(...args) {
148 super(...args);
149 Object.setPrototypeOf(this, MiddlewareArray.prototype);
150 }
151 static get [Symbol.species]() {
152 return MiddlewareArray;
153 }
154 concat(...arr) {
155 return super.concat.apply(this, arr);
156 }
157 prepend(...arr) {
158 if (arr.length === 1 && Array.isArray(arr[0])) {
159 return new MiddlewareArray(...arr[0].concat(this));
160 }
161 return new MiddlewareArray(...arr.concat(this));
162 }
163};
164var EnhancerArray = class extends Array {
165 constructor(...args) {
166 super(...args);
167 Object.setPrototypeOf(this, EnhancerArray.prototype);
168 }
169 static get [Symbol.species]() {
170 return EnhancerArray;
171 }
172 concat(...arr) {
173 return super.concat.apply(this, arr);
174 }
175 prepend(...arr) {
176 if (arr.length === 1 && Array.isArray(arr[0])) {
177 return new EnhancerArray(...arr[0].concat(this));
178 }
179 return new EnhancerArray(...arr.concat(this));
180 }
181};
182function freezeDraftable(val) {
183 return isDraftable(val) ? createNextState(val, () => {
184 }) : val;
185}
186// src/immutableStateInvariantMiddleware.ts
187var isProduction = process.env.NODE_ENV === "production";
188var prefix = "Invariant failed";
189function invariant(condition, message) {
190 if (condition) {
191 return;
192 }
193 if (isProduction) {
194 throw new Error(prefix);
195 }
196 throw new Error(`${prefix}: ${message || ""}`);
197}
198function stringify(obj, serializer, indent, decycler) {
199 return JSON.stringify(obj, getSerialize(serializer, decycler), indent);
200}
201function getSerialize(serializer, decycler) {
202 let stack = [], keys = [];
203 if (!decycler)
204 decycler = function (_, value) {
205 if (stack[0] === value)
206 return "[Circular ~]";
207 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
208 };
209 return function (key, value) {
210 if (stack.length > 0) {
211 var thisPos = stack.indexOf(this);
212 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
213 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
214 if (~stack.indexOf(value))
215 value = decycler.call(this, key, value);
216 }
217 else
218 stack.push(value);
219 return serializer == null ? value : serializer.call(this, key, value);
220 };
221}
222function isImmutableDefault(value) {
223 return typeof value !== "object" || value == null || Object.isFrozen(value);
224}
225function trackForMutations(isImmutable, ignorePaths, obj) {
226 const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
227 return {
228 detectMutations() {
229 return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
230 }
231 };
232}
233function trackProperties(isImmutable, ignorePaths = [], obj, path = "", checkedObjects = new Set()) {
234 const tracked = { value: obj };
235 if (!isImmutable(obj) && !checkedObjects.has(obj)) {
236 checkedObjects.add(obj);
237 tracked.children = {};
238 for (const key in obj) {
239 const childPath = path ? path + "." + key : key;
240 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
241 continue;
242 }
243 tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
244 }
245 }
246 return tracked;
247}
248function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
249 const prevObj = trackedProperty ? trackedProperty.value : void 0;
250 const sameRef = prevObj === obj;
251 if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
252 return { wasMutated: true, path };
253 }
254 if (isImmutable(prevObj) || isImmutable(obj)) {
255 return { wasMutated: false };
256 }
257 const keysToDetect = {};
258 for (let key in trackedProperty.children) {
259 keysToDetect[key] = true;
260 }
261 for (let key in obj) {
262 keysToDetect[key] = true;
263 }
264 const hasIgnoredPaths = ignoredPaths.length > 0;
265 for (let key in keysToDetect) {
266 const nestedPath = path ? path + "." + key : key;
267 if (hasIgnoredPaths) {
268 const hasMatches = ignoredPaths.some((ignored) => {
269 if (ignored instanceof RegExp) {
270 return ignored.test(nestedPath);
271 }
272 return nestedPath === ignored;
273 });
274 if (hasMatches) {
275 continue;
276 }
277 }
278 const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
279 if (result.wasMutated) {
280 return result;
281 }
282 }
283 return { wasMutated: false };
284}
285function createImmutableStateInvariantMiddleware(options = {}) {
286 if (process.env.NODE_ENV === "production") {
287 return () => (next) => (action) => next(action);
288 }
289 let { isImmutable = isImmutableDefault, ignoredPaths, warnAfter = 32, ignore } = options;
290 ignoredPaths = ignoredPaths || ignore;
291 const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
292 return ({ getState }) => {
293 let state = getState();
294 let tracker = track(state);
295 let result;
296 return (next) => (action) => {
297 const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
298 measureUtils.measureTime(() => {
299 state = getState();
300 result = tracker.detectMutations();
301 tracker = track(state);
302 invariant(!result.wasMutated, `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)`);
303 });
304 const dispatchedAction = next(action);
305 measureUtils.measureTime(() => {
306 state = getState();
307 result = tracker.detectMutations();
308 tracker = track(state);
309 result.wasMutated && invariant(!result.wasMutated, `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)`);
310 });
311 measureUtils.warnIfExceeded();
312 return dispatchedAction;
313 };
314 };
315}
316// src/serializableStateInvariantMiddleware.ts
317function isPlain(val) {
318 const type = typeof val;
319 return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
320}
321function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
322 let foundNestedSerializable;
323 if (!isSerializable(value)) {
324 return {
325 keyPath: path || "<root>",
326 value
327 };
328 }
329 if (typeof value !== "object" || value === null) {
330 return false;
331 }
332 if (cache == null ? void 0 : cache.has(value))
333 return false;
334 const entries = getEntries != null ? getEntries(value) : Object.entries(value);
335 const hasIgnoredPaths = ignoredPaths.length > 0;
336 for (const [key, nestedValue] of entries) {
337 const nestedPath = path ? path + "." + key : key;
338 if (hasIgnoredPaths) {
339 const hasMatches = ignoredPaths.some((ignored) => {
340 if (ignored instanceof RegExp) {
341 return ignored.test(nestedPath);
342 }
343 return nestedPath === ignored;
344 });
345 if (hasMatches) {
346 continue;
347 }
348 }
349 if (!isSerializable(nestedValue)) {
350 return {
351 keyPath: nestedPath,
352 value: nestedValue
353 };
354 }
355 if (typeof nestedValue === "object") {
356 foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
357 if (foundNestedSerializable) {
358 return foundNestedSerializable;
359 }
360 }
361 }
362 if (cache && isNestedFrozen(value))
363 cache.add(value);
364 return false;
365}
366function isNestedFrozen(value) {
367 if (!Object.isFrozen(value))
368 return false;
369 for (const nestedValue of Object.values(value)) {
370 if (typeof nestedValue !== "object" || nestedValue === null)
371 continue;
372 if (!isNestedFrozen(nestedValue))
373 return false;
374 }
375 return true;
376}
377function createSerializableStateInvariantMiddleware(options = {}) {
378 if (process.env.NODE_ENV === "production") {
379 return () => (next) => (action) => next(action);
380 }
381 const { isSerializable = isPlain, getEntries, ignoredActions = [], ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"], ignoredPaths = [], warnAfter = 32, ignoreState = false, ignoreActions = false, disableCache = false } = options;
382 const cache = !disableCache && WeakSet ? new WeakSet() : void 0;
383 return (storeAPI) => (next) => (action) => {
384 const result = next(action);
385 const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
386 if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
387 measureUtils.measureTime(() => {
388 const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
389 if (foundActionNonSerializableValue) {
390 const { keyPath, value } = foundActionNonSerializableValue;
391 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)");
392 }
393 });
394 }
395 if (!ignoreState) {
396 measureUtils.measureTime(() => {
397 const state = storeAPI.getState();
398 const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
399 if (foundStateNonSerializableValue) {
400 const { keyPath, value } = foundStateNonSerializableValue;
401 console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
402Take a look at the reducer(s) handling this action type: ${action.type}.
403(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
404 }
405 });
406 measureUtils.warnIfExceeded();
407 }
408 return result;
409 };
410}
411// src/getDefaultMiddleware.ts
412function isBoolean(x) {
413 return typeof x === "boolean";
414}
415function curryGetDefaultMiddleware() {
416 return function curriedGetDefaultMiddleware(options) {
417 return getDefaultMiddleware(options);
418 };
419}
420function getDefaultMiddleware(options = {}) {
421 const { thunk = true, immutableCheck = true, serializableCheck = true, actionCreatorCheck = true } = options;
422 let middlewareArray = new MiddlewareArray();
423 if (thunk) {
424 if (isBoolean(thunk)) {
425 middlewareArray.push(thunkMiddleware);
426 }
427 else {
428 middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));
429 }
430 }
431 if (process.env.NODE_ENV !== "production") {
432 if (immutableCheck) {
433 let immutableOptions = {};
434 if (!isBoolean(immutableCheck)) {
435 immutableOptions = immutableCheck;
436 }
437 middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
438 }
439 if (serializableCheck) {
440 let serializableOptions = {};
441 if (!isBoolean(serializableCheck)) {
442 serializableOptions = serializableCheck;
443 }
444 middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
445 }
446 if (actionCreatorCheck) {
447 let actionCreatorOptions = {};
448 if (!isBoolean(actionCreatorCheck)) {
449 actionCreatorOptions = actionCreatorCheck;
450 }
451 middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
452 }
453 }
454 return middlewareArray;
455}
456// src/configureStore.ts
457var IS_PRODUCTION = process.env.NODE_ENV === "production";
458function configureStore(options) {
459 const curriedGetDefaultMiddleware = curryGetDefaultMiddleware();
460 const { reducer = void 0, middleware = curriedGetDefaultMiddleware(), devTools = true, preloadedState = void 0, enhancers = void 0 } = options || {};
461 let rootReducer;
462 if (typeof reducer === "function") {
463 rootReducer = reducer;
464 }
465 else if (isPlainObject(reducer)) {
466 rootReducer = combineReducers(reducer);
467 }
468 else {
469 throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');
470 }
471 let finalMiddleware = middleware;
472 if (typeof finalMiddleware === "function") {
473 finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);
474 if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
475 throw new Error("when using a middleware builder function, an array of middleware must be returned");
476 }
477 }
478 if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== "function")) {
479 throw new Error("each middleware provided to configureStore must be a function");
480 }
481 const middlewareEnhancer = applyMiddleware(...finalMiddleware);
482 let finalCompose = compose2;
483 if (devTools) {
484 finalCompose = composeWithDevTools(__spreadValues({
485 trace: !IS_PRODUCTION
486 }, typeof devTools === "object" && devTools));
487 }
488 const defaultEnhancers = new EnhancerArray(middlewareEnhancer);
489 let storeEnhancers = defaultEnhancers;
490 if (Array.isArray(enhancers)) {
491 storeEnhancers = [middlewareEnhancer, ...enhancers];
492 }
493 else if (typeof enhancers === "function") {
494 storeEnhancers = enhancers(defaultEnhancers);
495 }
496 const composedEnhancer = finalCompose(...storeEnhancers);
497 return createStore(rootReducer, preloadedState, composedEnhancer);
498}
499// src/createReducer.ts
500import createNextState2, { isDraft as isDraft2, isDraftable as isDraftable2 } from "immer";
501// src/mapBuilders.ts
502function executeReducerBuilderCallback(builderCallback) {
503 const actionsMap = {};
504 const actionMatchers = [];
505 let defaultCaseReducer;
506 const builder = {
507 addCase(typeOrActionCreator, reducer) {
508 if (process.env.NODE_ENV !== "production") {
509 if (actionMatchers.length > 0) {
510 throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");
511 }
512 if (defaultCaseReducer) {
513 throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");
514 }
515 }
516 const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
517 if (!type) {
518 throw new Error("`builder.addCase` cannot be called with an empty action type");
519 }
520 if (type in actionsMap) {
521 throw new Error("`builder.addCase` cannot be called with two reducers for the same action type");
522 }
523 actionsMap[type] = reducer;
524 return builder;
525 },
526 addMatcher(matcher, reducer) {
527 if (process.env.NODE_ENV !== "production") {
528 if (defaultCaseReducer) {
529 throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
530 }
531 }
532 actionMatchers.push({ matcher, reducer });
533 return builder;
534 },
535 addDefaultCase(reducer) {
536 if (process.env.NODE_ENV !== "production") {
537 if (defaultCaseReducer) {
538 throw new Error("`builder.addDefaultCase` can only be called once");
539 }
540 }
541 defaultCaseReducer = reducer;
542 return builder;
543 }
544 };
545 builderCallback(builder);
546 return [actionsMap, actionMatchers, defaultCaseReducer];
547}
548// src/createReducer.ts
549function isStateFunction(x) {
550 return typeof x === "function";
551}
552var hasWarnedAboutObjectNotation = false;
553function createReducer(initialState, mapOrBuilderCallback, actionMatchers = [], defaultCaseReducer) {
554 if (process.env.NODE_ENV !== "production") {
555 if (typeof mapOrBuilderCallback === "object") {
556 if (!hasWarnedAboutObjectNotation) {
557 hasWarnedAboutObjectNotation = true;
558 console.warn("The object notation for `createReducer` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
559 }
560 }
561 }
562 let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer];
563 let getInitialState;
564 if (isStateFunction(initialState)) {
565 getInitialState = () => freezeDraftable(initialState());
566 }
567 else {
568 const frozenInitialState = freezeDraftable(initialState);
569 getInitialState = () => frozenInitialState;
570 }
571 function reducer(state = getInitialState(), action) {
572 let caseReducers = [
573 actionsMap[action.type],
574 ...finalActionMatchers.filter(({ matcher }) => matcher(action)).map(({ reducer: reducer2 }) => reducer2)
575 ];
576 if (caseReducers.filter((cr) => !!cr).length === 0) {
577 caseReducers = [finalDefaultCaseReducer];
578 }
579 return caseReducers.reduce((previousState, caseReducer) => {
580 if (caseReducer) {
581 if (isDraft2(previousState)) {
582 const draft = previousState;
583 const result = caseReducer(draft, action);
584 if (result === void 0) {
585 return previousState;
586 }
587 return result;
588 }
589 else if (!isDraftable2(previousState)) {
590 const result = caseReducer(previousState, action);
591 if (result === void 0) {
592 if (previousState === null) {
593 return previousState;
594 }
595 throw Error("A case reducer on a non-draftable value must not return undefined");
596 }
597 return result;
598 }
599 else {
600 return createNextState2(previousState, (draft) => {
601 return caseReducer(draft, action);
602 });
603 }
604 }
605 return previousState;
606 }, state);
607 }
608 reducer.getInitialState = getInitialState;
609 return reducer;
610}
611// src/createSlice.ts
612var hasWarnedAboutObjectNotation2 = false;
613function getType2(slice, actionKey) {
614 return `${slice}/${actionKey}`;
615}
616function createSlice(options) {
617 const { name } = options;
618 if (!name) {
619 throw new Error("`name` is a required option for createSlice");
620 }
621 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
622 if (options.initialState === void 0) {
623 console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
624 }
625 }
626 const initialState = typeof options.initialState == "function" ? options.initialState : freezeDraftable(options.initialState);
627 const reducers = options.reducers || {};
628 const reducerNames = Object.keys(reducers);
629 const sliceCaseReducersByName = {};
630 const sliceCaseReducersByType = {};
631 const actionCreators = {};
632 reducerNames.forEach((reducerName) => {
633 const maybeReducerWithPrepare = reducers[reducerName];
634 const type = getType2(name, reducerName);
635 let caseReducer;
636 let prepareCallback;
637 if ("reducer" in maybeReducerWithPrepare) {
638 caseReducer = maybeReducerWithPrepare.reducer;
639 prepareCallback = maybeReducerWithPrepare.prepare;
640 }
641 else {
642 caseReducer = maybeReducerWithPrepare;
643 }
644 sliceCaseReducersByName[reducerName] = caseReducer;
645 sliceCaseReducersByType[type] = caseReducer;
646 actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);
647 });
648 function buildReducer() {
649 if (process.env.NODE_ENV !== "production") {
650 if (typeof options.extraReducers === "object") {
651 if (!hasWarnedAboutObjectNotation2) {
652 hasWarnedAboutObjectNotation2 = true;
653 console.warn("The object notation for `createSlice.extraReducers` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
654 }
655 }
656 }
657 const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
658 const finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);
659 return createReducer(initialState, (builder) => {
660 for (let key in finalCaseReducers) {
661 builder.addCase(key, finalCaseReducers[key]);
662 }
663 for (let m of actionMatchers) {
664 builder.addMatcher(m.matcher, m.reducer);
665 }
666 if (defaultCaseReducer) {
667 builder.addDefaultCase(defaultCaseReducer);
668 }
669 });
670 }
671 let _reducer;
672 return {
673 name,
674 reducer(state, action) {
675 if (!_reducer)
676 _reducer = buildReducer();
677 return _reducer(state, action);
678 },
679 actions: actionCreators,
680 caseReducers: sliceCaseReducersByName,
681 getInitialState() {
682 if (!_reducer)
683 _reducer = buildReducer();
684 return _reducer.getInitialState();
685 }
686 };
687}
688// src/entities/entity_state.ts
689function getInitialEntityState() {
690 return {
691 ids: [],
692 entities: {}
693 };
694}
695function createInitialStateFactory() {
696 function getInitialState(additionalState = {}) {
697 return Object.assign(getInitialEntityState(), additionalState);
698 }
699 return { getInitialState };
700}
701// src/entities/state_selectors.ts
702function createSelectorsFactory() {
703 function getSelectors(selectState) {
704 const selectIds = (state) => state.ids;
705 const selectEntities = (state) => state.entities;
706 const selectAll = createDraftSafeSelector(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
707 const selectId = (_, id) => id;
708 const selectById = (entities, id) => entities[id];
709 const selectTotal = createDraftSafeSelector(selectIds, (ids) => ids.length);
710 if (!selectState) {
711 return {
712 selectIds,
713 selectEntities,
714 selectAll,
715 selectTotal,
716 selectById: createDraftSafeSelector(selectEntities, selectId, selectById)
717 };
718 }
719 const selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);
720 return {
721 selectIds: createDraftSafeSelector(selectState, selectIds),
722 selectEntities: selectGlobalizedEntities,
723 selectAll: createDraftSafeSelector(selectState, selectAll),
724 selectTotal: createDraftSafeSelector(selectState, selectTotal),
725 selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)
726 };
727 }
728 return { getSelectors };
729}
730// src/entities/state_adapter.ts
731import createNextState3, { isDraft as isDraft3 } from "immer";
732function createSingleArgumentStateOperator(mutator) {
733 const operator = createStateOperator((_, state) => mutator(state));
734 return function operation(state) {
735 return operator(state, void 0);
736 };
737}
738function createStateOperator(mutator) {
739 return function operation(state, arg) {
740 function isPayloadActionArgument(arg2) {
741 return isFSA(arg2);
742 }
743 const runMutator = (draft) => {
744 if (isPayloadActionArgument(arg)) {
745 mutator(arg.payload, draft);
746 }
747 else {
748 mutator(arg, draft);
749 }
750 };
751 if (isDraft3(state)) {
752 runMutator(state);
753 return state;
754 }
755 else {
756 return createNextState3(state, runMutator);
757 }
758 };
759}
760// src/entities/utils.ts
761function selectIdValue(entity, selectId) {
762 const key = selectId(entity);
763 if (process.env.NODE_ENV !== "production" && key === void 0) {
764 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());
765 }
766 return key;
767}
768function ensureEntitiesArray(entities) {
769 if (!Array.isArray(entities)) {
770 entities = Object.values(entities);
771 }
772 return entities;
773}
774function splitAddedUpdatedEntities(newEntities, selectId, state) {
775 newEntities = ensureEntitiesArray(newEntities);
776 const added = [];
777 const updated = [];
778 for (const entity of newEntities) {
779 const id = selectIdValue(entity, selectId);
780 if (id in state.entities) {
781 updated.push({ id, changes: entity });
782 }
783 else {
784 added.push(entity);
785 }
786 }
787 return [added, updated];
788}
789// src/entities/unsorted_state_adapter.ts
790function createUnsortedStateAdapter(selectId) {
791 function addOneMutably(entity, state) {
792 const key = selectIdValue(entity, selectId);
793 if (key in state.entities) {
794 return;
795 }
796 state.ids.push(key);
797 state.entities[key] = entity;
798 }
799 function addManyMutably(newEntities, state) {
800 newEntities = ensureEntitiesArray(newEntities);
801 for (const entity of newEntities) {
802 addOneMutably(entity, state);
803 }
804 }
805 function setOneMutably(entity, state) {
806 const key = selectIdValue(entity, selectId);
807 if (!(key in state.entities)) {
808 state.ids.push(key);
809 }
810 state.entities[key] = entity;
811 }
812 function setManyMutably(newEntities, state) {
813 newEntities = ensureEntitiesArray(newEntities);
814 for (const entity of newEntities) {
815 setOneMutably(entity, state);
816 }
817 }
818 function setAllMutably(newEntities, state) {
819 newEntities = ensureEntitiesArray(newEntities);
820 state.ids = [];
821 state.entities = {};
822 addManyMutably(newEntities, state);
823 }
824 function removeOneMutably(key, state) {
825 return removeManyMutably([key], state);
826 }
827 function removeManyMutably(keys, state) {
828 let didMutate = false;
829 keys.forEach((key) => {
830 if (key in state.entities) {
831 delete state.entities[key];
832 didMutate = true;
833 }
834 });
835 if (didMutate) {
836 state.ids = state.ids.filter((id) => id in state.entities);
837 }
838 }
839 function removeAllMutably(state) {
840 Object.assign(state, {
841 ids: [],
842 entities: {}
843 });
844 }
845 function takeNewKey(keys, update, state) {
846 const original2 = state.entities[update.id];
847 const updated = Object.assign({}, original2, update.changes);
848 const newKey = selectIdValue(updated, selectId);
849 const hasNewKey = newKey !== update.id;
850 if (hasNewKey) {
851 keys[update.id] = newKey;
852 delete state.entities[update.id];
853 }
854 state.entities[newKey] = updated;
855 return hasNewKey;
856 }
857 function updateOneMutably(update, state) {
858 return updateManyMutably([update], state);
859 }
860 function updateManyMutably(updates, state) {
861 const newKeys = {};
862 const updatesPerEntity = {};
863 updates.forEach((update) => {
864 if (update.id in state.entities) {
865 updatesPerEntity[update.id] = {
866 id: update.id,
867 changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)
868 };
869 }
870 });
871 updates = Object.values(updatesPerEntity);
872 const didMutateEntities = updates.length > 0;
873 if (didMutateEntities) {
874 const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
875 if (didMutateIds) {
876 state.ids = Object.keys(state.entities);
877 }
878 }
879 }
880 function upsertOneMutably(entity, state) {
881 return upsertManyMutably([entity], state);
882 }
883 function upsertManyMutably(newEntities, state) {
884 const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
885 updateManyMutably(updated, state);
886 addManyMutably(added, state);
887 }
888 return {
889 removeAll: createSingleArgumentStateOperator(removeAllMutably),
890 addOne: createStateOperator(addOneMutably),
891 addMany: createStateOperator(addManyMutably),
892 setOne: createStateOperator(setOneMutably),
893 setMany: createStateOperator(setManyMutably),
894 setAll: createStateOperator(setAllMutably),
895 updateOne: createStateOperator(updateOneMutably),
896 updateMany: createStateOperator(updateManyMutably),
897 upsertOne: createStateOperator(upsertOneMutably),
898 upsertMany: createStateOperator(upsertManyMutably),
899 removeOne: createStateOperator(removeOneMutably),
900 removeMany: createStateOperator(removeManyMutably)
901 };
902}
903// src/entities/sorted_state_adapter.ts
904function createSortedStateAdapter(selectId, sort) {
905 const { removeOne, removeMany, removeAll } = createUnsortedStateAdapter(selectId);
906 function addOneMutably(entity, state) {
907 return addManyMutably([entity], state);
908 }
909 function addManyMutably(newEntities, state) {
910 newEntities = ensureEntitiesArray(newEntities);
911 const models = newEntities.filter((model) => !(selectIdValue(model, selectId) in state.entities));
912 if (models.length !== 0) {
913 merge(models, state);
914 }
915 }
916 function setOneMutably(entity, state) {
917 return setManyMutably([entity], state);
918 }
919 function setManyMutably(newEntities, state) {
920 newEntities = ensureEntitiesArray(newEntities);
921 if (newEntities.length !== 0) {
922 merge(newEntities, state);
923 }
924 }
925 function setAllMutably(newEntities, state) {
926 newEntities = ensureEntitiesArray(newEntities);
927 state.entities = {};
928 state.ids = [];
929 addManyMutably(newEntities, state);
930 }
931 function updateOneMutably(update, state) {
932 return updateManyMutably([update], state);
933 }
934 function updateManyMutably(updates, state) {
935 let appliedUpdates = false;
936 for (let update of updates) {
937 const entity = state.entities[update.id];
938 if (!entity) {
939 continue;
940 }
941 appliedUpdates = true;
942 Object.assign(entity, update.changes);
943 const newId = selectId(entity);
944 if (update.id !== newId) {
945 delete state.entities[update.id];
946 state.entities[newId] = entity;
947 }
948 }
949 if (appliedUpdates) {
950 resortEntities(state);
951 }
952 }
953 function upsertOneMutably(entity, state) {
954 return upsertManyMutably([entity], state);
955 }
956 function upsertManyMutably(newEntities, state) {
957 const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
958 updateManyMutably(updated, state);
959 addManyMutably(added, state);
960 }
961 function areArraysEqual(a, b) {
962 if (a.length !== b.length) {
963 return false;
964 }
965 for (let i = 0; i < a.length && i < b.length; i++) {
966 if (a[i] === b[i]) {
967 continue;
968 }
969 return false;
970 }
971 return true;
972 }
973 function merge(models, state) {
974 models.forEach((model) => {
975 state.entities[selectId(model)] = model;
976 });
977 resortEntities(state);
978 }
979 function resortEntities(state) {
980 const allEntities = Object.values(state.entities);
981 allEntities.sort(sort);
982 const newSortedIds = allEntities.map(selectId);
983 const { ids } = state;
984 if (!areArraysEqual(ids, newSortedIds)) {
985 state.ids = newSortedIds;
986 }
987 }
988 return {
989 removeOne,
990 removeMany,
991 removeAll,
992 addOne: createStateOperator(addOneMutably),
993 updateOne: createStateOperator(updateOneMutably),
994 upsertOne: createStateOperator(upsertOneMutably),
995 setOne: createStateOperator(setOneMutably),
996 setMany: createStateOperator(setManyMutably),
997 setAll: createStateOperator(setAllMutably),
998 addMany: createStateOperator(addManyMutably),
999 updateMany: createStateOperator(updateManyMutably),
1000 upsertMany: createStateOperator(upsertManyMutably)
1001 };
1002}
1003// src/entities/create_adapter.ts
1004function createEntityAdapter(options = {}) {
1005 const { selectId, sortComparer } = __spreadValues({
1006 sortComparer: false,
1007 selectId: (instance) => instance.id
1008 }, options);
1009 const stateFactory = createInitialStateFactory();
1010 const selectorsFactory = createSelectorsFactory();
1011 const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
1012 return __spreadValues(__spreadValues(__spreadValues({
1013 selectId,
1014 sortComparer
1015 }, stateFactory), selectorsFactory), stateAdapter);
1016}
1017// src/nanoid.ts
1018var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
1019var nanoid = (size = 21) => {
1020 let id = "";
1021 let i = size;
1022 while (i--) {
1023 id += urlAlphabet[Math.random() * 64 | 0];
1024 }
1025 return id;
1026};
1027// src/createAsyncThunk.ts
1028var commonProperties = [
1029 "name",
1030 "message",
1031 "stack",
1032 "code"
1033];
1034var RejectWithValue = class {
1035 constructor(payload, meta) {
1036 this.payload = payload;
1037 this.meta = meta;
1038 }
1039};
1040var FulfillWithMeta = class {
1041 constructor(payload, meta) {
1042 this.payload = payload;
1043 this.meta = meta;
1044 }
1045};
1046var miniSerializeError = (value) => {
1047 if (typeof value === "object" && value !== null) {
1048 const simpleError = {};
1049 for (const property of commonProperties) {
1050 if (typeof value[property] === "string") {
1051 simpleError[property] = value[property];
1052 }
1053 }
1054 return simpleError;
1055 }
1056 return { message: String(value) };
1057};
1058var createAsyncThunk = (() => {
1059 function createAsyncThunk2(typePrefix, payloadCreator, options) {
1060 const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
1061 payload,
1062 meta: __spreadProps(__spreadValues({}, meta || {}), {
1063 arg,
1064 requestId,
1065 requestStatus: "fulfilled"
1066 })
1067 }));
1068 const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
1069 payload: void 0,
1070 meta: __spreadProps(__spreadValues({}, meta || {}), {
1071 arg,
1072 requestId,
1073 requestStatus: "pending"
1074 })
1075 }));
1076 const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
1077 payload,
1078 error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
1079 meta: __spreadProps(__spreadValues({}, meta || {}), {
1080 arg,
1081 requestId,
1082 rejectedWithValue: !!payload,
1083 requestStatus: "rejected",
1084 aborted: (error == null ? void 0 : error.name) === "AbortError",
1085 condition: (error == null ? void 0 : error.name) === "ConditionError"
1086 })
1087 }));
1088 let displayedWarning = false;
1089 const AC = typeof AbortController !== "undefined" ? AbortController : class {
1090 constructor() {
1091 this.signal = {
1092 aborted: false,
1093 addEventListener() {
1094 },
1095 dispatchEvent() {
1096 return false;
1097 },
1098 onabort() {
1099 },
1100 removeEventListener() {
1101 },
1102 reason: void 0,
1103 throwIfAborted() {
1104 }
1105 };
1106 }
1107 abort() {
1108 if (process.env.NODE_ENV !== "production") {
1109 if (!displayedWarning) {
1110 displayedWarning = true;
1111 console.info(`This platform does not implement AbortController.
1112If you want to use the AbortController to react to \`abort\` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.`);
1113 }
1114 }
1115 }
1116 };
1117 function actionCreator(arg) {
1118 return (dispatch, getState, extra) => {
1119 const requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
1120 const abortController = new AC();
1121 let abortReason;
1122 let started = false;
1123 function abort(reason) {
1124 abortReason = reason;
1125 abortController.abort();
1126 }
1127 const promise2 = async function () {
1128 var _a, _b;
1129 let finalAction;
1130 try {
1131 let conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState, extra });
1132 if (isThenable(conditionResult)) {
1133 conditionResult = await conditionResult;
1134 }
1135 if (conditionResult === false || abortController.signal.aborted) {
1136 throw {
1137 name: "ConditionError",
1138 message: "Aborted due to condition callback returning false."
1139 };
1140 }
1141 started = true;
1142 const abortedPromise = new Promise((_, reject) => abortController.signal.addEventListener("abort", () => reject({
1143 name: "AbortError",
1144 message: abortReason || "Aborted"
1145 })));
1146 dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, { requestId, arg }, { getState, extra })));
1147 finalAction = await Promise.race([
1148 abortedPromise,
1149 Promise.resolve(payloadCreator(arg, {
1150 dispatch,
1151 getState,
1152 extra,
1153 requestId,
1154 signal: abortController.signal,
1155 abort,
1156 rejectWithValue: (value, meta) => {
1157 return new RejectWithValue(value, meta);
1158 },
1159 fulfillWithValue: (value, meta) => {
1160 return new FulfillWithMeta(value, meta);
1161 }
1162 })).then((result) => {
1163 if (result instanceof RejectWithValue) {
1164 throw result;
1165 }
1166 if (result instanceof FulfillWithMeta) {
1167 return fulfilled(result.payload, requestId, arg, result.meta);
1168 }
1169 return fulfilled(result, requestId, arg);
1170 })
1171 ]);
1172 }
1173 catch (err) {
1174 finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
1175 }
1176 const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
1177 if (!skipDispatch) {
1178 dispatch(finalAction);
1179 }
1180 return finalAction;
1181 }();
1182 return Object.assign(promise2, {
1183 abort,
1184 requestId,
1185 arg,
1186 unwrap() {
1187 return promise2.then(unwrapResult);
1188 }
1189 });
1190 };
1191 }
1192 return Object.assign(actionCreator, {
1193 pending,
1194 rejected,
1195 fulfilled,
1196 typePrefix
1197 });
1198 }
1199 createAsyncThunk2.withTypes = () => createAsyncThunk2;
1200 return createAsyncThunk2;
1201})();
1202function unwrapResult(action) {
1203 if (action.meta && action.meta.rejectedWithValue) {
1204 throw action.payload;
1205 }
1206 if (action.error) {
1207 throw action.error;
1208 }
1209 return action.payload;
1210}
1211function isThenable(value) {
1212 return value !== null && typeof value === "object" && typeof value.then === "function";
1213}
1214// src/matchers.ts
1215var matches = (matcher, action) => {
1216 if (hasMatchFunction(matcher)) {
1217 return matcher.match(action);
1218 }
1219 else {
1220 return matcher(action);
1221 }
1222};
1223function isAnyOf(...matchers) {
1224 return (action) => {
1225 return matchers.some((matcher) => matches(matcher, action));
1226 };
1227}
1228function isAllOf(...matchers) {
1229 return (action) => {
1230 return matchers.every((matcher) => matches(matcher, action));
1231 };
1232}
1233function hasExpectedRequestMetadata(action, validStatus) {
1234 if (!action || !action.meta)
1235 return false;
1236 const hasValidRequestId = typeof action.meta.requestId === "string";
1237 const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
1238 return hasValidRequestId && hasValidRequestStatus;
1239}
1240function isAsyncThunkArray(a) {
1241 return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
1242}
1243function isPending(...asyncThunks) {
1244 if (asyncThunks.length === 0) {
1245 return (action) => hasExpectedRequestMetadata(action, ["pending"]);
1246 }
1247 if (!isAsyncThunkArray(asyncThunks)) {
1248 return isPending()(asyncThunks[0]);
1249 }
1250 return (action) => {
1251 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.pending);
1252 const combinedMatcher = isAnyOf(...matchers);
1253 return combinedMatcher(action);
1254 };
1255}
1256function isRejected(...asyncThunks) {
1257 if (asyncThunks.length === 0) {
1258 return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
1259 }
1260 if (!isAsyncThunkArray(asyncThunks)) {
1261 return isRejected()(asyncThunks[0]);
1262 }
1263 return (action) => {
1264 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.rejected);
1265 const combinedMatcher = isAnyOf(...matchers);
1266 return combinedMatcher(action);
1267 };
1268}
1269function isRejectedWithValue(...asyncThunks) {
1270 const hasFlag = (action) => {
1271 return action && action.meta && action.meta.rejectedWithValue;
1272 };
1273 if (asyncThunks.length === 0) {
1274 return (action) => {
1275 const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
1276 return combinedMatcher(action);
1277 };
1278 }
1279 if (!isAsyncThunkArray(asyncThunks)) {
1280 return isRejectedWithValue()(asyncThunks[0]);
1281 }
1282 return (action) => {
1283 const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
1284 return combinedMatcher(action);
1285 };
1286}
1287function isFulfilled(...asyncThunks) {
1288 if (asyncThunks.length === 0) {
1289 return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
1290 }
1291 if (!isAsyncThunkArray(asyncThunks)) {
1292 return isFulfilled()(asyncThunks[0]);
1293 }
1294 return (action) => {
1295 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.fulfilled);
1296 const combinedMatcher = isAnyOf(...matchers);
1297 return combinedMatcher(action);
1298 };
1299}
1300function isAsyncThunkAction(...asyncThunks) {
1301 if (asyncThunks.length === 0) {
1302 return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
1303 }
1304 if (!isAsyncThunkArray(asyncThunks)) {
1305 return isAsyncThunkAction()(asyncThunks[0]);
1306 }
1307 return (action) => {
1308 const matchers = [];
1309 for (const asyncThunk of asyncThunks) {
1310 matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
1311 }
1312 const combinedMatcher = isAnyOf(...matchers);
1313 return combinedMatcher(action);
1314 };
1315}
1316// src/listenerMiddleware/utils.ts
1317var assertFunction = (func, expected) => {
1318 if (typeof func !== "function") {
1319 throw new TypeError(`${expected} is not a function`);
1320 }
1321};
1322var noop = () => {
1323};
1324var catchRejection = (promise2, onError = noop) => {
1325 promise2.catch(onError);
1326 return promise2;
1327};
1328var addAbortSignalListener = (abortSignal, callback) => {
1329 abortSignal.addEventListener("abort", callback, { once: true });
1330 return () => abortSignal.removeEventListener("abort", callback);
1331};
1332var abortControllerWithReason = (abortController, reason) => {
1333 const signal = abortController.signal;
1334 if (signal.aborted) {
1335 return;
1336 }
1337 if (!("reason" in signal)) {
1338 Object.defineProperty(signal, "reason", {
1339 enumerable: true,
1340 value: reason,
1341 configurable: true,
1342 writable: true
1343 });
1344 }
1345 ;
1346 abortController.abort(reason);
1347};
1348// src/listenerMiddleware/exceptions.ts
1349var task = "task";
1350var listener = "listener";
1351var completed = "completed";
1352var cancelled = "cancelled";
1353var taskCancelled = `task-${cancelled}`;
1354var taskCompleted = `task-${completed}`;
1355var listenerCancelled = `${listener}-${cancelled}`;
1356var listenerCompleted = `${listener}-${completed}`;
1357var TaskAbortError = class {
1358 constructor(code) {
1359 this.code = code;
1360 this.name = "TaskAbortError";
1361 this.message = `${task} ${cancelled} (reason: ${code})`;
1362 }
1363};
1364// src/listenerMiddleware/task.ts
1365var validateActive = (signal) => {
1366 if (signal.aborted) {
1367 throw new TaskAbortError(signal.reason);
1368 }
1369};
1370function raceWithSignal(signal, promise2) {
1371 let cleanup = noop;
1372 return new Promise((resolve, reject) => {
1373 const notifyRejection = () => reject(new TaskAbortError(signal.reason));
1374 if (signal.aborted) {
1375 notifyRejection();
1376 return;
1377 }
1378 cleanup = addAbortSignalListener(signal, notifyRejection);
1379 promise2.finally(() => cleanup()).then(resolve, reject);
1380 }).finally(() => {
1381 cleanup = noop;
1382 });
1383}
1384var runTask = async (task2, cleanUp) => {
1385 try {
1386 await Promise.resolve();
1387 const value = await task2();
1388 return {
1389 status: "ok",
1390 value
1391 };
1392 }
1393 catch (error) {
1394 return {
1395 status: error instanceof TaskAbortError ? "cancelled" : "rejected",
1396 error
1397 };
1398 }
1399 finally {
1400 cleanUp == null ? void 0 : cleanUp();
1401 }
1402};
1403var createPause = (signal) => {
1404 return (promise2) => {
1405 return catchRejection(raceWithSignal(signal, promise2).then((output) => {
1406 validateActive(signal);
1407 return output;
1408 }));
1409 };
1410};
1411var createDelay = (signal) => {
1412 const pause = createPause(signal);
1413 return (timeoutMs) => {
1414 return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
1415 };
1416};
1417// src/listenerMiddleware/index.ts
1418var { assign } = Object;
1419var INTERNAL_NIL_TOKEN = {};
1420var alm = "listenerMiddleware";
1421var createFork = (parentAbortSignal, parentBlockingPromises) => {
1422 const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));
1423 return (taskExecutor, opts) => {
1424 assertFunction(taskExecutor, "taskExecutor");
1425 const childAbortController = new AbortController();
1426 linkControllers(childAbortController);
1427 const result = runTask(async () => {
1428 validateActive(parentAbortSignal);
1429 validateActive(childAbortController.signal);
1430 const result2 = await taskExecutor({
1431 pause: createPause(childAbortController.signal),
1432 delay: createDelay(childAbortController.signal),
1433 signal: childAbortController.signal
1434 });
1435 validateActive(childAbortController.signal);
1436 return result2;
1437 }, () => abortControllerWithReason(childAbortController, taskCompleted));
1438 if (opts == null ? void 0 : opts.autoJoin) {
1439 parentBlockingPromises.push(result);
1440 }
1441 return {
1442 result: createPause(parentAbortSignal)(result),
1443 cancel() {
1444 abortControllerWithReason(childAbortController, taskCancelled);
1445 }
1446 };
1447 };
1448};
1449var createTakePattern = (startListening, signal) => {
1450 const take = async (predicate, timeout) => {
1451 validateActive(signal);
1452 let unsubscribe = () => {
1453 };
1454 const tuplePromise = new Promise((resolve, reject) => {
1455 let stopListening = startListening({
1456 predicate,
1457 effect: (action, listenerApi) => {
1458 listenerApi.unsubscribe();
1459 resolve([
1460 action,
1461 listenerApi.getState(),
1462 listenerApi.getOriginalState()
1463 ]);
1464 }
1465 });
1466 unsubscribe = () => {
1467 stopListening();
1468 reject();
1469 };
1470 });
1471 const promises = [
1472 tuplePromise
1473 ];
1474 if (timeout != null) {
1475 promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
1476 }
1477 try {
1478 const output = await raceWithSignal(signal, Promise.race(promises));
1479 validateActive(signal);
1480 return output;
1481 }
1482 finally {
1483 unsubscribe();
1484 }
1485 };
1486 return (predicate, timeout) => catchRejection(take(predicate, timeout));
1487};
1488var getListenerEntryPropsFrom = (options) => {
1489 let { type, actionCreator, matcher, predicate, effect } = options;
1490 if (type) {
1491 predicate = createAction(type).match;
1492 }
1493 else if (actionCreator) {
1494 type = actionCreator.type;
1495 predicate = actionCreator.match;
1496 }
1497 else if (matcher) {
1498 predicate = matcher;
1499 }
1500 else if (predicate) {
1501 }
1502 else {
1503 throw new Error("Creating or removing a listener requires one of the known fields for matching an action");
1504 }
1505 assertFunction(effect, "options.listener");
1506 return { predicate, type, effect };
1507};
1508var createListenerEntry = (options) => {
1509 const { type, predicate, effect } = getListenerEntryPropsFrom(options);
1510 const id = nanoid();
1511 const entry = {
1512 id,
1513 effect,
1514 type,
1515 predicate,
1516 pending: new Set(),
1517 unsubscribe: () => {
1518 throw new Error("Unsubscribe not initialized");
1519 }
1520 };
1521 return entry;
1522};
1523var cancelActiveListeners = (entry) => {
1524 entry.pending.forEach((controller) => {
1525 abortControllerWithReason(controller, listenerCancelled);
1526 });
1527};
1528var createClearListenerMiddleware = (listenerMap) => {
1529 return () => {
1530 listenerMap.forEach(cancelActiveListeners);
1531 listenerMap.clear();
1532 };
1533};
1534var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
1535 try {
1536 errorHandler(errorToNotify, errorInfo);
1537 }
1538 catch (errorHandlerError) {
1539 setTimeout(() => {
1540 throw errorHandlerError;
1541 }, 0);
1542 }
1543};
1544var addListener = createAction(`${alm}/add`);
1545var clearAllListeners = createAction(`${alm}/removeAll`);
1546var removeListener = createAction(`${alm}/remove`);
1547var defaultErrorHandler = (...args) => {
1548 console.error(`${alm}/error`, ...args);
1549};
1550function createListenerMiddleware(middlewareOptions = {}) {
1551 const listenerMap = new Map();
1552 const { extra, onError = defaultErrorHandler } = middlewareOptions;
1553 assertFunction(onError, "onError");
1554 const insertEntry = (entry) => {
1555 entry.unsubscribe = () => listenerMap.delete(entry.id);
1556 listenerMap.set(entry.id, entry);
1557 return (cancelOptions) => {
1558 entry.unsubscribe();
1559 if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {
1560 cancelActiveListeners(entry);
1561 }
1562 };
1563 };
1564 const findListenerEntry = (comparator) => {
1565 for (const entry of Array.from(listenerMap.values())) {
1566 if (comparator(entry)) {
1567 return entry;
1568 }
1569 }
1570 return void 0;
1571 };
1572 const startListening = (options) => {
1573 let entry = findListenerEntry((existingEntry) => existingEntry.effect === options.effect);
1574 if (!entry) {
1575 entry = createListenerEntry(options);
1576 }
1577 return insertEntry(entry);
1578 };
1579 const stopListening = (options) => {
1580 const { type, effect, predicate } = getListenerEntryPropsFrom(options);
1581 const entry = findListenerEntry((entry2) => {
1582 const matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
1583 return matchPredicateOrType && entry2.effect === effect;
1584 });
1585 if (entry) {
1586 entry.unsubscribe();
1587 if (options.cancelActive) {
1588 cancelActiveListeners(entry);
1589 }
1590 }
1591 return !!entry;
1592 };
1593 const notifyListener = async (entry, action, api, getOriginalState) => {
1594 const internalTaskController = new AbortController();
1595 const take = createTakePattern(startListening, internalTaskController.signal);
1596 const autoJoinPromises = [];
1597 try {
1598 entry.pending.add(internalTaskController);
1599 await Promise.resolve(entry.effect(action, assign({}, api, {
1600 getOriginalState,
1601 condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
1602 take,
1603 delay: createDelay(internalTaskController.signal),
1604 pause: createPause(internalTaskController.signal),
1605 extra,
1606 signal: internalTaskController.signal,
1607 fork: createFork(internalTaskController.signal, autoJoinPromises),
1608 unsubscribe: entry.unsubscribe,
1609 subscribe: () => {
1610 listenerMap.set(entry.id, entry);
1611 },
1612 cancelActiveListeners: () => {
1613 entry.pending.forEach((controller, _, set) => {
1614 if (controller !== internalTaskController) {
1615 abortControllerWithReason(controller, listenerCancelled);
1616 set.delete(controller);
1617 }
1618 });
1619 }
1620 })));
1621 }
1622 catch (listenerError) {
1623 if (!(listenerError instanceof TaskAbortError)) {
1624 safelyNotifyError(onError, listenerError, {
1625 raisedBy: "effect"
1626 });
1627 }
1628 }
1629 finally {
1630 await Promise.allSettled(autoJoinPromises);
1631 abortControllerWithReason(internalTaskController, listenerCompleted);
1632 entry.pending.delete(internalTaskController);
1633 }
1634 };
1635 const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
1636 const middleware = (api) => (next) => (action) => {
1637 if (!isAction(action)) {
1638 return next(action);
1639 }
1640 if (addListener.match(action)) {
1641 return startListening(action.payload);
1642 }
1643 if (clearAllListeners.match(action)) {
1644 clearListenerMiddleware();
1645 return;
1646 }
1647 if (removeListener.match(action)) {
1648 return stopListening(action.payload);
1649 }
1650 let originalState = api.getState();
1651 const getOriginalState = () => {
1652 if (originalState === INTERNAL_NIL_TOKEN) {
1653 throw new Error(`${alm}: getOriginalState can only be called synchronously`);
1654 }
1655 return originalState;
1656 };
1657 let result;
1658 try {
1659 result = next(action);
1660 if (listenerMap.size > 0) {
1661 let currentState = api.getState();
1662 const listenerEntries = Array.from(listenerMap.values());
1663 for (let entry of listenerEntries) {
1664 let runListener = false;
1665 try {
1666 runListener = entry.predicate(action, currentState, originalState);
1667 }
1668 catch (predicateError) {
1669 runListener = false;
1670 safelyNotifyError(onError, predicateError, {
1671 raisedBy: "predicate"
1672 });
1673 }
1674 if (!runListener) {
1675 continue;
1676 }
1677 notifyListener(entry, action, api, getOriginalState);
1678 }
1679 }
1680 }
1681 finally {
1682 originalState = INTERNAL_NIL_TOKEN;
1683 }
1684 return result;
1685 };
1686 return {
1687 middleware,
1688 startListening,
1689 stopListening,
1690 clearListeners: clearListenerMiddleware
1691 };
1692}
1693// src/autoBatchEnhancer.ts
1694var SHOULD_AUTOBATCH = "RTK_autoBatch";
1695var prepareAutoBatched = () => (payload) => ({
1696 payload,
1697 meta: { [SHOULD_AUTOBATCH]: true }
1698});
1699var promise;
1700var queueMicrotaskShim = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : globalThis) : (cb) => (promise || (promise = Promise.resolve())).then(cb).catch((err) => setTimeout(() => {
1701 throw err;
1702}, 0));
1703var createQueueWithTimer = (timeout) => {
1704 return (notify) => {
1705 setTimeout(notify, timeout);
1706 };
1707};
1708var rAF = typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);
1709var autoBatchEnhancer = (options = { type: "raf" }) => (next) => (...args) => {
1710 const store = next(...args);
1711 let notifying = true;
1712 let shouldNotifyAtEndOfTick = false;
1713 let notificationQueued = false;
1714 const listeners = new Set();
1715 const queueCallback = options.type === "tick" ? queueMicrotaskShim : options.type === "raf" ? rAF : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
1716 const notifyListeners = () => {
1717 notificationQueued = false;
1718 if (shouldNotifyAtEndOfTick) {
1719 shouldNotifyAtEndOfTick = false;
1720 listeners.forEach((l) => l());
1721 }
1722 };
1723 return Object.assign({}, store, {
1724 subscribe(listener2) {
1725 const wrappedListener = () => notifying && listener2();
1726 const unsubscribe = store.subscribe(wrappedListener);
1727 listeners.add(listener2);
1728 return () => {
1729 unsubscribe();
1730 listeners.delete(listener2);
1731 };
1732 },
1733 dispatch(action) {
1734 var _a;
1735 try {
1736 notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);
1737 shouldNotifyAtEndOfTick = !notifying;
1738 if (shouldNotifyAtEndOfTick) {
1739 if (!notificationQueued) {
1740 notificationQueued = true;
1741 queueCallback(notifyListeners);
1742 }
1743 }
1744 return store.dispatch(action);
1745 }
1746 finally {
1747 notifying = true;
1748 }
1749 }
1750 });
1751};
1752// src/index.ts
1753enableES5();
1754export { EnhancerArray, MiddlewareArray, SHOULD_AUTOBATCH, TaskAbortError, addListener, autoBatchEnhancer, clearAllListeners, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, default2 as createNextState, createReducer, createSelector2 as createSelector, createSerializableStateInvariantMiddleware, createSlice, current2 as current, findNonSerializableValue, freeze, getDefaultMiddleware, getType, isAction, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isDraft4 as isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject, isRejected, isRejectedWithValue, miniSerializeError, nanoid, original, prepareAutoBatched, removeListener, unwrapResult };
1755//# sourceMappingURL=redux-toolkit.modern.js.map
\No newline at end of file