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