UNPKG

@evertbouw/redux-toolkit

Version:
1,525 lines (1,252 loc) 50.2 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.RTK = {})); }(this, (function (exports) { 'use strict'; function symbolObservablePonyfill(root) { var result; var Symbol = root.Symbol; if (typeof Symbol === 'function') { if (Symbol.observable) { result = Symbol.observable; } else { result = Symbol('observable'); Symbol.observable = result; } } else { result = '@@observable'; } return result; } /* global window */ var root; if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (typeof module !== 'undefined') { root = module; } else { root = Function('return this')(); } var result = symbolObservablePonyfill(root); /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var randomString = function randomString() { return Math.random().toString(36).substring(7).split('').join('.'); }; var ActionTypes = { INIT: "@@redux/INIT" + randomString(), REPLACE: "@@redux/REPLACE" + randomString(), PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); } }; /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false; var proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto; } /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} [enhancer] The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function'); } if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { if (isDispatching) { throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.'); } return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected the listener to be a function.'); } if (isDispatching) { throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } if (isDispatching) { throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'); } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!isPlainObject(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; listener(); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.REPLACE }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/tc39/proposal-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object' || observer === null) { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[result] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[result] = observable, _ref2; } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); } catch (e) {} // eslint-disable-line no-empty } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action'; return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined."; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!isPlainObject(inputState)) { return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\""); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (action && action.type === ActionTypes.REPLACE) return; if (unexpectedKeys.length > 0) { return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored."); } } function assertReducerShape(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined."); } if (typeof reducer(undefined, { type: ActionTypes.PROBE_UNKNOWN_ACTION() }) === 'undefined') { throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null."); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; { if (typeof reducers[key] === 'undefined') { warning("No reducer provided for key \"" + key + "\""); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); var unexpectedKeyCache; { unexpectedKeyCache = {}; } var shapeAssertionError; try { assertReducerShape(finalReducers); } catch (e) { shapeAssertionError = e; } return function combination(state, action) { if (state === void 0) { state = {}; } if (shapeAssertionError) { throw shapeAssertionError; } { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { warning(warningMessage); } } var hasChanged = false; var nextState = {}; for (var _i = 0; _i < finalReducerKeys.length; _i++) { var _key = finalReducerKeys[_i]; var reducer = finalReducers[_key]; var previousStateForKey = state[_key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(_key, action); throw new Error(errorMessage); } nextState[_key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(this, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?"); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(void 0, arguments)); }; }); } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function () { var store = createStore.apply(void 0, arguments); var _dispatch = function dispatch() { throw new Error("Dispatching while constructing your middleware is not allowed. " + "Other middleware would not be applied to this dispatch."); }; var middlewareAPI = { getState: store.getState, dispatch: function dispatch() { return _dispatch.apply(void 0, arguments); } }; var chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = compose.apply(void 0, chain)(store.dispatch); return _objectSpread({}, store, { dispatch: _dispatch }); }; }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if ( typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.'); } var redux = ({ __proto__: null, createStore: createStore, combineReducers: combineReducers, bindActionCreators: bindActionCreators, applyMiddleware: applyMiddleware, compose: compose, __DO_NOT_USE__ActionTypes: ActionTypes }); function defaultEqualityCheck(a, b) { return a === b; } function areArgumentsShallowlyEqual(equalityCheck, prev, next) { if (prev === null || next === null || prev.length !== next.length) { return false; } // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible. var length = prev.length; for (var i = 0; i < length; i++) { if (!equalityCheck(prev[i], next[i])) { return false; } } return true; } function defaultMemoize(func) { var equalityCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultEqualityCheck; var lastArgs = null; var lastResult = null; // we reference arguments instead of spreading them for performance reasons return function () { if (!areArgumentsShallowlyEqual(equalityCheck, lastArgs, arguments)) { // apply arguments instead of spreading for performance. lastResult = func.apply(null, arguments); } lastArgs = arguments; return lastResult; }; } function getDependencies(funcs) { var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs; if (!dependencies.every(function (dep) { return typeof dep === 'function'; })) { var dependencyTypes = dependencies.map(function (dep) { return typeof dep; }).join(', '); throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']')); } return dependencies; } function createSelectorCreator(memoize) { for (var _len = arguments.length, memoizeOptions = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { memoizeOptions[_key - 1] = arguments[_key]; } return function () { for (var _len2 = arguments.length, funcs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { funcs[_key2] = arguments[_key2]; } var recomputations = 0; var resultFunc = funcs.pop(); var dependencies = getDependencies(funcs); var memoizedResultFunc = memoize.apply(undefined, [function () { recomputations++; // apply arguments instead of spreading for performance. return resultFunc.apply(null, arguments); }].concat(memoizeOptions)); // If a selector is called with the exact same arguments we don't need to traverse our dependencies again. var selector = memoize(function () { var params = []; var length = dependencies.length; for (var i = 0; i < length; i++) { // apply arguments instead of spreading and mutate a local list of params for performance. params.push(dependencies[i].apply(null, arguments)); } // apply arguments instead of spreading for performance. return memoizedResultFunc.apply(null, params); }); selector.resultFunc = resultFunc; selector.dependencies = dependencies; selector.recomputations = function () { return recomputations; }; selector.resetRecomputations = function () { return recomputations = 0; }; return selector; }; } var createSelector = createSelectorCreator(defaultMemoize); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var reduxDevtoolsExtension = createCommonjsModule(function (module, exports) { var compose = redux.compose; exports.__esModule = true; exports.composeWithDevTools = ( typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() { if (arguments.length === 0) return undefined; if (typeof arguments[0] === 'object') return compose; return compose.apply(null, arguments); } ); exports.devToolsEnhancer = ( typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() { return function(noop) { return noop; } } ); }); unwrapExports(reduxDevtoolsExtension); var reduxDevtoolsExtension_1 = reduxDevtoolsExtension.composeWithDevTools; var reduxDevtoolsExtension_2 = reduxDevtoolsExtension.devToolsEnhancer; /** * Returns true if the passed value is "plain" object, i.e. an object whose * protoype is the root `Object.prototype`. This includes objects created * using object literals, but not for instance for class instances. * * @param {any} value The value to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject$1(value) { if (typeof value !== 'object' || value === null) return false; var proto = value; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(value) === proto; } function createThunkMiddleware(extraArgument) { return function (_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; return function (next) { return function (action) { if (typeof action === 'function') { return action(dispatch, getState, extraArgument); } return next(action); }; }; }; } var thunk = createThunkMiddleware(); thunk.withExtraArgument = createThunkMiddleware; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var invariant = function(condition, format, a, b, c, d, e, f) { { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; var invariant_1 = invariant; var stringify_1 = createCommonjsModule(function (module, exports) { exports = module.exports = stringify; exports.getSerialize = serializer; function stringify(obj, replacer, spaces, cycleReplacer) { return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) } function serializer(replacer, cycleReplacer) { var stack = [], keys = []; if (cycleReplacer == null) cycleReplacer = function(key, value) { if (stack[0] === value) return "[Circular ~]" return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" }; return function(key, value) { if (stack.length > 0) { var thisPos = stack.indexOf(this); ~thisPos ? stack.splice(thisPos + 1) : stack.push(this); ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key); if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value); } else stack.push(value); return replacer == null ? value : replacer.call(this, key, value) } } }); var stringify_2 = stringify_1.getSerialize; var isImmutable = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = isImmutableDefault; function isImmutableDefault(value) { return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object' || value === null || typeof value === 'undefined'; } }); unwrapExports(isImmutable); var trackForMutations_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = trackForMutations; function trackForMutations(isImmutable, ignore, obj) { var trackedProperties = trackProperties(isImmutable, ignore, obj); return { detectMutations: function detectMutations() { return _detectMutations(isImmutable, ignore, trackedProperties, obj); } }; } function trackProperties(isImmutable) { var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var obj = arguments[2]; var path = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; var tracked = { value: obj }; if (!isImmutable(obj)) { tracked.children = {}; for (var key in obj) { var childPath = path.concat(key); if (ignore.length && ignore.indexOf(childPath.join('.')) !== -1) { continue; } tracked.children[key] = trackProperties(isImmutable, ignore, obj[key], childPath); } } return tracked; } function _detectMutations(isImmutable) { var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var trackedProperty = arguments[2]; var obj = arguments[3]; var sameParentRef = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var path = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; var prevObj = trackedProperty ? trackedProperty.value : undefined; var sameRef = prevObj === obj; if (sameParentRef && !sameRef && !Number.isNaN(obj)) { return { wasMutated: true, path: path }; } if (isImmutable(prevObj) || isImmutable(obj)) { return { wasMutated: false }; } // Gather all keys from prev (tracked) and after objs var keysToDetect = {}; Object.keys(trackedProperty.children).forEach(function (key) { keysToDetect[key] = true; }); Object.keys(obj).forEach(function (key) { keysToDetect[key] = true; }); var keys = Object.keys(keysToDetect); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var childPath = path.concat(key); if (ignore.length && ignore.indexOf(childPath.join('.')) !== -1) { continue; } var result = _detectMutations(isImmutable, ignore, trackedProperty.children[key], obj[key], sameRef, childPath); if (result.wasMutated) { return result; } } return { wasMutated: false }; } }); unwrapExports(trackForMutations_1); var dist = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = immutableStateInvariantMiddleware; var _invariant2 = _interopRequireDefault(invariant_1); var _jsonStringifySafe2 = _interopRequireDefault(stringify_1); var _isImmutable2 = _interopRequireDefault(isImmutable); var _trackForMutations2 = _interopRequireDefault(trackForMutations_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var BETWEEN_DISPATCHES_MESSAGE = ['A state mutation was detected between dispatches, in the path `%s`.', 'This may cause incorrect behavior.', '(http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)'].join(' '); var INSIDE_DISPATCH_MESSAGE = ['A state mutation was detected inside a dispatch, in the path: `%s`.', 'Take a look at the reducer(s) handling the action %s.', '(http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)'].join(' '); function immutableStateInvariantMiddleware() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$isImmutable = options.isImmutable, isImmutable = _options$isImmutable === undefined ? _isImmutable2.default : _options$isImmutable, ignore = options.ignore; var track = _trackForMutations2.default.bind(null, isImmutable, ignore); return function (_ref) { var getState = _ref.getState; var state = getState(); var tracker = track(state); var result = void 0; return function (next) { return function (action) { state = getState(); result = tracker.detectMutations(); // Track before potentially not meeting the invariant tracker = track(state); (0, _invariant2.default)(!result.wasMutated, BETWEEN_DISPATCHES_MESSAGE, (result.path || []).join('.')); var dispatchedAction = next(action); state = getState(); result = tracker.detectMutations(); // Track before potentially not meeting the invariant tracker = track(state); result.wasMutated && (0, _invariant2.default)(!result.wasMutated, INSIDE_DISPATCH_MESSAGE, (result.path || []).join('.'), (0, _jsonStringifySafe2.default)(action)); return dispatchedAction; }; }; }; } }); var createImmutableStateInvariantMiddleware = unwrapExports(dist); /** * Returns true if the passed value is "plain", i.e. a value that is either * directly JSON-serializable (boolean, number, string, array, plain object) * or `undefined`. * * @param val The value to check. * * @public */ function isPlain(val) { return typeof val === 'undefined' || val === null || typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number' || Array.isArray(val) || isPlainObject$1(val); } /** * @public */ function findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths) { if (path === void 0) { path = []; } if (isSerializable === void 0) { isSerializable = isPlain; } if (ignoredPaths === void 0) { ignoredPaths = []; } var foundNestedSerializable; if (!isSerializable(value)) { return { keyPath: path.join('.') || '<root>', value: value }; } if (typeof value !== 'object' || value === null) { return false; } var entries = getEntries != null ? getEntries(value) : Object.entries(value); var hasIgnoredPaths = ignoredPaths.length > 0; for (var _iterator = entries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var _ref2 = _ref, property = _ref2[0], nestedValue = _ref2[1]; var nestedPath = path.concat(property); if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath.join('.')) >= 0) { continue; } if (!isSerializable(nestedValue)) { return { keyPath: nestedPath.join('.'), value: nestedValue }; } if (typeof nestedValue === 'object') { foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths); if (foundNestedSerializable) { return foundNestedSerializable; } } } return false; } /** * Creates a middleware that, after every state change, checks if the new * state is serializable. If a non-serializable value is found within the * state, an error is printed to the console. * * @param options Middleware options. * * @public */ function createSerializableStateInvariantMiddleware(options) { if (options === void 0) { options = {}; } var _options = options, _options$isSerializab = _options.isSerializable, isSerializable = _options$isSerializab === void 0 ? isPlain : _options$isSerializab, getEntries = _options.getEntries, _options$ignoredActio = _options.ignoredActions, ignoredActions = _options$ignoredActio === void 0 ? [] : _options$ignoredActio, _options$ignoredPaths = _options.ignoredPaths, ignoredPaths = _options$ignoredPaths === void 0 ? [] : _options$ignoredPaths; return function (storeAPI) { return function (next) { return function (action) { if (ignoredActions.length && ignoredActions.indexOf(action.type) !== -1) { return next(action); } var foundActionNonSerializableValue = findNonSerializableValue(action, [], isSerializable, getEntries); if (foundActionNonSerializableValue) { var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value; 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)'); } var result = next(action); var state = storeAPI.getState(); var foundStateNonSerializableValue = findNonSerializableValue(state, [], isSerializable, getEntries, ignoredPaths); if (foundStateNonSerializableValue) { var _keyPath = foundStateNonSerializableValue.keyPath, _value = foundStateNonSerializableValue.value; console.error("A non-serializable value was detected in the state, in the path: `" + _keyPath + "`. Value:", _value, "\nTake a look at the reducer(s) handling this action type: " + action.type + ".\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"); } return result; }; }; }; } function isBoolean(x) { return typeof x === 'boolean'; } /** * Returns any array containing the default middleware installed by * `configureStore()`. Useful if you want to configure your store with a custom * `middleware` array but still keep the default set. * * @return The default middleware used by `configureStore()`. * * @public */ function getDefaultMiddleware(options) { if (options === void 0) { options = {}; } var _options = options, _options$thunk = _options.thunk, thunk$1 = _options$thunk === void 0 ? true : _options$thunk, _options$immutableChe = _options.immutableCheck, immutableCheck = _options$immutableChe === void 0 ? true : _options$immutableChe, _options$serializable = _options.serializableCheck, serializableCheck = _options$serializable === void 0 ? true : _options$serializable; var middlewareArray = []; if (thunk$1) { if (isBoolean(thunk$1)) { middlewareArray.push(thunk); } else { middlewareArray.push(thunk.withExtraArgument(thunk$1.extraArgument)); } } { if (immutableCheck) { /* PROD_START_REMOVE_UMD */ var immutableOptions = {}; if (!isBoolean(immutableCheck)) { immutableOptions = immutableCheck; } middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions)); /* PROD_STOP_REMOVE_UMD */ } if (serializableCheck) { var serializableOptions = {}; if (!isBoolean(serializableCheck)) { serializableOptions = serializableCheck; } middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions)); } } return middlewareArray; } var IS_PRODUCTION = "development" === 'production'; /** * A friendly abstraction over the standard Redux `createStore()` function. * * @param config The store configuration. * @returns A configured Redux store. * * @public */ function configureStore(options) { var _ref = options || {}, _ref$reducer = _ref.reducer, reducer = _ref$reducer === void 0 ? undefined : _ref$reducer, _ref$middleware = _ref.middleware, middleware = _ref$middleware === void 0 ? getDefaultMiddleware() : _ref$middleware, _ref$devTools = _ref.devTools, devTools = _ref$devTools === void 0 ? true : _ref$devTools, _ref$preloadedState = _ref.preloadedState, preloadedState = _ref$preloadedState === void 0 ? undefined : _ref$preloadedState, _ref$enhancers = _ref.enhancers, enhancers = _ref$enhancers === void 0 ? undefined : _ref$enhancers; var rootReducer; if (typeof reducer === 'function') { rootReducer = reducer; } else if (isPlainObject$1(reducer)) { rootReducer = combineReducers(reducer); } else { throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers'); } var middlewareEnhancer = applyMiddleware.apply(void 0, middleware); var finalCompose = compose; if (devTools) { finalCompose = reduxDevtoolsExtension_1(_extends({ // Enable capture of stack traces for dispatched Redux actions trace: !IS_PRODUCTION }, typeof devTools === 'object' && devTools)); } var storeEnhancers = [middlewareEnhancer]; if (Array.isArray(enhancers)) { storeEnhancers = [middlewareEnhancer].concat(enhancers); } else if (typeof enhancers === 'function') { storeEnhancers = enhancers(storeEnhancers); } var composedEnhancer = finalCompose.apply(void 0, storeEnhancers); return createStore(rootReducer, preloadedState, composedEnhancer); } function createAction(type, prepareAction) { function actionCreator() { if (prepareAction) { var prepared = prepareAction.apply(void 0, arguments); if (!prepared) { throw new Error('prepareAction did not return an object'); } return _extends({ type: type, payload: prepared.payload }, 'meta' in prepared && { meta: prepared.meta }, {}, 'error' in prepared && { error: prepared.error }); } return { type: type, payload: arguments.length <= 0 ? undefined : arguments[0] }; } actionCreator.toString = function () { return "" + type; }; actionCreator.type = type; actionCreator.match = function (action) { return action.type === type; }; return actionCreator; } /** * Returns the action type of the actions created by the passed * `createAction()`-generated action creator (arbitrary action creators * are not supported). * * @param action The action creator whose action type to get. * @returns The action type used by the action creator. * * @public */ function getType(actionCreator) { return "" + actionCreator; } function executeReducerBuilderCallback(builderCallback) { var actionsMap = {}; var builder = { addCase: function addCase(typeOrActionCreator, reducer) { var type = typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type; if (type in actionsMap) { throw new Error('addCase cannot be called with two reducers for the same action type'); } actionsMap[type] = reducer; return builder; } }; builderCallback(builder); return actionsMap; } function createReducer(initialState, mapOrBuilderCallback) { var actionsMap = typeof mapOrBuilderCallback === 'function' ? executeReducerBuilderCallback(mapOrBuilderCallback) : mapOrBuilderCallback; return function (state, action) { if (state === void 0) { state = initialState; } var reducer = actionsMap[action.type]; return reducer === undefined ? state : reducer(state, action); }; } function getType$1(slice, actionKey) { return slice + "/" + actionKey; } /** * A function that accepts an initial state, an object full of reducer * functions, and a "slice name", and automatically generates * action creators and action types that correspond to the * reducers and state. * * The `reducer` argument is passed to `createReducer()`. * * @public */ function createSlice(options) { var name = options.name, initialState = options.initialState; if (!name) { throw new Error('`name` is a required option for createSlice'); } var reducers = options.reducers || {}; var extraReducers = typeof options.extraReducers === 'undefined' ? {} : typeof options.extraReducers === 'function' ? executeReducerBuilderCallback(options.extraReducers) : options.extraReducers; var reducerNames = Object.keys(reducers); var sliceCaseReducersByName = {}; var sliceCaseReducersByType = {}; var actionCreators = {}; reducerNames.forEach(function (reducerName) { var maybeReducerWithPrepare = reducers[reducerName]; var type = getType$1(name, reducerName); var caseReducer; var prepareCallback; if ('reducer' in maybeReducerWithPrepare) { caseReducer = maybeReducerWithPrepare.reducer; prepareCallback = maybeReducerWithPrepare.prepare; } else { caseReducer = maybeReducerWithPrepare; } sliceCaseReducersByName[reducerName] = caseReducer; sliceCaseReducersByType[type] = caseReducer; actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type); }); var finalCaseReducers = _extends({}, extraReducers, {}, sliceCaseReducersByType); var reducer = createReducer(initialState, finalCaseReducers); return { name: name, reducer: reducer, actions: actionCreators, caseReducers: sliceCaseReducersByName }; } exports.__DO_NOT_USE__ActionTypes = ActionTypes; exports.applyMiddleware = applyMiddleware; exports.bindActionCreators = bindActionCreators; exports.combineReducers = combineReducers; exports.compose = compose; exports.configureStore = configureStore; exports.createAction = createAction; exports.createReducer = createReducer; exports.createSelector = createSelector; exports.createSerializableStateInvariantMiddleware = createSerializableStateInvariantMiddleware; exports.createSlice = createSlice; exports.createStore = create