`.\n * @returns {Function} A `useDispatch` hook bound to the specified context.\n */\n\nexport function createDispatchHook(context = ReactReduxContext) {\n const useStore = // @ts-ignore\n context === ReactReduxContext ? useDefaultStore : createStoreHook(context);\n return function useDispatch() {\n const store = useStore(); // @ts-ignore\n\n return store.dispatch;\n };\n}\n/**\n * A hook to access the redux `dispatch` function.\n *\n * @returns {any|function} redux store's `dispatch` function\n *\n * @example\n *\n * import React, { useCallback } from 'react'\n * import { useDispatch } from 'react-redux'\n *\n * export const CounterComponent = ({ value }) => {\n * const dispatch = useDispatch()\n * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])\n * return (\n * \n * {value}\n * \n *
\n * )\n * }\n */\n\nexport const useDispatch = /*#__PURE__*/createDispatchHook();","// The primary entry point assumes we're working with standard ReactDOM/RN, but\n// older versions that do not include `useSyncExternalStore` (React 16.9 - 17.x).\n// Because of that, the useSyncExternalStore compat shim is needed.\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport { unstable_batchedUpdates as batch } from './utils/reactBatchedUpdates';\nimport { setBatch } from './utils/batch';\nimport { initializeUseSelector } from './hooks/useSelector';\nimport { initializeConnect } from './components/connect';\ninitializeUseSelector(useSyncExternalStoreWithSelector);\ninitializeConnect(useSyncExternalStore); // Enable batched updates in our subscriptions for use\n// with standard React renderers (ReactDOM, React Native)\n\nsetBatch(batch);\nexport { batch };\nexport * from './exports';","function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?n.add(t):n[r]=t}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i(n,(function(n,r){return d(r,!0)}),!0)),n}function h(){n(2)}function y(n){return null==n||\"object\"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function m(n,r){tn[n]||(tn[n]=r)}function _(){return\"production\"===process.env.NODE_ENV||U||n(0),U}function j(n,r){r&&(b(\"Patches\"),n.u=[],n.s=[],n.v=r)}function g(n){O(n),n.p.forEach(S),n.p=null}function O(n){n===U&&(U=n.l)}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.g=!0}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.O||b(\"ES5\").S(e,r,o),o?(i[Q].P&&(g(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b(\"Patches\").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),g(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o,u=o,a=!1;3===e.i&&(u=new Set(o),o.clear(),a=!0),i(u,(function(r,i){return A(n,e,o,r,i,t,a)})),x(n,o,!1),t&&n.u&&b(\"Patches\").N(e,t,n.u,n.s)}return e.o}function A(e,i,o,a,c,s,v){if(\"production\"!==process.env.NODE_ENV&&c===o&&n(5),r(c)){var p=M(e,c,s&&i&&3!==i.i&&!u(i.R,a)?s.concat(a):void 0);if(f(o,a,p),!r(p))return;e.m=!1}else v&&o.add(c);if(t(c)&&!y(c)){if(!e.h.D&&e._<1)return;M(e,c),i&&i.A.l||x(e,c)}}function x(n,r,t){void 0===t&&(t=!1),!n.l&&n.h.D&&n.m&&d(r,t)}function z(n,r){var t=n[Q];return(t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t)}}function k(n){n.P||(n.P=!0,n.l&&k(n.l))}function E(n){n.o||(n.o=l(n.t))}function N(n,r,t){var e=s(r)?b(\"MapSet\").F(r,t):v(r)?b(\"MapSet\").T(r,t):n.O?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,R:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b(\"ES5\").J(r,t);return(t?t.A:_()).p.push(e),e}function R(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b(\"ES5\").K(u)))return u.t;u.I=!0,e=D(r,c),u.I=!1}else e=D(r,c);return i(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t))})),3===c?new Set(e):e}(e)}function D(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}function F(){function t(n,r){var t=s[n];return t?t.enumerable=r:s[n]=t={configurable:!0,enumerable:r,get:function(){var r=this[Q];return\"production\"!==process.env.NODE_ENV&&f(r),en.get(r,n)},set:function(r){var t=this[Q];\"production\"!==process.env.NODE_ENV&&f(t),en.set(t,n,r)}},t}function e(n){for(var r=n.length-1;r>=0;r--){var t=n[r][Q];if(!t.P)switch(t.i){case 5:a(t)&&k(t);break;case 4:o(t)&&k(t)}}}function o(n){for(var r=n.t,t=n.k,e=nn(t),i=e.length-1;i>=0;i--){var o=e[i];if(o!==Q){var a=r[o];if(void 0===a&&!u(r,o))return!0;var f=t[o],s=f&&f[Q];if(s?s.t!==a:!c(f,a))return!0}}var v=!!r[Q];return e.length!==nn(r).length+(v?0:1)}function a(n){var r=n.k;if(r.length!==n.t.length)return!0;var t=Object.getOwnPropertyDescriptor(r,r.length-1);if(t&&!t.get)return!0;for(var e=0;e1?t-1:0),o=1;o1?t-1:0),o=1;o=0;e--){var i=t[e];if(0===i.path.length&&\"replace\"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b(\"Patches\").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce,cn=an.produceWithPatches.bind(an),sn=an.setAutoFreeze.bind(an),vn=an.setUseProxies.bind(an),pn=an.applyPatches.bind(an),ln=an.createDraft.bind(an),dn=an.finishDraft.bind(an);export default fn;export{un as Immer,pn as applyPatches,K as castDraft,$ as castImmutable,ln as createDraft,R as current,J as enableAllPlugins,F as enableES5,C as enableMapSet,T as enablePatches,dn as finishDraft,d as freeze,L as immerable,r as isDraft,t as isDraftable,H as nothing,e as original,fn as produce,cn as produceWithPatches,sn as setAutoFreeze,vn as setUseProxies};\n//# sourceMappingURL=immer.esm.js.map\n","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}","import defineProperty from \"./defineProperty.js\";\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n return keys;\n}\nexport default function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n}","import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';\n\n/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nfunction formatProdErrorMessage(code) {\n return \"Minified Redux error #\" + code + \"; visit https://redux.js.org/Errors?code=\" + code + \" for the full message or \" + 'use the non-minified dev environment for full errors. ';\n}\n\n// Inlined version of the `symbol-observable` polyfill\nvar $$observable = (function () {\n return typeof Symbol === 'function' && Symbol.observable || '@@observable';\n})();\n\n/**\n * These are private action types reserved by Redux.\n * For any unknown actions, you must return the current state.\n * If the current state is undefined, you must return the initial state.\n * Do not reference these action types directly in your code.\n */\nvar randomString = function randomString() {\n return Math.random().toString(36).substring(7).split('').join('.');\n};\n\nvar ActionTypes = {\n INIT: \"@@redux/INIT\" + randomString(),\n REPLACE: \"@@redux/REPLACE\" + randomString(),\n PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {\n return \"@@redux/PROBE_UNKNOWN_ACTION\" + randomString();\n }\n};\n\n/**\n * @param {any} obj The object to inspect.\n * @returns {boolean} True if the argument appears to be a plain object.\n */\nfunction isPlainObject(obj) {\n if (typeof obj !== 'object' || obj === null) return false;\n var proto = obj;\n\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(obj) === proto;\n}\n\n// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of\nfunction miniKindOf(val) {\n if (val === void 0) return 'undefined';\n if (val === null) return 'null';\n var type = typeof val;\n\n switch (type) {\n case 'boolean':\n case 'string':\n case 'number':\n case 'symbol':\n case 'function':\n {\n return type;\n }\n }\n\n if (Array.isArray(val)) return 'array';\n if (isDate(val)) return 'date';\n if (isError(val)) return 'error';\n var constructorName = ctorName(val);\n\n switch (constructorName) {\n case 'Symbol':\n case 'Promise':\n case 'WeakMap':\n case 'WeakSet':\n case 'Map':\n case 'Set':\n return constructorName;\n } // other\n\n\n return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n}\n\nfunction ctorName(val) {\n return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isError(val) {\n return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';\n}\n\nfunction isDate(val) {\n if (val instanceof Date) return true;\n return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';\n}\n\nfunction kindOf(val) {\n var typeOfVal = typeof val;\n\n if (process.env.NODE_ENV !== 'production') {\n typeOfVal = miniKindOf(val);\n }\n\n return typeOfVal;\n}\n\n/**\n * @deprecated\n *\n * **We recommend using the `configureStore` method\n * of the `@reduxjs/toolkit` package**, which replaces `createStore`.\n *\n * Redux Toolkit is our recommended approach for writing Redux logic today,\n * including store setup, reducers, data fetching, and more.\n *\n * **For more details, please read this Redux docs page:**\n * **https://redux.js.org/introduction/why-rtk-is-redux-today**\n *\n * `configureStore` from Redux Toolkit is an improved version of `createStore` that\n * simplifies setup and helps avoid common bugs.\n *\n * You should not be using the `redux` core package by itself today, except for learning purposes.\n * The `createStore` method from the core `redux` package will not be removed, but we encourage\n * all users to migrate to using Redux Toolkit for all Redux code.\n *\n * If you want to use `createStore` without this visual deprecation warning, use\n * the `legacy_createStore` import instead:\n *\n * `import { legacy_createStore as createStore} from 'redux'`\n *\n */\n\nfunction createStore(reducer, preloadedState, enhancer) {\n var _ref2;\n\n if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');\n }\n\n if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {\n enhancer = preloadedState;\n preloadedState = undefined;\n }\n\n if (typeof enhancer !== 'undefined') {\n if (typeof enhancer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : \"Expected the enhancer to be a function. Instead, received: '\" + kindOf(enhancer) + \"'\");\n }\n\n return enhancer(createStore)(reducer, preloadedState);\n }\n\n if (typeof reducer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : \"Expected the root reducer to be a function. Instead, received: '\" + kindOf(reducer) + \"'\");\n }\n\n var currentReducer = reducer;\n var currentState = preloadedState;\n var currentListeners = [];\n var nextListeners = currentListeners;\n var isDispatching = false;\n /**\n * This makes a shallow copy of currentListeners so we can use\n * nextListeners as a temporary list while dispatching.\n *\n * This prevents any bugs around consumers calling\n * subscribe/unsubscribe in the middle of a dispatch.\n */\n\n function ensureCanMutateNextListeners() {\n if (nextListeners === currentListeners) {\n nextListeners = currentListeners.slice();\n }\n }\n /**\n * Reads the state tree managed by the store.\n *\n * @returns {any} The current state tree of your application.\n */\n\n\n function getState() {\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : '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.');\n }\n\n return currentState;\n }\n /**\n * Adds a change listener. It will be called any time an action is dispatched,\n * and some part of the state tree may potentially have changed. You may then\n * call `getState()` to read the current state tree inside the callback.\n *\n * You may call `dispatch()` from a change listener, with the following\n * caveats:\n *\n * 1. The subscriptions are snapshotted just before every `dispatch()` call.\n * If you subscribe or unsubscribe while the listeners are being invoked, this\n * will not have any effect on the `dispatch()` that is currently in progress.\n * However, the next `dispatch()` call, whether nested or not, will use a more\n * recent snapshot of the subscription list.\n *\n * 2. The listener should not expect to see all state changes, as the state\n * might have been updated multiple times during a nested `dispatch()` before\n * the listener is called. It is, however, guaranteed that all subscribers\n * registered before the `dispatch()` started will be called with the latest\n * state by the time it exits.\n *\n * @param {Function} listener A callback to be invoked on every dispatch.\n * @returns {Function} A function to remove this change listener.\n */\n\n\n function subscribe(listener) {\n if (typeof listener !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : \"Expected the listener to be a function. Instead, received: '\" + kindOf(listener) + \"'\");\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : '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/store#subscribelistener for more details.');\n }\n\n var isSubscribed = true;\n ensureCanMutateNextListeners();\n nextListeners.push(listener);\n return function unsubscribe() {\n if (!isSubscribed) {\n return;\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');\n }\n\n isSubscribed = false;\n ensureCanMutateNextListeners();\n var index = nextListeners.indexOf(listener);\n nextListeners.splice(index, 1);\n currentListeners = null;\n };\n }\n /**\n * Dispatches an action. It is the only way to trigger a state change.\n *\n * The `reducer` function, used to create the store, will be called with the\n * current state tree and the given `action`. Its return value will\n * be considered the **next** state of the tree, and the change listeners\n * will be notified.\n *\n * The base implementation only supports plain object actions. If you want to\n * dispatch a Promise, an Observable, a thunk, or something else, you need to\n * wrap your store creating function into the corresponding middleware. For\n * example, see the documentation for the `redux-thunk` package. Even the\n * middleware will eventually dispatch plain object actions using this method.\n *\n * @param {Object} action A plain object representing “what changed”. It is\n * a good idea to keep actions serializable so you can record and replay user\n * sessions, or use the time travelling `redux-devtools`. An action must have\n * a `type` property which may not be `undefined`. It is a good idea to use\n * string constants for action types.\n *\n * @returns {Object} For convenience, the same action object you dispatched.\n *\n * Note that, if you use a custom middleware, it may wrap `dispatch()` to\n * return something else (for example, a Promise you can await).\n */\n\n\n function dispatch(action) {\n if (!isPlainObject(action)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : \"Actions must be plain objects. Instead, the actual type was: '\" + kindOf(action) + \"'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.\");\n }\n\n if (typeof action.type === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : 'Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.');\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : 'Reducers may not dispatch actions.');\n }\n\n try {\n isDispatching = true;\n currentState = currentReducer(currentState, action);\n } finally {\n isDispatching = false;\n }\n\n var listeners = currentListeners = nextListeners;\n\n for (var i = 0; i < listeners.length; i++) {\n var listener = listeners[i];\n listener();\n }\n\n return action;\n }\n /**\n * Replaces the reducer currently used by the store to calculate the state.\n *\n * You might need this if your app implements code splitting and you want to\n * load some of the reducers dynamically. You might also need this if you\n * implement a hot reloading mechanism for Redux.\n *\n * @param {Function} nextReducer The reducer for the store to use instead.\n * @returns {void}\n */\n\n\n function replaceReducer(nextReducer) {\n if (typeof nextReducer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : \"Expected the nextReducer to be a function. Instead, received: '\" + kindOf(nextReducer));\n }\n\n currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.\n // Any reducers that existed in both the new and old rootReducer\n // will receive the previous state. This effectively populates\n // the new state tree with any relevant data from the old one.\n\n dispatch({\n type: ActionTypes.REPLACE\n });\n }\n /**\n * Interoperability point for observable/reactive libraries.\n * @returns {observable} A minimal observable of state changes.\n * For more information, see the observable proposal:\n * https://github.com/tc39/proposal-observable\n */\n\n\n function observable() {\n var _ref;\n\n var outerSubscribe = subscribe;\n return _ref = {\n /**\n * The minimal observable subscription method.\n * @param {Object} observer Any object that can be used as an observer.\n * The observer object should have a `next` method.\n * @returns {subscription} An object with an `unsubscribe` method that can\n * be used to unsubscribe the observable from the store, and prevent further\n * emission of values from the observable.\n */\n subscribe: function subscribe(observer) {\n if (typeof observer !== 'object' || observer === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : \"Expected the observer to be an object. Instead, received: '\" + kindOf(observer) + \"'\");\n }\n\n function observeState() {\n if (observer.next) {\n observer.next(getState());\n }\n }\n\n observeState();\n var unsubscribe = outerSubscribe(observeState);\n return {\n unsubscribe: unsubscribe\n };\n }\n }, _ref[$$observable] = function () {\n return this;\n }, _ref;\n } // When a store is created, an \"INIT\" action is dispatched so that every\n // reducer returns their initial state. This effectively populates\n // the initial state tree.\n\n\n dispatch({\n type: ActionTypes.INIT\n });\n return _ref2 = {\n dispatch: dispatch,\n subscribe: subscribe,\n getState: getState,\n replaceReducer: replaceReducer\n }, _ref2[$$observable] = observable, _ref2;\n}\n/**\n * Creates a Redux store that holds the state tree.\n *\n * **We recommend using `configureStore` from the\n * `@reduxjs/toolkit` package**, which replaces `createStore`:\n * **https://redux.js.org/introduction/why-rtk-is-redux-today**\n *\n * The only way to change the data in the store is to call `dispatch()` on it.\n *\n * There should only be a single store in your app. To specify how different\n * parts of the state tree respond to actions, you may combine several reducers\n * into a single reducer function by using `combineReducers`.\n *\n * @param {Function} reducer A function that returns the next state tree, given\n * the current state tree and the action to handle.\n *\n * @param {any} [preloadedState] The initial state. You may optionally specify it\n * to hydrate the state from the server in universal apps, or to restore a\n * previously serialized user session.\n * If you use `combineReducers` to produce the root reducer function, this must be\n * an object with the same shape as `combineReducers` keys.\n *\n * @param {Function} [enhancer] The store enhancer. You may optionally specify it\n * to enhance the store with third-party capabilities such as middleware,\n * time travel, persistence, etc. The only store enhancer that ships with Redux\n * is `applyMiddleware()`.\n *\n * @returns {Store} A Redux store that lets you read the state, dispatch actions\n * and subscribe to changes.\n */\n\nvar legacy_createStore = createStore;\n\n/**\n * Prints a warning in the console if it exists.\n *\n * @param {String} message The warning message.\n * @returns {void}\n */\nfunction warning(message) {\n /* eslint-disable no-console */\n if (typeof console !== 'undefined' && typeof console.error === 'function') {\n console.error(message);\n }\n /* eslint-enable no-console */\n\n\n try {\n // This error was thrown as a convenience so that if you enable\n // \"break on all exceptions\" in your console,\n // it would pause the execution at this line.\n throw new Error(message);\n } catch (e) {} // eslint-disable-line no-empty\n\n}\n\nfunction getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {\n var reducerKeys = Object.keys(reducers);\n var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';\n\n if (reducerKeys.length === 0) {\n return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';\n }\n\n if (!isPlainObject(inputState)) {\n return \"The \" + argumentName + \" has unexpected type of \\\"\" + kindOf(inputState) + \"\\\". Expected argument to be an object with the following \" + (\"keys: \\\"\" + reducerKeys.join('\", \"') + \"\\\"\");\n }\n\n var unexpectedKeys = Object.keys(inputState).filter(function (key) {\n return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];\n });\n unexpectedKeys.forEach(function (key) {\n unexpectedKeyCache[key] = true;\n });\n if (action && action.type === ActionTypes.REPLACE) return;\n\n if (unexpectedKeys.length > 0) {\n 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.\");\n }\n}\n\nfunction assertReducerShape(reducers) {\n Object.keys(reducers).forEach(function (key) {\n var reducer = reducers[key];\n var initialState = reducer(undefined, {\n type: ActionTypes.INIT\n });\n\n if (typeof initialState === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : \"The slice reducer for key \\\"\" + 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.\");\n }\n\n if (typeof reducer(undefined, {\n type: ActionTypes.PROBE_UNKNOWN_ACTION()\n }) === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : \"The slice reducer for key \\\"\" + 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.\");\n }\n });\n}\n/**\n * Turns an object whose values are different reducer functions, into a single\n * reducer function. It will call every child reducer, and gather their results\n * into a single state object, whose keys correspond to the keys of the passed\n * reducer functions.\n *\n * @param {Object} reducers An object whose values correspond to different\n * reducer functions that need to be combined into one. One handy way to obtain\n * it is to use ES6 `import * as reducers` syntax. The reducers may never return\n * undefined for any action. Instead, they should return their initial state\n * if the state passed to them was undefined, and the current state for any\n * unrecognized action.\n *\n * @returns {Function} A reducer function that invokes every reducer inside the\n * passed object, and builds a state object with the same shape.\n */\n\n\nfunction combineReducers(reducers) {\n var reducerKeys = Object.keys(reducers);\n var finalReducers = {};\n\n for (var i = 0; i < reducerKeys.length; i++) {\n var key = reducerKeys[i];\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof reducers[key] === 'undefined') {\n warning(\"No reducer provided for key \\\"\" + key + \"\\\"\");\n }\n }\n\n if (typeof reducers[key] === 'function') {\n finalReducers[key] = reducers[key];\n }\n }\n\n var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same\n // keys multiple times.\n\n var unexpectedKeyCache;\n\n if (process.env.NODE_ENV !== 'production') {\n unexpectedKeyCache = {};\n }\n\n var shapeAssertionError;\n\n try {\n assertReducerShape(finalReducers);\n } catch (e) {\n shapeAssertionError = e;\n }\n\n return function combination(state, action) {\n if (state === void 0) {\n state = {};\n }\n\n if (shapeAssertionError) {\n throw shapeAssertionError;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);\n\n if (warningMessage) {\n warning(warningMessage);\n }\n }\n\n var hasChanged = false;\n var nextState = {};\n\n for (var _i = 0; _i < finalReducerKeys.length; _i++) {\n var _key = finalReducerKeys[_i];\n var reducer = finalReducers[_key];\n var previousStateForKey = state[_key];\n var nextStateForKey = reducer(previousStateForKey, action);\n\n if (typeof nextStateForKey === 'undefined') {\n var actionType = action && action.type;\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : \"When called with an action of type \" + (actionType ? \"\\\"\" + String(actionType) + \"\\\"\" : '(unknown type)') + \", the slice reducer for key \\\"\" + _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.\");\n }\n\n nextState[_key] = nextStateForKey;\n hasChanged = hasChanged || nextStateForKey !== previousStateForKey;\n }\n\n hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;\n return hasChanged ? nextState : state;\n };\n}\n\nfunction bindActionCreator(actionCreator, dispatch) {\n return function () {\n return dispatch(actionCreator.apply(this, arguments));\n };\n}\n/**\n * Turns an object whose values are action creators, into an object with the\n * same keys, but with every function wrapped into a `dispatch` call so they\n * may be invoked directly. This is just a convenience method, as you can call\n * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.\n *\n * For convenience, you can also pass an action creator as the first argument,\n * and get a dispatch wrapped function in return.\n *\n * @param {Function|Object} actionCreators An object whose values are action\n * creator functions. One handy way to obtain it is to use ES6 `import * as`\n * syntax. You may also pass a single function.\n *\n * @param {Function} dispatch The `dispatch` function available on your Redux\n * store.\n *\n * @returns {Function|Object} The object mimicking the original object, but with\n * every action creator wrapped into the `dispatch` call. If you passed a\n * function as `actionCreators`, the return value will also be a single\n * function.\n */\n\n\nfunction bindActionCreators(actionCreators, dispatch) {\n if (typeof actionCreators === 'function') {\n return bindActionCreator(actionCreators, dispatch);\n }\n\n if (typeof actionCreators !== 'object' || actionCreators === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : \"bindActionCreators expected an object or a function, but instead received: '\" + kindOf(actionCreators) + \"'. \" + \"Did you write \\\"import ActionCreators from\\\" instead of \\\"import * as ActionCreators from\\\"?\");\n }\n\n var boundActionCreators = {};\n\n for (var key in actionCreators) {\n var actionCreator = actionCreators[key];\n\n if (typeof actionCreator === 'function') {\n boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);\n }\n }\n\n return boundActionCreators;\n}\n\n/**\n * Composes single-argument functions from right to left. The rightmost\n * function can take multiple arguments as it provides the signature for\n * the resulting composite function.\n *\n * @param {...Function} funcs The functions to compose.\n * @returns {Function} A function obtained by composing the argument functions\n * from right to left. For example, compose(f, g, h) is identical to doing\n * (...args) => f(g(h(...args))).\n */\nfunction compose() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n if (funcs.length === 0) {\n return function (arg) {\n return arg;\n };\n }\n\n if (funcs.length === 1) {\n return funcs[0];\n }\n\n return funcs.reduce(function (a, b) {\n return function () {\n return a(b.apply(void 0, arguments));\n };\n });\n}\n\n/**\n * Creates a store enhancer that applies middleware to the dispatch method\n * of the Redux store. This is handy for a variety of tasks, such as expressing\n * asynchronous actions in a concise manner, or logging every action payload.\n *\n * See `redux-thunk` package as an example of the Redux middleware.\n *\n * Because middleware is potentially asynchronous, this should be the first\n * store enhancer in the composition chain.\n *\n * Note that each middleware will be given the `dispatch` and `getState` functions\n * as named arguments.\n *\n * @param {...Function} middlewares The middleware chain to be applied.\n * @returns {Function} A store enhancer applying the middleware.\n */\n\nfunction applyMiddleware() {\n for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {\n middlewares[_key] = arguments[_key];\n }\n\n return function (createStore) {\n return function () {\n var store = createStore.apply(void 0, arguments);\n\n var _dispatch = function dispatch() {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');\n };\n\n var middlewareAPI = {\n getState: store.getState,\n dispatch: function dispatch() {\n return _dispatch.apply(void 0, arguments);\n }\n };\n var chain = middlewares.map(function (middleware) {\n return middleware(middlewareAPI);\n });\n _dispatch = compose.apply(void 0, chain)(store.dispatch);\n return _objectSpread(_objectSpread({}, store), {}, {\n dispatch: _dispatch\n });\n };\n };\n}\n\nexport { ActionTypes as __DO_NOT_USE__ActionTypes, applyMiddleware, bindActionCreators, combineReducers, compose, createStore, legacy_createStore };\n","// Cache implementation based on Erik Rasmussen's `lru-memoize`:\n// https://github.com/erikras/lru-memoize\nvar NOT_FOUND = 'NOT_FOUND';\n\nfunction createSingletonCache(equals) {\n var entry;\n return {\n get: function get(key) {\n if (entry && equals(entry.key, key)) {\n return entry.value;\n }\n\n return NOT_FOUND;\n },\n put: function put(key, value) {\n entry = {\n key: key,\n value: value\n };\n },\n getEntries: function getEntries() {\n return entry ? [entry] : [];\n },\n clear: function clear() {\n entry = undefined;\n }\n };\n}\n\nfunction createLruCache(maxSize, equals) {\n var entries = [];\n\n function get(key) {\n var cacheIndex = entries.findIndex(function (entry) {\n return equals(key, entry.key);\n }); // We found a cached entry\n\n if (cacheIndex > -1) {\n var entry = entries[cacheIndex]; // Cached entry not at top of cache, move it to the top\n\n if (cacheIndex > 0) {\n entries.splice(cacheIndex, 1);\n entries.unshift(entry);\n }\n\n return entry.value;\n } // No entry found in cache, return sentinel\n\n\n return NOT_FOUND;\n }\n\n function put(key, value) {\n if (get(key) === NOT_FOUND) {\n // TODO Is unshift slow?\n entries.unshift({\n key: key,\n value: value\n });\n\n if (entries.length > maxSize) {\n entries.pop();\n }\n }\n }\n\n function getEntries() {\n return entries;\n }\n\n function clear() {\n entries = [];\n }\n\n return {\n get: get,\n put: put,\n getEntries: getEntries,\n clear: clear\n };\n}\n\nexport var defaultEqualityCheck = function defaultEqualityCheck(a, b) {\n return a === b;\n};\nexport function createCacheKeyComparator(equalityCheck) {\n return function areArgumentsShallowlyEqual(prev, next) {\n if (prev === null || next === null || prev.length !== next.length) {\n return false;\n } // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.\n\n\n var length = prev.length;\n\n for (var i = 0; i < length; i++) {\n if (!equalityCheck(prev[i], next[i])) {\n return false;\n }\n }\n\n return true;\n };\n}\n// defaultMemoize now supports a configurable cache size with LRU behavior,\n// and optional comparison of the result value with existing values\nexport function defaultMemoize(func, equalityCheckOrOptions) {\n var providedOptions = typeof equalityCheckOrOptions === 'object' ? equalityCheckOrOptions : {\n equalityCheck: equalityCheckOrOptions\n };\n var _providedOptions$equa = providedOptions.equalityCheck,\n equalityCheck = _providedOptions$equa === void 0 ? defaultEqualityCheck : _providedOptions$equa,\n _providedOptions$maxS = providedOptions.maxSize,\n maxSize = _providedOptions$maxS === void 0 ? 1 : _providedOptions$maxS,\n resultEqualityCheck = providedOptions.resultEqualityCheck;\n var comparator = createCacheKeyComparator(equalityCheck);\n var cache = maxSize === 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator); // we reference arguments instead of spreading them for performance reasons\n\n function memoized() {\n var value = cache.get(arguments);\n\n if (value === NOT_FOUND) {\n // @ts-ignore\n value = func.apply(null, arguments);\n\n if (resultEqualityCheck) {\n var entries = cache.getEntries();\n var matchingEntry = entries.find(function (entry) {\n return resultEqualityCheck(entry.value, value);\n });\n\n if (matchingEntry) {\n value = matchingEntry.value;\n }\n }\n\n cache.put(arguments, value);\n }\n\n return value;\n }\n\n memoized.clearCache = function () {\n return cache.clear();\n };\n\n return memoized;\n}","import { defaultMemoize, defaultEqualityCheck } from './defaultMemoize';\nexport { defaultMemoize, defaultEqualityCheck };\n\nfunction getDependencies(funcs) {\n var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs;\n\n if (!dependencies.every(function (dep) {\n return typeof dep === 'function';\n })) {\n var dependencyTypes = dependencies.map(function (dep) {\n return typeof dep === 'function' ? \"function \" + (dep.name || 'unnamed') + \"()\" : typeof dep;\n }).join(', ');\n throw new Error(\"createSelector expects all input-selectors to be functions, but received the following types: [\" + dependencyTypes + \"]\");\n }\n\n return dependencies;\n}\n\nexport function createSelectorCreator(memoize) {\n for (var _len = arguments.length, memoizeOptionsFromArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n memoizeOptionsFromArgs[_key - 1] = arguments[_key];\n }\n\n var createSelector = function createSelector() {\n for (var _len2 = arguments.length, funcs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n funcs[_key2] = arguments[_key2];\n }\n\n var _recomputations = 0;\n\n var _lastResult; // Due to the intricacies of rest params, we can't do an optional arg after `...funcs`.\n // So, start by declaring the default value here.\n // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.)\n\n\n var directlyPassedOptions = {\n memoizeOptions: undefined\n }; // Normally, the result func or \"output selector\" is the last arg\n\n var resultFunc = funcs.pop(); // If the result func is actually an _object_, assume it's our options object\n\n if (typeof resultFunc === 'object') {\n directlyPassedOptions = resultFunc; // and pop the real result func off\n\n resultFunc = funcs.pop();\n }\n\n if (typeof resultFunc !== 'function') {\n throw new Error(\"createSelector expects an output function after the inputs, but received: [\" + typeof resultFunc + \"]\");\n } // Determine which set of options we're using. Prefer options passed directly,\n // but fall back to options given to createSelectorCreator.\n\n\n var _directlyPassedOption = directlyPassedOptions,\n _directlyPassedOption2 = _directlyPassedOption.memoizeOptions,\n memoizeOptions = _directlyPassedOption2 === void 0 ? memoizeOptionsFromArgs : _directlyPassedOption2; // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer\n // is an array. In most libs I've looked at, it's an equality function or options object.\n // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full\n // user-provided array of options. Otherwise, it must be just the _first_ arg, and so\n // we wrap it in an array so we can apply it.\n\n var finalMemoizeOptions = Array.isArray(memoizeOptions) ? memoizeOptions : [memoizeOptions];\n var dependencies = getDependencies(funcs);\n var memoizedResultFunc = memoize.apply(void 0, [function recomputationWrapper() {\n _recomputations++; // apply arguments instead of spreading for performance.\n\n return resultFunc.apply(null, arguments);\n }].concat(finalMemoizeOptions)); // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.\n\n var selector = memoize(function dependenciesChecker() {\n var params = [];\n var length = dependencies.length;\n\n for (var i = 0; i < length; i++) {\n // apply arguments instead of spreading and mutate a local list of params for performance.\n // @ts-ignore\n params.push(dependencies[i].apply(null, arguments));\n } // apply arguments instead of spreading for performance.\n\n\n _lastResult = memoizedResultFunc.apply(null, params);\n return _lastResult;\n });\n Object.assign(selector, {\n resultFunc: resultFunc,\n memoizedResultFunc: memoizedResultFunc,\n dependencies: dependencies,\n lastResult: function lastResult() {\n return _lastResult;\n },\n recomputations: function recomputations() {\n return _recomputations;\n },\n resetRecomputations: function resetRecomputations() {\n return _recomputations = 0;\n }\n });\n return selector;\n }; // @ts-ignore\n\n\n return createSelector;\n}\nexport var createSelector = /* #__PURE__ */createSelectorCreator(defaultMemoize);\n// Manual definition of state and output arguments\nexport var createStructuredSelector = function createStructuredSelector(selectors, selectorCreator) {\n if (selectorCreator === void 0) {\n selectorCreator = createSelector;\n }\n\n if (typeof selectors !== 'object') {\n throw new Error('createStructuredSelector expects first argument to be an object ' + (\"where each property is a selector, instead received a \" + typeof selectors));\n }\n\n var objectKeys = Object.keys(selectors);\n var resultSelector = selectorCreator( // @ts-ignore\n objectKeys.map(function (key) {\n return selectors[key];\n }), function () {\n for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n values[_key3] = arguments[_key3];\n }\n\n return values.reduce(function (composition, value, index) {\n composition[objectKeys[index]] = value;\n return composition;\n }, {});\n });\n return resultSelector;\n};","/** A function that accepts a potential \"extra argument\" value to be injected later,\r\n * and returns an instance of the thunk middleware that uses that value\r\n */\nfunction createThunkMiddleware(extraArgument) {\n // Standard Redux middleware definition pattern:\n // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware\n var middleware = function middleware(_ref) {\n var dispatch = _ref.dispatch,\n getState = _ref.getState;\n return function (next) {\n return function (action) {\n // The thunk middleware looks for any functions that were passed to `store.dispatch`.\n // If this \"action\" is really a function, call it and return the result.\n if (typeof action === 'function') {\n // Inject the store's `dispatch` and `getState` methods, as well as any \"extra arg\"\n return action(dispatch, getState, extraArgument);\n } // Otherwise, pass the action down the middleware chain as usual\n\n\n return next(action);\n };\n };\n };\n\n return middleware;\n}\n\nvar thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version\n// with whatever \"extra arg\" they want to inject into their thunks\n\nthunk.withExtraArgument = createThunkMiddleware;\nexport default thunk;","var __extends = (this && this.__extends) || (function () {\r\n var extendStatics = function (d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n };\r\n return function (d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n})();\r\nvar __generator = (this && this.__generator) || function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n};\r\nvar __spreadArray = (this && this.__spreadArray) || function (to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n};\r\nvar __defProp = Object.defineProperty;\r\nvar __defProps = Object.defineProperties;\r\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\r\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\r\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\r\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\r\nvar __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };\r\nvar __spreadValues = function (a, b) {\r\n for (var prop in b || (b = {}))\r\n if (__hasOwnProp.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n if (__getOwnPropSymbols)\r\n for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {\r\n var prop = _c[_i];\r\n if (__propIsEnum.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n }\r\n return a;\r\n};\r\nvar __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };\r\nvar __async = function (__this, __arguments, generator) {\r\n return new Promise(function (resolve, reject) {\r\n var fulfilled = function (value) {\r\n try {\r\n step(generator.next(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var rejected = function (value) {\r\n try {\r\n step(generator.throw(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };\r\n step((generator = generator.apply(__this, __arguments)).next());\r\n });\r\n};\r\n// src/index.ts\r\nimport { enableES5 } from \"immer\";\r\nexport * from \"redux\";\r\nimport { default as default2, current as current2, freeze, original, isDraft as isDraft4 } from \"immer\";\r\nimport { createSelector as createSelector2 } from \"reselect\";\r\n// src/createDraftSafeSelector.ts\r\nimport { current, isDraft } from \"immer\";\r\nimport { createSelector } from \"reselect\";\r\nvar createDraftSafeSelector = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var selector = createSelector.apply(void 0, args);\r\n var wrappedSelector = function (value) {\r\n var rest = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n rest[_i - 1] = arguments[_i];\r\n }\r\n return selector.apply(void 0, __spreadArray([isDraft(value) ? current(value) : value], rest));\r\n };\r\n return wrappedSelector;\r\n};\r\n// src/configureStore.ts\r\nimport { createStore, compose as compose2, applyMiddleware, combineReducers } from \"redux\";\r\n// src/devtoolsExtension.ts\r\nimport { compose } from \"redux\";\r\nvar composeWithDevTools = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {\r\n if (arguments.length === 0)\r\n return void 0;\r\n if (typeof arguments[0] === \"object\")\r\n return compose;\r\n return compose.apply(null, arguments);\r\n};\r\nvar devToolsEnhancer = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {\r\n return function (noop2) {\r\n return noop2;\r\n };\r\n};\r\n// src/isPlainObject.ts\r\nfunction isPlainObject(value) {\r\n if (typeof value !== \"object\" || value === null)\r\n return false;\r\n var proto = Object.getPrototypeOf(value);\r\n if (proto === null)\r\n return true;\r\n var baseProto = proto;\r\n while (Object.getPrototypeOf(baseProto) !== null) {\r\n baseProto = Object.getPrototypeOf(baseProto);\r\n }\r\n return proto === baseProto;\r\n}\r\n// src/getDefaultMiddleware.ts\r\nimport thunkMiddleware from \"redux-thunk\";\r\n// src/utils.ts\r\nimport createNextState, { isDraftable } from \"immer\";\r\nfunction getTimeMeasureUtils(maxDelay, fnName) {\r\n var elapsed = 0;\r\n return {\r\n measureTime: function (fn) {\r\n var started = Date.now();\r\n try {\r\n return fn();\r\n }\r\n finally {\r\n var finished = Date.now();\r\n elapsed += finished - started;\r\n }\r\n },\r\n warnIfExceeded: function () {\r\n if (elapsed > maxDelay) {\r\n console.warn(fnName + \" took \" + elapsed + \"ms, which is more than the warning threshold of \" + maxDelay + \"ms. \\nIf 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.\\nIt is disabled in production builds, so you don't need to worry about that.\");\r\n }\r\n }\r\n };\r\n}\r\nvar MiddlewareArray = /** @class */ (function (_super) {\r\n __extends(MiddlewareArray, _super);\r\n function MiddlewareArray() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var _this = _super.apply(this, args) || this;\r\n Object.setPrototypeOf(_this, MiddlewareArray.prototype);\r\n return _this;\r\n }\r\n Object.defineProperty(MiddlewareArray, Symbol.species, {\r\n get: function () {\r\n return MiddlewareArray;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n MiddlewareArray.prototype.concat = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n return _super.prototype.concat.apply(this, arr);\r\n };\r\n MiddlewareArray.prototype.prepend = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr[0].concat(this))))();\r\n }\r\n return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr.concat(this))))();\r\n };\r\n return MiddlewareArray;\r\n}(Array));\r\nvar EnhancerArray = /** @class */ (function (_super) {\r\n __extends(EnhancerArray, _super);\r\n function EnhancerArray() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var _this = _super.apply(this, args) || this;\r\n Object.setPrototypeOf(_this, EnhancerArray.prototype);\r\n return _this;\r\n }\r\n Object.defineProperty(EnhancerArray, Symbol.species, {\r\n get: function () {\r\n return EnhancerArray;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n EnhancerArray.prototype.concat = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n return _super.prototype.concat.apply(this, arr);\r\n };\r\n EnhancerArray.prototype.prepend = function () {\r\n var arr = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n arr[_i] = arguments[_i];\r\n }\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr[0].concat(this))))();\r\n }\r\n return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr.concat(this))))();\r\n };\r\n return EnhancerArray;\r\n}(Array));\r\nfunction freezeDraftable(val) {\r\n return isDraftable(val) ? createNextState(val, function () {\r\n }) : val;\r\n}\r\n// src/immutableStateInvariantMiddleware.ts\r\nvar isProduction = process.env.NODE_ENV === \"production\";\r\nvar prefix = \"Invariant failed\";\r\nfunction invariant(condition, message) {\r\n if (condition) {\r\n return;\r\n }\r\n if (isProduction) {\r\n throw new Error(prefix);\r\n }\r\n throw new Error(prefix + \": \" + (message || \"\"));\r\n}\r\nfunction stringify(obj, serializer, indent, decycler) {\r\n return JSON.stringify(obj, getSerialize(serializer, decycler), indent);\r\n}\r\nfunction getSerialize(serializer, decycler) {\r\n var stack = [], keys = [];\r\n if (!decycler)\r\n decycler = function (_, value) {\r\n if (stack[0] === value)\r\n return \"[Circular ~]\";\r\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\r\n };\r\n return function (key, value) {\r\n if (stack.length > 0) {\r\n var thisPos = stack.indexOf(this);\r\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\r\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\r\n if (~stack.indexOf(value))\r\n value = decycler.call(this, key, value);\r\n }\r\n else\r\n stack.push(value);\r\n return serializer == null ? value : serializer.call(this, key, value);\r\n };\r\n}\r\nfunction isImmutableDefault(value) {\r\n return typeof value !== \"object\" || value == null || Object.isFrozen(value);\r\n}\r\nfunction trackForMutations(isImmutable, ignorePaths, obj) {\r\n var trackedProperties = trackProperties(isImmutable, ignorePaths, obj);\r\n return {\r\n detectMutations: function () {\r\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);\r\n }\r\n };\r\n}\r\nfunction trackProperties(isImmutable, ignorePaths, obj, path) {\r\n if (ignorePaths === void 0) { ignorePaths = []; }\r\n if (path === void 0) { path = \"\"; }\r\n var tracked = { value: obj };\r\n if (!isImmutable(obj)) {\r\n tracked.children = {};\r\n for (var key in obj) {\r\n var childPath = path ? path + \".\" + key : key;\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue;\r\n }\r\n tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);\r\n }\r\n }\r\n return tracked;\r\n}\r\nfunction detectMutations(isImmutable, ignoredPaths, trackedProperty, obj, sameParentRef, path) {\r\n if (ignoredPaths === void 0) { ignoredPaths = []; }\r\n if (sameParentRef === void 0) { sameParentRef = false; }\r\n if (path === void 0) { path = \"\"; }\r\n var prevObj = trackedProperty ? trackedProperty.value : void 0;\r\n var sameRef = prevObj === obj;\r\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\r\n return { wasMutated: true, path: path };\r\n }\r\n if (isImmutable(prevObj) || isImmutable(obj)) {\r\n return { wasMutated: false };\r\n }\r\n var keysToDetect = {};\r\n for (var key in trackedProperty.children) {\r\n keysToDetect[key] = true;\r\n }\r\n for (var key in obj) {\r\n keysToDetect[key] = true;\r\n }\r\n var hasIgnoredPaths = ignoredPaths.length > 0;\r\n var _loop_1 = function (key) {\r\n var nestedPath = path ? path + \".\" + key : key;\r\n if (hasIgnoredPaths) {\r\n var hasMatches = ignoredPaths.some(function (ignored) {\r\n if (ignored instanceof RegExp) {\r\n return ignored.test(nestedPath);\r\n }\r\n return nestedPath === ignored;\r\n });\r\n if (hasMatches) {\r\n return \"continue\";\r\n }\r\n }\r\n var result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\r\n if (result.wasMutated) {\r\n return { value: result };\r\n }\r\n };\r\n for (var key in keysToDetect) {\r\n var state_1 = _loop_1(key);\r\n if (typeof state_1 === \"object\")\r\n return state_1.value;\r\n }\r\n return { wasMutated: false };\r\n}\r\nfunction createImmutableStateInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _c = options.isImmutable, isImmutable = _c === void 0 ? isImmutableDefault : _c, ignoredPaths = options.ignoredPaths, _d = options.warnAfter, warnAfter = _d === void 0 ? 32 : _d, ignore = options.ignore;\r\n ignoredPaths = ignoredPaths || ignore;\r\n var track = trackForMutations.bind(null, isImmutable, ignoredPaths);\r\n return function (_c) {\r\n var getState = _c.getState;\r\n var state = getState();\r\n var tracker = track(state);\r\n var result;\r\n return function (next) { return function (action) {\r\n var measureUtils = getTimeMeasureUtils(warnAfter, \"ImmutableStateInvariantMiddleware\");\r\n measureUtils.measureTime(function () {\r\n state = getState();\r\n result = tracker.detectMutations();\r\n tracker = track(state);\r\n 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)\");\r\n });\r\n var dispatchedAction = next(action);\r\n measureUtils.measureTime(function () {\r\n state = getState();\r\n result = tracker.detectMutations();\r\n tracker = track(state);\r\n 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)\");\r\n });\r\n measureUtils.warnIfExceeded();\r\n return dispatchedAction;\r\n }; };\r\n };\r\n}\r\n// src/serializableStateInvariantMiddleware.ts\r\nfunction isPlain(val) {\r\n var type = typeof val;\r\n return val == null || type === \"string\" || type === \"boolean\" || type === \"number\" || Array.isArray(val) || isPlainObject(val);\r\n}\r\nfunction findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths, cache) {\r\n if (path === void 0) { path = \"\"; }\r\n if (isSerializable === void 0) { isSerializable = isPlain; }\r\n if (ignoredPaths === void 0) { ignoredPaths = []; }\r\n var foundNestedSerializable;\r\n if (!isSerializable(value)) {\r\n return {\r\n keyPath: path || \"\",\r\n value: value\r\n };\r\n }\r\n if (typeof value !== \"object\" || value === null) {\r\n return false;\r\n }\r\n if (cache == null ? void 0 : cache.has(value))\r\n return false;\r\n var entries = getEntries != null ? getEntries(value) : Object.entries(value);\r\n var hasIgnoredPaths = ignoredPaths.length > 0;\r\n var _loop_2 = function (key, nestedValue) {\r\n var nestedPath = path ? path + \".\" + key : key;\r\n if (hasIgnoredPaths) {\r\n var hasMatches = ignoredPaths.some(function (ignored) {\r\n if (ignored instanceof RegExp) {\r\n return ignored.test(nestedPath);\r\n }\r\n return nestedPath === ignored;\r\n });\r\n if (hasMatches) {\r\n return \"continue\";\r\n }\r\n }\r\n if (!isSerializable(nestedValue)) {\r\n return { value: {\r\n keyPath: nestedPath,\r\n value: nestedValue\r\n } };\r\n }\r\n if (typeof nestedValue === \"object\") {\r\n foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\r\n if (foundNestedSerializable) {\r\n return { value: foundNestedSerializable };\r\n }\r\n }\r\n };\r\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\r\n var _c = entries_1[_i], key = _c[0], nestedValue = _c[1];\r\n var state_2 = _loop_2(key, nestedValue);\r\n if (typeof state_2 === \"object\")\r\n return state_2.value;\r\n }\r\n if (cache && isNestedFrozen(value))\r\n cache.add(value);\r\n return false;\r\n}\r\nfunction isNestedFrozen(value) {\r\n if (!Object.isFrozen(value))\r\n return false;\r\n for (var _i = 0, _c = Object.values(value); _i < _c.length; _i++) {\r\n var nestedValue = _c[_i];\r\n if (typeof nestedValue !== \"object\" || nestedValue === null)\r\n continue;\r\n if (!isNestedFrozen(nestedValue))\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction createSerializableStateInvariantMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n if (process.env.NODE_ENV === \"production\") {\r\n return function () { return function (next) { return function (action) { return next(action); }; }; };\r\n }\r\n var _c = options.isSerializable, isSerializable = _c === void 0 ? isPlain : _c, getEntries = options.getEntries, _d = options.ignoredActions, ignoredActions = _d === void 0 ? [] : _d, _e = options.ignoredActionPaths, ignoredActionPaths = _e === void 0 ? [\"meta.arg\", \"meta.baseQueryMeta\"] : _e, _f = options.ignoredPaths, ignoredPaths = _f === void 0 ? [] : _f, _g = options.warnAfter, warnAfter = _g === void 0 ? 32 : _g, _h = options.ignoreState, ignoreState = _h === void 0 ? false : _h, _j = options.ignoreActions, ignoreActions = _j === void 0 ? false : _j, _k = options.disableCache, disableCache = _k === void 0 ? false : _k;\r\n var cache = !disableCache && WeakSet ? new WeakSet() : void 0;\r\n return function (storeAPI) { return function (next) { return function (action) {\r\n var result = next(action);\r\n var measureUtils = getTimeMeasureUtils(warnAfter, \"SerializableStateInvariantMiddleware\");\r\n if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {\r\n measureUtils.measureTime(function () {\r\n var foundActionNonSerializableValue = findNonSerializableValue(action, \"\", isSerializable, getEntries, ignoredActionPaths, cache);\r\n if (foundActionNonSerializableValue) {\r\n var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value;\r\n 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)\");\r\n }\r\n });\r\n }\r\n if (!ignoreState) {\r\n measureUtils.measureTime(function () {\r\n var state = storeAPI.getState();\r\n var foundStateNonSerializableValue = findNonSerializableValue(state, \"\", isSerializable, getEntries, ignoredPaths, cache);\r\n if (foundStateNonSerializableValue) {\r\n var keyPath = foundStateNonSerializableValue.keyPath, value = foundStateNonSerializableValue.value;\r\n 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)\");\r\n }\r\n });\r\n measureUtils.warnIfExceeded();\r\n }\r\n return result;\r\n }; }; };\r\n}\r\n// src/getDefaultMiddleware.ts\r\nfunction isBoolean(x) {\r\n return typeof x === \"boolean\";\r\n}\r\nfunction curryGetDefaultMiddleware() {\r\n return function curriedGetDefaultMiddleware(options) {\r\n return getDefaultMiddleware(options);\r\n };\r\n}\r\nfunction getDefaultMiddleware(options) {\r\n if (options === void 0) { options = {}; }\r\n var _c = options.thunk, thunk = _c === void 0 ? true : _c, _d = options.immutableCheck, immutableCheck = _d === void 0 ? true : _d, _e = options.serializableCheck, serializableCheck = _e === void 0 ? true : _e;\r\n var middlewareArray = new MiddlewareArray();\r\n if (thunk) {\r\n if (isBoolean(thunk)) {\r\n middlewareArray.push(thunkMiddleware);\r\n }\r\n else {\r\n middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));\r\n }\r\n }\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (immutableCheck) {\r\n var immutableOptions = {};\r\n if (!isBoolean(immutableCheck)) {\r\n immutableOptions = immutableCheck;\r\n }\r\n middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\r\n }\r\n if (serializableCheck) {\r\n var serializableOptions = {};\r\n if (!isBoolean(serializableCheck)) {\r\n serializableOptions = serializableCheck;\r\n }\r\n middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\r\n }\r\n }\r\n return middlewareArray;\r\n}\r\n// src/configureStore.ts\r\nvar IS_PRODUCTION = process.env.NODE_ENV === \"production\";\r\nfunction configureStore(options) {\r\n var curriedGetDefaultMiddleware = curryGetDefaultMiddleware();\r\n var _c = options || {}, _d = _c.reducer, reducer = _d === void 0 ? void 0 : _d, _e = _c.middleware, middleware = _e === void 0 ? curriedGetDefaultMiddleware() : _e, _f = _c.devTools, devTools = _f === void 0 ? true : _f, _g = _c.preloadedState, preloadedState = _g === void 0 ? void 0 : _g, _h = _c.enhancers, enhancers = _h === void 0 ? void 0 : _h;\r\n var rootReducer;\r\n if (typeof reducer === \"function\") {\r\n rootReducer = reducer;\r\n }\r\n else if (isPlainObject(reducer)) {\r\n rootReducer = combineReducers(reducer);\r\n }\r\n else {\r\n throw new Error('\"reducer\" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');\r\n }\r\n var finalMiddleware = middleware;\r\n if (typeof finalMiddleware === \"function\") {\r\n finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);\r\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\r\n throw new Error(\"when using a middleware builder function, an array of middleware must be returned\");\r\n }\r\n }\r\n if (!IS_PRODUCTION && finalMiddleware.some(function (item) { return typeof item !== \"function\"; })) {\r\n throw new Error(\"each middleware provided to configureStore must be a function\");\r\n }\r\n var middlewareEnhancer = applyMiddleware.apply(void 0, finalMiddleware);\r\n var finalCompose = compose2;\r\n if (devTools) {\r\n finalCompose = composeWithDevTools(__spreadValues({\r\n trace: !IS_PRODUCTION\r\n }, typeof devTools === \"object\" && devTools));\r\n }\r\n var defaultEnhancers = new EnhancerArray(middlewareEnhancer);\r\n var storeEnhancers = defaultEnhancers;\r\n if (Array.isArray(enhancers)) {\r\n storeEnhancers = __spreadArray([middlewareEnhancer], enhancers);\r\n }\r\n else if (typeof enhancers === \"function\") {\r\n storeEnhancers = enhancers(defaultEnhancers);\r\n }\r\n var composedEnhancer = finalCompose.apply(void 0, storeEnhancers);\r\n return createStore(rootReducer, preloadedState, composedEnhancer);\r\n}\r\n// src/createAction.ts\r\nfunction createAction(type, prepareAction) {\r\n function actionCreator() {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n if (prepareAction) {\r\n var prepared = prepareAction.apply(void 0, args);\r\n if (!prepared) {\r\n throw new Error(\"prepareAction did not return an object\");\r\n }\r\n return __spreadValues(__spreadValues({\r\n type: type,\r\n payload: prepared.payload\r\n }, \"meta\" in prepared && { meta: prepared.meta }), \"error\" in prepared && { error: prepared.error });\r\n }\r\n return { type: type, payload: args[0] };\r\n }\r\n actionCreator.toString = function () { return \"\" + type; };\r\n actionCreator.type = type;\r\n actionCreator.match = function (action) { return action.type === type; };\r\n return actionCreator;\r\n}\r\nfunction isAction(action) {\r\n return isPlainObject(action) && \"type\" in action;\r\n}\r\nfunction isFSA(action) {\r\n return isAction(action) && typeof action.type === \"string\" && Object.keys(action).every(isValidKey);\r\n}\r\nfunction isValidKey(key) {\r\n return [\"type\", \"payload\", \"error\", \"meta\"].indexOf(key) > -1;\r\n}\r\nfunction getType(actionCreator) {\r\n return \"\" + actionCreator;\r\n}\r\n// src/createReducer.ts\r\nimport createNextState2, { isDraft as isDraft2, isDraftable as isDraftable2 } from \"immer\";\r\n// src/mapBuilders.ts\r\nfunction executeReducerBuilderCallback(builderCallback) {\r\n var actionsMap = {};\r\n var actionMatchers = [];\r\n var defaultCaseReducer;\r\n var builder = {\r\n addCase: function (typeOrActionCreator, reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (actionMatchers.length > 0) {\r\n throw new Error(\"`builder.addCase` should only be called before calling `builder.addMatcher`\");\r\n }\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addCase` should only be called before calling `builder.addDefaultCase`\");\r\n }\r\n }\r\n var type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\r\n if (type in actionsMap) {\r\n throw new Error(\"addCase cannot be called with two reducers for the same action type\");\r\n }\r\n actionsMap[type] = reducer;\r\n return builder;\r\n },\r\n addMatcher: function (matcher, reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`\");\r\n }\r\n }\r\n actionMatchers.push({ matcher: matcher, reducer: reducer });\r\n return builder;\r\n },\r\n addDefaultCase: function (reducer) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (defaultCaseReducer) {\r\n throw new Error(\"`builder.addDefaultCase` can only be called once\");\r\n }\r\n }\r\n defaultCaseReducer = reducer;\r\n return builder;\r\n }\r\n };\r\n builderCallback(builder);\r\n return [actionsMap, actionMatchers, defaultCaseReducer];\r\n}\r\n// src/createReducer.ts\r\nfunction isStateFunction(x) {\r\n return typeof x === \"function\";\r\n}\r\nvar hasWarnedAboutObjectNotation = false;\r\nfunction createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) {\r\n if (actionMatchers === void 0) { actionMatchers = []; }\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (typeof mapOrBuilderCallback === \"object\") {\r\n if (!hasWarnedAboutObjectNotation) {\r\n hasWarnedAboutObjectNotation = true;\r\n console.warn(\"The object notation for `createReducer` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\r\n }\r\n }\r\n }\r\n var _c = typeof mapOrBuilderCallback === \"function\" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _c[0], finalActionMatchers = _c[1], finalDefaultCaseReducer = _c[2];\r\n var getInitialState;\r\n if (isStateFunction(initialState)) {\r\n getInitialState = function () { return freezeDraftable(initialState()); };\r\n }\r\n else {\r\n var frozenInitialState_1 = freezeDraftable(initialState);\r\n getInitialState = function () { return frozenInitialState_1; };\r\n }\r\n function reducer(state, action) {\r\n if (state === void 0) { state = getInitialState(); }\r\n var caseReducers = __spreadArray([\r\n actionsMap[action.type]\r\n ], finalActionMatchers.filter(function (_c) {\r\n var matcher = _c.matcher;\r\n return matcher(action);\r\n }).map(function (_c) {\r\n var reducer2 = _c.reducer;\r\n return reducer2;\r\n }));\r\n if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) {\r\n caseReducers = [finalDefaultCaseReducer];\r\n }\r\n return caseReducers.reduce(function (previousState, caseReducer) {\r\n if (caseReducer) {\r\n if (isDraft2(previousState)) {\r\n var draft = previousState;\r\n var result = caseReducer(draft, action);\r\n if (result === void 0) {\r\n return previousState;\r\n }\r\n return result;\r\n }\r\n else if (!isDraftable2(previousState)) {\r\n var result = caseReducer(previousState, action);\r\n if (result === void 0) {\r\n if (previousState === null) {\r\n return previousState;\r\n }\r\n throw Error(\"A case reducer on a non-draftable value must not return undefined\");\r\n }\r\n return result;\r\n }\r\n else {\r\n return createNextState2(previousState, function (draft) {\r\n return caseReducer(draft, action);\r\n });\r\n }\r\n }\r\n return previousState;\r\n }, state);\r\n }\r\n reducer.getInitialState = getInitialState;\r\n return reducer;\r\n}\r\n// src/createSlice.ts\r\nvar hasWarnedAboutObjectNotation2 = false;\r\nfunction getType2(slice, actionKey) {\r\n return slice + \"/\" + actionKey;\r\n}\r\nfunction createSlice(options) {\r\n var name = options.name;\r\n if (!name) {\r\n throw new Error(\"`name` is a required option for createSlice\");\r\n }\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n if (options.initialState === void 0) {\r\n console.error(\"You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`\");\r\n }\r\n }\r\n var initialState = typeof options.initialState == \"function\" ? options.initialState : freezeDraftable(options.initialState);\r\n var reducers = options.reducers || {};\r\n var reducerNames = Object.keys(reducers);\r\n var sliceCaseReducersByName = {};\r\n var sliceCaseReducersByType = {};\r\n var actionCreators = {};\r\n reducerNames.forEach(function (reducerName) {\r\n var maybeReducerWithPrepare = reducers[reducerName];\r\n var type = getType2(name, reducerName);\r\n var caseReducer;\r\n var prepareCallback;\r\n if (\"reducer\" in maybeReducerWithPrepare) {\r\n caseReducer = maybeReducerWithPrepare.reducer;\r\n prepareCallback = maybeReducerWithPrepare.prepare;\r\n }\r\n else {\r\n caseReducer = maybeReducerWithPrepare;\r\n }\r\n sliceCaseReducersByName[reducerName] = caseReducer;\r\n sliceCaseReducersByType[type] = caseReducer;\r\n actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);\r\n });\r\n function buildReducer() {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (typeof options.extraReducers === \"object\") {\r\n if (!hasWarnedAboutObjectNotation2) {\r\n hasWarnedAboutObjectNotation2 = true;\r\n console.warn(\"The object notation for `createSlice.extraReducers` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\r\n }\r\n }\r\n }\r\n var _c = typeof options.extraReducers === \"function\" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers], _d = _c[0], extraReducers = _d === void 0 ? {} : _d, _e = _c[1], actionMatchers = _e === void 0 ? [] : _e, _f = _c[2], defaultCaseReducer = _f === void 0 ? void 0 : _f;\r\n var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);\r\n return createReducer(initialState, function (builder) {\r\n for (var key in finalCaseReducers) {\r\n builder.addCase(key, finalCaseReducers[key]);\r\n }\r\n for (var _i = 0, actionMatchers_1 = actionMatchers; _i < actionMatchers_1.length; _i++) {\r\n var m = actionMatchers_1[_i];\r\n builder.addMatcher(m.matcher, m.reducer);\r\n }\r\n if (defaultCaseReducer) {\r\n builder.addDefaultCase(defaultCaseReducer);\r\n }\r\n });\r\n }\r\n var _reducer;\r\n return {\r\n name: name,\r\n reducer: function (state, action) {\r\n if (!_reducer)\r\n _reducer = buildReducer();\r\n return _reducer(state, action);\r\n },\r\n actions: actionCreators,\r\n caseReducers: sliceCaseReducersByName,\r\n getInitialState: function () {\r\n if (!_reducer)\r\n _reducer = buildReducer();\r\n return _reducer.getInitialState();\r\n }\r\n };\r\n}\r\n// src/entities/entity_state.ts\r\nfunction getInitialEntityState() {\r\n return {\r\n ids: [],\r\n entities: {}\r\n };\r\n}\r\nfunction createInitialStateFactory() {\r\n function getInitialState(additionalState) {\r\n if (additionalState === void 0) { additionalState = {}; }\r\n return Object.assign(getInitialEntityState(), additionalState);\r\n }\r\n return { getInitialState: getInitialState };\r\n}\r\n// src/entities/state_selectors.ts\r\nfunction createSelectorsFactory() {\r\n function getSelectors(selectState) {\r\n var selectIds = function (state) { return state.ids; };\r\n var selectEntities = function (state) { return state.entities; };\r\n var selectAll = createDraftSafeSelector(selectIds, selectEntities, function (ids, entities) { return ids.map(function (id) { return entities[id]; }); });\r\n var selectId = function (_, id) { return id; };\r\n var selectById = function (entities, id) { return entities[id]; };\r\n var selectTotal = createDraftSafeSelector(selectIds, function (ids) { return ids.length; });\r\n if (!selectState) {\r\n return {\r\n selectIds: selectIds,\r\n selectEntities: selectEntities,\r\n selectAll: selectAll,\r\n selectTotal: selectTotal,\r\n selectById: createDraftSafeSelector(selectEntities, selectId, selectById)\r\n };\r\n }\r\n var selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);\r\n return {\r\n selectIds: createDraftSafeSelector(selectState, selectIds),\r\n selectEntities: selectGlobalizedEntities,\r\n selectAll: createDraftSafeSelector(selectState, selectAll),\r\n selectTotal: createDraftSafeSelector(selectState, selectTotal),\r\n selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)\r\n };\r\n }\r\n return { getSelectors: getSelectors };\r\n}\r\n// src/entities/state_adapter.ts\r\nimport createNextState3, { isDraft as isDraft3 } from \"immer\";\r\nfunction createSingleArgumentStateOperator(mutator) {\r\n var operator = createStateOperator(function (_, state) { return mutator(state); });\r\n return function operation(state) {\r\n return operator(state, void 0);\r\n };\r\n}\r\nfunction createStateOperator(mutator) {\r\n return function operation(state, arg) {\r\n function isPayloadActionArgument(arg2) {\r\n return isFSA(arg2);\r\n }\r\n var runMutator = function (draft) {\r\n if (isPayloadActionArgument(arg)) {\r\n mutator(arg.payload, draft);\r\n }\r\n else {\r\n mutator(arg, draft);\r\n }\r\n };\r\n if (isDraft3(state)) {\r\n runMutator(state);\r\n return state;\r\n }\r\n else {\r\n return createNextState3(state, runMutator);\r\n }\r\n };\r\n}\r\n// src/entities/utils.ts\r\nfunction selectIdValue(entity, selectId) {\r\n var key = selectId(entity);\r\n if (process.env.NODE_ENV !== \"production\" && key === void 0) {\r\n 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());\r\n }\r\n return key;\r\n}\r\nfunction ensureEntitiesArray(entities) {\r\n if (!Array.isArray(entities)) {\r\n entities = Object.values(entities);\r\n }\r\n return entities;\r\n}\r\nfunction splitAddedUpdatedEntities(newEntities, selectId, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n var added = [];\r\n var updated = [];\r\n for (var _i = 0, newEntities_1 = newEntities; _i < newEntities_1.length; _i++) {\r\n var entity = newEntities_1[_i];\r\n var id = selectIdValue(entity, selectId);\r\n if (id in state.entities) {\r\n updated.push({ id: id, changes: entity });\r\n }\r\n else {\r\n added.push(entity);\r\n }\r\n }\r\n return [added, updated];\r\n}\r\n// src/entities/unsorted_state_adapter.ts\r\nfunction createUnsortedStateAdapter(selectId) {\r\n function addOneMutably(entity, state) {\r\n var key = selectIdValue(entity, selectId);\r\n if (key in state.entities) {\r\n return;\r\n }\r\n state.ids.push(key);\r\n state.entities[key] = entity;\r\n }\r\n function addManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n for (var _i = 0, newEntities_2 = newEntities; _i < newEntities_2.length; _i++) {\r\n var entity = newEntities_2[_i];\r\n addOneMutably(entity, state);\r\n }\r\n }\r\n function setOneMutably(entity, state) {\r\n var key = selectIdValue(entity, selectId);\r\n if (!(key in state.entities)) {\r\n state.ids.push(key);\r\n }\r\n state.entities[key] = entity;\r\n }\r\n function setManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n for (var _i = 0, newEntities_3 = newEntities; _i < newEntities_3.length; _i++) {\r\n var entity = newEntities_3[_i];\r\n setOneMutably(entity, state);\r\n }\r\n }\r\n function setAllMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n state.ids = [];\r\n state.entities = {};\r\n addManyMutably(newEntities, state);\r\n }\r\n function removeOneMutably(key, state) {\r\n return removeManyMutably([key], state);\r\n }\r\n function removeManyMutably(keys, state) {\r\n var didMutate = false;\r\n keys.forEach(function (key) {\r\n if (key in state.entities) {\r\n delete state.entities[key];\r\n didMutate = true;\r\n }\r\n });\r\n if (didMutate) {\r\n state.ids = state.ids.filter(function (id) { return id in state.entities; });\r\n }\r\n }\r\n function removeAllMutably(state) {\r\n Object.assign(state, {\r\n ids: [],\r\n entities: {}\r\n });\r\n }\r\n function takeNewKey(keys, update, state) {\r\n var original2 = state.entities[update.id];\r\n var updated = Object.assign({}, original2, update.changes);\r\n var newKey = selectIdValue(updated, selectId);\r\n var hasNewKey = newKey !== update.id;\r\n if (hasNewKey) {\r\n keys[update.id] = newKey;\r\n delete state.entities[update.id];\r\n }\r\n state.entities[newKey] = updated;\r\n return hasNewKey;\r\n }\r\n function updateOneMutably(update, state) {\r\n return updateManyMutably([update], state);\r\n }\r\n function updateManyMutably(updates, state) {\r\n var newKeys = {};\r\n var updatesPerEntity = {};\r\n updates.forEach(function (update) {\r\n if (update.id in state.entities) {\r\n updatesPerEntity[update.id] = {\r\n id: update.id,\r\n changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)\r\n };\r\n }\r\n });\r\n updates = Object.values(updatesPerEntity);\r\n var didMutateEntities = updates.length > 0;\r\n if (didMutateEntities) {\r\n var didMutateIds = updates.filter(function (update) { return takeNewKey(newKeys, update, state); }).length > 0;\r\n if (didMutateIds) {\r\n state.ids = Object.keys(state.entities);\r\n }\r\n }\r\n }\r\n function upsertOneMutably(entity, state) {\r\n return upsertManyMutably([entity], state);\r\n }\r\n function upsertManyMutably(newEntities, state) {\r\n var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];\r\n updateManyMutably(updated, state);\r\n addManyMutably(added, state);\r\n }\r\n return {\r\n removeAll: createSingleArgumentStateOperator(removeAllMutably),\r\n addOne: createStateOperator(addOneMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n upsertMany: createStateOperator(upsertManyMutably),\r\n removeOne: createStateOperator(removeOneMutably),\r\n removeMany: createStateOperator(removeManyMutably)\r\n };\r\n}\r\n// src/entities/sorted_state_adapter.ts\r\nfunction createSortedStateAdapter(selectId, sort) {\r\n var _c = createUnsortedStateAdapter(selectId), removeOne = _c.removeOne, removeMany = _c.removeMany, removeAll = _c.removeAll;\r\n function addOneMutably(entity, state) {\r\n return addManyMutably([entity], state);\r\n }\r\n function addManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n var models = newEntities.filter(function (model) { return !(selectIdValue(model, selectId) in state.entities); });\r\n if (models.length !== 0) {\r\n merge(models, state);\r\n }\r\n }\r\n function setOneMutably(entity, state) {\r\n return setManyMutably([entity], state);\r\n }\r\n function setManyMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n if (newEntities.length !== 0) {\r\n merge(newEntities, state);\r\n }\r\n }\r\n function setAllMutably(newEntities, state) {\r\n newEntities = ensureEntitiesArray(newEntities);\r\n state.entities = {};\r\n state.ids = [];\r\n addManyMutably(newEntities, state);\r\n }\r\n function updateOneMutably(update, state) {\r\n return updateManyMutably([update], state);\r\n }\r\n function updateManyMutably(updates, state) {\r\n var appliedUpdates = false;\r\n for (var _i = 0, updates_1 = updates; _i < updates_1.length; _i++) {\r\n var update = updates_1[_i];\r\n var entity = state.entities[update.id];\r\n if (!entity) {\r\n continue;\r\n }\r\n appliedUpdates = true;\r\n Object.assign(entity, update.changes);\r\n var newId = selectId(entity);\r\n if (update.id !== newId) {\r\n delete state.entities[update.id];\r\n state.entities[newId] = entity;\r\n }\r\n }\r\n if (appliedUpdates) {\r\n resortEntities(state);\r\n }\r\n }\r\n function upsertOneMutably(entity, state) {\r\n return upsertManyMutably([entity], state);\r\n }\r\n function upsertManyMutably(newEntities, state) {\r\n var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];\r\n updateManyMutably(updated, state);\r\n addManyMutably(added, state);\r\n }\r\n function areArraysEqual(a, b) {\r\n if (a.length !== b.length) {\r\n return false;\r\n }\r\n for (var i = 0; i < a.length && i < b.length; i++) {\r\n if (a[i] === b[i]) {\r\n continue;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n function merge(models, state) {\r\n models.forEach(function (model) {\r\n state.entities[selectId(model)] = model;\r\n });\r\n resortEntities(state);\r\n }\r\n function resortEntities(state) {\r\n var allEntities = Object.values(state.entities);\r\n allEntities.sort(sort);\r\n var newSortedIds = allEntities.map(selectId);\r\n var ids = state.ids;\r\n if (!areArraysEqual(ids, newSortedIds)) {\r\n state.ids = newSortedIds;\r\n }\r\n }\r\n return {\r\n removeOne: removeOne,\r\n removeMany: removeMany,\r\n removeAll: removeAll,\r\n addOne: createStateOperator(addOneMutably),\r\n updateOne: createStateOperator(updateOneMutably),\r\n upsertOne: createStateOperator(upsertOneMutably),\r\n setOne: createStateOperator(setOneMutably),\r\n setMany: createStateOperator(setManyMutably),\r\n setAll: createStateOperator(setAllMutably),\r\n addMany: createStateOperator(addManyMutably),\r\n updateMany: createStateOperator(updateManyMutably),\r\n upsertMany: createStateOperator(upsertManyMutably)\r\n };\r\n}\r\n// src/entities/create_adapter.ts\r\nfunction createEntityAdapter(options) {\r\n if (options === void 0) { options = {}; }\r\n var _c = __spreadValues({\r\n sortComparer: false,\r\n selectId: function (instance) { return instance.id; }\r\n }, options), selectId = _c.selectId, sortComparer = _c.sortComparer;\r\n var stateFactory = createInitialStateFactory();\r\n var selectorsFactory = createSelectorsFactory();\r\n var stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\r\n return __spreadValues(__spreadValues(__spreadValues({\r\n selectId: selectId,\r\n sortComparer: sortComparer\r\n }, stateFactory), selectorsFactory), stateAdapter);\r\n}\r\n// src/nanoid.ts\r\nvar urlAlphabet = \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\r\nvar nanoid = function (size) {\r\n if (size === void 0) { size = 21; }\r\n var id = \"\";\r\n var i = size;\r\n while (i--) {\r\n id += urlAlphabet[Math.random() * 64 | 0];\r\n }\r\n return id;\r\n};\r\n// src/createAsyncThunk.ts\r\nvar commonProperties = [\r\n \"name\",\r\n \"message\",\r\n \"stack\",\r\n \"code\"\r\n];\r\nvar RejectWithValue = /** @class */ (function () {\r\n function RejectWithValue(payload, meta) {\r\n this.payload = payload;\r\n this.meta = meta;\r\n }\r\n return RejectWithValue;\r\n}());\r\nvar FulfillWithMeta = /** @class */ (function () {\r\n function FulfillWithMeta(payload, meta) {\r\n this.payload = payload;\r\n this.meta = meta;\r\n }\r\n return FulfillWithMeta;\r\n}());\r\nvar miniSerializeError = function (value) {\r\n if (typeof value === \"object\" && value !== null) {\r\n var simpleError = {};\r\n for (var _i = 0, commonProperties_1 = commonProperties; _i < commonProperties_1.length; _i++) {\r\n var property = commonProperties_1[_i];\r\n if (typeof value[property] === \"string\") {\r\n simpleError[property] = value[property];\r\n }\r\n }\r\n return simpleError;\r\n }\r\n return { message: String(value) };\r\n};\r\nvar createAsyncThunk = (function () {\r\n function createAsyncThunk2(typePrefix, payloadCreator, options) {\r\n var fulfilled = createAction(typePrefix + \"/fulfilled\", function (payload, requestId, arg, meta) { return ({\r\n payload: payload,\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n requestStatus: \"fulfilled\"\r\n })\r\n }); });\r\n var pending = createAction(typePrefix + \"/pending\", function (requestId, arg, meta) { return ({\r\n payload: void 0,\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n requestStatus: \"pending\"\r\n })\r\n }); });\r\n var rejected = createAction(typePrefix + \"/rejected\", function (error, requestId, arg, payload, meta) { return ({\r\n payload: payload,\r\n error: (options && options.serializeError || miniSerializeError)(error || \"Rejected\"),\r\n meta: __spreadProps(__spreadValues({}, meta || {}), {\r\n arg: arg,\r\n requestId: requestId,\r\n rejectedWithValue: !!payload,\r\n requestStatus: \"rejected\",\r\n aborted: (error == null ? void 0 : error.name) === \"AbortError\",\r\n condition: (error == null ? void 0 : error.name) === \"ConditionError\"\r\n })\r\n }); });\r\n var displayedWarning = false;\r\n var AC = typeof AbortController !== \"undefined\" ? AbortController : /** @class */ (function () {\r\n function class_1() {\r\n this.signal = {\r\n aborted: false,\r\n addEventListener: function () {\r\n },\r\n dispatchEvent: function () {\r\n return false;\r\n },\r\n onabort: function () {\r\n },\r\n removeEventListener: function () {\r\n },\r\n reason: void 0,\r\n throwIfAborted: function () {\r\n }\r\n };\r\n }\r\n class_1.prototype.abort = function () {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (!displayedWarning) {\r\n displayedWarning = true;\r\n console.info(\"This platform does not implement AbortController. \\nIf you want to use the AbortController to react to `abort` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.\");\r\n }\r\n }\r\n };\r\n return class_1;\r\n }());\r\n function actionCreator(arg) {\r\n return function (dispatch, getState, extra) {\r\n var requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();\r\n var abortController = new AC();\r\n var abortReason;\r\n var started = false;\r\n function abort(reason) {\r\n abortReason = reason;\r\n abortController.abort();\r\n }\r\n var promise2 = function () {\r\n return __async(this, null, function () {\r\n var _a, _b, finalAction, conditionResult, abortedPromise, err_1, skipDispatch;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n _c.trys.push([0, 4, , 5]);\r\n conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState: getState, extra: extra });\r\n if (!isThenable(conditionResult)) return [3 /*break*/, 2];\r\n return [4 /*yield*/, conditionResult];\r\n case 1:\r\n conditionResult = _c.sent();\r\n _c.label = 2;\r\n case 2:\r\n if (conditionResult === false || abortController.signal.aborted) {\r\n throw {\r\n name: \"ConditionError\",\r\n message: \"Aborted due to condition callback returning false.\"\r\n };\r\n }\r\n started = true;\r\n abortedPromise = new Promise(function (_, reject) { return abortController.signal.addEventListener(\"abort\", function () { return reject({\r\n name: \"AbortError\",\r\n message: abortReason || \"Aborted\"\r\n }); }); });\r\n dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, { requestId: requestId, arg: arg }, { getState: getState, extra: extra })));\r\n return [4 /*yield*/, Promise.race([\r\n abortedPromise,\r\n Promise.resolve(payloadCreator(arg, {\r\n dispatch: dispatch,\r\n getState: getState,\r\n extra: extra,\r\n requestId: requestId,\r\n signal: abortController.signal,\r\n abort: abort,\r\n rejectWithValue: function (value, meta) {\r\n return new RejectWithValue(value, meta);\r\n },\r\n fulfillWithValue: function (value, meta) {\r\n return new FulfillWithMeta(value, meta);\r\n }\r\n })).then(function (result) {\r\n if (result instanceof RejectWithValue) {\r\n throw result;\r\n }\r\n if (result instanceof FulfillWithMeta) {\r\n return fulfilled(result.payload, requestId, arg, result.meta);\r\n }\r\n return fulfilled(result, requestId, arg);\r\n })\r\n ])];\r\n case 3:\r\n finalAction = _c.sent();\r\n return [3 /*break*/, 5];\r\n case 4:\r\n err_1 = _c.sent();\r\n finalAction = err_1 instanceof RejectWithValue ? rejected(null, requestId, arg, err_1.payload, err_1.meta) : rejected(err_1, requestId, arg);\r\n return [3 /*break*/, 5];\r\n case 5:\r\n skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;\r\n if (!skipDispatch) {\r\n dispatch(finalAction);\r\n }\r\n return [2 /*return*/, finalAction];\r\n }\r\n });\r\n });\r\n }();\r\n return Object.assign(promise2, {\r\n abort: abort,\r\n requestId: requestId,\r\n arg: arg,\r\n unwrap: function () {\r\n return promise2.then(unwrapResult);\r\n }\r\n });\r\n };\r\n }\r\n return Object.assign(actionCreator, {\r\n pending: pending,\r\n rejected: rejected,\r\n fulfilled: fulfilled,\r\n typePrefix: typePrefix\r\n });\r\n }\r\n createAsyncThunk2.withTypes = function () { return createAsyncThunk2; };\r\n return createAsyncThunk2;\r\n})();\r\nfunction unwrapResult(action) {\r\n if (action.meta && action.meta.rejectedWithValue) {\r\n throw action.payload;\r\n }\r\n if (action.error) {\r\n throw action.error;\r\n }\r\n return action.payload;\r\n}\r\nfunction isThenable(value) {\r\n return value !== null && typeof value === \"object\" && typeof value.then === \"function\";\r\n}\r\n// src/tsHelpers.ts\r\nvar hasMatchFunction = function (v) {\r\n return v && typeof v.match === \"function\";\r\n};\r\n// src/matchers.ts\r\nvar matches = function (matcher, action) {\r\n if (hasMatchFunction(matcher)) {\r\n return matcher.match(action);\r\n }\r\n else {\r\n return matcher(action);\r\n }\r\n};\r\nfunction isAnyOf() {\r\n var matchers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n matchers[_i] = arguments[_i];\r\n }\r\n return function (action) {\r\n return matchers.some(function (matcher) { return matches(matcher, action); });\r\n };\r\n}\r\nfunction isAllOf() {\r\n var matchers = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n matchers[_i] = arguments[_i];\r\n }\r\n return function (action) {\r\n return matchers.every(function (matcher) { return matches(matcher, action); });\r\n };\r\n}\r\nfunction hasExpectedRequestMetadata(action, validStatus) {\r\n if (!action || !action.meta)\r\n return false;\r\n var hasValidRequestId = typeof action.meta.requestId === \"string\";\r\n var hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\r\n return hasValidRequestId && hasValidRequestStatus;\r\n}\r\nfunction isAsyncThunkArray(a) {\r\n return typeof a[0] === \"function\" && \"pending\" in a[0] && \"fulfilled\" in a[0] && \"rejected\" in a[0];\r\n}\r\nfunction isPending() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"pending\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isPending()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.pending; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isRejected() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"rejected\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejected()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.rejected; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isRejectedWithValue() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n var hasFlag = function (action) {\r\n return action && action.meta && action.meta.rejectedWithValue;\r\n };\r\n if (asyncThunks.length === 0) {\r\n return function (action) {\r\n var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);\r\n return combinedMatcher(action);\r\n };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isRejectedWithValue()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isFulfilled() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"fulfilled\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isFulfilled()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.fulfilled; });\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\nfunction isAsyncThunkAction() {\r\n var asyncThunks = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n asyncThunks[_i] = arguments[_i];\r\n }\r\n if (asyncThunks.length === 0) {\r\n return function (action) { return hasExpectedRequestMetadata(action, [\"pending\", \"fulfilled\", \"rejected\"]); };\r\n }\r\n if (!isAsyncThunkArray(asyncThunks)) {\r\n return isAsyncThunkAction()(asyncThunks[0]);\r\n }\r\n return function (action) {\r\n var matchers = [];\r\n for (var _i = 0, asyncThunks_1 = asyncThunks; _i < asyncThunks_1.length; _i++) {\r\n var asyncThunk = asyncThunks_1[_i];\r\n matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);\r\n }\r\n var combinedMatcher = isAnyOf.apply(void 0, matchers);\r\n return combinedMatcher(action);\r\n };\r\n}\r\n// src/listenerMiddleware/utils.ts\r\nvar assertFunction = function (func, expected) {\r\n if (typeof func !== \"function\") {\r\n throw new TypeError(expected + \" is not a function\");\r\n }\r\n};\r\nvar noop = function () {\r\n};\r\nvar catchRejection = function (promise2, onError) {\r\n if (onError === void 0) { onError = noop; }\r\n promise2.catch(onError);\r\n return promise2;\r\n};\r\nvar addAbortSignalListener = function (abortSignal, callback) {\r\n abortSignal.addEventListener(\"abort\", callback, { once: true });\r\n return function () { return abortSignal.removeEventListener(\"abort\", callback); };\r\n};\r\nvar abortControllerWithReason = function (abortController, reason) {\r\n var signal = abortController.signal;\r\n if (signal.aborted) {\r\n return;\r\n }\r\n if (!(\"reason\" in signal)) {\r\n Object.defineProperty(signal, \"reason\", {\r\n enumerable: true,\r\n value: reason,\r\n configurable: true,\r\n writable: true\r\n });\r\n }\r\n ;\r\n abortController.abort(reason);\r\n};\r\n// src/listenerMiddleware/exceptions.ts\r\nvar task = \"task\";\r\nvar listener = \"listener\";\r\nvar completed = \"completed\";\r\nvar cancelled = \"cancelled\";\r\nvar taskCancelled = \"task-\" + cancelled;\r\nvar taskCompleted = \"task-\" + completed;\r\nvar listenerCancelled = listener + \"-\" + cancelled;\r\nvar listenerCompleted = listener + \"-\" + completed;\r\nvar TaskAbortError = /** @class */ (function () {\r\n function TaskAbortError(code) {\r\n this.code = code;\r\n this.name = \"TaskAbortError\";\r\n this.message = task + \" \" + cancelled + \" (reason: \" + code + \")\";\r\n }\r\n return TaskAbortError;\r\n}());\r\n// src/listenerMiddleware/task.ts\r\nvar validateActive = function (signal) {\r\n if (signal.aborted) {\r\n throw new TaskAbortError(signal.reason);\r\n }\r\n};\r\nfunction raceWithSignal(signal, promise2) {\r\n var cleanup = noop;\r\n return new Promise(function (resolve, reject) {\r\n var notifyRejection = function () { return reject(new TaskAbortError(signal.reason)); };\r\n if (signal.aborted) {\r\n notifyRejection();\r\n return;\r\n }\r\n cleanup = addAbortSignalListener(signal, notifyRejection);\r\n promise2.finally(function () { return cleanup(); }).then(resolve, reject);\r\n }).finally(function () {\r\n cleanup = noop;\r\n });\r\n}\r\nvar runTask = function (task2, cleanUp) { return __async(void 0, null, function () {\r\n var value, error_1;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n _c.trys.push([0, 3, 4, 5]);\r\n return [4 /*yield*/, Promise.resolve()];\r\n case 1:\r\n _c.sent();\r\n return [4 /*yield*/, task2()];\r\n case 2:\r\n value = _c.sent();\r\n return [2 /*return*/, {\r\n status: \"ok\",\r\n value: value\r\n }];\r\n case 3:\r\n error_1 = _c.sent();\r\n return [2 /*return*/, {\r\n status: error_1 instanceof TaskAbortError ? \"cancelled\" : \"rejected\",\r\n error: error_1\r\n }];\r\n case 4:\r\n cleanUp == null ? void 0 : cleanUp();\r\n return [7 /*endfinally*/];\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n}); };\r\nvar createPause = function (signal) {\r\n return function (promise2) {\r\n return catchRejection(raceWithSignal(signal, promise2).then(function (output) {\r\n validateActive(signal);\r\n return output;\r\n }));\r\n };\r\n};\r\nvar createDelay = function (signal) {\r\n var pause = createPause(signal);\r\n return function (timeoutMs) {\r\n return pause(new Promise(function (resolve) { return setTimeout(resolve, timeoutMs); }));\r\n };\r\n};\r\n// src/listenerMiddleware/index.ts\r\nvar assign = Object.assign;\r\nvar INTERNAL_NIL_TOKEN = {};\r\nvar alm = \"listenerMiddleware\";\r\nvar createFork = function (parentAbortSignal) {\r\n var linkControllers = function (controller) { return addAbortSignalListener(parentAbortSignal, function () { return abortControllerWithReason(controller, parentAbortSignal.reason); }); };\r\n return function (taskExecutor) {\r\n assertFunction(taskExecutor, \"taskExecutor\");\r\n var childAbortController = new AbortController();\r\n linkControllers(childAbortController);\r\n var result = runTask(function () { return __async(void 0, null, function () {\r\n var result2;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n validateActive(parentAbortSignal);\r\n validateActive(childAbortController.signal);\r\n return [4 /*yield*/, taskExecutor({\r\n pause: createPause(childAbortController.signal),\r\n delay: createDelay(childAbortController.signal),\r\n signal: childAbortController.signal\r\n })];\r\n case 1:\r\n result2 = _c.sent();\r\n validateActive(childAbortController.signal);\r\n return [2 /*return*/, result2];\r\n }\r\n });\r\n }); }, function () { return abortControllerWithReason(childAbortController, taskCompleted); });\r\n return {\r\n result: createPause(parentAbortSignal)(result),\r\n cancel: function () {\r\n abortControllerWithReason(childAbortController, taskCancelled);\r\n }\r\n };\r\n };\r\n};\r\nvar createTakePattern = function (startListening, signal) {\r\n var take = function (predicate, timeout) { return __async(void 0, null, function () {\r\n var unsubscribe, tuplePromise, promises, output;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n validateActive(signal);\r\n unsubscribe = function () {\r\n };\r\n tuplePromise = new Promise(function (resolve, reject) {\r\n var stopListening = startListening({\r\n predicate: predicate,\r\n effect: function (action, listenerApi) {\r\n listenerApi.unsubscribe();\r\n resolve([\r\n action,\r\n listenerApi.getState(),\r\n listenerApi.getOriginalState()\r\n ]);\r\n }\r\n });\r\n unsubscribe = function () {\r\n stopListening();\r\n reject();\r\n };\r\n });\r\n promises = [\r\n tuplePromise\r\n ];\r\n if (timeout != null) {\r\n promises.push(new Promise(function (resolve) { return setTimeout(resolve, timeout, null); }));\r\n }\r\n _c.label = 1;\r\n case 1:\r\n _c.trys.push([1, , 3, 4]);\r\n return [4 /*yield*/, raceWithSignal(signal, Promise.race(promises))];\r\n case 2:\r\n output = _c.sent();\r\n validateActive(signal);\r\n return [2 /*return*/, output];\r\n case 3:\r\n unsubscribe();\r\n return [7 /*endfinally*/];\r\n case 4: return [2 /*return*/];\r\n }\r\n });\r\n }); };\r\n return function (predicate, timeout) { return catchRejection(take(predicate, timeout)); };\r\n};\r\nvar getListenerEntryPropsFrom = function (options) {\r\n var type = options.type, actionCreator = options.actionCreator, matcher = options.matcher, predicate = options.predicate, effect = options.effect;\r\n if (type) {\r\n predicate = createAction(type).match;\r\n }\r\n else if (actionCreator) {\r\n type = actionCreator.type;\r\n predicate = actionCreator.match;\r\n }\r\n else if (matcher) {\r\n predicate = matcher;\r\n }\r\n else if (predicate) {\r\n }\r\n else {\r\n throw new Error(\"Creating or removing a listener requires one of the known fields for matching an action\");\r\n }\r\n assertFunction(effect, \"options.listener\");\r\n return { predicate: predicate, type: type, effect: effect };\r\n};\r\nvar createListenerEntry = function (options) {\r\n var _c = getListenerEntryPropsFrom(options), type = _c.type, predicate = _c.predicate, effect = _c.effect;\r\n var id = nanoid();\r\n var entry = {\r\n id: id,\r\n effect: effect,\r\n type: type,\r\n predicate: predicate,\r\n pending: new Set(),\r\n unsubscribe: function () {\r\n throw new Error(\"Unsubscribe not initialized\");\r\n }\r\n };\r\n return entry;\r\n};\r\nvar cancelActiveListeners = function (entry) {\r\n entry.pending.forEach(function (controller) {\r\n abortControllerWithReason(controller, listenerCancelled);\r\n });\r\n};\r\nvar createClearListenerMiddleware = function (listenerMap) {\r\n return function () {\r\n listenerMap.forEach(cancelActiveListeners);\r\n listenerMap.clear();\r\n };\r\n};\r\nvar safelyNotifyError = function (errorHandler, errorToNotify, errorInfo) {\r\n try {\r\n errorHandler(errorToNotify, errorInfo);\r\n }\r\n catch (errorHandlerError) {\r\n setTimeout(function () {\r\n throw errorHandlerError;\r\n }, 0);\r\n }\r\n};\r\nvar addListener = createAction(alm + \"/add\");\r\nvar clearAllListeners = createAction(alm + \"/removeAll\");\r\nvar removeListener = createAction(alm + \"/remove\");\r\nvar defaultErrorHandler = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n console.error.apply(console, __spreadArray([alm + \"/error\"], args));\r\n};\r\nfunction createListenerMiddleware(middlewareOptions) {\r\n var _this = this;\r\n if (middlewareOptions === void 0) { middlewareOptions = {}; }\r\n var listenerMap = new Map();\r\n var extra = middlewareOptions.extra, _c = middlewareOptions.onError, onError = _c === void 0 ? defaultErrorHandler : _c;\r\n assertFunction(onError, \"onError\");\r\n var insertEntry = function (entry) {\r\n entry.unsubscribe = function () { return listenerMap.delete(entry.id); };\r\n listenerMap.set(entry.id, entry);\r\n return function (cancelOptions) {\r\n entry.unsubscribe();\r\n if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {\r\n cancelActiveListeners(entry);\r\n }\r\n };\r\n };\r\n var findListenerEntry = function (comparator) {\r\n for (var _i = 0, _c = Array.from(listenerMap.values()); _i < _c.length; _i++) {\r\n var entry = _c[_i];\r\n if (comparator(entry)) {\r\n return entry;\r\n }\r\n }\r\n return void 0;\r\n };\r\n var startListening = function (options) {\r\n var entry = findListenerEntry(function (existingEntry) { return existingEntry.effect === options.effect; });\r\n if (!entry) {\r\n entry = createListenerEntry(options);\r\n }\r\n return insertEntry(entry);\r\n };\r\n var stopListening = function (options) {\r\n var _c = getListenerEntryPropsFrom(options), type = _c.type, effect = _c.effect, predicate = _c.predicate;\r\n var entry = findListenerEntry(function (entry2) {\r\n var matchPredicateOrType = typeof type === \"string\" ? entry2.type === type : entry2.predicate === predicate;\r\n return matchPredicateOrType && entry2.effect === effect;\r\n });\r\n if (entry) {\r\n entry.unsubscribe();\r\n if (options.cancelActive) {\r\n cancelActiveListeners(entry);\r\n }\r\n }\r\n return !!entry;\r\n };\r\n var notifyListener = function (entry, action, api, getOriginalState) { return __async(_this, null, function () {\r\n var internalTaskController, take, listenerError_1;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n internalTaskController = new AbortController();\r\n take = createTakePattern(startListening, internalTaskController.signal);\r\n _c.label = 1;\r\n case 1:\r\n _c.trys.push([1, 3, 4, 5]);\r\n entry.pending.add(internalTaskController);\r\n return [4 /*yield*/, Promise.resolve(entry.effect(action, assign({}, api, {\r\n getOriginalState: getOriginalState,\r\n condition: function (predicate, timeout) { return take(predicate, timeout).then(Boolean); },\r\n take: take,\r\n delay: createDelay(internalTaskController.signal),\r\n pause: createPause(internalTaskController.signal),\r\n extra: extra,\r\n signal: internalTaskController.signal,\r\n fork: createFork(internalTaskController.signal),\r\n unsubscribe: entry.unsubscribe,\r\n subscribe: function () {\r\n listenerMap.set(entry.id, entry);\r\n },\r\n cancelActiveListeners: function () {\r\n entry.pending.forEach(function (controller, _, set) {\r\n if (controller !== internalTaskController) {\r\n abortControllerWithReason(controller, listenerCancelled);\r\n set.delete(controller);\r\n }\r\n });\r\n }\r\n })))];\r\n case 2:\r\n _c.sent();\r\n return [3 /*break*/, 5];\r\n case 3:\r\n listenerError_1 = _c.sent();\r\n if (!(listenerError_1 instanceof TaskAbortError)) {\r\n safelyNotifyError(onError, listenerError_1, {\r\n raisedBy: \"effect\"\r\n });\r\n }\r\n return [3 /*break*/, 5];\r\n case 4:\r\n abortControllerWithReason(internalTaskController, listenerCompleted);\r\n entry.pending.delete(internalTaskController);\r\n return [7 /*endfinally*/];\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n }); };\r\n var clearListenerMiddleware = createClearListenerMiddleware(listenerMap);\r\n var middleware = function (api) { return function (next) { return function (action) {\r\n if (!isAction(action)) {\r\n return next(action);\r\n }\r\n if (addListener.match(action)) {\r\n return startListening(action.payload);\r\n }\r\n if (clearAllListeners.match(action)) {\r\n clearListenerMiddleware();\r\n return;\r\n }\r\n if (removeListener.match(action)) {\r\n return stopListening(action.payload);\r\n }\r\n var originalState = api.getState();\r\n var getOriginalState = function () {\r\n if (originalState === INTERNAL_NIL_TOKEN) {\r\n throw new Error(alm + \": getOriginalState can only be called synchronously\");\r\n }\r\n return originalState;\r\n };\r\n var result;\r\n try {\r\n result = next(action);\r\n if (listenerMap.size > 0) {\r\n var currentState = api.getState();\r\n var listenerEntries = Array.from(listenerMap.values());\r\n for (var _i = 0, listenerEntries_1 = listenerEntries; _i < listenerEntries_1.length; _i++) {\r\n var entry = listenerEntries_1[_i];\r\n var runListener = false;\r\n try {\r\n runListener = entry.predicate(action, currentState, originalState);\r\n }\r\n catch (predicateError) {\r\n runListener = false;\r\n safelyNotifyError(onError, predicateError, {\r\n raisedBy: \"predicate\"\r\n });\r\n }\r\n if (!runListener) {\r\n continue;\r\n }\r\n notifyListener(entry, action, api, getOriginalState);\r\n }\r\n }\r\n }\r\n finally {\r\n originalState = INTERNAL_NIL_TOKEN;\r\n }\r\n return result;\r\n }; }; };\r\n return {\r\n middleware: middleware,\r\n startListening: startListening,\r\n stopListening: stopListening,\r\n clearListeners: clearListenerMiddleware\r\n };\r\n}\r\n// src/autoBatchEnhancer.ts\r\nvar SHOULD_AUTOBATCH = \"RTK_autoBatch\";\r\nvar prepareAutoBatched = function () { return function (payload) {\r\n var _c;\r\n return ({\r\n payload: payload,\r\n meta: (_c = {}, _c[SHOULD_AUTOBATCH] = true, _c)\r\n });\r\n}; };\r\nvar promise;\r\nvar queueMicrotaskShim = typeof queueMicrotask === \"function\" ? queueMicrotask.bind(typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : globalThis) : function (cb) { return (promise || (promise = Promise.resolve())).then(cb).catch(function (err) { return setTimeout(function () {\r\n throw err;\r\n}, 0); }); };\r\nvar createQueueWithTimer = function (timeout) {\r\n return function (notify) {\r\n setTimeout(notify, timeout);\r\n };\r\n};\r\nvar rAF = typeof window !== \"undefined\" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);\r\nvar autoBatchEnhancer = function (options) {\r\n if (options === void 0) { options = { type: \"raf\" }; }\r\n return function (next) { return function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var store = next.apply(void 0, args);\r\n var notifying = true;\r\n var shouldNotifyAtEndOfTick = false;\r\n var notificationQueued = false;\r\n var listeners = new Set();\r\n var queueCallback = options.type === \"tick\" ? queueMicrotaskShim : options.type === \"raf\" ? rAF : options.type === \"callback\" ? options.queueNotification : createQueueWithTimer(options.timeout);\r\n var notifyListeners = function () {\r\n notificationQueued = false;\r\n if (shouldNotifyAtEndOfTick) {\r\n shouldNotifyAtEndOfTick = false;\r\n listeners.forEach(function (l) { return l(); });\r\n }\r\n };\r\n return Object.assign({}, store, {\r\n subscribe: function (listener2) {\r\n var wrappedListener = function () { return notifying && listener2(); };\r\n var unsubscribe = store.subscribe(wrappedListener);\r\n listeners.add(listener2);\r\n return function () {\r\n unsubscribe();\r\n listeners.delete(listener2);\r\n };\r\n },\r\n dispatch: function (action) {\r\n var _a;\r\n try {\r\n notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);\r\n shouldNotifyAtEndOfTick = !notifying;\r\n if (shouldNotifyAtEndOfTick) {\r\n if (!notificationQueued) {\r\n notificationQueued = true;\r\n queueCallback(notifyListeners);\r\n }\r\n }\r\n return store.dispatch(action);\r\n }\r\n finally {\r\n notifying = true;\r\n }\r\n }\r\n });\r\n }; };\r\n};\r\n// src/index.ts\r\nenableES5();\r\nexport { EnhancerArray, MiddlewareArray, SHOULD_AUTOBATCH, TaskAbortError, addListener, autoBatchEnhancer, clearAllListeners, configureStore, createAction, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, default2 as createNextState, createReducer, createSelector2 as createSelector, createSerializableStateInvariantMiddleware, createSlice, current2 as current, findNonSerializableValue, freeze, getDefaultMiddleware, getType, isAction, isAllOf, isAnyOf, isAsyncThunkAction, isDraft4 as isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject, isRejected, isRejectedWithValue, miniSerializeError, nanoid, original, prepareAutoBatched, removeListener, unwrapResult };\r\n//# sourceMappingURL=redux-toolkit.esm.js.map","var __generator = (this && this.__generator) || function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n};\r\nvar __spreadArray = (this && this.__spreadArray) || function (to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n};\r\nvar __defProp = Object.defineProperty;\r\nvar __defProps = Object.defineProperties;\r\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\r\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\r\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\r\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\r\nvar __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };\r\nvar __spreadValues = function (a, b) {\r\n for (var prop in b || (b = {}))\r\n if (__hasOwnProp.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n if (__getOwnPropSymbols)\r\n for (var _j = 0, _k = __getOwnPropSymbols(b); _j < _k.length; _j++) {\r\n var prop = _k[_j];\r\n if (__propIsEnum.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n }\r\n return a;\r\n};\r\nvar __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };\r\nvar __objRest = function (source, exclude) {\r\n var target = {};\r\n for (var prop in source)\r\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\r\n target[prop] = source[prop];\r\n if (source != null && __getOwnPropSymbols)\r\n for (var _j = 0, _k = __getOwnPropSymbols(source); _j < _k.length; _j++) {\r\n var prop = _k[_j];\r\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\r\n target[prop] = source[prop];\r\n }\r\n return target;\r\n};\r\nvar __async = function (__this, __arguments, generator) {\r\n return new Promise(function (resolve, reject) {\r\n var fulfilled = function (value) {\r\n try {\r\n step(generator.next(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var rejected = function (value) {\r\n try {\r\n step(generator.throw(value));\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n };\r\n var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };\r\n step((generator = generator.apply(__this, __arguments)).next());\r\n });\r\n};\r\n// src/query/core/apiState.ts\r\nvar QueryStatus;\r\n(function (QueryStatus2) {\r\n QueryStatus2[\"uninitialized\"] = \"uninitialized\";\r\n QueryStatus2[\"pending\"] = \"pending\";\r\n QueryStatus2[\"fulfilled\"] = \"fulfilled\";\r\n QueryStatus2[\"rejected\"] = \"rejected\";\r\n})(QueryStatus || (QueryStatus = {}));\r\nfunction getRequestStatusFlags(status) {\r\n return {\r\n status: status,\r\n isUninitialized: status === QueryStatus.uninitialized,\r\n isLoading: status === QueryStatus.pending,\r\n isSuccess: status === QueryStatus.fulfilled,\r\n isError: status === QueryStatus.rejected\r\n };\r\n}\r\n// src/query/utils/isAbsoluteUrl.ts\r\nfunction isAbsoluteUrl(url) {\r\n return new RegExp(\"(^|:)//\").test(url);\r\n}\r\n// src/query/utils/joinUrls.ts\r\nvar withoutTrailingSlash = function (url) { return url.replace(/\\/$/, \"\"); };\r\nvar withoutLeadingSlash = function (url) { return url.replace(/^\\//, \"\"); };\r\nfunction joinUrls(base, url) {\r\n if (!base) {\r\n return url;\r\n }\r\n if (!url) {\r\n return base;\r\n }\r\n if (isAbsoluteUrl(url)) {\r\n return url;\r\n }\r\n var delimiter = base.endsWith(\"/\") || !url.startsWith(\"?\") ? \"/\" : \"\";\r\n base = withoutTrailingSlash(base);\r\n url = withoutLeadingSlash(url);\r\n return \"\" + base + delimiter + url;\r\n}\r\n// src/query/utils/flatten.ts\r\nvar flatten = function (arr) { return [].concat.apply([], arr); };\r\n// src/query/utils/isOnline.ts\r\nfunction isOnline() {\r\n return typeof navigator === \"undefined\" ? true : navigator.onLine === void 0 ? true : navigator.onLine;\r\n}\r\n// src/query/utils/isDocumentVisible.ts\r\nfunction isDocumentVisible() {\r\n if (typeof document === \"undefined\") {\r\n return true;\r\n }\r\n return document.visibilityState !== \"hidden\";\r\n}\r\n// src/query/utils/copyWithStructuralSharing.ts\r\nimport { isPlainObject as _iPO } from \"@reduxjs/toolkit\";\r\nvar isPlainObject = _iPO;\r\nfunction copyWithStructuralSharing(oldObj, newObj) {\r\n if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\r\n return newObj;\r\n }\r\n var newKeys = Object.keys(newObj);\r\n var oldKeys = Object.keys(oldObj);\r\n var isSameObject = newKeys.length === oldKeys.length;\r\n var mergeObj = Array.isArray(newObj) ? [] : {};\r\n for (var _j = 0, newKeys_1 = newKeys; _j < newKeys_1.length; _j++) {\r\n var key = newKeys_1[_j];\r\n mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\r\n if (isSameObject)\r\n isSameObject = oldObj[key] === mergeObj[key];\r\n }\r\n return isSameObject ? oldObj : mergeObj;\r\n}\r\n// src/query/fetchBaseQuery.ts\r\nimport { isPlainObject as isPlainObject2 } from \"@reduxjs/toolkit\";\r\nvar defaultFetchFn = function () {\r\n var args = [];\r\n for (var _j = 0; _j < arguments.length; _j++) {\r\n args[_j] = arguments[_j];\r\n }\r\n return fetch.apply(void 0, args);\r\n};\r\nvar defaultValidateStatus = function (response) { return response.status >= 200 && response.status <= 299; };\r\nvar defaultIsJsonContentType = function (headers) { return /ion\\/(vnd\\.api\\+)?json/.test(headers.get(\"content-type\") || \"\"); };\r\nfunction stripUndefined(obj) {\r\n if (!isPlainObject2(obj)) {\r\n return obj;\r\n }\r\n var copy = __spreadValues({}, obj);\r\n for (var _j = 0, _k = Object.entries(copy); _j < _k.length; _j++) {\r\n var _l = _k[_j], k = _l[0], v = _l[1];\r\n if (v === void 0)\r\n delete copy[k];\r\n }\r\n return copy;\r\n}\r\nfunction fetchBaseQuery(_a) {\r\n var _this = this;\r\n if (_a === void 0) { _a = {}; }\r\n var _b = _a, baseUrl = _b.baseUrl, _j = _b.prepareHeaders, prepareHeaders = _j === void 0 ? function (x) { return x; } : _j, _k = _b.fetchFn, fetchFn = _k === void 0 ? defaultFetchFn : _k, paramsSerializer = _b.paramsSerializer, _l = _b.isJsonContentType, isJsonContentType = _l === void 0 ? defaultIsJsonContentType : _l, _m = _b.jsonContentType, jsonContentType = _m === void 0 ? \"application/json\" : _m, jsonReplacer = _b.jsonReplacer, defaultTimeout = _b.timeout, globalResponseHandler = _b.responseHandler, globalValidateStatus = _b.validateStatus, baseFetchOptions = __objRest(_b, [\r\n \"baseUrl\",\r\n \"prepareHeaders\",\r\n \"fetchFn\",\r\n \"paramsSerializer\",\r\n \"isJsonContentType\",\r\n \"jsonContentType\",\r\n \"jsonReplacer\",\r\n \"timeout\",\r\n \"responseHandler\",\r\n \"validateStatus\"\r\n ]);\r\n if (typeof fetch === \"undefined\" && fetchFn === defaultFetchFn) {\r\n console.warn(\"Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.\");\r\n }\r\n return function (arg, api) { return __async(_this, null, function () {\r\n var signal, getState, extra, endpoint, forced, type, meta, _a2, url, _j, headers, _k, params, _l, responseHandler, _m, validateStatus, _o, timeout, rest, config, _p, isJsonifiable, divider, query, request, requestClone, response, timedOut, timeoutId, e_1, responseClone, resultData, responseText, handleResponseError_1, e_2;\r\n return __generator(this, function (_q) {\r\n switch (_q.label) {\r\n case 0:\r\n signal = api.signal, getState = api.getState, extra = api.extra, endpoint = api.endpoint, forced = api.forced, type = api.type;\r\n _a2 = typeof arg == \"string\" ? { url: arg } : arg, url = _a2.url, _j = _a2.headers, headers = _j === void 0 ? new Headers(baseFetchOptions.headers) : _j, _k = _a2.params, params = _k === void 0 ? void 0 : _k, _l = _a2.responseHandler, responseHandler = _l === void 0 ? globalResponseHandler != null ? globalResponseHandler : \"json\" : _l, _m = _a2.validateStatus, validateStatus = _m === void 0 ? globalValidateStatus != null ? globalValidateStatus : defaultValidateStatus : _m, _o = _a2.timeout, timeout = _o === void 0 ? defaultTimeout : _o, rest = __objRest(_a2, [\r\n \"url\",\r\n \"headers\",\r\n \"params\",\r\n \"responseHandler\",\r\n \"validateStatus\",\r\n \"timeout\"\r\n ]);\r\n config = __spreadValues(__spreadProps(__spreadValues({}, baseFetchOptions), {\r\n signal: signal\r\n }), rest);\r\n headers = new Headers(stripUndefined(headers));\r\n _p = config;\r\n return [4 /*yield*/, prepareHeaders(headers, {\r\n getState: getState,\r\n extra: extra,\r\n endpoint: endpoint,\r\n forced: forced,\r\n type: type\r\n })];\r\n case 1:\r\n _p.headers = (_q.sent()) || headers;\r\n isJsonifiable = function (body) { return typeof body === \"object\" && (isPlainObject2(body) || Array.isArray(body) || typeof body.toJSON === \"function\"); };\r\n if (!config.headers.has(\"content-type\") && isJsonifiable(config.body)) {\r\n config.headers.set(\"content-type\", jsonContentType);\r\n }\r\n if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {\r\n config.body = JSON.stringify(config.body, jsonReplacer);\r\n }\r\n if (params) {\r\n divider = ~url.indexOf(\"?\") ? \"&\" : \"?\";\r\n query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\r\n url += divider + query;\r\n }\r\n url = joinUrls(baseUrl, url);\r\n request = new Request(url, config);\r\n requestClone = request.clone();\r\n meta = { request: requestClone };\r\n timedOut = false, timeoutId = timeout && setTimeout(function () {\r\n timedOut = true;\r\n api.abort();\r\n }, timeout);\r\n _q.label = 2;\r\n case 2:\r\n _q.trys.push([2, 4, 5, 6]);\r\n return [4 /*yield*/, fetchFn(request)];\r\n case 3:\r\n response = _q.sent();\r\n return [3 /*break*/, 6];\r\n case 4:\r\n e_1 = _q.sent();\r\n return [2 /*return*/, {\r\n error: {\r\n status: timedOut ? \"TIMEOUT_ERROR\" : \"FETCH_ERROR\",\r\n error: String(e_1)\r\n },\r\n meta: meta\r\n }];\r\n case 5:\r\n if (timeoutId)\r\n clearTimeout(timeoutId);\r\n return [7 /*endfinally*/];\r\n case 6:\r\n responseClone = response.clone();\r\n meta.response = responseClone;\r\n responseText = \"\";\r\n _q.label = 7;\r\n case 7:\r\n _q.trys.push([7, 9, , 10]);\r\n return [4 /*yield*/, Promise.all([\r\n handleResponse(response, responseHandler).then(function (r) { return resultData = r; }, function (e) { return handleResponseError_1 = e; }),\r\n responseClone.text().then(function (r) { return responseText = r; }, function () {\r\n })\r\n ])];\r\n case 8:\r\n _q.sent();\r\n if (handleResponseError_1)\r\n throw handleResponseError_1;\r\n return [3 /*break*/, 10];\r\n case 9:\r\n e_2 = _q.sent();\r\n return [2 /*return*/, {\r\n error: {\r\n status: \"PARSING_ERROR\",\r\n originalStatus: response.status,\r\n data: responseText,\r\n error: String(e_2)\r\n },\r\n meta: meta\r\n }];\r\n case 10: return [2 /*return*/, validateStatus(response, resultData) ? {\r\n data: resultData,\r\n meta: meta\r\n } : {\r\n error: {\r\n status: response.status,\r\n data: resultData\r\n },\r\n meta: meta\r\n }];\r\n }\r\n });\r\n }); };\r\n function handleResponse(response, responseHandler) {\r\n return __async(this, null, function () {\r\n var text;\r\n return __generator(this, function (_j) {\r\n switch (_j.label) {\r\n case 0:\r\n if (typeof responseHandler === \"function\") {\r\n return [2 /*return*/, responseHandler(response)];\r\n }\r\n if (responseHandler === \"content-type\") {\r\n responseHandler = isJsonContentType(response.headers) ? \"json\" : \"text\";\r\n }\r\n if (!(responseHandler === \"json\")) return [3 /*break*/, 2];\r\n return [4 /*yield*/, response.text()];\r\n case 1:\r\n text = _j.sent();\r\n return [2 /*return*/, text.length ? JSON.parse(text) : null];\r\n case 2: return [2 /*return*/, response.text()];\r\n }\r\n });\r\n });\r\n }\r\n}\r\n// src/query/HandledError.ts\r\nvar HandledError = /** @class */ (function () {\r\n function HandledError(value, meta) {\r\n if (meta === void 0) { meta = void 0; }\r\n this.value = value;\r\n this.meta = meta;\r\n }\r\n return HandledError;\r\n}());\r\n// src/query/retry.ts\r\nfunction defaultBackoff(attempt, maxRetries) {\r\n if (attempt === void 0) { attempt = 0; }\r\n if (maxRetries === void 0) { maxRetries = 5; }\r\n return __async(this, null, function () {\r\n var attempts, timeout;\r\n return __generator(this, function (_j) {\r\n switch (_j.label) {\r\n case 0:\r\n attempts = Math.min(attempt, maxRetries);\r\n timeout = ~~((Math.random() + 0.4) * (300 << attempts));\r\n return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(function (res) { return resolve(res); }, timeout); })];\r\n case 1:\r\n _j.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction fail(e) {\r\n throw Object.assign(new HandledError({ error: e }), {\r\n throwImmediately: true\r\n });\r\n}\r\nvar EMPTY_OPTIONS = {};\r\nvar retryWithBackoff = function (baseQuery, defaultOptions) { return function (args, api, extraOptions) { return __async(void 0, null, function () {\r\n var possibleMaxRetries, maxRetries, defaultRetryCondition, options, retry2, result, e_3;\r\n return __generator(this, function (_j) {\r\n switch (_j.label) {\r\n case 0:\r\n possibleMaxRetries = [\r\n 5,\r\n (defaultOptions || EMPTY_OPTIONS).maxRetries,\r\n (extraOptions || EMPTY_OPTIONS).maxRetries\r\n ].filter(function (x) { return x !== void 0; });\r\n maxRetries = possibleMaxRetries.slice(-1)[0];\r\n defaultRetryCondition = function (_, __, _j) {\r\n var attempt = _j.attempt;\r\n return attempt <= maxRetries;\r\n };\r\n options = __spreadValues(__spreadValues({\r\n maxRetries: maxRetries,\r\n backoff: defaultBackoff,\r\n retryCondition: defaultRetryCondition\r\n }, defaultOptions), extraOptions);\r\n retry2 = 0;\r\n _j.label = 1;\r\n case 1:\r\n if (!true) return [3 /*break*/, 7];\r\n _j.label = 2;\r\n case 2:\r\n _j.trys.push([2, 4, , 6]);\r\n return [4 /*yield*/, baseQuery(args, api, extraOptions)];\r\n case 3:\r\n result = _j.sent();\r\n if (result.error) {\r\n throw new HandledError(result);\r\n }\r\n return [2 /*return*/, result];\r\n case 4:\r\n e_3 = _j.sent();\r\n retry2++;\r\n if (e_3.throwImmediately) {\r\n if (e_3 instanceof HandledError) {\r\n return [2 /*return*/, e_3.value];\r\n }\r\n throw e_3;\r\n }\r\n if (e_3 instanceof HandledError && !options.retryCondition(e_3.value.error, args, {\r\n attempt: retry2,\r\n baseQueryApi: api,\r\n extraOptions: extraOptions\r\n })) {\r\n return [2 /*return*/, e_3.value];\r\n }\r\n return [4 /*yield*/, options.backoff(retry2, options.maxRetries)];\r\n case 5:\r\n _j.sent();\r\n return [3 /*break*/, 6];\r\n case 6: return [3 /*break*/, 1];\r\n case 7: return [2 /*return*/];\r\n }\r\n });\r\n}); }; };\r\nvar retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail: fail });\r\n// src/query/core/setupListeners.ts\r\nimport { createAction } from \"@reduxjs/toolkit\";\r\nvar onFocus = /* @__PURE__ */ createAction(\"__rtkq/focused\");\r\nvar onFocusLost = /* @__PURE__ */ createAction(\"__rtkq/unfocused\");\r\nvar onOnline = /* @__PURE__ */ createAction(\"__rtkq/online\");\r\nvar onOffline = /* @__PURE__ */ createAction(\"__rtkq/offline\");\r\nvar initialized = false;\r\nfunction setupListeners(dispatch, customHandler) {\r\n function defaultHandler() {\r\n var handleFocus = function () { return dispatch(onFocus()); };\r\n var handleFocusLost = function () { return dispatch(onFocusLost()); };\r\n var handleOnline = function () { return dispatch(onOnline()); };\r\n var handleOffline = function () { return dispatch(onOffline()); };\r\n var handleVisibilityChange = function () {\r\n if (window.document.visibilityState === \"visible\") {\r\n handleFocus();\r\n }\r\n else {\r\n handleFocusLost();\r\n }\r\n };\r\n if (!initialized) {\r\n if (typeof window !== \"undefined\" && window.addEventListener) {\r\n window.addEventListener(\"visibilitychange\", handleVisibilityChange, false);\r\n window.addEventListener(\"focus\", handleFocus, false);\r\n window.addEventListener(\"online\", handleOnline, false);\r\n window.addEventListener(\"offline\", handleOffline, false);\r\n initialized = true;\r\n }\r\n }\r\n var unsubscribe = function () {\r\n window.removeEventListener(\"focus\", handleFocus);\r\n window.removeEventListener(\"visibilitychange\", handleVisibilityChange);\r\n window.removeEventListener(\"online\", handleOnline);\r\n window.removeEventListener(\"offline\", handleOffline);\r\n initialized = false;\r\n };\r\n return unsubscribe;\r\n }\r\n return customHandler ? customHandler(dispatch, { onFocus: onFocus, onFocusLost: onFocusLost, onOffline: onOffline, onOnline: onOnline }) : defaultHandler();\r\n}\r\n// src/query/core/buildSelectors.ts\r\nimport { createNextState as createNextState2, createSelector } from \"@reduxjs/toolkit\";\r\n// src/query/endpointDefinitions.ts\r\nvar DefinitionType;\r\n(function (DefinitionType2) {\r\n DefinitionType2[\"query\"] = \"query\";\r\n DefinitionType2[\"mutation\"] = \"mutation\";\r\n})(DefinitionType || (DefinitionType = {}));\r\nfunction isQueryDefinition(e) {\r\n return e.type === DefinitionType.query;\r\n}\r\nfunction isMutationDefinition(e) {\r\n return e.type === DefinitionType.mutation;\r\n}\r\nfunction calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {\r\n if (isFunction(description)) {\r\n return description(result, error, queryArg, meta).map(expandTagDescription).map(assertTagTypes);\r\n }\r\n if (Array.isArray(description)) {\r\n return description.map(expandTagDescription).map(assertTagTypes);\r\n }\r\n return [];\r\n}\r\nfunction isFunction(t) {\r\n return typeof t === \"function\";\r\n}\r\nfunction expandTagDescription(description) {\r\n return typeof description === \"string\" ? { type: description } : description;\r\n}\r\n// src/query/core/buildSlice.ts\r\nimport { combineReducers, createAction as createAction2, createSlice, isAnyOf, isFulfilled as isFulfilled2, isRejectedWithValue as isRejectedWithValue2, createNextState, prepareAutoBatched } from \"@reduxjs/toolkit\";\r\n// src/query/utils/isNotNullish.ts\r\nfunction isNotNullish(v) {\r\n return v != null;\r\n}\r\n// src/query/core/buildInitiate.ts\r\nvar forceQueryFnSymbol = Symbol(\"forceQueryFn\");\r\nvar isUpsertQuery = function (arg) { return typeof arg[forceQueryFnSymbol] === \"function\"; };\r\nfunction buildInitiate(_j) {\r\n var serializeQueryArgs = _j.serializeQueryArgs, queryThunk = _j.queryThunk, mutationThunk = _j.mutationThunk, api = _j.api, context = _j.context;\r\n var runningQueries = new Map();\r\n var runningMutations = new Map();\r\n var _k = api.internalActions, unsubscribeQueryResult = _k.unsubscribeQueryResult, removeMutationResult = _k.removeMutationResult, updateSubscriptionOptions = _k.updateSubscriptionOptions;\r\n return {\r\n buildInitiateQuery: buildInitiateQuery,\r\n buildInitiateMutation: buildInitiateMutation,\r\n getRunningQueryThunk: getRunningQueryThunk,\r\n getRunningMutationThunk: getRunningMutationThunk,\r\n getRunningQueriesThunk: getRunningQueriesThunk,\r\n getRunningMutationsThunk: getRunningMutationsThunk,\r\n getRunningOperationPromises: getRunningOperationPromises,\r\n removalWarning: removalWarning\r\n };\r\n function removalWarning() {\r\n throw new Error(\"This method had to be removed due to a conceptual bug in RTK.\\n Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.\\n See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.\");\r\n }\r\n function getRunningOperationPromises() {\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n removalWarning();\r\n }\r\n else {\r\n var extract = function (v) { return Array.from(v.values()).flatMap(function (queriesForStore) { return queriesForStore ? Object.values(queriesForStore) : []; }); };\r\n return __spreadArray(__spreadArray([], extract(runningQueries)), extract(runningMutations)).filter(isNotNullish);\r\n }\r\n }\r\n function getRunningQueryThunk(endpointName, queryArgs) {\r\n return function (dispatch) {\r\n var _a;\r\n var endpointDefinition = context.endpointDefinitions[endpointName];\r\n var queryCacheKey = serializeQueryArgs({\r\n queryArgs: queryArgs,\r\n endpointDefinition: endpointDefinition,\r\n endpointName: endpointName\r\n });\r\n return (_a = runningQueries.get(dispatch)) == null ? void 0 : _a[queryCacheKey];\r\n };\r\n }\r\n function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {\r\n return function (dispatch) {\r\n var _a;\r\n return (_a = runningMutations.get(dispatch)) == null ? void 0 : _a[fixedCacheKeyOrRequestId];\r\n };\r\n }\r\n function getRunningQueriesThunk() {\r\n return function (dispatch) { return Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish); };\r\n }\r\n function getRunningMutationsThunk() {\r\n return function (dispatch) { return Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish); };\r\n }\r\n function middlewareWarning(dispatch) {\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (middlewareWarning.triggered)\r\n return;\r\n var registered = dispatch(api.internalActions.internal_probeSubscription({\r\n queryCacheKey: \"DOES_NOT_EXIST\",\r\n requestId: \"DUMMY_REQUEST_ID\"\r\n }));\r\n middlewareWarning.triggered = true;\r\n if (typeof registered !== \"boolean\") {\r\n throw new Error(\"Warning: Middleware for RTK-Query API at reducerPath \\\"\" + api.reducerPath + \"\\\" has not been added to the store.\\nYou must add the middleware for RTK-Query to function correctly!\");\r\n }\r\n }\r\n }\r\n function buildInitiateQuery(endpointName, endpointDefinition) {\r\n var queryAction = function (arg, _j) {\r\n var _k = _j === void 0 ? {} : _j, _l = _k.subscribe, subscribe = _l === void 0 ? true : _l, forceRefetch = _k.forceRefetch, subscriptionOptions = _k.subscriptionOptions, _m = forceQueryFnSymbol, forceQueryFn = _k[_m];\r\n return function (dispatch, getState) {\r\n var _j;\r\n var _a;\r\n var queryCacheKey = serializeQueryArgs({\r\n queryArgs: arg,\r\n endpointDefinition: endpointDefinition,\r\n endpointName: endpointName\r\n });\r\n var thunk = queryThunk((_j = {\r\n type: \"query\",\r\n subscribe: subscribe,\r\n forceRefetch: forceRefetch,\r\n subscriptionOptions: subscriptionOptions,\r\n endpointName: endpointName,\r\n originalArgs: arg,\r\n queryCacheKey: queryCacheKey\r\n },\r\n _j[forceQueryFnSymbol] = forceQueryFn,\r\n _j));\r\n var selector = api.endpoints[endpointName].select(arg);\r\n var thunkResult = dispatch(thunk);\r\n var stateAfter = selector(getState());\r\n middlewareWarning(dispatch);\r\n var requestId = thunkResult.requestId, abort = thunkResult.abort;\r\n var skippedSynchronously = stateAfter.requestId !== requestId;\r\n var runningQuery = (_a = runningQueries.get(dispatch)) == null ? void 0 : _a[queryCacheKey];\r\n var selectFromState = function () { return selector(getState()); };\r\n var statePromise = Object.assign(forceQueryFn ? thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ? Promise.resolve(stateAfter) : Promise.all([runningQuery, thunkResult]).then(selectFromState), {\r\n arg: arg,\r\n requestId: requestId,\r\n subscriptionOptions: subscriptionOptions,\r\n queryCacheKey: queryCacheKey,\r\n abort: abort,\r\n unwrap: function () {\r\n return __async(this, null, function () {\r\n var result;\r\n return __generator(this, function (_j) {\r\n switch (_j.label) {\r\n case 0: return [4 /*yield*/, statePromise];\r\n case 1:\r\n result = _j.sent();\r\n if (result.isError) {\r\n throw result.error;\r\n }\r\n return [2 /*return*/, result.data];\r\n }\r\n });\r\n });\r\n },\r\n refetch: function () { return dispatch(queryAction(arg, { subscribe: false, forceRefetch: true })); },\r\n unsubscribe: function () {\r\n if (subscribe)\r\n dispatch(unsubscribeQueryResult({\r\n queryCacheKey: queryCacheKey,\r\n requestId: requestId\r\n }));\r\n },\r\n updateSubscriptionOptions: function (options) {\r\n statePromise.subscriptionOptions = options;\r\n dispatch(updateSubscriptionOptions({\r\n endpointName: endpointName,\r\n requestId: requestId,\r\n queryCacheKey: queryCacheKey,\r\n options: options\r\n }));\r\n }\r\n });\r\n if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\r\n var running_1 = runningQueries.get(dispatch) || {};\r\n running_1[queryCacheKey] = statePromise;\r\n runningQueries.set(dispatch, running_1);\r\n statePromise.then(function () {\r\n delete running_1[queryCacheKey];\r\n if (!Object.keys(running_1).length) {\r\n runningQueries.delete(dispatch);\r\n }\r\n });\r\n }\r\n return statePromise;\r\n };\r\n };\r\n return queryAction;\r\n }\r\n function buildInitiateMutation(endpointName) {\r\n return function (arg, _j) {\r\n var _k = _j === void 0 ? {} : _j, _l = _k.track, track = _l === void 0 ? true : _l, fixedCacheKey = _k.fixedCacheKey;\r\n return function (dispatch, getState) {\r\n var thunk = mutationThunk({\r\n type: \"mutation\",\r\n endpointName: endpointName,\r\n originalArgs: arg,\r\n track: track,\r\n fixedCacheKey: fixedCacheKey\r\n });\r\n var thunkResult = dispatch(thunk);\r\n middlewareWarning(dispatch);\r\n var requestId = thunkResult.requestId, abort = thunkResult.abort, unwrap = thunkResult.unwrap;\r\n var returnValuePromise = thunkResult.unwrap().then(function (data) { return ({ data: data }); }).catch(function (error) { return ({ error: error }); });\r\n var reset = function () {\r\n dispatch(removeMutationResult({ requestId: requestId, fixedCacheKey: fixedCacheKey }));\r\n };\r\n var ret = Object.assign(returnValuePromise, {\r\n arg: thunkResult.arg,\r\n requestId: requestId,\r\n abort: abort,\r\n unwrap: unwrap,\r\n unsubscribe: reset,\r\n reset: reset\r\n });\r\n var running = runningMutations.get(dispatch) || {};\r\n runningMutations.set(dispatch, running);\r\n running[requestId] = ret;\r\n ret.then(function () {\r\n delete running[requestId];\r\n if (!Object.keys(running).length) {\r\n runningMutations.delete(dispatch);\r\n }\r\n });\r\n if (fixedCacheKey) {\r\n running[fixedCacheKey] = ret;\r\n ret.then(function () {\r\n if (running[fixedCacheKey] === ret) {\r\n delete running[fixedCacheKey];\r\n if (!Object.keys(running).length) {\r\n runningMutations.delete(dispatch);\r\n }\r\n }\r\n });\r\n }\r\n return ret;\r\n };\r\n };\r\n }\r\n}\r\n// src/query/core/buildThunks.ts\r\nimport { isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue } from \"@reduxjs/toolkit\";\r\nimport { isDraftable, produceWithPatches } from \"immer\";\r\nimport { createAsyncThunk, SHOULD_AUTOBATCH } from \"@reduxjs/toolkit\";\r\nfunction defaultTransformResponse(baseQueryReturnValue) {\r\n return baseQueryReturnValue;\r\n}\r\nfunction buildThunks(_j) {\r\n var _this = this;\r\n var reducerPath = _j.reducerPath, baseQuery = _j.baseQuery, endpointDefinitions = _j.context.endpointDefinitions, serializeQueryArgs = _j.serializeQueryArgs, api = _j.api;\r\n var patchQueryData = function (endpointName, args, patches) { return function (dispatch) {\r\n var endpointDefinition = endpointDefinitions[endpointName];\r\n dispatch(api.internalActions.queryResultPatched({\r\n queryCacheKey: serializeQueryArgs({\r\n queryArgs: args,\r\n endpointDefinition: endpointDefinition,\r\n endpointName: endpointName\r\n }),\r\n patches: patches\r\n }));\r\n }; };\r\n var updateQueryData = function (endpointName, args, updateRecipe) { return function (dispatch, getState) {\r\n var _j, _k;\r\n var currentState = api.endpoints[endpointName].select(args)(getState());\r\n var ret = {\r\n patches: [],\r\n inversePatches: [],\r\n undo: function () { return dispatch(api.util.patchQueryData(endpointName, args, ret.inversePatches)); }\r\n };\r\n if (currentState.status === QueryStatus.uninitialized) {\r\n return ret;\r\n }\r\n if (\"data\" in currentState) {\r\n if (isDraftable(currentState.data)) {\r\n var _l = produceWithPatches(currentState.data, updateRecipe), patches = _l[1], inversePatches = _l[2];\r\n (_j = ret.patches).push.apply(_j, patches);\r\n (_k = ret.inversePatches).push.apply(_k, inversePatches);\r\n }\r\n else {\r\n var value = updateRecipe(currentState.data);\r\n ret.patches.push({ op: \"replace\", path: [], value: value });\r\n ret.inversePatches.push({\r\n op: \"replace\",\r\n path: [],\r\n value: currentState.data\r\n });\r\n }\r\n }\r\n dispatch(api.util.patchQueryData(endpointName, args, ret.patches));\r\n return ret;\r\n }; };\r\n var upsertQueryData = function (endpointName, args, value) { return function (dispatch) {\r\n var _j;\r\n return dispatch(api.endpoints[endpointName].initiate(args, (_j = {\r\n subscribe: false,\r\n forceRefetch: true\r\n },\r\n _j[forceQueryFnSymbol] = function () { return ({\r\n data: value\r\n }); },\r\n _j)));\r\n }; };\r\n var executeEndpoint = function (_0, _1) { return __async(_this, [_0, _1], function (arg, _j) {\r\n var endpointDefinition, transformResponse, result, baseQueryApi_1, forceQueryFn, what, err, _k, _l, key, _m, error_1, catchedError, transformErrorResponse, _o, e_4;\r\n var _p, _q;\r\n var signal = _j.signal, abort = _j.abort, rejectWithValue = _j.rejectWithValue, fulfillWithValue = _j.fulfillWithValue, dispatch = _j.dispatch, getState = _j.getState, extra = _j.extra;\r\n return __generator(this, function (_r) {\r\n switch (_r.label) {\r\n case 0:\r\n endpointDefinition = endpointDefinitions[arg.endpointName];\r\n _r.label = 1;\r\n case 1:\r\n _r.trys.push([1, 8, , 13]);\r\n transformResponse = defaultTransformResponse;\r\n result = void 0;\r\n baseQueryApi_1 = {\r\n signal: signal,\r\n abort: abort,\r\n dispatch: dispatch,\r\n getState: getState,\r\n extra: extra,\r\n endpoint: arg.endpointName,\r\n type: arg.type,\r\n forced: arg.type === \"query\" ? isForcedQuery(arg, getState()) : void 0\r\n };\r\n forceQueryFn = arg.type === \"query\" ? arg[forceQueryFnSymbol] : void 0;\r\n if (!forceQueryFn) return [3 /*break*/, 2];\r\n result = forceQueryFn();\r\n return [3 /*break*/, 6];\r\n case 2:\r\n if (!endpointDefinition.query) return [3 /*break*/, 4];\r\n return [4 /*yield*/, baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi_1, endpointDefinition.extraOptions)];\r\n case 3:\r\n result = _r.sent();\r\n if (endpointDefinition.transformResponse) {\r\n transformResponse = endpointDefinition.transformResponse;\r\n }\r\n return [3 /*break*/, 6];\r\n case 4: return [4 /*yield*/, endpointDefinition.queryFn(arg.originalArgs, baseQueryApi_1, endpointDefinition.extraOptions, function (arg2) { return baseQuery(arg2, baseQueryApi_1, endpointDefinition.extraOptions); })];\r\n case 5:\r\n result = _r.sent();\r\n _r.label = 6;\r\n case 6:\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n what = endpointDefinition.query ? \"`baseQuery`\" : \"`queryFn`\";\r\n err = void 0;\r\n if (!result) {\r\n err = what + \" did not return anything.\";\r\n }\r\n else if (typeof result !== \"object\") {\r\n err = what + \" did not return an object.\";\r\n }\r\n else if (result.error && result.data) {\r\n err = what + \" returned an object containing both `error` and `result`.\";\r\n }\r\n else if (result.error === void 0 && result.data === void 0) {\r\n err = what + \" returned an object containing neither a valid `error` and `result`. At least one of them should not be `undefined`\";\r\n }\r\n else {\r\n for (_k = 0, _l = Object.keys(result); _k < _l.length; _k++) {\r\n key = _l[_k];\r\n if (key !== \"error\" && key !== \"data\" && key !== \"meta\") {\r\n err = \"The object returned by \" + what + \" has the unknown property \" + key + \".\";\r\n break;\r\n }\r\n }\r\n }\r\n if (err) {\r\n console.error(\"Error encountered handling the endpoint \" + arg.endpointName + \".\\n \" + err + \"\\n It needs to return an object with either the shape `{ data: }` or `{ error: }` that may contain an optional `meta` property.\\n Object returned was:\", result);\r\n }\r\n }\r\n if (result.error)\r\n throw new HandledError(result.error, result.meta);\r\n _m = fulfillWithValue;\r\n return [4 /*yield*/, transformResponse(result.data, result.meta, arg.originalArgs)];\r\n case 7: return [2 /*return*/, _m.apply(void 0, [_r.sent(), (_p = {\r\n fulfilledTimeStamp: Date.now(),\r\n baseQueryMeta: result.meta\r\n },\r\n _p[SHOULD_AUTOBATCH] = true,\r\n _p)])];\r\n case 8:\r\n error_1 = _r.sent();\r\n catchedError = error_1;\r\n if (!(catchedError instanceof HandledError)) return [3 /*break*/, 12];\r\n transformErrorResponse = defaultTransformResponse;\r\n if (endpointDefinition.query && endpointDefinition.transformErrorResponse) {\r\n transformErrorResponse = endpointDefinition.transformErrorResponse;\r\n }\r\n _r.label = 9;\r\n case 9:\r\n _r.trys.push([9, 11, , 12]);\r\n _o = rejectWithValue;\r\n return [4 /*yield*/, transformErrorResponse(catchedError.value, catchedError.meta, arg.originalArgs)];\r\n case 10: return [2 /*return*/, _o.apply(void 0, [_r.sent(), (_q = { baseQueryMeta: catchedError.meta }, _q[SHOULD_AUTOBATCH] = true, _q)])];\r\n case 11:\r\n e_4 = _r.sent();\r\n catchedError = e_4;\r\n return [3 /*break*/, 12];\r\n case 12:\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV !== \"production\") {\r\n console.error(\"An unhandled error occurred processing a request for the endpoint \\\"\" + arg.endpointName + \"\\\".\\nIn the case of an unhandled error, no tags will be \\\"provided\\\" or \\\"invalidated\\\".\", catchedError);\r\n }\r\n else {\r\n console.error(catchedError);\r\n }\r\n throw catchedError;\r\n case 13: return [2 /*return*/];\r\n }\r\n });\r\n }); };\r\n function isForcedQuery(arg, state) {\r\n var _a, _b, _c, _d;\r\n var requestState = (_b = (_a = state[reducerPath]) == null ? void 0 : _a.queries) == null ? void 0 : _b[arg.queryCacheKey];\r\n var baseFetchOnMountOrArgChange = (_c = state[reducerPath]) == null ? void 0 : _c.config.refetchOnMountOrArgChange;\r\n var fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;\r\n var refetchVal = (_d = arg.forceRefetch) != null ? _d : arg.subscribe && baseFetchOnMountOrArgChange;\r\n if (refetchVal) {\r\n return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;\r\n }\r\n return false;\r\n }\r\n var queryThunk = createAsyncThunk(reducerPath + \"/executeQuery\", executeEndpoint, {\r\n getPendingMeta: function () {\r\n var _j;\r\n return _j = { startedTimeStamp: Date.now() }, _j[SHOULD_AUTOBATCH] = true, _j;\r\n },\r\n condition: function (queryThunkArgs, _j) {\r\n var getState = _j.getState;\r\n var _a, _b, _c;\r\n var state = getState();\r\n var requestState = (_b = (_a = state[reducerPath]) == null ? void 0 : _a.queries) == null ? void 0 : _b[queryThunkArgs.queryCacheKey];\r\n var fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;\r\n var currentArg = queryThunkArgs.originalArgs;\r\n var previousArg = requestState == null ? void 0 : requestState.originalArgs;\r\n var endpointDefinition = endpointDefinitions[queryThunkArgs.endpointName];\r\n if (isUpsertQuery(queryThunkArgs)) {\r\n return true;\r\n }\r\n if ((requestState == null ? void 0 : requestState.status) === \"pending\") {\r\n return false;\r\n }\r\n if (isForcedQuery(queryThunkArgs, state)) {\r\n return true;\r\n }\r\n if (isQueryDefinition(endpointDefinition) && ((_c = endpointDefinition == null ? void 0 : endpointDefinition.forceRefetch) == null ? void 0 : _c.call(endpointDefinition, {\r\n currentArg: currentArg,\r\n previousArg: previousArg,\r\n endpointState: requestState,\r\n state: state\r\n }))) {\r\n return true;\r\n }\r\n if (fulfilledVal) {\r\n return false;\r\n }\r\n return true;\r\n },\r\n dispatchConditionRejection: true\r\n });\r\n var mutationThunk = createAsyncThunk(reducerPath + \"/executeMutation\", executeEndpoint, {\r\n getPendingMeta: function () {\r\n var _j;\r\n return _j = { startedTimeStamp: Date.now() }, _j[SHOULD_AUTOBATCH] = true, _j;\r\n }\r\n });\r\n var hasTheForce = function (options) { return \"force\" in options; };\r\n var hasMaxAge = function (options) { return \"ifOlderThan\" in options; };\r\n var prefetch = function (endpointName, arg, options) { return function (dispatch, getState) {\r\n var force = hasTheForce(options) && options.force;\r\n var maxAge = hasMaxAge(options) && options.ifOlderThan;\r\n var queryAction = function (force2) {\r\n if (force2 === void 0) { force2 = true; }\r\n return api.endpoints[endpointName].initiate(arg, { forceRefetch: force2 });\r\n };\r\n var latestStateValue = api.endpoints[endpointName].select(arg)(getState());\r\n if (force) {\r\n dispatch(queryAction());\r\n }\r\n else if (maxAge) {\r\n var lastFulfilledTs = latestStateValue == null ? void 0 : latestStateValue.fulfilledTimeStamp;\r\n if (!lastFulfilledTs) {\r\n dispatch(queryAction());\r\n return;\r\n }\r\n var shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;\r\n if (shouldRetrigger) {\r\n dispatch(queryAction());\r\n }\r\n }\r\n else {\r\n dispatch(queryAction(false));\r\n }\r\n }; };\r\n function matchesEndpoint(endpointName) {\r\n return function (action) {\r\n var _a, _b;\r\n return ((_b = (_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.arg) == null ? void 0 : _b.endpointName) === endpointName;\r\n };\r\n }\r\n function buildMatchThunkActions(thunk, endpointName) {\r\n return {\r\n matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\r\n matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\r\n matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\r\n };\r\n }\r\n return {\r\n queryThunk: queryThunk,\r\n mutationThunk: mutationThunk,\r\n prefetch: prefetch,\r\n updateQueryData: updateQueryData,\r\n upsertQueryData: upsertQueryData,\r\n patchQueryData: patchQueryData,\r\n buildMatchThunkActions: buildMatchThunkActions\r\n };\r\n}\r\nfunction calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {\r\n return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, \"baseQueryMeta\" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);\r\n}\r\n// src/query/core/buildSlice.ts\r\nimport { isDraft } from \"immer\";\r\nimport { applyPatches, original } from \"immer\";\r\nfunction updateQuerySubstateIfExists(state, queryCacheKey, update) {\r\n var substate = state[queryCacheKey];\r\n if (substate) {\r\n update(substate);\r\n }\r\n}\r\nfunction getMutationCacheKey(id) {\r\n var _a;\r\n return (_a = \"arg\" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) != null ? _a : id.requestId;\r\n}\r\nfunction updateMutationSubstateIfExists(state, id, update) {\r\n var substate = state[getMutationCacheKey(id)];\r\n if (substate) {\r\n update(substate);\r\n }\r\n}\r\nvar initialState = {};\r\nfunction buildSlice(_j) {\r\n var reducerPath = _j.reducerPath, queryThunk = _j.queryThunk, mutationThunk = _j.mutationThunk, _k = _j.context, definitions = _k.endpointDefinitions, apiUid = _k.apiUid, extractRehydrationInfo = _k.extractRehydrationInfo, hasRehydrationInfo = _k.hasRehydrationInfo, assertTagType = _j.assertTagType, config = _j.config;\r\n var resetApiState = createAction2(reducerPath + \"/resetApiState\");\r\n var querySlice = createSlice({\r\n name: reducerPath + \"/queries\",\r\n initialState: initialState,\r\n reducers: {\r\n removeQueryResult: {\r\n reducer: function (draft, _j) {\r\n var queryCacheKey = _j.payload.queryCacheKey;\r\n delete draft[queryCacheKey];\r\n },\r\n prepare: prepareAutoBatched()\r\n },\r\n queryResultPatched: function (draft, _j) {\r\n var _k = _j.payload, queryCacheKey = _k.queryCacheKey, patches = _k.patches;\r\n updateQuerySubstateIfExists(draft, queryCacheKey, function (substate) {\r\n substate.data = applyPatches(substate.data, patches.concat());\r\n });\r\n }\r\n },\r\n extraReducers: function (builder) {\r\n builder.addCase(queryThunk.pending, function (draft, _j) {\r\n var meta = _j.meta, arg = _j.meta.arg;\r\n var _a, _b;\r\n var upserting = isUpsertQuery(arg);\r\n if (arg.subscribe || upserting) {\r\n (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {\r\n status: QueryStatus.uninitialized,\r\n endpointName: arg.endpointName\r\n };\r\n }\r\n updateQuerySubstateIfExists(draft, arg.queryCacheKey, function (substate) {\r\n substate.status = QueryStatus.pending;\r\n substate.requestId = upserting && substate.requestId ? substate.requestId : meta.requestId;\r\n if (arg.originalArgs !== void 0) {\r\n substate.originalArgs = arg.originalArgs;\r\n }\r\n substate.startedTimeStamp = meta.startedTimeStamp;\r\n });\r\n }).addCase(queryThunk.fulfilled, function (draft, _j) {\r\n var meta = _j.meta, payload = _j.payload;\r\n updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, function (substate) {\r\n var _a;\r\n if (substate.requestId !== meta.requestId && !isUpsertQuery(meta.arg))\r\n return;\r\n var merge = definitions[meta.arg.endpointName].merge;\r\n substate.status = QueryStatus.fulfilled;\r\n if (merge) {\r\n if (substate.data !== void 0) {\r\n var fulfilledTimeStamp_1 = meta.fulfilledTimeStamp, arg_1 = meta.arg, baseQueryMeta_1 = meta.baseQueryMeta, requestId_1 = meta.requestId;\r\n var newData = createNextState(substate.data, function (draftSubstateData) {\r\n return merge(draftSubstateData, payload, {\r\n arg: arg_1.originalArgs,\r\n baseQueryMeta: baseQueryMeta_1,\r\n fulfilledTimeStamp: fulfilledTimeStamp_1,\r\n requestId: requestId_1\r\n });\r\n });\r\n substate.data = newData;\r\n }\r\n else {\r\n substate.data = payload;\r\n }\r\n }\r\n else {\r\n substate.data = ((_a = definitions[meta.arg.endpointName].structuralSharing) != null ? _a : true) ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\r\n }\r\n delete substate.error;\r\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\r\n });\r\n }).addCase(queryThunk.rejected, function (draft, _j) {\r\n var _k = _j.meta, condition = _k.condition, arg = _k.arg, requestId = _k.requestId, error = _j.error, payload = _j.payload;\r\n updateQuerySubstateIfExists(draft, arg.queryCacheKey, function (substate) {\r\n if (condition) {\r\n }\r\n else {\r\n if (substate.requestId !== requestId)\r\n return;\r\n substate.status = QueryStatus.rejected;\r\n substate.error = payload != null ? payload : error;\r\n }\r\n });\r\n }).addMatcher(hasRehydrationInfo, function (draft, action) {\r\n var queries = extractRehydrationInfo(action).queries;\r\n for (var _j = 0, _k = Object.entries(queries); _j < _k.length; _j++) {\r\n var _l = _k[_j], key = _l[0], entry = _l[1];\r\n if ((entry == null ? void 0 : entry.status) === QueryStatus.fulfilled || (entry == null ? void 0 : entry.status) === QueryStatus.rejected) {\r\n draft[key] = entry;\r\n }\r\n }\r\n });\r\n }\r\n });\r\n var mutationSlice = createSlice({\r\n name: reducerPath + \"/mutations\",\r\n initialState: initialState,\r\n reducers: {\r\n removeMutationResult: {\r\n reducer: function (draft, _j) {\r\n var payload = _j.payload;\r\n var cacheKey = getMutationCacheKey(payload);\r\n if (cacheKey in draft) {\r\n delete draft[cacheKey];\r\n }\r\n },\r\n prepare: prepareAutoBatched()\r\n }\r\n },\r\n extraReducers: function (builder) {\r\n builder.addCase(mutationThunk.pending, function (draft, _j) {\r\n var meta = _j.meta, _k = _j.meta, requestId = _k.requestId, arg = _k.arg, startedTimeStamp = _k.startedTimeStamp;\r\n if (!arg.track)\r\n return;\r\n draft[getMutationCacheKey(meta)] = {\r\n requestId: requestId,\r\n status: QueryStatus.pending,\r\n endpointName: arg.endpointName,\r\n startedTimeStamp: startedTimeStamp\r\n };\r\n }).addCase(mutationThunk.fulfilled, function (draft, _j) {\r\n var payload = _j.payload, meta = _j.meta;\r\n if (!meta.arg.track)\r\n return;\r\n updateMutationSubstateIfExists(draft, meta, function (substate) {\r\n if (substate.requestId !== meta.requestId)\r\n return;\r\n substate.status = QueryStatus.fulfilled;\r\n substate.data = payload;\r\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\r\n });\r\n }).addCase(mutationThunk.rejected, function (draft, _j) {\r\n var payload = _j.payload, error = _j.error, meta = _j.meta;\r\n if (!meta.arg.track)\r\n return;\r\n updateMutationSubstateIfExists(draft, meta, function (substate) {\r\n if (substate.requestId !== meta.requestId)\r\n return;\r\n substate.status = QueryStatus.rejected;\r\n substate.error = payload != null ? payload : error;\r\n });\r\n }).addMatcher(hasRehydrationInfo, function (draft, action) {\r\n var mutations = extractRehydrationInfo(action).mutations;\r\n for (var _j = 0, _k = Object.entries(mutations); _j < _k.length; _j++) {\r\n var _l = _k[_j], key = _l[0], entry = _l[1];\r\n if (((entry == null ? void 0 : entry.status) === QueryStatus.fulfilled || (entry == null ? void 0 : entry.status) === QueryStatus.rejected) && key !== (entry == null ? void 0 : entry.requestId)) {\r\n draft[key] = entry;\r\n }\r\n }\r\n });\r\n }\r\n });\r\n var invalidationSlice = createSlice({\r\n name: reducerPath + \"/invalidation\",\r\n initialState: initialState,\r\n reducers: {},\r\n extraReducers: function (builder) {\r\n builder.addCase(querySlice.actions.removeQueryResult, function (draft, _j) {\r\n var queryCacheKey = _j.payload.queryCacheKey;\r\n for (var _k = 0, _l = Object.values(draft); _k < _l.length; _k++) {\r\n var tagTypeSubscriptions = _l[_k];\r\n for (var _m = 0, _o = Object.values(tagTypeSubscriptions); _m < _o.length; _m++) {\r\n var idSubscriptions = _o[_m];\r\n var foundAt = idSubscriptions.indexOf(queryCacheKey);\r\n if (foundAt !== -1) {\r\n idSubscriptions.splice(foundAt, 1);\r\n }\r\n }\r\n }\r\n }).addMatcher(hasRehydrationInfo, function (draft, action) {\r\n var _a, _b, _c, _d;\r\n var provided = extractRehydrationInfo(action).provided;\r\n for (var _j = 0, _k = Object.entries(provided); _j < _k.length; _j++) {\r\n var _l = _k[_j], type = _l[0], incomingTags = _l[1];\r\n for (var _m = 0, _o = Object.entries(incomingTags); _m < _o.length; _m++) {\r\n var _p = _o[_m], id = _p[0], cacheKeys = _p[1];\r\n var subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || \"__internal_without_id\"]) != null ? _d : _b[_c] = [];\r\n for (var _q = 0, cacheKeys_1 = cacheKeys; _q < cacheKeys_1.length; _q++) {\r\n var queryCacheKey = cacheKeys_1[_q];\r\n var alreadySubscribed = subscribedQueries.includes(queryCacheKey);\r\n if (!alreadySubscribed) {\r\n subscribedQueries.push(queryCacheKey);\r\n }\r\n }\r\n }\r\n }\r\n }).addMatcher(isAnyOf(isFulfilled2(queryThunk), isRejectedWithValue2(queryThunk)), function (draft, action) {\r\n var _a, _b, _c, _d;\r\n var providedTags = calculateProvidedByThunk(action, \"providesTags\", definitions, assertTagType);\r\n var queryCacheKey = action.meta.arg.queryCacheKey;\r\n for (var _j = 0, _k = Object.values(draft); _j < _k.length; _j++) {\r\n var tagTypeSubscriptions = _k[_j];\r\n for (var _l = 0, _m = Object.values(tagTypeSubscriptions); _l < _m.length; _l++) {\r\n var idSubscriptions = _m[_l];\r\n var foundAt = idSubscriptions.indexOf(queryCacheKey);\r\n if (foundAt !== -1) {\r\n idSubscriptions.splice(foundAt, 1);\r\n }\r\n }\r\n }\r\n for (var _o = 0, providedTags_1 = providedTags; _o < providedTags_1.length; _o++) {\r\n var _p = providedTags_1[_o], type = _p.type, id = _p.id;\r\n var subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || \"__internal_without_id\"]) != null ? _d : _b[_c] = [];\r\n var alreadySubscribed = subscribedQueries.includes(queryCacheKey);\r\n if (!alreadySubscribed) {\r\n subscribedQueries.push(queryCacheKey);\r\n }\r\n }\r\n });\r\n }\r\n });\r\n var subscriptionSlice = createSlice({\r\n name: reducerPath + \"/subscriptions\",\r\n initialState: initialState,\r\n reducers: {\r\n updateSubscriptionOptions: function (d, a) {\r\n },\r\n unsubscribeQueryResult: function (d, a) {\r\n },\r\n internal_probeSubscription: function (d, a) {\r\n }\r\n }\r\n });\r\n var internalSubscriptionsSlice = createSlice({\r\n name: reducerPath + \"/internalSubscriptions\",\r\n initialState: initialState,\r\n reducers: {\r\n subscriptionsUpdated: {\r\n reducer: function (state, action) {\r\n return applyPatches(state, action.payload);\r\n },\r\n prepare: prepareAutoBatched()\r\n }\r\n }\r\n });\r\n var configSlice = createSlice({\r\n name: reducerPath + \"/config\",\r\n initialState: __spreadValues({\r\n online: isOnline(),\r\n focused: isDocumentVisible(),\r\n middlewareRegistered: false\r\n }, config),\r\n reducers: {\r\n middlewareRegistered: function (state, _j) {\r\n var payload = _j.payload;\r\n state.middlewareRegistered = state.middlewareRegistered === \"conflict\" || apiUid !== payload ? \"conflict\" : true;\r\n }\r\n },\r\n extraReducers: function (builder) {\r\n builder.addCase(onOnline, function (state) {\r\n state.online = true;\r\n }).addCase(onOffline, function (state) {\r\n state.online = false;\r\n }).addCase(onFocus, function (state) {\r\n state.focused = true;\r\n }).addCase(onFocusLost, function (state) {\r\n state.focused = false;\r\n }).addMatcher(hasRehydrationInfo, function (draft) { return __spreadValues({}, draft); });\r\n }\r\n });\r\n var combinedReducer = combineReducers({\r\n queries: querySlice.reducer,\r\n mutations: mutationSlice.reducer,\r\n provided: invalidationSlice.reducer,\r\n subscriptions: internalSubscriptionsSlice.reducer,\r\n config: configSlice.reducer\r\n });\r\n var reducer = function (state, action) { return combinedReducer(resetApiState.match(action) ? void 0 : state, action); };\r\n var actions = __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, configSlice.actions), querySlice.actions), subscriptionSlice.actions), internalSubscriptionsSlice.actions), mutationSlice.actions), {\r\n unsubscribeMutationResult: mutationSlice.actions.removeMutationResult,\r\n resetApiState: resetApiState\r\n });\r\n return { reducer: reducer, actions: actions };\r\n}\r\n// src/query/core/buildSelectors.ts\r\nvar skipToken = /* @__PURE__ */ Symbol.for(\"RTKQ/skipToken\");\r\nvar skipSelector = skipToken;\r\nvar initialSubState = {\r\n status: QueryStatus.uninitialized\r\n};\r\nvar defaultQuerySubState = /* @__PURE__ */ createNextState2(initialSubState, function () {\r\n});\r\nvar defaultMutationSubState = /* @__PURE__ */ createNextState2(initialSubState, function () {\r\n});\r\nfunction buildSelectors(_j) {\r\n var serializeQueryArgs = _j.serializeQueryArgs, reducerPath = _j.reducerPath;\r\n var selectSkippedQuery = function (state) { return defaultQuerySubState; };\r\n var selectSkippedMutation = function (state) { return defaultMutationSubState; };\r\n return { buildQuerySelector: buildQuerySelector, buildMutationSelector: buildMutationSelector, selectInvalidatedBy: selectInvalidatedBy };\r\n function withRequestFlags(substate) {\r\n return __spreadValues(__spreadValues({}, substate), getRequestStatusFlags(substate.status));\r\n }\r\n function selectInternalState(rootState) {\r\n var state = rootState[reducerPath];\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (!state) {\r\n if (selectInternalState.triggered)\r\n return state;\r\n selectInternalState.triggered = true;\r\n console.error(\"Error: No data found at `state.\" + reducerPath + \"`. Did you forget to add the reducer to the store?\");\r\n }\r\n }\r\n return state;\r\n }\r\n function buildQuerySelector(endpointName, endpointDefinition) {\r\n return function (queryArgs) {\r\n var serializedArgs = serializeQueryArgs({\r\n queryArgs: queryArgs,\r\n endpointDefinition: endpointDefinition,\r\n endpointName: endpointName\r\n });\r\n var selectQuerySubstate = function (state) {\r\n var _a, _b, _c;\r\n return (_c = (_b = (_a = selectInternalState(state)) == null ? void 0 : _a.queries) == null ? void 0 : _b[serializedArgs]) != null ? _c : defaultQuerySubState;\r\n };\r\n var finalSelectQuerySubState = queryArgs === skipToken ? selectSkippedQuery : selectQuerySubstate;\r\n return createSelector(finalSelectQuerySubState, withRequestFlags);\r\n };\r\n }\r\n function buildMutationSelector() {\r\n return function (id) {\r\n var _a;\r\n var mutationId;\r\n if (typeof id === \"object\") {\r\n mutationId = (_a = getMutationCacheKey(id)) != null ? _a : skipToken;\r\n }\r\n else {\r\n mutationId = id;\r\n }\r\n var selectMutationSubstate = function (state) {\r\n var _a2, _b, _c;\r\n return (_c = (_b = (_a2 = selectInternalState(state)) == null ? void 0 : _a2.mutations) == null ? void 0 : _b[mutationId]) != null ? _c : defaultMutationSubState;\r\n };\r\n var finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\r\n return createSelector(finalSelectMutationSubstate, withRequestFlags);\r\n };\r\n }\r\n function selectInvalidatedBy(state, tags) {\r\n var _a;\r\n var apiState = state[reducerPath];\r\n var toInvalidate = new Set();\r\n for (var _j = 0, _k = tags.map(expandTagDescription); _j < _k.length; _j++) {\r\n var tag = _k[_j];\r\n var provided = apiState.provided[tag.type];\r\n if (!provided) {\r\n continue;\r\n }\r\n var invalidateSubscriptions = (_a = tag.id !== void 0 ? provided[tag.id] : flatten(Object.values(provided))) != null ? _a : [];\r\n for (var _l = 0, invalidateSubscriptions_1 = invalidateSubscriptions; _l < invalidateSubscriptions_1.length; _l++) {\r\n var invalidate = invalidateSubscriptions_1[_l];\r\n toInvalidate.add(invalidate);\r\n }\r\n }\r\n return flatten(Array.from(toInvalidate.values()).map(function (queryCacheKey) {\r\n var querySubState = apiState.queries[queryCacheKey];\r\n return querySubState ? [\r\n {\r\n queryCacheKey: queryCacheKey,\r\n endpointName: querySubState.endpointName,\r\n originalArgs: querySubState.originalArgs\r\n }\r\n ] : [];\r\n }));\r\n }\r\n}\r\n// src/query/defaultSerializeQueryArgs.ts\r\nimport { isPlainObject as isPlainObject3 } from \"@reduxjs/toolkit\";\r\nvar cache = WeakMap ? new WeakMap() : void 0;\r\nvar defaultSerializeQueryArgs = function (_j) {\r\n var endpointName = _j.endpointName, queryArgs = _j.queryArgs;\r\n var serialized = \"\";\r\n var cached = cache == null ? void 0 : cache.get(queryArgs);\r\n if (typeof cached === \"string\") {\r\n serialized = cached;\r\n }\r\n else {\r\n var stringified = JSON.stringify(queryArgs, function (key, value) { return isPlainObject3(value) ? Object.keys(value).sort().reduce(function (acc, key2) {\r\n acc[key2] = value[key2];\r\n return acc;\r\n }, {}) : value; });\r\n if (isPlainObject3(queryArgs)) {\r\n cache == null ? void 0 : cache.set(queryArgs, stringified);\r\n }\r\n serialized = stringified;\r\n }\r\n return endpointName + \"(\" + serialized + \")\";\r\n};\r\n// src/query/createApi.ts\r\nimport { nanoid } from \"@reduxjs/toolkit\";\r\nimport { defaultMemoize } from \"reselect\";\r\nfunction buildCreateApi() {\r\n var modules = [];\r\n for (var _j = 0; _j < arguments.length; _j++) {\r\n modules[_j] = arguments[_j];\r\n }\r\n return function baseCreateApi(options) {\r\n var extractRehydrationInfo = defaultMemoize(function (action) {\r\n var _a, _b;\r\n return (_b = options.extractRehydrationInfo) == null ? void 0 : _b.call(options, action, {\r\n reducerPath: (_a = options.reducerPath) != null ? _a : \"api\"\r\n });\r\n });\r\n var optionsWithDefaults = __spreadProps(__spreadValues({\r\n reducerPath: \"api\",\r\n keepUnusedDataFor: 60,\r\n refetchOnMountOrArgChange: false,\r\n refetchOnFocus: false,\r\n refetchOnReconnect: false\r\n }, options), {\r\n extractRehydrationInfo: extractRehydrationInfo,\r\n serializeQueryArgs: function (queryArgsApi) {\r\n var finalSerializeQueryArgs = defaultSerializeQueryArgs;\r\n if (\"serializeQueryArgs\" in queryArgsApi.endpointDefinition) {\r\n var endpointSQA_1 = queryArgsApi.endpointDefinition.serializeQueryArgs;\r\n finalSerializeQueryArgs = function (queryArgsApi2) {\r\n var initialResult = endpointSQA_1(queryArgsApi2);\r\n if (typeof initialResult === \"string\") {\r\n return initialResult;\r\n }\r\n else {\r\n return defaultSerializeQueryArgs(__spreadProps(__spreadValues({}, queryArgsApi2), {\r\n queryArgs: initialResult\r\n }));\r\n }\r\n };\r\n }\r\n else if (options.serializeQueryArgs) {\r\n finalSerializeQueryArgs = options.serializeQueryArgs;\r\n }\r\n return finalSerializeQueryArgs(queryArgsApi);\r\n },\r\n tagTypes: __spreadArray([], options.tagTypes || [])\r\n });\r\n var context = {\r\n endpointDefinitions: {},\r\n batch: function (fn) {\r\n fn();\r\n },\r\n apiUid: nanoid(),\r\n extractRehydrationInfo: extractRehydrationInfo,\r\n hasRehydrationInfo: defaultMemoize(function (action) { return extractRehydrationInfo(action) != null; })\r\n };\r\n var api = {\r\n injectEndpoints: injectEndpoints,\r\n enhanceEndpoints: function (_j) {\r\n var addTagTypes = _j.addTagTypes, endpoints = _j.endpoints;\r\n if (addTagTypes) {\r\n for (var _k = 0, addTagTypes_1 = addTagTypes; _k < addTagTypes_1.length; _k++) {\r\n var eT = addTagTypes_1[_k];\r\n if (!optionsWithDefaults.tagTypes.includes(eT)) {\r\n ;\r\n optionsWithDefaults.tagTypes.push(eT);\r\n }\r\n }\r\n }\r\n if (endpoints) {\r\n for (var _l = 0, _m = Object.entries(endpoints); _l < _m.length; _l++) {\r\n var _o = _m[_l], endpointName = _o[0], partialDefinition = _o[1];\r\n if (typeof partialDefinition === \"function\") {\r\n partialDefinition(context.endpointDefinitions[endpointName]);\r\n }\r\n else {\r\n Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);\r\n }\r\n }\r\n }\r\n return api;\r\n }\r\n };\r\n var initializedModules = modules.map(function (m) { return m.init(api, optionsWithDefaults, context); });\r\n function injectEndpoints(inject) {\r\n var evaluatedEndpoints = inject.endpoints({\r\n query: function (x) { return __spreadProps(__spreadValues({}, x), { type: DefinitionType.query }); },\r\n mutation: function (x) { return __spreadProps(__spreadValues({}, x), { type: DefinitionType.mutation }); }\r\n });\r\n for (var _j = 0, _k = Object.entries(evaluatedEndpoints); _j < _k.length; _j++) {\r\n var _l = _k[_j], endpointName = _l[0], definition = _l[1];\r\n if (!inject.overrideExisting && endpointName in context.endpointDefinitions) {\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n console.error(\"called `injectEndpoints` to override already-existing endpointName \" + endpointName + \" without specifying `overrideExisting: true`\");\r\n }\r\n continue;\r\n }\r\n context.endpointDefinitions[endpointName] = definition;\r\n for (var _m = 0, initializedModules_1 = initializedModules; _m < initializedModules_1.length; _m++) {\r\n var m = initializedModules_1[_m];\r\n m.injectEndpoint(endpointName, definition);\r\n }\r\n }\r\n return api;\r\n }\r\n return api.injectEndpoints({ endpoints: options.endpoints });\r\n };\r\n}\r\n// src/query/fakeBaseQuery.ts\r\nfunction fakeBaseQuery() {\r\n return function () {\r\n throw new Error(\"When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.\");\r\n };\r\n}\r\n// src/query/core/buildMiddleware/index.ts\r\nimport { createAction as createAction3 } from \"@reduxjs/toolkit\";\r\n// src/query/core/buildMiddleware/cacheCollection.ts\r\nfunction isObjectEmpty(obj) {\r\n for (var k in obj) {\r\n return false;\r\n }\r\n return true;\r\n}\r\nvar THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;\r\nvar buildCacheCollectionHandler = function (_j) {\r\n var reducerPath = _j.reducerPath, api = _j.api, context = _j.context, internalState = _j.internalState;\r\n var _k = api.internalActions, removeQueryResult = _k.removeQueryResult, unsubscribeQueryResult = _k.unsubscribeQueryResult;\r\n function anySubscriptionsRemainingForKey(queryCacheKey) {\r\n var subscriptions = internalState.currentSubscriptions[queryCacheKey];\r\n return !!subscriptions && !isObjectEmpty(subscriptions);\r\n }\r\n var currentRemovalTimeouts = {};\r\n var handler = function (action, mwApi, internalState2) {\r\n var _a;\r\n if (unsubscribeQueryResult.match(action)) {\r\n var state = mwApi.getState()[reducerPath];\r\n var queryCacheKey = action.payload.queryCacheKey;\r\n handleUnsubscribe(queryCacheKey, (_a = state.queries[queryCacheKey]) == null ? void 0 : _a.endpointName, mwApi, state.config);\r\n }\r\n if (api.util.resetApiState.match(action)) {\r\n for (var _j = 0, _k = Object.entries(currentRemovalTimeouts); _j < _k.length; _j++) {\r\n var _l = _k[_j], key = _l[0], timeout = _l[1];\r\n if (timeout)\r\n clearTimeout(timeout);\r\n delete currentRemovalTimeouts[key];\r\n }\r\n }\r\n if (context.hasRehydrationInfo(action)) {\r\n var state = mwApi.getState()[reducerPath];\r\n var queries = context.extractRehydrationInfo(action).queries;\r\n for (var _m = 0, _o = Object.entries(queries); _m < _o.length; _m++) {\r\n var _p = _o[_m], queryCacheKey = _p[0], queryState = _p[1];\r\n handleUnsubscribe(queryCacheKey, queryState == null ? void 0 : queryState.endpointName, mwApi, state.config);\r\n }\r\n }\r\n };\r\n function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {\r\n var _a;\r\n var endpointDefinition = context.endpointDefinitions[endpointName];\r\n var keepUnusedDataFor = (_a = endpointDefinition == null ? void 0 : endpointDefinition.keepUnusedDataFor) != null ? _a : config.keepUnusedDataFor;\r\n if (keepUnusedDataFor === Infinity) {\r\n return;\r\n }\r\n var finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\r\n if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\r\n var currentTimeout = currentRemovalTimeouts[queryCacheKey];\r\n if (currentTimeout) {\r\n clearTimeout(currentTimeout);\r\n }\r\n currentRemovalTimeouts[queryCacheKey] = setTimeout(function () {\r\n if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\r\n api2.dispatch(removeQueryResult({ queryCacheKey: queryCacheKey }));\r\n }\r\n delete currentRemovalTimeouts[queryCacheKey];\r\n }, finalKeepUnusedDataFor * 1e3);\r\n }\r\n }\r\n return handler;\r\n};\r\n// src/query/core/buildMiddleware/invalidationByTags.ts\r\nimport { isAnyOf as isAnyOf2, isFulfilled as isFulfilled3, isRejectedWithValue as isRejectedWithValue3 } from \"@reduxjs/toolkit\";\r\nvar buildInvalidationByTagsHandler = function (_j) {\r\n var reducerPath = _j.reducerPath, context = _j.context, endpointDefinitions = _j.context.endpointDefinitions, mutationThunk = _j.mutationThunk, api = _j.api, assertTagType = _j.assertTagType, refetchQuery = _j.refetchQuery;\r\n var removeQueryResult = api.internalActions.removeQueryResult;\r\n var isThunkActionWithTags = isAnyOf2(isFulfilled3(mutationThunk), isRejectedWithValue3(mutationThunk));\r\n var handler = function (action, mwApi) {\r\n if (isThunkActionWithTags(action)) {\r\n invalidateTags(calculateProvidedByThunk(action, \"invalidatesTags\", endpointDefinitions, assertTagType), mwApi);\r\n }\r\n if (api.util.invalidateTags.match(action)) {\r\n invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);\r\n }\r\n };\r\n function invalidateTags(tags, mwApi) {\r\n var rootState = mwApi.getState();\r\n var state = rootState[reducerPath];\r\n var toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\r\n context.batch(function () {\r\n var _a;\r\n var valuesArray = Array.from(toInvalidate.values());\r\n for (var _j = 0, valuesArray_1 = valuesArray; _j < valuesArray_1.length; _j++) {\r\n var queryCacheKey = valuesArray_1[_j].queryCacheKey;\r\n var querySubState = state.queries[queryCacheKey];\r\n var subscriptionSubState = (_a = state.subscriptions[queryCacheKey]) != null ? _a : {};\r\n if (querySubState) {\r\n if (Object.keys(subscriptionSubState).length === 0) {\r\n mwApi.dispatch(removeQueryResult({\r\n queryCacheKey: queryCacheKey\r\n }));\r\n }\r\n else if (querySubState.status !== QueryStatus.uninitialized) {\r\n mwApi.dispatch(refetchQuery(querySubState, queryCacheKey));\r\n }\r\n }\r\n }\r\n });\r\n }\r\n return handler;\r\n};\r\n// src/query/core/buildMiddleware/polling.ts\r\nvar buildPollingHandler = function (_j) {\r\n var reducerPath = _j.reducerPath, queryThunk = _j.queryThunk, api = _j.api, refetchQuery = _j.refetchQuery, internalState = _j.internalState;\r\n var currentPolls = {};\r\n var handler = function (action, mwApi) {\r\n if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\r\n updatePollingInterval(action.payload, mwApi);\r\n }\r\n if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\r\n updatePollingInterval(action.meta.arg, mwApi);\r\n }\r\n if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\r\n startNextPoll(action.meta.arg, mwApi);\r\n }\r\n if (api.util.resetApiState.match(action)) {\r\n clearPolls();\r\n }\r\n };\r\n function startNextPoll(_j, api2) {\r\n var queryCacheKey = _j.queryCacheKey;\r\n var state = api2.getState()[reducerPath];\r\n var querySubState = state.queries[queryCacheKey];\r\n var subscriptions = internalState.currentSubscriptions[queryCacheKey];\r\n if (!querySubState || querySubState.status === QueryStatus.uninitialized)\r\n return;\r\n var lowestPollingInterval = findLowestPollingInterval(subscriptions);\r\n if (!Number.isFinite(lowestPollingInterval))\r\n return;\r\n var currentPoll = currentPolls[queryCacheKey];\r\n if (currentPoll == null ? void 0 : currentPoll.timeout) {\r\n clearTimeout(currentPoll.timeout);\r\n currentPoll.timeout = void 0;\r\n }\r\n var nextPollTimestamp = Date.now() + lowestPollingInterval;\r\n var currentInterval = currentPolls[queryCacheKey] = {\r\n nextPollTimestamp: nextPollTimestamp,\r\n pollingInterval: lowestPollingInterval,\r\n timeout: setTimeout(function () {\r\n currentInterval.timeout = void 0;\r\n api2.dispatch(refetchQuery(querySubState, queryCacheKey));\r\n }, lowestPollingInterval)\r\n };\r\n }\r\n function updatePollingInterval(_j, api2) {\r\n var queryCacheKey = _j.queryCacheKey;\r\n var state = api2.getState()[reducerPath];\r\n var querySubState = state.queries[queryCacheKey];\r\n var subscriptions = internalState.currentSubscriptions[queryCacheKey];\r\n if (!querySubState || querySubState.status === QueryStatus.uninitialized) {\r\n return;\r\n }\r\n var lowestPollingInterval = findLowestPollingInterval(subscriptions);\r\n if (!Number.isFinite(lowestPollingInterval)) {\r\n cleanupPollForKey(queryCacheKey);\r\n return;\r\n }\r\n var currentPoll = currentPolls[queryCacheKey];\r\n var nextPollTimestamp = Date.now() + lowestPollingInterval;\r\n if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\r\n startNextPoll({ queryCacheKey: queryCacheKey }, api2);\r\n }\r\n }\r\n function cleanupPollForKey(key) {\r\n var existingPoll = currentPolls[key];\r\n if (existingPoll == null ? void 0 : existingPoll.timeout) {\r\n clearTimeout(existingPoll.timeout);\r\n }\r\n delete currentPolls[key];\r\n }\r\n function clearPolls() {\r\n for (var _j = 0, _k = Object.keys(currentPolls); _j < _k.length; _j++) {\r\n var key = _k[_j];\r\n cleanupPollForKey(key);\r\n }\r\n }\r\n function findLowestPollingInterval(subscribers) {\r\n if (subscribers === void 0) { subscribers = {}; }\r\n var lowestPollingInterval = Number.POSITIVE_INFINITY;\r\n for (var key in subscribers) {\r\n if (!!subscribers[key].pollingInterval) {\r\n lowestPollingInterval = Math.min(subscribers[key].pollingInterval, lowestPollingInterval);\r\n }\r\n }\r\n return lowestPollingInterval;\r\n }\r\n return handler;\r\n};\r\n// src/query/core/buildMiddleware/windowEventHandling.ts\r\nvar buildWindowEventHandler = function (_j) {\r\n var reducerPath = _j.reducerPath, context = _j.context, api = _j.api, refetchQuery = _j.refetchQuery, internalState = _j.internalState;\r\n var removeQueryResult = api.internalActions.removeQueryResult;\r\n var handler = function (action, mwApi) {\r\n if (onFocus.match(action)) {\r\n refetchValidQueries(mwApi, \"refetchOnFocus\");\r\n }\r\n if (onOnline.match(action)) {\r\n refetchValidQueries(mwApi, \"refetchOnReconnect\");\r\n }\r\n };\r\n function refetchValidQueries(api2, type) {\r\n var state = api2.getState()[reducerPath];\r\n var queries = state.queries;\r\n var subscriptions = internalState.currentSubscriptions;\r\n context.batch(function () {\r\n for (var _j = 0, _k = Object.keys(subscriptions); _j < _k.length; _j++) {\r\n var queryCacheKey = _k[_j];\r\n var querySubState = queries[queryCacheKey];\r\n var subscriptionSubState = subscriptions[queryCacheKey];\r\n if (!subscriptionSubState || !querySubState)\r\n continue;\r\n var shouldRefetch = Object.values(subscriptionSubState).some(function (sub) { return sub[type] === true; }) || Object.values(subscriptionSubState).every(function (sub) { return sub[type] === void 0; }) && state.config[type];\r\n if (shouldRefetch) {\r\n if (Object.keys(subscriptionSubState).length === 0) {\r\n api2.dispatch(removeQueryResult({\r\n queryCacheKey: queryCacheKey\r\n }));\r\n }\r\n else if (querySubState.status !== QueryStatus.uninitialized) {\r\n api2.dispatch(refetchQuery(querySubState, queryCacheKey));\r\n }\r\n }\r\n }\r\n });\r\n }\r\n return handler;\r\n};\r\n// src/query/core/buildMiddleware/cacheLifecycle.ts\r\nimport { isAsyncThunkAction, isFulfilled as isFulfilled4 } from \"@reduxjs/toolkit\";\r\nvar neverResolvedError = new Error(\"Promise never resolved before cacheEntryRemoved.\");\r\nvar buildCacheLifecycleHandler = function (_j) {\r\n var api = _j.api, reducerPath = _j.reducerPath, context = _j.context, queryThunk = _j.queryThunk, mutationThunk = _j.mutationThunk, internalState = _j.internalState;\r\n var isQueryThunk = isAsyncThunkAction(queryThunk);\r\n var isMutationThunk = isAsyncThunkAction(mutationThunk);\r\n var isFulfilledThunk = isFulfilled4(queryThunk, mutationThunk);\r\n var lifecycleMap = {};\r\n var handler = function (action, mwApi, stateBefore) {\r\n var cacheKey = getCacheKey(action);\r\n if (queryThunk.pending.match(action)) {\r\n var oldState = stateBefore[reducerPath].queries[cacheKey];\r\n var state = mwApi.getState()[reducerPath].queries[cacheKey];\r\n if (!oldState && state) {\r\n handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);\r\n }\r\n }\r\n else if (mutationThunk.pending.match(action)) {\r\n var state = mwApi.getState()[reducerPath].mutations[cacheKey];\r\n if (state) {\r\n handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);\r\n }\r\n }\r\n else if (isFulfilledThunk(action)) {\r\n var lifecycle = lifecycleMap[cacheKey];\r\n if (lifecycle == null ? void 0 : lifecycle.valueResolved) {\r\n lifecycle.valueResolved({\r\n data: action.payload,\r\n meta: action.meta.baseQueryMeta\r\n });\r\n delete lifecycle.valueResolved;\r\n }\r\n }\r\n else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {\r\n var lifecycle = lifecycleMap[cacheKey];\r\n if (lifecycle) {\r\n delete lifecycleMap[cacheKey];\r\n lifecycle.cacheEntryRemoved();\r\n }\r\n }\r\n else if (api.util.resetApiState.match(action)) {\r\n for (var _j = 0, _k = Object.entries(lifecycleMap); _j < _k.length; _j++) {\r\n var _l = _k[_j], cacheKey2 = _l[0], lifecycle = _l[1];\r\n delete lifecycleMap[cacheKey2];\r\n lifecycle.cacheEntryRemoved();\r\n }\r\n }\r\n };\r\n function getCacheKey(action) {\r\n if (isQueryThunk(action))\r\n return action.meta.arg.queryCacheKey;\r\n if (isMutationThunk(action))\r\n return action.meta.requestId;\r\n if (api.internalActions.removeQueryResult.match(action))\r\n return action.payload.queryCacheKey;\r\n if (api.internalActions.removeMutationResult.match(action))\r\n return getMutationCacheKey(action.payload);\r\n return \"\";\r\n }\r\n function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {\r\n var endpointDefinition = context.endpointDefinitions[endpointName];\r\n var onCacheEntryAdded = endpointDefinition == null ? void 0 : endpointDefinition.onCacheEntryAdded;\r\n if (!onCacheEntryAdded)\r\n return;\r\n var lifecycle = {};\r\n var cacheEntryRemoved = new Promise(function (resolve) {\r\n lifecycle.cacheEntryRemoved = resolve;\r\n });\r\n var cacheDataLoaded = Promise.race([\r\n new Promise(function (resolve) {\r\n lifecycle.valueResolved = resolve;\r\n }),\r\n cacheEntryRemoved.then(function () {\r\n throw neverResolvedError;\r\n })\r\n ]);\r\n cacheDataLoaded.catch(function () {\r\n });\r\n lifecycleMap[queryCacheKey] = lifecycle;\r\n var selector = api.endpoints[endpointName].select(endpointDefinition.type === DefinitionType.query ? originalArgs : queryCacheKey);\r\n var extra = mwApi.dispatch(function (_, __, extra2) { return extra2; });\r\n var lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {\r\n getCacheEntry: function () { return selector(mwApi.getState()); },\r\n requestId: requestId,\r\n extra: extra,\r\n updateCachedData: endpointDefinition.type === DefinitionType.query ? function (updateRecipe) { return mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)); } : void 0,\r\n cacheDataLoaded: cacheDataLoaded,\r\n cacheEntryRemoved: cacheEntryRemoved\r\n });\r\n var runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);\r\n Promise.resolve(runningHandler).catch(function (e) {\r\n if (e === neverResolvedError)\r\n return;\r\n throw e;\r\n });\r\n }\r\n return handler;\r\n};\r\n// src/query/core/buildMiddleware/queryLifecycle.ts\r\nimport { isPending as isPending2, isRejected as isRejected2, isFulfilled as isFulfilled5 } from \"@reduxjs/toolkit\";\r\nvar buildQueryLifecycleHandler = function (_j) {\r\n var api = _j.api, context = _j.context, queryThunk = _j.queryThunk, mutationThunk = _j.mutationThunk;\r\n var isPendingThunk = isPending2(queryThunk, mutationThunk);\r\n var isRejectedThunk = isRejected2(queryThunk, mutationThunk);\r\n var isFullfilledThunk = isFulfilled5(queryThunk, mutationThunk);\r\n var lifecycleMap = {};\r\n var handler = function (action, mwApi) {\r\n var _a, _b, _c;\r\n if (isPendingThunk(action)) {\r\n var _j = action.meta, requestId = _j.requestId, _k = _j.arg, endpointName_1 = _k.endpointName, originalArgs_1 = _k.originalArgs;\r\n var endpointDefinition = context.endpointDefinitions[endpointName_1];\r\n var onQueryStarted = endpointDefinition == null ? void 0 : endpointDefinition.onQueryStarted;\r\n if (onQueryStarted) {\r\n var lifecycle_1 = {};\r\n var queryFulfilled = new Promise(function (resolve, reject) {\r\n lifecycle_1.resolve = resolve;\r\n lifecycle_1.reject = reject;\r\n });\r\n queryFulfilled.catch(function () {\r\n });\r\n lifecycleMap[requestId] = lifecycle_1;\r\n var selector_1 = api.endpoints[endpointName_1].select(endpointDefinition.type === DefinitionType.query ? originalArgs_1 : requestId);\r\n var extra = mwApi.dispatch(function (_, __, extra2) { return extra2; });\r\n var lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {\r\n getCacheEntry: function () { return selector_1(mwApi.getState()); },\r\n requestId: requestId,\r\n extra: extra,\r\n updateCachedData: endpointDefinition.type === DefinitionType.query ? function (updateRecipe) { return mwApi.dispatch(api.util.updateQueryData(endpointName_1, originalArgs_1, updateRecipe)); } : void 0,\r\n queryFulfilled: queryFulfilled\r\n });\r\n onQueryStarted(originalArgs_1, lifecycleApi);\r\n }\r\n }\r\n else if (isFullfilledThunk(action)) {\r\n var _l = action.meta, requestId = _l.requestId, baseQueryMeta = _l.baseQueryMeta;\r\n (_a = lifecycleMap[requestId]) == null ? void 0 : _a.resolve({\r\n data: action.payload,\r\n meta: baseQueryMeta\r\n });\r\n delete lifecycleMap[requestId];\r\n }\r\n else if (isRejectedThunk(action)) {\r\n var _m = action.meta, requestId = _m.requestId, rejectedWithValue = _m.rejectedWithValue, baseQueryMeta = _m.baseQueryMeta;\r\n (_c = lifecycleMap[requestId]) == null ? void 0 : _c.reject({\r\n error: (_b = action.payload) != null ? _b : action.error,\r\n isUnhandledError: !rejectedWithValue,\r\n meta: baseQueryMeta\r\n });\r\n delete lifecycleMap[requestId];\r\n }\r\n };\r\n return handler;\r\n};\r\n// src/query/core/buildMiddleware/devMiddleware.ts\r\nvar buildDevCheckHandler = function (_j) {\r\n var api = _j.api, apiUid = _j.context.apiUid, reducerPath = _j.reducerPath;\r\n return function (action, mwApi) {\r\n var _a, _b;\r\n if (api.util.resetApiState.match(action)) {\r\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\r\n }\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && ((_b = (_a = mwApi.getState()[reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered) === \"conflict\") {\r\n console.warn(\"There is a mismatch between slice and middleware for the reducerPath \\\"\" + reducerPath + \"\\\".\\nYou can only have one api per reducer path, this will lead to crashes in various situations!\" + (reducerPath === \"api\" ? \"\\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!\" : \"\"));\r\n }\r\n }\r\n };\r\n};\r\n// src/query/core/buildMiddleware/batchActions.ts\r\nimport { produceWithPatches as produceWithPatches2 } from \"immer\";\r\nvar promise;\r\nvar queueMicrotaskShim = typeof queueMicrotask === \"function\" ? queueMicrotask.bind(typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : globalThis) : function (cb) { return (promise || (promise = Promise.resolve())).then(cb).catch(function (err) { return setTimeout(function () {\r\n throw err;\r\n}, 0); }); };\r\nvar buildBatchedActionsHandler = function (_j) {\r\n var api = _j.api, queryThunk = _j.queryThunk, internalState = _j.internalState;\r\n var subscriptionsPrefix = api.reducerPath + \"/subscriptions\";\r\n var previousSubscriptions = null;\r\n var dispatchQueued = false;\r\n var _k = api.internalActions, updateSubscriptionOptions = _k.updateSubscriptionOptions, unsubscribeQueryResult = _k.unsubscribeQueryResult;\r\n var actuallyMutateSubscriptions = function (mutableState, action) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h, _i;\r\n if (updateSubscriptionOptions.match(action)) {\r\n var _j = action.payload, queryCacheKey = _j.queryCacheKey, requestId = _j.requestId, options = _j.options;\r\n if ((_a = mutableState == null ? void 0 : mutableState[queryCacheKey]) == null ? void 0 : _a[requestId]) {\r\n mutableState[queryCacheKey][requestId] = options;\r\n }\r\n return true;\r\n }\r\n if (unsubscribeQueryResult.match(action)) {\r\n var _k = action.payload, queryCacheKey = _k.queryCacheKey, requestId = _k.requestId;\r\n if (mutableState[queryCacheKey]) {\r\n delete mutableState[queryCacheKey][requestId];\r\n }\r\n return true;\r\n }\r\n if (api.internalActions.removeQueryResult.match(action)) {\r\n delete mutableState[action.payload.queryCacheKey];\r\n return true;\r\n }\r\n if (queryThunk.pending.match(action)) {\r\n var _l = action.meta, arg = _l.arg, requestId = _l.requestId;\r\n if (arg.subscribe) {\r\n var substate = (_c = mutableState[_b = arg.queryCacheKey]) != null ? _c : mutableState[_b] = {};\r\n substate[requestId] = (_e = (_d = arg.subscriptionOptions) != null ? _d : substate[requestId]) != null ? _e : {};\r\n return true;\r\n }\r\n }\r\n if (queryThunk.rejected.match(action)) {\r\n var _m = action.meta, condition = _m.condition, arg = _m.arg, requestId = _m.requestId;\r\n if (condition && arg.subscribe) {\r\n var substate = (_g = mutableState[_f = arg.queryCacheKey]) != null ? _g : mutableState[_f] = {};\r\n substate[requestId] = (_i = (_h = arg.subscriptionOptions) != null ? _h : substate[requestId]) != null ? _i : {};\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n return function (action, mwApi) {\r\n var _a, _b;\r\n if (!previousSubscriptions) {\r\n previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));\r\n }\r\n if (api.util.resetApiState.match(action)) {\r\n previousSubscriptions = internalState.currentSubscriptions = {};\r\n return [true, false];\r\n }\r\n if (api.internalActions.internal_probeSubscription.match(action)) {\r\n var _j = action.payload, queryCacheKey = _j.queryCacheKey, requestId = _j.requestId;\r\n var hasSubscription = !!((_a = internalState.currentSubscriptions[queryCacheKey]) == null ? void 0 : _a[requestId]);\r\n return [false, hasSubscription];\r\n }\r\n var didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\r\n if (didMutate) {\r\n if (!dispatchQueued) {\r\n queueMicrotaskShim(function () {\r\n var newSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));\r\n var _j = produceWithPatches2(previousSubscriptions, function () { return newSubscriptions; }), patches = _j[1];\r\n mwApi.next(api.internalActions.subscriptionsUpdated(patches));\r\n previousSubscriptions = newSubscriptions;\r\n dispatchQueued = false;\r\n });\r\n dispatchQueued = true;\r\n }\r\n var isSubscriptionSliceAction = !!((_b = action.type) == null ? void 0 : _b.startsWith(subscriptionsPrefix));\r\n var isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\r\n var actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\r\n return [actionShouldContinue, false];\r\n }\r\n return [true, false];\r\n };\r\n};\r\n// src/query/core/buildMiddleware/index.ts\r\nfunction buildMiddleware(input) {\r\n var reducerPath = input.reducerPath, queryThunk = input.queryThunk, api = input.api, context = input.context;\r\n var apiUid = context.apiUid;\r\n var actions = {\r\n invalidateTags: createAction3(reducerPath + \"/invalidateTags\")\r\n };\r\n var isThisApiSliceAction = function (action) {\r\n return !!action && typeof action.type === \"string\" && action.type.startsWith(reducerPath + \"/\");\r\n };\r\n var handlerBuilders = [\r\n buildDevCheckHandler,\r\n buildCacheCollectionHandler,\r\n buildInvalidationByTagsHandler,\r\n buildPollingHandler,\r\n buildCacheLifecycleHandler,\r\n buildQueryLifecycleHandler\r\n ];\r\n var middleware = function (mwApi) {\r\n var initialized2 = false;\r\n var internalState = {\r\n currentSubscriptions: {}\r\n };\r\n var builderArgs = __spreadProps(__spreadValues({}, input), {\r\n internalState: internalState,\r\n refetchQuery: refetchQuery\r\n });\r\n var handlers = handlerBuilders.map(function (build) { return build(builderArgs); });\r\n var batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\r\n var windowEventsHandler = buildWindowEventHandler(builderArgs);\r\n return function (next) {\r\n return function (action) {\r\n if (!initialized2) {\r\n initialized2 = true;\r\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\r\n }\r\n var mwApiWithNext = __spreadProps(__spreadValues({}, mwApi), { next: next });\r\n var stateBefore = mwApi.getState();\r\n var _j = batchedActionsHandler(action, mwApiWithNext, stateBefore), actionShouldContinue = _j[0], hasSubscription = _j[1];\r\n var res;\r\n if (actionShouldContinue) {\r\n res = next(action);\r\n }\r\n else {\r\n res = hasSubscription;\r\n }\r\n if (!!mwApi.getState()[reducerPath]) {\r\n windowEventsHandler(action, mwApiWithNext, stateBefore);\r\n if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\r\n for (var _k = 0, handlers_1 = handlers; _k < handlers_1.length; _k++) {\r\n var handler = handlers_1[_k];\r\n handler(action, mwApiWithNext, stateBefore);\r\n }\r\n }\r\n }\r\n return res;\r\n };\r\n };\r\n };\r\n return { middleware: middleware, actions: actions };\r\n function refetchQuery(querySubState, queryCacheKey, override) {\r\n if (override === void 0) { override = {}; }\r\n return queryThunk(__spreadValues({\r\n type: \"query\",\r\n endpointName: querySubState.endpointName,\r\n originalArgs: querySubState.originalArgs,\r\n subscribe: false,\r\n forceRefetch: true,\r\n queryCacheKey: queryCacheKey\r\n }, override));\r\n }\r\n}\r\n// src/query/tsHelpers.ts\r\nfunction assertCast(v) {\r\n}\r\nfunction safeAssign(target) {\r\n var args = [];\r\n for (var _j = 1; _j < arguments.length; _j++) {\r\n args[_j - 1] = arguments[_j];\r\n }\r\n Object.assign.apply(Object, __spreadArray([target], args));\r\n}\r\n// src/query/core/module.ts\r\nimport { enablePatches } from \"immer\";\r\nvar coreModuleName = /* @__PURE__ */ Symbol();\r\nvar coreModule = function () { return ({\r\n name: coreModuleName,\r\n init: function (api, _j, context) {\r\n var baseQuery = _j.baseQuery, tagTypes = _j.tagTypes, reducerPath = _j.reducerPath, serializeQueryArgs = _j.serializeQueryArgs, keepUnusedDataFor = _j.keepUnusedDataFor, refetchOnMountOrArgChange = _j.refetchOnMountOrArgChange, refetchOnFocus = _j.refetchOnFocus, refetchOnReconnect = _j.refetchOnReconnect;\r\n enablePatches();\r\n assertCast(serializeQueryArgs);\r\n var assertTagType = function (tag) {\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\r\n if (!tagTypes.includes(tag.type)) {\r\n console.error(\"Tag type '\" + tag.type + \"' was used, but not specified in `tagTypes`!\");\r\n }\r\n }\r\n return tag;\r\n };\r\n Object.assign(api, {\r\n reducerPath: reducerPath,\r\n endpoints: {},\r\n internalActions: {\r\n onOnline: onOnline,\r\n onOffline: onOffline,\r\n onFocus: onFocus,\r\n onFocusLost: onFocusLost\r\n },\r\n util: {}\r\n });\r\n var _k = buildThunks({\r\n baseQuery: baseQuery,\r\n reducerPath: reducerPath,\r\n context: context,\r\n api: api,\r\n serializeQueryArgs: serializeQueryArgs\r\n }), queryThunk = _k.queryThunk, mutationThunk = _k.mutationThunk, patchQueryData = _k.patchQueryData, updateQueryData = _k.updateQueryData, upsertQueryData = _k.upsertQueryData, prefetch = _k.prefetch, buildMatchThunkActions = _k.buildMatchThunkActions;\r\n var _l = buildSlice({\r\n context: context,\r\n queryThunk: queryThunk,\r\n mutationThunk: mutationThunk,\r\n reducerPath: reducerPath,\r\n assertTagType: assertTagType,\r\n config: {\r\n refetchOnFocus: refetchOnFocus,\r\n refetchOnReconnect: refetchOnReconnect,\r\n refetchOnMountOrArgChange: refetchOnMountOrArgChange,\r\n keepUnusedDataFor: keepUnusedDataFor,\r\n reducerPath: reducerPath\r\n }\r\n }), reducer = _l.reducer, sliceActions = _l.actions;\r\n safeAssign(api.util, {\r\n patchQueryData: patchQueryData,\r\n updateQueryData: updateQueryData,\r\n upsertQueryData: upsertQueryData,\r\n prefetch: prefetch,\r\n resetApiState: sliceActions.resetApiState\r\n });\r\n safeAssign(api.internalActions, sliceActions);\r\n var _m = buildMiddleware({\r\n reducerPath: reducerPath,\r\n context: context,\r\n queryThunk: queryThunk,\r\n mutationThunk: mutationThunk,\r\n api: api,\r\n assertTagType: assertTagType\r\n }), middleware = _m.middleware, middlewareActions = _m.actions;\r\n safeAssign(api.util, middlewareActions);\r\n safeAssign(api, { reducer: reducer, middleware: middleware });\r\n var _o = buildSelectors({\r\n serializeQueryArgs: serializeQueryArgs,\r\n reducerPath: reducerPath\r\n }), buildQuerySelector = _o.buildQuerySelector, buildMutationSelector = _o.buildMutationSelector, selectInvalidatedBy = _o.selectInvalidatedBy;\r\n safeAssign(api.util, { selectInvalidatedBy: selectInvalidatedBy });\r\n var _p = buildInitiate({\r\n queryThunk: queryThunk,\r\n mutationThunk: mutationThunk,\r\n api: api,\r\n serializeQueryArgs: serializeQueryArgs,\r\n context: context\r\n }), buildInitiateQuery = _p.buildInitiateQuery, buildInitiateMutation = _p.buildInitiateMutation, getRunningMutationThunk = _p.getRunningMutationThunk, getRunningMutationsThunk = _p.getRunningMutationsThunk, getRunningQueriesThunk = _p.getRunningQueriesThunk, getRunningQueryThunk = _p.getRunningQueryThunk, getRunningOperationPromises = _p.getRunningOperationPromises, removalWarning = _p.removalWarning;\r\n safeAssign(api.util, {\r\n getRunningOperationPromises: getRunningOperationPromises,\r\n getRunningOperationPromise: removalWarning,\r\n getRunningMutationThunk: getRunningMutationThunk,\r\n getRunningMutationsThunk: getRunningMutationsThunk,\r\n getRunningQueryThunk: getRunningQueryThunk,\r\n getRunningQueriesThunk: getRunningQueriesThunk\r\n });\r\n return {\r\n name: coreModuleName,\r\n injectEndpoint: function (endpointName, definition) {\r\n var _a, _b;\r\n var anyApi = api;\r\n (_b = (_a = anyApi.endpoints)[endpointName]) != null ? _b : _a[endpointName] = {};\r\n if (isQueryDefinition(definition)) {\r\n safeAssign(anyApi.endpoints[endpointName], {\r\n name: endpointName,\r\n select: buildQuerySelector(endpointName, definition),\r\n initiate: buildInitiateQuery(endpointName, definition)\r\n }, buildMatchThunkActions(queryThunk, endpointName));\r\n }\r\n else if (isMutationDefinition(definition)) {\r\n safeAssign(anyApi.endpoints[endpointName], {\r\n name: endpointName,\r\n select: buildMutationSelector(),\r\n initiate: buildInitiateMutation(endpointName)\r\n }, buildMatchThunkActions(mutationThunk, endpointName));\r\n }\r\n }\r\n };\r\n }\r\n}); };\r\n// src/query/core/index.ts\r\nvar createApi = /* @__PURE__ */ buildCreateApi(coreModule());\r\nexport { QueryStatus, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, defaultSerializeQueryArgs, fakeBaseQuery, fetchBaseQuery, retry, setupListeners, skipSelector, skipToken };\r\n//# sourceMappingURL=rtk-query.esm.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n};\r\nvar __defProp = Object.defineProperty;\r\nvar __defProps = Object.defineProperties;\r\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\r\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\r\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\r\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\r\nvar __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };\r\nvar __spreadValues = function (a, b) {\r\n for (var prop in b || (b = {}))\r\n if (__hasOwnProp.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n if (__getOwnPropSymbols)\r\n for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {\r\n var prop = _c[_i];\r\n if (__propIsEnum.call(b, prop))\r\n __defNormalProp(a, prop, b[prop]);\r\n }\r\n return a;\r\n};\r\nvar __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };\r\n// src/query/react/index.ts\r\nimport { coreModule, buildCreateApi } from \"@reduxjs/toolkit/query\";\r\n// src/query/react/buildHooks.ts\r\nimport { createSelector } from \"@reduxjs/toolkit\";\r\nimport { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from \"react\";\r\nimport { QueryStatus, skipToken } from \"@reduxjs/toolkit/query\";\r\nimport { shallowEqual as shallowEqual2 } from \"react-redux\";\r\n// src/query/react/useSerializedStableValue.ts\r\nimport { useEffect, useRef, useMemo } from \"react\";\r\nfunction useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {\r\n var incoming = useMemo(function () { return ({\r\n queryArgs: queryArgs,\r\n serialized: typeof queryArgs == \"object\" ? serialize({ queryArgs: queryArgs, endpointDefinition: endpointDefinition, endpointName: endpointName }) : queryArgs\r\n }); }, [queryArgs, serialize, endpointDefinition, endpointName]);\r\n var cache2 = useRef(incoming);\r\n useEffect(function () {\r\n if (cache2.current.serialized !== incoming.serialized) {\r\n cache2.current = incoming;\r\n }\r\n }, [incoming]);\r\n return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;\r\n}\r\n// src/query/react/constants.ts\r\nvar UNINITIALIZED_VALUE = Symbol();\r\n// src/query/react/useShallowStableValue.ts\r\nimport { useEffect as useEffect2, useRef as useRef2 } from \"react\";\r\nimport { shallowEqual } from \"react-redux\";\r\nfunction useShallowStableValue(value) {\r\n var cache2 = useRef2(value);\r\n useEffect2(function () {\r\n if (!shallowEqual(cache2.current, value)) {\r\n cache2.current = value;\r\n }\r\n }, [value]);\r\n return shallowEqual(cache2.current, value) ? cache2.current : value;\r\n}\r\n// src/query/defaultSerializeQueryArgs.ts\r\nimport { isPlainObject } from \"@reduxjs/toolkit\";\r\nvar cache = WeakMap ? new WeakMap() : void 0;\r\nvar defaultSerializeQueryArgs = function (_c) {\r\n var endpointName = _c.endpointName, queryArgs = _c.queryArgs;\r\n var serialized = \"\";\r\n var cached = cache == null ? void 0 : cache.get(queryArgs);\r\n if (typeof cached === \"string\") {\r\n serialized = cached;\r\n }\r\n else {\r\n var stringified = JSON.stringify(queryArgs, function (key, value) { return isPlainObject(value) ? Object.keys(value).sort().reduce(function (acc, key2) {\r\n acc[key2] = value[key2];\r\n return acc;\r\n }, {}) : value; });\r\n if (isPlainObject(queryArgs)) {\r\n cache == null ? void 0 : cache.set(queryArgs, stringified);\r\n }\r\n serialized = stringified;\r\n }\r\n return endpointName + \"(\" + serialized + \")\";\r\n};\r\n// src/query/react/buildHooks.ts\r\nvar useIsomorphicLayoutEffect = typeof window !== \"undefined\" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;\r\nvar defaultMutationStateSelector = function (x) { return x; };\r\nvar noPendingQueryStateSelector = function (selected) {\r\n if (selected.isUninitialized) {\r\n return __spreadProps(__spreadValues({}, selected), {\r\n isUninitialized: false,\r\n isFetching: true,\r\n isLoading: selected.data !== void 0 ? false : true,\r\n status: QueryStatus.pending\r\n });\r\n }\r\n return selected;\r\n};\r\nfunction buildHooks(_c) {\r\n var api = _c.api, _d = _c.moduleOptions, batch = _d.batch, useDispatch = _d.useDispatch, useSelector = _d.useSelector, useStore = _d.useStore, unstable__sideEffectsInRender = _d.unstable__sideEffectsInRender, serializeQueryArgs = _c.serializeQueryArgs, context = _c.context;\r\n var usePossiblyImmediateEffect = unstable__sideEffectsInRender ? function (cb) { return cb(); } : useEffect3;\r\n return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };\r\n function queryStatePreSelector(currentState, lastResult, queryArgs) {\r\n if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {\r\n var endpointName = lastResult.endpointName;\r\n var endpointDefinition = context.endpointDefinitions[endpointName];\r\n if (serializeQueryArgs({\r\n queryArgs: lastResult.originalArgs,\r\n endpointDefinition: endpointDefinition,\r\n endpointName: endpointName\r\n }) === serializeQueryArgs({\r\n queryArgs: queryArgs,\r\n endpointDefinition: endpointDefinition,\r\n endpointName: endpointName\r\n }))\r\n lastResult = void 0;\r\n }\r\n var data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;\r\n if (data === void 0)\r\n data = currentState.data;\r\n var hasData = data !== void 0;\r\n var isFetching = currentState.isLoading;\r\n var isLoading = !hasData && isFetching;\r\n var isSuccess = currentState.isSuccess || isFetching && hasData;\r\n return __spreadProps(__spreadValues({}, currentState), {\r\n data: data,\r\n currentData: currentState.data,\r\n isFetching: isFetching,\r\n isLoading: isLoading,\r\n isSuccess: isSuccess\r\n });\r\n }\r\n function usePrefetch(endpointName, defaultOptions) {\r\n var dispatch = useDispatch();\r\n var stableDefaultOptions = useShallowStableValue(defaultOptions);\r\n return useCallback(function (arg, options) { return dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))); }, [endpointName, dispatch, stableDefaultOptions]);\r\n }\r\n function buildQueryHooks(name) {\r\n var useQuerySubscription = function (arg, _c) {\r\n var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, refetchOnMountOrArgChange = _d.refetchOnMountOrArgChange, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.pollingInterval, pollingInterval = _f === void 0 ? 0 : _f;\r\n var initiate = api.endpoints[name].initiate;\r\n var dispatch = useDispatch();\r\n var stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);\r\n var stableSubscriptionOptions = useShallowStableValue({\r\n refetchOnReconnect: refetchOnReconnect,\r\n refetchOnFocus: refetchOnFocus,\r\n pollingInterval: pollingInterval\r\n });\r\n var lastRenderHadSubscription = useRef3(false);\r\n var promiseRef = useRef3();\r\n var _g = promiseRef.current || {}, queryCacheKey = _g.queryCacheKey, requestId = _g.requestId;\r\n var currentRenderHasSubscription = false;\r\n if (queryCacheKey && requestId) {\r\n var returnedValue = dispatch(api.internalActions.internal_probeSubscription({\r\n queryCacheKey: queryCacheKey,\r\n requestId: requestId\r\n }));\r\n if (process.env.NODE_ENV !== \"production\") {\r\n if (typeof returnedValue !== \"boolean\") {\r\n throw new Error(\"Warning: Middleware for RTK-Query API at reducerPath \\\"\" + api.reducerPath + \"\\\" has not been added to the store.\\n You must add the middleware for RTK-Query to function correctly!\");\r\n }\r\n }\r\n currentRenderHasSubscription = !!returnedValue;\r\n }\r\n var subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;\r\n usePossiblyImmediateEffect(function () {\r\n lastRenderHadSubscription.current = currentRenderHasSubscription;\r\n });\r\n usePossiblyImmediateEffect(function () {\r\n if (subscriptionRemoved) {\r\n promiseRef.current = void 0;\r\n }\r\n }, [subscriptionRemoved]);\r\n usePossiblyImmediateEffect(function () {\r\n var _a;\r\n var lastPromise = promiseRef.current;\r\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"removeMeOnCompilation\") {\r\n console.log(subscriptionRemoved);\r\n }\r\n if (stableArg === skipToken) {\r\n lastPromise == null ? void 0 : lastPromise.unsubscribe();\r\n promiseRef.current = void 0;\r\n return;\r\n }\r\n var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;\r\n if (!lastPromise || lastPromise.arg !== stableArg) {\r\n lastPromise == null ? void 0 : lastPromise.unsubscribe();\r\n var promise = dispatch(initiate(stableArg, {\r\n subscriptionOptions: stableSubscriptionOptions,\r\n forceRefetch: refetchOnMountOrArgChange\r\n }));\r\n promiseRef.current = promise;\r\n }\r\n else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\r\n lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);\r\n }\r\n }, [\r\n dispatch,\r\n initiate,\r\n refetchOnMountOrArgChange,\r\n stableArg,\r\n stableSubscriptionOptions,\r\n subscriptionRemoved\r\n ]);\r\n useEffect3(function () {\r\n return function () {\r\n var _a;\r\n (_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();\r\n promiseRef.current = void 0;\r\n };\r\n }, []);\r\n return useMemo2(function () { return ({\r\n refetch: function () {\r\n var _a;\r\n if (!promiseRef.current)\r\n throw new Error(\"Cannot refetch a query that has not been started yet.\");\r\n return (_a = promiseRef.current) == null ? void 0 : _a.refetch();\r\n }\r\n }); }, []);\r\n };\r\n var useLazyQuerySubscription = function (_c) {\r\n var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, _e = _d.pollingInterval, pollingInterval = _e === void 0 ? 0 : _e;\r\n var initiate = api.endpoints[name].initiate;\r\n var dispatch = useDispatch();\r\n var _f = useState(UNINITIALIZED_VALUE), arg = _f[0], setArg = _f[1];\r\n var promiseRef = useRef3();\r\n var stableSubscriptionOptions = useShallowStableValue({\r\n refetchOnReconnect: refetchOnReconnect,\r\n refetchOnFocus: refetchOnFocus,\r\n pollingInterval: pollingInterval\r\n });\r\n usePossiblyImmediateEffect(function () {\r\n var _a, _b;\r\n var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;\r\n if (stableSubscriptionOptions !== lastSubscriptionOptions) {\r\n (_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);\r\n }\r\n }, [stableSubscriptionOptions]);\r\n var subscriptionOptionsRef = useRef3(stableSubscriptionOptions);\r\n usePossiblyImmediateEffect(function () {\r\n subscriptionOptionsRef.current = stableSubscriptionOptions;\r\n }, [stableSubscriptionOptions]);\r\n var trigger = useCallback(function (arg2, preferCacheValue) {\r\n if (preferCacheValue === void 0) { preferCacheValue = false; }\r\n var promise;\r\n batch(function () {\r\n var _a;\r\n (_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();\r\n promiseRef.current = promise = dispatch(initiate(arg2, {\r\n subscriptionOptions: subscriptionOptionsRef.current,\r\n forceRefetch: !preferCacheValue\r\n }));\r\n setArg(arg2);\r\n });\r\n return promise;\r\n }, [dispatch, initiate]);\r\n useEffect3(function () {\r\n return function () {\r\n var _a;\r\n (_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();\r\n };\r\n }, []);\r\n useEffect3(function () {\r\n if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\r\n trigger(arg, true);\r\n }\r\n }, [arg, trigger]);\r\n return useMemo2(function () { return [trigger, arg]; }, [trigger, arg]);\r\n };\r\n var useQueryState = function (arg, _c) {\r\n var _d = _c === void 0 ? {} : _c, _e = _d.skip, skip = _e === void 0 ? false : _e, selectFromResult = _d.selectFromResult;\r\n var select = api.endpoints[name].select;\r\n var stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);\r\n var lastValue = useRef3();\r\n var selectDefaultResult = useMemo2(function () { return createSelector([\r\n select(stableArg),\r\n function (_, lastResult) { return lastResult; },\r\n function (_) { return stableArg; }\r\n ], queryStatePreSelector); }, [select, stableArg]);\r\n var querySelector = useMemo2(function () { return selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult; }, [selectDefaultResult, selectFromResult]);\r\n var currentState = useSelector(function (state) { return querySelector(state, lastValue.current); }, shallowEqual2);\r\n var store = useStore();\r\n var newLastValue = selectDefaultResult(store.getState(), lastValue.current);\r\n useIsomorphicLayoutEffect(function () {\r\n lastValue.current = newLastValue;\r\n }, [newLastValue]);\r\n return currentState;\r\n };\r\n return {\r\n useQueryState: useQueryState,\r\n useQuerySubscription: useQuerySubscription,\r\n useLazyQuerySubscription: useLazyQuerySubscription,\r\n useLazyQuery: function (options) {\r\n var _c = useLazyQuerySubscription(options), trigger = _c[0], arg = _c[1];\r\n var queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {\r\n skip: arg === UNINITIALIZED_VALUE\r\n }));\r\n var info = useMemo2(function () { return ({ lastArg: arg }); }, [arg]);\r\n return useMemo2(function () { return [trigger, queryStateResults, info]; }, [trigger, queryStateResults, info]);\r\n },\r\n useQuery: function (arg, options) {\r\n var querySubscriptionResults = useQuerySubscription(arg, options);\r\n var queryStateResults = useQueryState(arg, __spreadValues({\r\n selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector\r\n }, options));\r\n var data = queryStateResults.data, status = queryStateResults.status, isLoading = queryStateResults.isLoading, isSuccess = queryStateResults.isSuccess, isError = queryStateResults.isError, error = queryStateResults.error;\r\n useDebugValue({ data: data, status: status, isLoading: isLoading, isSuccess: isSuccess, isError: isError, error: error });\r\n return useMemo2(function () { return __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults); }, [queryStateResults, querySubscriptionResults]);\r\n }\r\n };\r\n }\r\n function buildMutationHook(name) {\r\n return function (_c) {\r\n var _d = _c === void 0 ? {} : _c, _e = _d.selectFromResult, selectFromResult = _e === void 0 ? defaultMutationStateSelector : _e, fixedCacheKey = _d.fixedCacheKey;\r\n var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;\r\n var dispatch = useDispatch();\r\n var _g = useState(), promise = _g[0], setPromise = _g[1];\r\n useEffect3(function () { return function () {\r\n if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {\r\n promise == null ? void 0 : promise.reset();\r\n }\r\n }; }, [promise]);\r\n var triggerMutation = useCallback(function (arg) {\r\n var promise2 = dispatch(initiate(arg, { fixedCacheKey: fixedCacheKey }));\r\n setPromise(promise2);\r\n return promise2;\r\n }, [dispatch, initiate, fixedCacheKey]);\r\n var requestId = (promise || {}).requestId;\r\n var mutationSelector = useMemo2(function () { return createSelector([select({ fixedCacheKey: fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult); }, [select, promise, selectFromResult, fixedCacheKey]);\r\n var currentState = useSelector(mutationSelector, shallowEqual2);\r\n var originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;\r\n var reset = useCallback(function () {\r\n batch(function () {\r\n if (promise) {\r\n setPromise(void 0);\r\n }\r\n if (fixedCacheKey) {\r\n dispatch(api.internalActions.removeMutationResult({\r\n requestId: requestId,\r\n fixedCacheKey: fixedCacheKey\r\n }));\r\n }\r\n });\r\n }, [dispatch, fixedCacheKey, promise, requestId]);\r\n var endpointName = currentState.endpointName, data = currentState.data, status = currentState.status, isLoading = currentState.isLoading, isSuccess = currentState.isSuccess, isError = currentState.isError, error = currentState.error;\r\n useDebugValue({\r\n endpointName: endpointName,\r\n data: data,\r\n status: status,\r\n isLoading: isLoading,\r\n isSuccess: isSuccess,\r\n isError: isError,\r\n error: error\r\n });\r\n var finalState = useMemo2(function () { return __spreadProps(__spreadValues({}, currentState), { originalArgs: originalArgs, reset: reset }); }, [currentState, originalArgs, reset]);\r\n return useMemo2(function () { return [triggerMutation, finalState]; }, [triggerMutation, finalState]);\r\n };\r\n }\r\n}\r\n// src/query/endpointDefinitions.ts\r\nvar DefinitionType;\r\n(function (DefinitionType2) {\r\n DefinitionType2[\"query\"] = \"query\";\r\n DefinitionType2[\"mutation\"] = \"mutation\";\r\n})(DefinitionType || (DefinitionType = {}));\r\nfunction isQueryDefinition(e) {\r\n return e.type === DefinitionType.query;\r\n}\r\nfunction isMutationDefinition(e) {\r\n return e.type === DefinitionType.mutation;\r\n}\r\n// src/query/utils/capitalize.ts\r\nfunction capitalize(str) {\r\n return str.replace(str[0], str[0].toUpperCase());\r\n}\r\n// src/query/tsHelpers.ts\r\nfunction safeAssign(target) {\r\n var args = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n args[_i - 1] = arguments[_i];\r\n }\r\n Object.assign.apply(Object, __spreadArray([target], args));\r\n}\r\n// src/query/react/module.ts\r\nimport { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from \"react-redux\";\r\nvar reactHooksModuleName = /* @__PURE__ */ Symbol();\r\nvar reactHooksModule = function (_c) {\r\n var _d = _c === void 0 ? {} : _c, _e = _d.batch, batch = _e === void 0 ? rrBatch : _e, _f = _d.useDispatch, useDispatch = _f === void 0 ? rrUseDispatch : _f, _g = _d.useSelector, useSelector = _g === void 0 ? rrUseSelector : _g, _h = _d.useStore, useStore = _h === void 0 ? rrUseStore : _h, _j = _d.unstable__sideEffectsInRender, unstable__sideEffectsInRender = _j === void 0 ? false : _j;\r\n return ({\r\n name: reactHooksModuleName,\r\n init: function (api, _c, context) {\r\n var serializeQueryArgs = _c.serializeQueryArgs;\r\n var anyApi = api;\r\n var _d = buildHooks({\r\n api: api,\r\n moduleOptions: {\r\n batch: batch,\r\n useDispatch: useDispatch,\r\n useSelector: useSelector,\r\n useStore: useStore,\r\n unstable__sideEffectsInRender: unstable__sideEffectsInRender\r\n },\r\n serializeQueryArgs: serializeQueryArgs,\r\n context: context\r\n }), buildQueryHooks = _d.buildQueryHooks, buildMutationHook = _d.buildMutationHook, usePrefetch = _d.usePrefetch;\r\n safeAssign(anyApi, { usePrefetch: usePrefetch });\r\n safeAssign(context, { batch: batch });\r\n return {\r\n injectEndpoint: function (endpointName, definition) {\r\n if (isQueryDefinition(definition)) {\r\n var _c = buildQueryHooks(endpointName), useQuery = _c.useQuery, useLazyQuery = _c.useLazyQuery, useLazyQuerySubscription = _c.useLazyQuerySubscription, useQueryState = _c.useQueryState, useQuerySubscription = _c.useQuerySubscription;\r\n safeAssign(anyApi.endpoints[endpointName], {\r\n useQuery: useQuery,\r\n useLazyQuery: useLazyQuery,\r\n useLazyQuerySubscription: useLazyQuerySubscription,\r\n useQueryState: useQueryState,\r\n useQuerySubscription: useQuerySubscription\r\n });\r\n api[\"use\" + capitalize(endpointName) + \"Query\"] = useQuery;\r\n api[\"useLazy\" + capitalize(endpointName) + \"Query\"] = useLazyQuery;\r\n }\r\n else if (isMutationDefinition(definition)) {\r\n var useMutation = buildMutationHook(endpointName);\r\n safeAssign(anyApi.endpoints[endpointName], {\r\n useMutation: useMutation\r\n });\r\n api[\"use\" + capitalize(endpointName) + \"Mutation\"] = useMutation;\r\n }\r\n }\r\n };\r\n }\r\n });\r\n};\r\n// src/query/react/index.ts\r\nexport * from \"@reduxjs/toolkit/query\";\r\n// src/query/react/ApiProvider.tsx\r\nimport { configureStore } from \"@reduxjs/toolkit\";\r\nimport { useEffect as useEffect4 } from \"react\";\r\nimport React from \"react\";\r\nimport { Provider } from \"react-redux\";\r\nimport { setupListeners } from \"@reduxjs/toolkit/query\";\r\nfunction ApiProvider(props) {\r\n var store = React.useState(function () {\r\n var _c;\r\n return configureStore({\r\n reducer: (_c = {},\r\n _c[props.api.reducerPath] = props.api.reducer,\r\n _c),\r\n middleware: function (gDM) { return gDM().concat(props.api.middleware); }\r\n });\r\n })[0];\r\n useEffect4(function () { return props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners); }, [props.setupListeners, store.dispatch]);\r\n return /* @__PURE__ */ React.createElement(Provider, {\r\n store: store,\r\n context: props.context\r\n }, props.children);\r\n}\r\n// src/query/react/index.ts\r\nvar createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());\r\nexport { ApiProvider, createApi, reactHooksModule };\r\n//# sourceMappingURL=rtk-query-react.esm.js.map","export default {}",";(function (root, factory) {\n\tif (typeof exports === \"object\") {\n\t\t// CommonJS\n\t\tmodule.exports = exports = factory();\n\t}\n\telse if (typeof define === \"function\" && define.amd) {\n\t\t// AMD\n\t\tdefine([], factory);\n\t}\n\telse {\n\t\t// Global (browser)\n\t\troot.CryptoJS = factory();\n\t}\n}(this, function () {\n\n\t/*globals window, global, require*/\n\n\t/**\n\t * CryptoJS core components.\n\t */\n\tvar CryptoJS = CryptoJS || (function (Math, undefined) {\n\n\t var crypto;\n\n\t // Native crypto from window (Browser)\n\t if (typeof window !== 'undefined' && window.crypto) {\n\t crypto = window.crypto;\n\t }\n\n\t // Native crypto in web worker (Browser)\n\t if (typeof self !== 'undefined' && self.crypto) {\n\t crypto = self.crypto;\n\t }\n\n\t // Native crypto from worker\n\t if (typeof globalThis !== 'undefined' && globalThis.crypto) {\n\t crypto = globalThis.crypto;\n\t }\n\n\t // Native (experimental IE 11) crypto from window (Browser)\n\t if (!crypto && typeof window !== 'undefined' && window.msCrypto) {\n\t crypto = window.msCrypto;\n\t }\n\n\t // Native crypto from global (NodeJS)\n\t if (!crypto && typeof global !== 'undefined' && global.crypto) {\n\t crypto = global.crypto;\n\t }\n\n\t // Native crypto import via require (NodeJS)\n\t if (!crypto && typeof require === 'function') {\n\t try {\n\t crypto = require('crypto');\n\t } catch (err) {}\n\t }\n\n\t /*\n\t * Cryptographically secure pseudorandom number generator\n\t *\n\t * As Math.random() is cryptographically not safe to use\n\t */\n\t var cryptoSecureRandomInt = function () {\n\t if (crypto) {\n\t // Use getRandomValues method (Browser)\n\t if (typeof crypto.getRandomValues === 'function') {\n\t try {\n\t return crypto.getRandomValues(new Uint32Array(1))[0];\n\t } catch (err) {}\n\t }\n\n\t // Use randomBytes method (NodeJS)\n\t if (typeof crypto.randomBytes === 'function') {\n\t try {\n\t return crypto.randomBytes(4).readInt32LE();\n\t } catch (err) {}\n\t }\n\t }\n\n\t throw new Error('Native crypto module could not be used to get secure random number.');\n\t };\n\n\t /*\n\t * Local polyfill of Object.create\n\n\t */\n\t var create = Object.create || (function () {\n\t function F() {}\n\n\t return function (obj) {\n\t var subtype;\n\n\t F.prototype = obj;\n\n\t subtype = new F();\n\n\t F.prototype = null;\n\n\t return subtype;\n\t };\n\t }());\n\n\t /**\n\t * CryptoJS namespace.\n\t */\n\t var C = {};\n\n\t /**\n\t * Library namespace.\n\t */\n\t var C_lib = C.lib = {};\n\n\t /**\n\t * Base object for prototypal inheritance.\n\t */\n\t var Base = C_lib.Base = (function () {\n\n\n\t return {\n\t /**\n\t * Creates a new object that inherits from this object.\n\t *\n\t * @param {Object} overrides Properties to copy into the new object.\n\t *\n\t * @return {Object} The new object.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var MyType = CryptoJS.lib.Base.extend({\n\t * field: 'value',\n\t *\n\t * method: function () {\n\t * }\n\t * });\n\t */\n\t extend: function (overrides) {\n\t // Spawn\n\t var subtype = create(this);\n\n\t // Augment\n\t if (overrides) {\n\t subtype.mixIn(overrides);\n\t }\n\n\t // Create default initializer\n\t if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {\n\t subtype.init = function () {\n\t subtype.$super.init.apply(this, arguments);\n\t };\n\t }\n\n\t // Initializer's prototype is the subtype object\n\t subtype.init.prototype = subtype;\n\n\t // Reference supertype\n\t subtype.$super = this;\n\n\t return subtype;\n\t },\n\n\t /**\n\t * Extends this object and runs the init method.\n\t * Arguments to create() will be passed to init().\n\t *\n\t * @return {Object} The new object.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var instance = MyType.create();\n\t */\n\t create: function () {\n\t var instance = this.extend();\n\t instance.init.apply(instance, arguments);\n\n\t return instance;\n\t },\n\n\t /**\n\t * Initializes a newly created object.\n\t * Override this method to add some logic when your objects are created.\n\t *\n\t * @example\n\t *\n\t * var MyType = CryptoJS.lib.Base.extend({\n\t * init: function () {\n\t * // ...\n\t * }\n\t * });\n\t */\n\t init: function () {\n\t },\n\n\t /**\n\t * Copies properties into this object.\n\t *\n\t * @param {Object} properties The properties to mix in.\n\t *\n\t * @example\n\t *\n\t * MyType.mixIn({\n\t * field: 'value'\n\t * });\n\t */\n\t mixIn: function (properties) {\n\t for (var propertyName in properties) {\n\t if (properties.hasOwnProperty(propertyName)) {\n\t this[propertyName] = properties[propertyName];\n\t }\n\t }\n\n\t // IE won't copy toString using the loop above\n\t if (properties.hasOwnProperty('toString')) {\n\t this.toString = properties.toString;\n\t }\n\t },\n\n\t /**\n\t * Creates a copy of this object.\n\t *\n\t * @return {Object} The clone.\n\t *\n\t * @example\n\t *\n\t * var clone = instance.clone();\n\t */\n\t clone: function () {\n\t return this.init.prototype.extend(this);\n\t }\n\t };\n\t }());\n\n\t /**\n\t * An array of 32-bit words.\n\t *\n\t * @property {Array} words The array of 32-bit words.\n\t * @property {number} sigBytes The number of significant bytes in this word array.\n\t */\n\t var WordArray = C_lib.WordArray = Base.extend({\n\t /**\n\t * Initializes a newly created word array.\n\t *\n\t * @param {Array} words (Optional) An array of 32-bit words.\n\t * @param {number} sigBytes (Optional) The number of significant bytes in the words.\n\t *\n\t * @example\n\t *\n\t * var wordArray = CryptoJS.lib.WordArray.create();\n\t * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);\n\t * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);\n\t */\n\t init: function (words, sigBytes) {\n\t words = this.words = words || [];\n\n\t if (sigBytes != undefined) {\n\t this.sigBytes = sigBytes;\n\t } else {\n\t this.sigBytes = words.length * 4;\n\t }\n\t },\n\n\t /**\n\t * Converts this word array to a string.\n\t *\n\t * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex\n\t *\n\t * @return {string} The stringified word array.\n\t *\n\t * @example\n\t *\n\t * var string = wordArray + '';\n\t * var string = wordArray.toString();\n\t * var string = wordArray.toString(CryptoJS.enc.Utf8);\n\t */\n\t toString: function (encoder) {\n\t return (encoder || Hex).stringify(this);\n\t },\n\n\t /**\n\t * Concatenates a word array to this word array.\n\t *\n\t * @param {WordArray} wordArray The word array to append.\n\t *\n\t * @return {WordArray} This word array.\n\t *\n\t * @example\n\t *\n\t * wordArray1.concat(wordArray2);\n\t */\n\t concat: function (wordArray) {\n\t // Shortcuts\n\t var thisWords = this.words;\n\t var thatWords = wordArray.words;\n\t var thisSigBytes = this.sigBytes;\n\t var thatSigBytes = wordArray.sigBytes;\n\n\t // Clamp excess bits\n\t this.clamp();\n\n\t // Concat\n\t if (thisSigBytes % 4) {\n\t // Copy one byte at a time\n\t for (var i = 0; i < thatSigBytes; i++) {\n\t var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n\t thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);\n\t }\n\t } else {\n\t // Copy one word at a time\n\t for (var j = 0; j < thatSigBytes; j += 4) {\n\t thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];\n\t }\n\t }\n\t this.sigBytes += thatSigBytes;\n\n\t // Chainable\n\t return this;\n\t },\n\n\t /**\n\t * Removes insignificant bits.\n\t *\n\t * @example\n\t *\n\t * wordArray.clamp();\n\t */\n\t clamp: function () {\n\t // Shortcuts\n\t var words = this.words;\n\t var sigBytes = this.sigBytes;\n\n\t // Clamp\n\t words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);\n\t words.length = Math.ceil(sigBytes / 4);\n\t },\n\n\t /**\n\t * Creates a copy of this word array.\n\t *\n\t * @return {WordArray} The clone.\n\t *\n\t * @example\n\t *\n\t * var clone = wordArray.clone();\n\t */\n\t clone: function () {\n\t var clone = Base.clone.call(this);\n\t clone.words = this.words.slice(0);\n\n\t return clone;\n\t },\n\n\t /**\n\t * Creates a word array filled with random bytes.\n\t *\n\t * @param {number} nBytes The number of random bytes to generate.\n\t *\n\t * @return {WordArray} The random word array.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var wordArray = CryptoJS.lib.WordArray.random(16);\n\t */\n\t random: function (nBytes) {\n\t var words = [];\n\n\t for (var i = 0; i < nBytes; i += 4) {\n\t words.push(cryptoSecureRandomInt());\n\t }\n\n\t return new WordArray.init(words, nBytes);\n\t }\n\t });\n\n\t /**\n\t * Encoder namespace.\n\t */\n\t var C_enc = C.enc = {};\n\n\t /**\n\t * Hex encoding strategy.\n\t */\n\t var Hex = C_enc.Hex = {\n\t /**\n\t * Converts a word array to a hex string.\n\t *\n\t * @param {WordArray} wordArray The word array.\n\t *\n\t * @return {string} The hex string.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var hexString = CryptoJS.enc.Hex.stringify(wordArray);\n\t */\n\t stringify: function (wordArray) {\n\t // Shortcuts\n\t var words = wordArray.words;\n\t var sigBytes = wordArray.sigBytes;\n\n\t // Convert\n\t var hexChars = [];\n\t for (var i = 0; i < sigBytes; i++) {\n\t var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n\t hexChars.push((bite >>> 4).toString(16));\n\t hexChars.push((bite & 0x0f).toString(16));\n\t }\n\n\t return hexChars.join('');\n\t },\n\n\t /**\n\t * Converts a hex string to a word array.\n\t *\n\t * @param {string} hexStr The hex string.\n\t *\n\t * @return {WordArray} The word array.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var wordArray = CryptoJS.enc.Hex.parse(hexString);\n\t */\n\t parse: function (hexStr) {\n\t // Shortcut\n\t var hexStrLength = hexStr.length;\n\n\t // Convert\n\t var words = [];\n\t for (var i = 0; i < hexStrLength; i += 2) {\n\t words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);\n\t }\n\n\t return new WordArray.init(words, hexStrLength / 2);\n\t }\n\t };\n\n\t /**\n\t * Latin1 encoding strategy.\n\t */\n\t var Latin1 = C_enc.Latin1 = {\n\t /**\n\t * Converts a word array to a Latin1 string.\n\t *\n\t * @param {WordArray} wordArray The word array.\n\t *\n\t * @return {string} The Latin1 string.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);\n\t */\n\t stringify: function (wordArray) {\n\t // Shortcuts\n\t var words = wordArray.words;\n\t var sigBytes = wordArray.sigBytes;\n\n\t // Convert\n\t var latin1Chars = [];\n\t for (var i = 0; i < sigBytes; i++) {\n\t var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n\t latin1Chars.push(String.fromCharCode(bite));\n\t }\n\n\t return latin1Chars.join('');\n\t },\n\n\t /**\n\t * Converts a Latin1 string to a word array.\n\t *\n\t * @param {string} latin1Str The Latin1 string.\n\t *\n\t * @return {WordArray} The word array.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);\n\t */\n\t parse: function (latin1Str) {\n\t // Shortcut\n\t var latin1StrLength = latin1Str.length;\n\n\t // Convert\n\t var words = [];\n\t for (var i = 0; i < latin1StrLength; i++) {\n\t words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);\n\t }\n\n\t return new WordArray.init(words, latin1StrLength);\n\t }\n\t };\n\n\t /**\n\t * UTF-8 encoding strategy.\n\t */\n\t var Utf8 = C_enc.Utf8 = {\n\t /**\n\t * Converts a word array to a UTF-8 string.\n\t *\n\t * @param {WordArray} wordArray The word array.\n\t *\n\t * @return {string} The UTF-8 string.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);\n\t */\n\t stringify: function (wordArray) {\n\t try {\n\t return decodeURIComponent(escape(Latin1.stringify(wordArray)));\n\t } catch (e) {\n\t throw new Error('Malformed UTF-8 data');\n\t }\n\t },\n\n\t /**\n\t * Converts a UTF-8 string to a word array.\n\t *\n\t * @param {string} utf8Str The UTF-8 string.\n\t *\n\t * @return {WordArray} The word array.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);\n\t */\n\t parse: function (utf8Str) {\n\t return Latin1.parse(unescape(encodeURIComponent(utf8Str)));\n\t }\n\t };\n\n\t /**\n\t * Abstract buffered block algorithm template.\n\t *\n\t * The property blockSize must be implemented in a concrete subtype.\n\t *\n\t * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0\n\t */\n\t var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({\n\t /**\n\t * Resets this block algorithm's data buffer to its initial state.\n\t *\n\t * @example\n\t *\n\t * bufferedBlockAlgorithm.reset();\n\t */\n\t reset: function () {\n\t // Initial values\n\t this._data = new WordArray.init();\n\t this._nDataBytes = 0;\n\t },\n\n\t /**\n\t * Adds new data to this block algorithm's buffer.\n\t *\n\t * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.\n\t *\n\t * @example\n\t *\n\t * bufferedBlockAlgorithm._append('data');\n\t * bufferedBlockAlgorithm._append(wordArray);\n\t */\n\t _append: function (data) {\n\t // Convert string to WordArray, else assume WordArray already\n\t if (typeof data == 'string') {\n\t data = Utf8.parse(data);\n\t }\n\n\t // Append\n\t this._data.concat(data);\n\t this._nDataBytes += data.sigBytes;\n\t },\n\n\t /**\n\t * Processes available data blocks.\n\t *\n\t * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.\n\t *\n\t * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.\n\t *\n\t * @return {WordArray} The processed data.\n\t *\n\t * @example\n\t *\n\t * var processedData = bufferedBlockAlgorithm._process();\n\t * var processedData = bufferedBlockAlgorithm._process(!!'flush');\n\t */\n\t _process: function (doFlush) {\n\t var processedWords;\n\n\t // Shortcuts\n\t var data = this._data;\n\t var dataWords = data.words;\n\t var dataSigBytes = data.sigBytes;\n\t var blockSize = this.blockSize;\n\t var blockSizeBytes = blockSize * 4;\n\n\t // Count blocks ready\n\t var nBlocksReady = dataSigBytes / blockSizeBytes;\n\t if (doFlush) {\n\t // Round up to include partial blocks\n\t nBlocksReady = Math.ceil(nBlocksReady);\n\t } else {\n\t // Round down to include only full blocks,\n\t // less the number of blocks that must remain in the buffer\n\t nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);\n\t }\n\n\t // Count words ready\n\t var nWordsReady = nBlocksReady * blockSize;\n\n\t // Count bytes ready\n\t var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);\n\n\t // Process blocks\n\t if (nWordsReady) {\n\t for (var offset = 0; offset < nWordsReady; offset += blockSize) {\n\t // Perform concrete-algorithm logic\n\t this._doProcessBlock(dataWords, offset);\n\t }\n\n\t // Remove processed words\n\t processedWords = dataWords.splice(0, nWordsReady);\n\t data.sigBytes -= nBytesReady;\n\t }\n\n\t // Return processed words\n\t return new WordArray.init(processedWords, nBytesReady);\n\t },\n\n\t /**\n\t * Creates a copy of this object.\n\t *\n\t * @return {Object} The clone.\n\t *\n\t * @example\n\t *\n\t * var clone = bufferedBlockAlgorithm.clone();\n\t */\n\t clone: function () {\n\t var clone = Base.clone.call(this);\n\t clone._data = this._data.clone();\n\n\t return clone;\n\t },\n\n\t _minBufferSize: 0\n\t });\n\n\t /**\n\t * Abstract hasher template.\n\t *\n\t * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)\n\t */\n\t var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({\n\t /**\n\t * Configuration options.\n\t */\n\t cfg: Base.extend(),\n\n\t /**\n\t * Initializes a newly created hasher.\n\t *\n\t * @param {Object} cfg (Optional) The configuration options to use for this hash computation.\n\t *\n\t * @example\n\t *\n\t * var hasher = CryptoJS.algo.SHA256.create();\n\t */\n\t init: function (cfg) {\n\t // Apply config defaults\n\t this.cfg = this.cfg.extend(cfg);\n\n\t // Set initial values\n\t this.reset();\n\t },\n\n\t /**\n\t * Resets this hasher to its initial state.\n\t *\n\t * @example\n\t *\n\t * hasher.reset();\n\t */\n\t reset: function () {\n\t // Reset data buffer\n\t BufferedBlockAlgorithm.reset.call(this);\n\n\t // Perform concrete-hasher logic\n\t this._doReset();\n\t },\n\n\t /**\n\t * Updates this hasher with a message.\n\t *\n\t * @param {WordArray|string} messageUpdate The message to append.\n\t *\n\t * @return {Hasher} This hasher.\n\t *\n\t * @example\n\t *\n\t * hasher.update('message');\n\t * hasher.update(wordArray);\n\t */\n\t update: function (messageUpdate) {\n\t // Append\n\t this._append(messageUpdate);\n\n\t // Update the hash\n\t this._process();\n\n\t // Chainable\n\t return this;\n\t },\n\n\t /**\n\t * Finalizes the hash computation.\n\t * Note that the finalize operation is effectively a destructive, read-once operation.\n\t *\n\t * @param {WordArray|string} messageUpdate (Optional) A final message update.\n\t *\n\t * @return {WordArray} The hash.\n\t *\n\t * @example\n\t *\n\t * var hash = hasher.finalize();\n\t * var hash = hasher.finalize('message');\n\t * var hash = hasher.finalize(wordArray);\n\t */\n\t finalize: function (messageUpdate) {\n\t // Final message update\n\t if (messageUpdate) {\n\t this._append(messageUpdate);\n\t }\n\n\t // Perform concrete-hasher logic\n\t var hash = this._doFinalize();\n\n\t return hash;\n\t },\n\n\t blockSize: 512/32,\n\n\t /**\n\t * Creates a shortcut function to a hasher's object interface.\n\t *\n\t * @param {Hasher} hasher The hasher to create a helper for.\n\t *\n\t * @return {Function} The shortcut function.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);\n\t */\n\t _createHelper: function (hasher) {\n\t return function (message, cfg) {\n\t return new hasher.init(cfg).finalize(message);\n\t };\n\t },\n\n\t /**\n\t * Creates a shortcut function to the HMAC's object interface.\n\t *\n\t * @param {Hasher} hasher The hasher to use in this HMAC helper.\n\t *\n\t * @return {Function} The shortcut function.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);\n\t */\n\t _createHmacHelper: function (hasher) {\n\t return function (message, key) {\n\t return new C_algo.HMAC.init(hasher, key).finalize(message);\n\t };\n\t }\n\t });\n\n\t /**\n\t * Algorithm namespace.\n\t */\n\t var C_algo = C.algo = {};\n\n\t return C;\n\t}(Math));\n\n\n\treturn CryptoJS;\n\n}));",";(function (root, factory) {\n\tif (typeof exports === \"object\") {\n\t\t// CommonJS\n\t\tmodule.exports = exports = factory(require(\"./core\"));\n\t}\n\telse if (typeof define === \"function\" && define.amd) {\n\t\t// AMD\n\t\tdefine([\"./core\"], factory);\n\t}\n\telse {\n\t\t// Global (browser)\n\t\tfactory(root.CryptoJS);\n\t}\n}(this, function (CryptoJS) {\n\n\t(function (Math) {\n\t // Shortcuts\n\t var C = CryptoJS;\n\t var C_lib = C.lib;\n\t var WordArray = C_lib.WordArray;\n\t var Hasher = C_lib.Hasher;\n\t var C_algo = C.algo;\n\n\t // Initialization and round constants tables\n\t var H = [];\n\t var K = [];\n\n\t // Compute constants\n\t (function () {\n\t function isPrime(n) {\n\t var sqrtN = Math.sqrt(n);\n\t for (var factor = 2; factor <= sqrtN; factor++) {\n\t if (!(n % factor)) {\n\t return false;\n\t }\n\t }\n\n\t return true;\n\t }\n\n\t function getFractionalBits(n) {\n\t return ((n - (n | 0)) * 0x100000000) | 0;\n\t }\n\n\t var n = 2;\n\t var nPrime = 0;\n\t while (nPrime < 64) {\n\t if (isPrime(n)) {\n\t if (nPrime < 8) {\n\t H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));\n\t }\n\t K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));\n\n\t nPrime++;\n\t }\n\n\t n++;\n\t }\n\t }());\n\n\t // Reusable object\n\t var W = [];\n\n\t /**\n\t * SHA-256 hash algorithm.\n\t */\n\t var SHA256 = C_algo.SHA256 = Hasher.extend({\n\t _doReset: function () {\n\t this._hash = new WordArray.init(H.slice(0));\n\t },\n\n\t _doProcessBlock: function (M, offset) {\n\t // Shortcut\n\t var H = this._hash.words;\n\n\t // Working variables\n\t var a = H[0];\n\t var b = H[1];\n\t var c = H[2];\n\t var d = H[3];\n\t var e = H[4];\n\t var f = H[5];\n\t var g = H[6];\n\t var h = H[7];\n\n\t // Computation\n\t for (var i = 0; i < 64; i++) {\n\t if (i < 16) {\n\t W[i] = M[offset + i] | 0;\n\t } else {\n\t var gamma0x = W[i - 15];\n\t var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^\n\t ((gamma0x << 14) | (gamma0x >>> 18)) ^\n\t (gamma0x >>> 3);\n\n\t var gamma1x = W[i - 2];\n\t var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^\n\t ((gamma1x << 13) | (gamma1x >>> 19)) ^\n\t (gamma1x >>> 10);\n\n\t W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];\n\t }\n\n\t var ch = (e & f) ^ (~e & g);\n\t var maj = (a & b) ^ (a & c) ^ (b & c);\n\n\t var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));\n\t var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));\n\n\t var t1 = h + sigma1 + ch + K[i] + W[i];\n\t var t2 = sigma0 + maj;\n\n\t h = g;\n\t g = f;\n\t f = e;\n\t e = (d + t1) | 0;\n\t d = c;\n\t c = b;\n\t b = a;\n\t a = (t1 + t2) | 0;\n\t }\n\n\t // Intermediate hash value\n\t H[0] = (H[0] + a) | 0;\n\t H[1] = (H[1] + b) | 0;\n\t H[2] = (H[2] + c) | 0;\n\t H[3] = (H[3] + d) | 0;\n\t H[4] = (H[4] + e) | 0;\n\t H[5] = (H[5] + f) | 0;\n\t H[6] = (H[6] + g) | 0;\n\t H[7] = (H[7] + h) | 0;\n\t },\n\n\t _doFinalize: function () {\n\t // Shortcuts\n\t var data = this._data;\n\t var dataWords = data.words;\n\n\t var nBitsTotal = this._nDataBytes * 8;\n\t var nBitsLeft = data.sigBytes * 8;\n\n\t // Add padding\n\t dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);\n\t dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);\n\t dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;\n\t data.sigBytes = dataWords.length * 4;\n\n\t // Hash final blocks\n\t this._process();\n\n\t // Return final computed hash\n\t return this._hash;\n\t },\n\n\t clone: function () {\n\t var clone = Hasher.clone.call(this);\n\t clone._hash = this._hash.clone();\n\n\t return clone;\n\t }\n\t });\n\n\t /**\n\t * Shortcut function to the hasher's object interface.\n\t *\n\t * @param {WordArray|string} message The message to hash.\n\t *\n\t * @return {WordArray} The hash.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var hash = CryptoJS.SHA256('message');\n\t * var hash = CryptoJS.SHA256(wordArray);\n\t */\n\t C.SHA256 = Hasher._createHelper(SHA256);\n\n\t /**\n\t * Shortcut function to the HMAC's object interface.\n\t *\n\t * @param {WordArray|string} message The message to hash.\n\t * @param {WordArray|string} key The secret key.\n\t *\n\t * @return {WordArray} The HMAC.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var hmac = CryptoJS.HmacSHA256(message, key);\n\t */\n\t C.HmacSHA256 = Hasher._createHmacHelper(SHA256);\n\t}(Math));\n\n\n\treturn CryptoJS.SHA256;\n\n}));",";(function (root, factory) {\n\tif (typeof exports === \"object\") {\n\t\t// CommonJS\n\t\tmodule.exports = exports = factory(require(\"./core\"));\n\t}\n\telse if (typeof define === \"function\" && define.amd) {\n\t\t// AMD\n\t\tdefine([\"./core\"], factory);\n\t}\n\telse {\n\t\t// Global (browser)\n\t\tfactory(root.CryptoJS);\n\t}\n}(this, function (CryptoJS) {\n\n\t(function () {\n\t // Shortcuts\n\t var C = CryptoJS;\n\t var C_lib = C.lib;\n\t var WordArray = C_lib.WordArray;\n\t var C_enc = C.enc;\n\n\t /**\n\t * Base64 encoding strategy.\n\t */\n\t var Base64 = C_enc.Base64 = {\n\t /**\n\t * Converts a word array to a Base64 string.\n\t *\n\t * @param {WordArray} wordArray The word array.\n\t *\n\t * @return {string} The Base64 string.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var base64String = CryptoJS.enc.Base64.stringify(wordArray);\n\t */\n\t stringify: function (wordArray) {\n\t // Shortcuts\n\t var words = wordArray.words;\n\t var sigBytes = wordArray.sigBytes;\n\t var map = this._map;\n\n\t // Clamp excess bits\n\t wordArray.clamp();\n\n\t // Convert\n\t var base64Chars = [];\n\t for (var i = 0; i < sigBytes; i += 3) {\n\t var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n\t var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;\n\t var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;\n\n\t var triplet = (byte1 << 16) | (byte2 << 8) | byte3;\n\n\t for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {\n\t base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));\n\t }\n\t }\n\n\t // Add padding\n\t var paddingChar = map.charAt(64);\n\t if (paddingChar) {\n\t while (base64Chars.length % 4) {\n\t base64Chars.push(paddingChar);\n\t }\n\t }\n\n\t return base64Chars.join('');\n\t },\n\n\t /**\n\t * Converts a Base64 string to a word array.\n\t *\n\t * @param {string} base64Str The Base64 string.\n\t *\n\t * @return {WordArray} The word array.\n\t *\n\t * @static\n\t *\n\t * @example\n\t *\n\t * var wordArray = CryptoJS.enc.Base64.parse(base64String);\n\t */\n\t parse: function (base64Str) {\n\t // Shortcuts\n\t var base64StrLength = base64Str.length;\n\t var map = this._map;\n\t var reverseMap = this._reverseMap;\n\n\t if (!reverseMap) {\n\t reverseMap = this._reverseMap = [];\n\t for (var j = 0; j < map.length; j++) {\n\t reverseMap[map.charCodeAt(j)] = j;\n\t }\n\t }\n\n\t // Ignore padding\n\t var paddingChar = map.charAt(64);\n\t if (paddingChar) {\n\t var paddingIndex = base64Str.indexOf(paddingChar);\n\t if (paddingIndex !== -1) {\n\t base64StrLength = paddingIndex;\n\t }\n\t }\n\n\t // Convert\n\t return parseLoop(base64Str, base64StrLength, reverseMap);\n\n\t },\n\n\t _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n\t };\n\n\t function parseLoop(base64Str, base64StrLength, reverseMap) {\n\t var words = [];\n\t var nBytes = 0;\n\t for (var i = 0; i < base64StrLength; i++) {\n\t if (i % 4) {\n\t var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);\n\t var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);\n\t var bitsCombined = bits1 | bits2;\n\t words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);\n\t nBytes++;\n\t }\n\t }\n\t return WordArray.create(words, nBytes);\n\t }\n\t}());\n\n\n\treturn CryptoJS.enc.Base64;\n\n}));",";(function (root, factory) {\n\tif (typeof exports === \"object\") {\n\t\t// CommonJS\n\t\tmodule.exports = exports = factory(require(\"./core\"));\n\t}\n\telse if (typeof define === \"function\" && define.amd) {\n\t\t// AMD\n\t\tdefine([\"./core\"], factory);\n\t}\n\telse {\n\t\t// Global (browser)\n\t\tfactory(root.CryptoJS);\n\t}\n}(this, function (CryptoJS) {\n\n\t(function () {\n\t // Check if typed arrays are supported\n\t if (typeof ArrayBuffer != 'function') {\n\t return;\n\t }\n\n\t // Shortcuts\n\t var C = CryptoJS;\n\t var C_lib = C.lib;\n\t var WordArray = C_lib.WordArray;\n\n\t // Reference original init\n\t var superInit = WordArray.init;\n\n\t // Augment WordArray.init to handle typed arrays\n\t var subInit = WordArray.init = function (typedArray) {\n\t // Convert buffers to uint8\n\t if (typedArray instanceof ArrayBuffer) {\n\t typedArray = new Uint8Array(typedArray);\n\t }\n\n\t // Convert other array views to uint8\n\t if (\n\t typedArray instanceof Int8Array ||\n\t (typeof Uint8ClampedArray !== \"undefined\" && typedArray instanceof Uint8ClampedArray) ||\n\t typedArray instanceof Int16Array ||\n\t typedArray instanceof Uint16Array ||\n\t typedArray instanceof Int32Array ||\n\t typedArray instanceof Uint32Array ||\n\t typedArray instanceof Float32Array ||\n\t typedArray instanceof Float64Array\n\t ) {\n\t typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);\n\t }\n\n\t // Handle Uint8Array\n\t if (typedArray instanceof Uint8Array) {\n\t // Shortcut\n\t var typedArrayByteLength = typedArray.byteLength;\n\n\t // Extract bytes\n\t var words = [];\n\t for (var i = 0; i < typedArrayByteLength; i++) {\n\t words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);\n\t }\n\n\t // Initialize this word array\n\t superInit.call(this, words, typedArrayByteLength);\n\t } else {\n\t // Else call normal init\n\t superInit.apply(this, arguments);\n\t }\n\t };\n\n\t subInit.prototype = WordArray;\n\t}());\n\n\n\treturn CryptoJS.lib.WordArray;\n\n}));","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar sha256_1 = __importDefault(require(\"crypto-js/sha256\"));\nvar enc_base64_1 = __importDefault(require(\"crypto-js/enc-base64\"));\nvar lib_typedarrays_1 = __importDefault(require(\"crypto-js/lib-typedarrays\"));\nvar PKCE = /** @class */ (function () {\n /**\n * Initialize the instance with configuration\n * @param {IConfig} config\n */\n function PKCE(config) {\n this.state = '';\n this.codeVerifier = '';\n this.config = config;\n }\n /**\n * Generate the authorize url\n * @param {object} additionalParams include additional parameters in the query\n * @return Promise\n */\n PKCE.prototype.authorizeUrl = function (additionalParams) {\n if (additionalParams === void 0) { additionalParams = {}; }\n var codeChallenge = this.pkceChallengeFromVerifier();\n var queryString = new URLSearchParams(Object.assign({\n response_type: 'code',\n client_id: this.config.client_id,\n state: this.getState(additionalParams.state || null),\n scope: this.config.requested_scopes,\n redirect_uri: this.config.redirect_uri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n }, additionalParams)).toString();\n return \"\".concat(this.config.authorization_endpoint, \"?\").concat(queryString);\n };\n /**\n * Given the return url, get a token from the oauth server\n * @param url current urlwith params from server\n * @param {object} additionalParams include additional parameters in the request body\n * @return {Promise}\n */\n PKCE.prototype.exchangeForAccessToken = function (url, additionalParams) {\n var _this = this;\n if (additionalParams === void 0) { additionalParams = {}; }\n return this.parseAuthResponseUrl(url).then(function (q) {\n return fetch(_this.config.token_endpoint, {\n method: 'POST',\n body: new URLSearchParams(Object.assign({\n grant_type: 'authorization_code',\n code: q.code,\n client_id: _this.config.client_id,\n redirect_uri: _this.config.redirect_uri,\n code_verifier: _this.getCodeVerifier(),\n }, additionalParams)),\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n },\n }).then(function (response) { return response.json(); });\n });\n };\n /**\n * Given a refresh token, return a new token from the oauth server\n * @param refreshTokens current refresh token from server\n * @return {Promise}\n */\n PKCE.prototype.refreshAccessToken = function (refreshToken) {\n return fetch(this.config.token_endpoint, {\n method: 'POST',\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.config.client_id,\n refresh_token: refreshToken,\n }),\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n },\n }).then(function (response) { return response.json(); });\n };\n /**\n * Get the current codeVerifier or generate a new one\n * @return {string}\n */\n PKCE.prototype.getCodeVerifier = function () {\n if (this.codeVerifier === '') {\n this.codeVerifier = this.randomStringFromStorage('pkce_code_verifier');\n }\n return this.codeVerifier;\n };\n /**\n * Get the current state or generate a new one\n * @return {string}\n */\n PKCE.prototype.getState = function (explicit) {\n if (explicit === void 0) { explicit = null; }\n var stateKey = 'pkce_state';\n if (explicit !== null) {\n this.getStore().setItem(stateKey, explicit);\n }\n if (this.state === '') {\n this.state = this.randomStringFromStorage(stateKey);\n }\n return this.state;\n };\n /**\n * Get the query params as json from a auth response url\n * @param {string} url a url expected to have AuthResponse params\n * @return {Promise}\n */\n PKCE.prototype.parseAuthResponseUrl = function (url) {\n var params = new URL(url).searchParams;\n return this.validateAuthResponse({\n error: params.get('error'),\n query: params.get('query'),\n state: params.get('state'),\n code: params.get('code'),\n });\n };\n /**\n * Generate a code challenge\n * @return {Promise}\n */\n PKCE.prototype.pkceChallengeFromVerifier = function () {\n var hashed = (0, sha256_1.default)(this.getCodeVerifier());\n return enc_base64_1.default.stringify(hashed).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n };\n /**\n * Get a random string from storage or store a new one and return it's value\n * @param {string} key\n * @return {string}\n */\n PKCE.prototype.randomStringFromStorage = function (key) {\n var fromStorage = this.getStore().getItem(key);\n if (fromStorage === null) {\n this.getStore().setItem(key, lib_typedarrays_1.default.random(64));\n }\n return this.getStore().getItem(key) || '';\n };\n /**\n * Validates params from auth response\n * @param {AuthResponse} queryParams\n * @return {Promise}\n */\n PKCE.prototype.validateAuthResponse = function (queryParams) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n if (queryParams.error) {\n return reject({ error: queryParams.error });\n }\n if (queryParams.state !== _this.getState()) {\n return reject({ error: 'Invalid State' });\n }\n return resolve(queryParams);\n });\n };\n /**\n * Get the storage (sessionStorage / localStorage) to use, defaults to sessionStorage\n * @return {Storage}\n */\n PKCE.prototype.getStore = function () {\n var _a;\n return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.storage) || sessionStorage;\n };\n return PKCE;\n}());\nexports.default = PKCE;\n","import PKCE from 'js-pkce';\nimport { clearTokens, getAccessToken, getRefreshToken, updateTokens } from './hooks/useAuthStorage.js';\n\nconst clientId = import.meta.env.OAUTH_CLIENT_ID;\nconst baseUrl = import.meta.env.BACKEND_URL + 'oauth/';\n\nconst urls = {\n authorize: baseUrl + 'authorize',\n token: baseUrl + 'token',\n revoke: baseUrl + 'revoke',\n};\n\nexport const scopes = ['account_data_read'].join(' ');\n\nconst pkce = new PKCE({\n client_id: clientId,\n redirect_uri: window.location.protocol + '//' + window.location.host + import.meta.env.BASE_URL + 'oauth-callback',\n authorization_endpoint: urls.authorize,\n token_endpoint: urls.token,\n requested_scopes: scopes,\n});\n\nexport const authorizeUrl = () => pkce.authorizeUrl();\nexport const exchangeForAccessToken = async () => pkce.exchangeForAccessToken(window.location.href);\n\nexport async function revokeToken(token) {\n return fetch(urls.revoke, {\n method: 'POST',\n headers: {\n 'Authorization': 'Bearer ' + getAccessToken(),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n client_id: clientId,\n token,\n }),\n });\n}\n\nexport async function refreshTokenIfNeeded() {\n const refreshToken = getRefreshToken();\n\n if (!refreshToken) {\n clearTokens();\n console.error('No refresh token found');\n return false;\n }\n\n try {\n updateTokens(await pkce.refreshAccessToken(refreshToken));\n }\n catch (e) {\n clearTokens();\n console.error(e);\n return false;\n }\n\n return true;\n}\n","import * as React from \"react\";\n\nfunction isShallowEqual(object1, object2) {\n const keys1 = Object.keys(object1);\n const keys2 = Object.keys(object2);\n\n if (keys1.length !== keys2.length) {\n return false;\n }\n\n for (let key of keys1) {\n if (object1[key] !== object2[key]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isTouchEvent({ nativeEvent }) {\n return window.TouchEvent\n ? nativeEvent instanceof TouchEvent\n : \"touches\" in nativeEvent;\n}\n\nfunction isMouseEvent(event) {\n return event.nativeEvent instanceof MouseEvent;\n}\n\nfunction throttle(cb, ms) {\n let lastTime = 0;\n return () => {\n const now = Date.now();\n if (now - lastTime >= ms) {\n cb();\n lastTime = now;\n }\n };\n}\n\nconst dispatchStorageEvent = (key, newValue) => {\n window.dispatchEvent(new StorageEvent(\"storage\", { key, newValue }));\n};\n\nexport function useBattery() {\n const [state, setState] = React.useState({\n supported: true,\n loading: true,\n level: null,\n charging: null,\n chargingTime: null,\n dischargingTime: null,\n });\n\n React.useEffect(() => {\n if (!navigator.getBattery) {\n setState((s) => ({\n ...s,\n supported: false,\n loading: false,\n }));\n return;\n }\n\n let battery = null;\n\n const handleChange = () => {\n setState({\n supported: true,\n loading: false,\n level: battery.level,\n charging: battery.charging,\n chargingTime: battery.chargingTime,\n dischargingTime: battery.dischargingTime,\n });\n };\n\n navigator.getBattery().then((b) => {\n battery = b;\n handleChange();\n\n b.addEventListener(\"levelchange\", handleChange);\n b.addEventListener(\"chargingchange\", handleChange);\n b.addEventListener(\"chargingtimechange\", handleChange);\n b.addEventListener(\"dischargingtimechange\", handleChange);\n });\n\n return () => {\n if (battery) {\n battery.removeEventListener(\"levelchange\", handleChange);\n battery.removeEventListener(\"chargingchange\", handleChange);\n battery.removeEventListener(\"chargingtimechange\", handleChange);\n battery.removeEventListener(\"dischargingtimechange\", handleChange);\n }\n };\n }, []);\n\n return state;\n}\n\nexport function useClickAway(cb) {\n const ref = React.useRef(null);\n const refCb = React.useRef(cb);\n\n React.useLayoutEffect(() => {\n refCb.current = cb;\n });\n\n React.useEffect(() => {\n const handler = (e) => {\n const element = ref.current;\n if (element && !element.contains(e.target)) {\n refCb.current(e);\n }\n };\n\n document.addEventListener(\"mousedown\", handler);\n document.addEventListener(\"touchstart\", handler);\n\n return () => {\n document.removeEventListener(\"mousedown\", handler);\n document.removeEventListener(\"touchstart\", handler);\n };\n }, []);\n\n return ref;\n}\n\nfunction oldSchoolCopy(text) {\n const tempTextArea = document.createElement(\"textarea\");\n tempTextArea.value = text;\n document.body.appendChild(tempTextArea);\n tempTextArea.select();\n document.execCommand(\"copy\");\n document.body.removeChild(tempTextArea);\n}\n\nexport function useCopyToClipboard() {\n const [state, setState] = React.useState(null);\n\n const copyToClipboard = React.useCallback((value) => {\n const handleCopy = async () => {\n try {\n if (navigator?.clipboard?.writeText) {\n await navigator.clipboard.writeText(value);\n setState(value);\n } else {\n throw new Error(\"writeText not supported\");\n }\n } catch (e) {\n oldSchoolCopy(value);\n setState(value);\n }\n };\n\n handleCopy();\n }, []);\n\n return [state, copyToClipboard];\n}\n\nexport function useCounter(startingValue = 0, options = {}) {\n const { min, max } = options;\n\n if (min && startingValue < min) {\n throw new Error(\n `Your starting value of ${startingValue} is less than your min of ${min}.`\n );\n }\n\n if (max && startingValue > max) {\n throw new Error(\n `Your starting value of ${startingValue} is greater than your max of ${max}.`\n );\n }\n\n const [count, setCount] = React.useState(startingValue);\n\n const increment = () => {\n const nextCount = count + 1;\n if (max && nextCount > max) {\n return;\n }\n\n setCount(nextCount);\n };\n\n const decrement = () => {\n const nextCount = count - 1;\n if (min && nextCount < min) {\n return;\n }\n\n setCount(nextCount);\n };\n\n const set = (nextCount) => {\n if (max && nextCount > max) {\n return;\n }\n\n if (min && nextCount < min) {\n return;\n }\n\n if (nextCount === count) {\n return;\n }\n\n setCount(nextCount);\n };\n\n const reset = () => {\n if (count === startingValue) {\n return;\n }\n\n setCount(startingValue);\n };\n\n return [\n count,\n {\n increment,\n decrement,\n set,\n reset,\n },\n ];\n}\n\nexport function useDebounce(value, delay) {\n const [debouncedValue, setDebouncedValue] = React.useState(value);\n\n React.useEffect(() => {\n const handler = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n return () => {\n clearTimeout(handler);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n\nexport function useDefault(initialValue, defaultValue) {\n const [state, setState] = React.useState(initialValue);\n\n if (typeof state === \"undefined\" || state === null) {\n return [defaultValue, setState];\n }\n\n return [state, setState];\n}\n\nexport function useDocumentTitle(title) {\n React.useEffect(() => {\n document.title = title;\n }, [title]);\n}\n\nexport function useFavicon(url) {\n React.useEffect(() => {\n const link =\n document.querySelector(\"link[rel*='icon']\") ||\n document.createElement(\"link\");\n link.type = \"image/x-icon\";\n link.rel = \"shortcut icon\";\n link.href = url;\n document.getElementsByTagName(\"head\")[0].appendChild(link);\n }, [url]);\n}\n\nexport function useGeolocation(options = {}) {\n const [state, setState] = React.useState({\n loading: true,\n accuracy: null,\n altitude: null,\n altitudeAccuracy: null,\n heading: null,\n latitude: null,\n longitude: null,\n speed: null,\n timestamp: null,\n error: null,\n });\n\n const optionsRef = React.useRef(options);\n\n React.useEffect(() => {\n const onEvent = ({ coords, timestamp }) => {\n setState({\n loading: false,\n timestamp,\n latitude: coords.latitude,\n longitude: coords.longitude,\n altitude: coords.altitude,\n accuracy: coords.accuracy,\n altitudeAccuracy: coords.altitudeAccuracy,\n heading: coords.heading,\n speed: coords.speed,\n });\n };\n\n const onEventError = (error) => {\n setState((s) => ({\n ...s,\n loading: false,\n error,\n }));\n };\n\n navigator.geolocation.getCurrentPosition(\n onEvent,\n onEventError,\n optionsRef.current\n );\n\n const watchId = navigator.geolocation.watchPosition(\n onEvent,\n onEventError,\n optionsRef.current\n );\n\n return () => {\n navigator.geolocation.clearWatch(watchId);\n };\n }, []);\n\n return state;\n}\n\nconst initialUseHistoryStateState = {\n past: [],\n present: null,\n future: [],\n};\n\nconst useHistoryStateReducer = (state, action) => {\n const { past, present, future } = state;\n\n if (action.type === \"UNDO\") {\n return {\n past: past.slice(0, past.length - 1),\n present: past[past.length - 1],\n future: [present, ...future],\n };\n } else if (action.type === \"REDO\") {\n return {\n past: [...past, present],\n present: future[0],\n future: future.slice(1),\n };\n } else if (action.type === \"SET\") {\n const { newPresent } = action;\n\n if (action.newPresent === present) {\n return state;\n }\n\n return {\n past: [...past, present],\n present: newPresent,\n future: [],\n };\n } else if (action.type === \"CLEAR\") {\n return {\n ...initialState,\n present: action.initialPresent,\n };\n } else {\n throw new Error(\"Unsupported action type\");\n }\n};\n\nexport function useHistoryState(initialPresent = {}) {\n const initialPresentRef = React.useRef(initialPresent);\n\n const [state, dispatch] = React.useReducer(useHistoryStateReducer, {\n ...initialUseHistoryStateState,\n present: initialPresentRef.current,\n });\n\n const canUndo = state.past.length !== 0;\n const canRedo = state.future.length !== 0;\n\n const undo = React.useCallback(() => {\n if (canUndo) {\n dispatch({ type: \"UNDO\" });\n }\n }, [canUndo]);\n\n const redo = React.useCallback(() => {\n if (canRedo) {\n dispatch({ type: \"REDO\" });\n }\n }, [canRedo]);\n\n const set = React.useCallback(\n (newPresent) => dispatch({ type: \"SET\", newPresent }),\n []\n );\n\n const clear = React.useCallback(\n () =>\n dispatch({ type: \"CLEAR\", initialPresent: initialPresentRef.current }),\n []\n );\n\n return { state: state.present, set, undo, redo, clear, canUndo, canRedo };\n}\n\nexport function useHover() {\n const [hovering, setHovering] = React.useState(false);\n const ref = React.useRef(null);\n\n React.useEffect(() => {\n const node = ref.current;\n\n if (!node) return;\n\n const handleMouseEnter = () => {\n setHovering(true);\n };\n\n const handleMouseLeave = () => {\n setHovering(false);\n };\n\n node.addEventListener(\"mouseenter\", handleMouseEnter);\n node.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n node.removeEventListener(\"mouseenter\", handleMouseEnter);\n node.removeEventListener(\"mouseleave\", handleMouseLeave);\n };\n }, []);\n\n return [ref, hovering];\n}\n\nexport function useIdle(ms = 1000 * 60) {\n const [idle, setIdle] = React.useState(false);\n\n React.useEffect(() => {\n let timeoutId;\n\n const handleTimeout = () => {\n setIdle(true);\n };\n\n const handleEvent = throttle((e) => {\n setIdle(false);\n\n window.clearTimeout(timeoutId);\n timeoutId = window.setTimeout(handleTimeout, ms);\n }, 500);\n\n const handleVisibilityChange = () => {\n if (!document.hidden) {\n handleEvent();\n }\n };\n\n timeoutId = window.setTimeout(handleTimeout, ms);\n\n window.addEventListener(\"mousemove\", handleEvent);\n window.addEventListener(\"mousedown\", handleEvent);\n window.addEventListener(\"resize\", handleEvent);\n window.addEventListener(\"keydown\", handleEvent);\n window.addEventListener(\"touchstart\", handleEvent);\n window.addEventListener(\"wheel\", handleEvent);\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n window.removeEventListener(\"mousemove\", handleEvent);\n window.removeEventListener(\"mousedown\", handleEvent);\n window.removeEventListener(\"resize\", handleEvent);\n window.removeEventListener(\"keydown\", handleEvent);\n window.removeEventListener(\"touchstart\", handleEvent);\n window.removeEventListener(\"wheel\", handleEvent);\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n window.clearTimeout(timeoutId);\n };\n }, [ms]);\n\n return idle;\n}\n\nexport function useIntersectionObserver(options = {}) {\n const { threshold = 1, root = null, rootMargin = \"0%\" } = options;\n const ref = React.useRef(null);\n const [entry, setEntry] = React.useState(null);\n\n React.useEffect(() => {\n const node = ref?.current;\n\n if (!node || typeof IntersectionObserver !== \"function\") {\n return;\n }\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n setEntry(entry);\n },\n { threshold, root, rootMargin }\n );\n\n observer.observe(node);\n\n return () => {\n setEntry(null);\n observer.disconnect();\n };\n }, [threshold, root, rootMargin]);\n\n return [ref, entry];\n}\n\nexport function useIsClient() {\n const [isClient, setIsClient] = React.useState(false);\n\n React.useEffect(() => {\n setIsClient(true);\n }, []);\n\n return isClient;\n}\n\nexport function useIsFirstRender() {\n const renderRef = React.useRef(true);\n\n if (renderRef.current === true) {\n renderRef.current = false;\n return true;\n }\n\n return renderRef.current;\n}\n\nexport function useList(defaultList = []) {\n const [list, setList] = React.useState(defaultList);\n\n const set = React.useCallback((l) => {\n setList(l);\n }, []);\n\n const push = React.useCallback((element) => {\n setList((l) => [...l, element]);\n }, []);\n\n const removeAt = React.useCallback((index) => {\n setList((l) => [...l.slice(0, index), ...l.slice(index + 1)]);\n }, []);\n\n const insertAt = React.useCallback((index, element) => {\n setList((l) => [...l.slice(0, index), element, ...l.slice(index)]);\n }, []);\n\n const updateAt = React.useCallback((index, element) => {\n setList((l) => l.map((e, i) => (i === index ? element : e)));\n }, []);\n\n const clear = React.useCallback(() => setList([]), []);\n\n return [list, { set, push, removeAt, insertAt, updateAt, clear }];\n}\n\nconst setLocalStorageItem = (key, value) => {\n const stringifiedValue = JSON.stringify(value);\n window.localStorage.setItem(key, stringifiedValue);\n dispatchStorageEvent(key, stringifiedValue);\n};\n\nconst removeLocalStorageItem = (key) => {\n window.localStorage.removeItem(key);\n dispatchStorageEvent(key, null);\n};\n\nconst getLocalStorageItem = (key) => {\n return window.localStorage.getItem(key);\n};\n\nconst useLocalStorageSubscribe = (callback) => {\n window.addEventListener(\"storage\", callback);\n return () => window.removeEventListener(\"storage\", callback);\n};\n\nconst getLocalStorageServerSnapshot = () => {\n throw Error(\"useLocalStorage is a client-only hook\");\n};\n\nexport function useLocalStorage(key, initialValue) {\n const getSnapshot = () => getLocalStorageItem(key);\n\n const store = React.useSyncExternalStore(\n useLocalStorageSubscribe,\n getSnapshot,\n getLocalStorageServerSnapshot\n );\n\n const setState = React.useCallback(\n (v) => {\n try {\n const nextState = typeof v === \"function\" ? v(JSON.parse(store)) : v;\n\n if (nextState === undefined || nextState === null) {\n removeLocalStorageItem(key);\n } else {\n setLocalStorageItem(key, nextState);\n }\n } catch (e) {\n console.warn(e);\n }\n },\n [key, store]\n );\n\n React.useEffect(() => {\n if (\n getLocalStorageItem(key) === null &&\n typeof initialValue !== \"undefined\"\n ) {\n setLocalStorageItem(key, initialValue);\n }\n }, [key, initialValue]);\n\n return [store ? JSON.parse(store) : initialValue, setState];\n}\n\nexport function useLockBodyScroll() {\n React.useEffect(() => {\n const originalStyle = window.getComputedStyle(document.body).overflow;\n document.body.style.overflow = \"hidden\";\n return () => {\n document.body.style.overflow = originalStyle;\n };\n }, []);\n}\n\nexport function useLongPress(callback, options = {}) {\n const { threshold = 400, onStart, onFinish, onCancel } = options;\n const isLongPressActive = React.useRef(false);\n const isPressed = React.useRef(false);\n const timerId = React.useRef();\n\n return React.useMemo(() => {\n if (typeof callback !== \"function\") {\n return {};\n }\n\n const start = (event) => {\n if (!isMouseEvent(event) && !isTouchEvent(event)) return;\n\n if (onStart) {\n onStart(event);\n }\n\n isPressed.current = true;\n timerId.current = setTimeout(() => {\n callback(event);\n isLongPressActive.current = true;\n }, threshold);\n };\n\n const cancel = (event) => {\n if (!isMouseEvent(event) && !isTouchEvent(event)) return;\n\n if (isLongPressActive.current) {\n if (onFinish) {\n onFinish(event);\n }\n } else if (isPressed.current) {\n if (onCancel) {\n onCancel(event);\n }\n }\n\n isLongPressActive.current = false;\n isPressed.current = false;\n\n if (timerId.current) {\n window.clearTimeout(timerId.current);\n }\n };\n\n const mouseHandlers = {\n onMouseDown: start,\n onMouseUp: cancel,\n onMouseLeave: cancel,\n };\n\n const touchHandlers = {\n onTouchStart: start,\n onTouchEnd: cancel,\n };\n\n return {\n ...mouseHandlers,\n ...touchHandlers,\n };\n }, [callback, threshold, onCancel, onFinish, onStart]);\n}\n\nexport function useMap(initialState) {\n const mapRef = React.useRef(new Map(initialState));\n const [, reRender] = React.useReducer((x) => x + 1, 0);\n\n mapRef.current.set = (...args) => {\n Map.prototype.set.apply(mapRef.current, args);\n reRender();\n return mapRef.current;\n };\n\n mapRef.current.clear = (...args) => {\n Map.prototype.clear.apply(mapRef.current, args);\n reRender();\n };\n\n mapRef.current.delete = (...args) => {\n const res = Map.prototype.delete.apply(mapRef.current, args);\n reRender();\n\n return res;\n };\n\n return mapRef.current;\n}\n\nexport function useMeasure() {\n const ref = React.useRef(null);\n const [rect, setRect] = React.useState({\n width: null,\n height: null,\n });\n\n React.useLayoutEffect(() => {\n if (!ref.current) return;\n\n const observer = new ResizeObserver(([entry]) => {\n if (entry && entry.contentRect) {\n setRect({\n width: entry.contentRect.width,\n height: entry.contentRect.height,\n });\n }\n });\n\n observer.observe(ref.current);\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return [ref, rect];\n}\n\nexport function useMediaQuery(query) {\n const subscribe = React.useCallback(\n (callback) => {\n const matchMedia = window.matchMedia(query);\n\n matchMedia.addEventListener(\"change\", callback);\n return () => {\n matchMedia.removeEventListener(\"change\", callback);\n };\n },\n [query]\n );\n\n const getSnapshot = () => {\n return window.matchMedia(query).matches;\n };\n\n const getServerSnapshot = () => {\n throw Error(\"useMediaQuery is a client-only hook\");\n };\n\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\nexport function useMouse() {\n const [state, setState] = React.useState({\n x: 0,\n y: 0,\n elementX: 0,\n elementY: 0,\n elementPositionX: 0,\n elementPositionY: 0,\n });\n\n const ref = React.useRef(null);\n\n React.useLayoutEffect(() => {\n const handleMouseMove = (event) => {\n let newState = {\n x: event.pageX,\n y: event.pageY,\n };\n\n if (ref.current instanceof HTMLElement) {\n const { left, top } = ref.current.getBoundingClientRect();\n const elementPositionX = left + window.pageXOffset;\n const elementPositionY = top + window.pageYOffset;\n const elementX = event.pageX - elementPositionX;\n const elementY = event.pageY - elementPositionY;\n\n newState.elementX = elementX;\n newState.elementY = elementY;\n newState.elementPositionX = elementPositionX;\n newState.elementPositionY = elementPositionY;\n }\n\n setState((s) => {\n return {\n ...s,\n ...newState,\n };\n });\n };\n\n document.addEventListener(\"mousemove\", handleMouseMove);\n\n return () => {\n document.removeEventListener(\"mousemove\", handleMouseMove);\n };\n }, []);\n\n return [state, ref];\n}\n\nconst getConnection = () => {\n return (\n navigator?.connection ||\n navigator?.mozConnection ||\n navigator?.webkitConnection\n );\n};\n\nexport function useNetworkState() {\n const cache = React.useRef({});\n\n const subscribe = React.useCallback((callback) => {\n window.addEventListener(\"online\", callback, { passive: true });\n window.addEventListener(\"offline\", callback, { passive: true });\n\n const connection = getConnection();\n\n if (connection) {\n connection.addEventListener(\"change\", callback, { passive: true });\n }\n\n return () => {\n window.removeEventListener(\"online\", callback);\n window.removeEventListener(\"offline\", callback);\n\n if (connection) {\n connection.removeEventListener(\"change\", callback);\n }\n };\n }, []);\n\n const getSnapshot = () => {\n const online = navigator.onLine;\n const connection = getConnection();\n\n const nextState = {\n online,\n downlink: connection?.downlink,\n downlinkMax: connection?.downlinkMax,\n effectiveType: connection?.effectiveType,\n rtt: connection?.rtt,\n saveData: connection?.saveData,\n type: connection?.type,\n };\n\n if (isShallowEqual(cache.current, nextState)) {\n return cache.current;\n } else {\n cache.current = nextState;\n return nextState;\n }\n };\n\n const getServerSnapshot = () => {\n throw Error(\"useNetworkState is a client-only hook\");\n };\n\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\nexport function useObjectState(initialValue) {\n const [state, setState] = React.useState(initialValue);\n\n const handleUpdate = React.useCallback((arg) => {\n if (typeof arg === \"function\") {\n setState((s) => {\n const newState = arg(s);\n\n return {\n ...s,\n ...newState,\n };\n });\n }\n\n if (typeof arg === \"object\") {\n setState((s) => ({\n ...s,\n ...arg,\n }));\n }\n }, []);\n\n return [state, handleUpdate];\n}\n\nexport function useOrientation() {\n const [orientation, setOrientation] = React.useState({\n angle: 0,\n type: \"landscape-primary\",\n });\n\n React.useLayoutEffect(() => {\n const handleChange = () => {\n const { angle, type } = window.screen.orientation;\n setOrientation({\n angle,\n type,\n });\n };\n\n const handle_orientationchange = () => {\n setOrientation({\n type: \"UNKNOWN\",\n angle: window.orientation,\n });\n };\n\n if (window.screen?.orientation) {\n handleChange();\n window.screen.orientation.addEventListener(\"change\", handleChange);\n } else {\n handle_orientationchange();\n window.addEventListener(\"orientationchange\", handle_orientationchange);\n }\n\n return () => {\n if (window.screen?.orientation) {\n window.screen.orientation.removeEventListener(\"change\", handleChange);\n } else {\n window.removeEventListener(\n \"orientationchange\",\n handle_orientationchange\n );\n }\n };\n }, []);\n\n return orientation;\n}\n\nconst usePreferredLanguageSubscribe = (cb) => {\n window.addEventListener(\"languagechange\", cb);\n return () => window.removeEventListener(\"languagechange\", cb);\n};\n\nconst getPreferredLanguageSnapshot = () => {\n return navigator.language;\n};\n\nconst getPreferredLanguageServerSnapshot = () => {\n throw Error(\"usePreferredLanguage is a client-only hook\");\n};\n\nexport function usePreferredLanguage() {\n return React.useSyncExternalStore(\n usePreferredLanguageSubscribe,\n getPreferredLanguageSnapshot,\n getPreferredLanguageServerSnapshot\n );\n}\n\nexport function usePrevious(value) {\n const [current, setCurrent] = React.useState(value);\n const [previous, setPrevious] = React.useState(null);\n\n if (value !== current) {\n setPrevious(current);\n setCurrent(value);\n }\n\n return previous;\n}\n\nexport function useQueue(initialValue = []) {\n const [queue, setQueue] = React.useState(initialValue);\n\n const add = React.useCallback((element) => {\n setQueue((q) => [...q, element]);\n }, []);\n\n const remove = React.useCallback(() => {\n let removedElement;\n\n setQueue(([first, ...q]) => {\n removedElement = first;\n return q;\n });\n\n return removedElement;\n }, []);\n\n const clear = React.useCallback(() => {\n setQueue([]);\n }, []);\n\n return {\n add,\n remove,\n clear,\n first: queue[0],\n last: queue[queue.length - 1],\n size: queue.length,\n queue,\n };\n}\n\nexport function useRenderCount() {\n const count = React.useRef(0);\n\n count.current++;\n\n return count.current;\n}\n\nexport function useRenderInfo(name = \"Unknown\") {\n const count = React.useRef(0);\n const lastRender = React.useRef();\n const now = Date.now();\n\n count.current++;\n\n React.useEffect(() => {\n lastRender.current = Date.now();\n });\n\n const sinceLastRender = lastRender.current ? now - lastRender.current : 0;\n\n if (process.env.NODE_ENV !== \"production\") {\n const info = {\n name,\n renders: count.current,\n sinceLastRender,\n timestamp: now,\n };\n\n console.log(info);\n\n return info;\n }\n}\n\nexport function useScript(src, options = {}) {\n const [status, setStatus] = React.useState(() => {\n if (!src) {\n return \"idle\";\n }\n\n return \"loading\";\n });\n\n const cachedScriptStatuses = React.useRef({});\n\n React.useEffect(() => {\n if (!src) return;\n\n const cachedScriptStatus = cachedScriptStatuses.current[src];\n if (cachedScriptStatus === \"ready\" || cachedScriptStatus === \"error\") {\n setStatus(cachedScriptStatus);\n return;\n }\n\n let script = document.querySelector(`script[src=\"${src}\"]`);\n\n if (script) {\n setStatus(cachedScriptStatus ?? \"loading\");\n } else {\n script = document.createElement(\"script\");\n script.src = src;\n script.async = true;\n document.body.appendChild(script);\n }\n\n const setStateFromEvent = (event) => {\n const newStatus = event.type === \"load\" ? \"ready\" : \"error\";\n setStatus(newStatus);\n cachedScriptStatuses.current[src] = newStatus;\n };\n\n script.addEventListener(\"load\", setStateFromEvent);\n script.addEventListener(\"error\", setStateFromEvent);\n\n return () => {\n if (script) {\n script.removeEventListener(\"load\", setStateFromEvent);\n script.removeEventListener(\"error\", setStateFromEvent);\n }\n\n if (script && options.removeOnUnmount) {\n script.remove();\n }\n };\n }, [src, options.removeOnUnmount]);\n\n return status;\n}\n\nconst setSessionStorageItem = (key, value) => {\n const stringifiedValue = JSON.stringify(value);\n window.sessionStorage.setItem(key, stringifiedValue);\n dispatchStorageEvent(key, stringifiedValue);\n};\n\nconst removeSessionStorageItem = (key) => {\n window.sessionStorage.removeItem(key);\n dispatchStorageEvent(key, null);\n};\n\nconst getSessionStorageItem = (key) => {\n return window.sessionStorage.getItem(key);\n};\n\nconst useSessionStorageSubscribe = (callback) => {\n window.addEventListener(\"storage\", callback);\n return () => window.removeEventListener(\"storage\", callback);\n};\n\nconst getSessionStorageServerSnapshot = () => {\n throw Error(\"useSessionStorage is a client-only hook\");\n};\n\nexport function useSessionStorage(key, initialValue) {\n const getSnapshot = () => getSessionStorageItem(key);\n\n const store = React.useSyncExternalStore(\n useSessionStorageSubscribe,\n getSnapshot,\n getSessionStorageServerSnapshot\n );\n\n const setState = React.useCallback(\n (v) => {\n try {\n const nextState = typeof v === \"function\" ? v(JSON.parse(store)) : v;\n\n if (nextState === undefined || nextState === null) {\n removeSessionStorageItem(key);\n } else {\n setSessionStorageItem(key, nextState);\n }\n } catch (e) {\n console.warn(e);\n }\n },\n [key, store]\n );\n\n React.useEffect(() => {\n if (\n getSessionStorageItem(key) === null &&\n typeof initialValue !== \"undefined\"\n ) {\n setSessionStorageItem(key, initialValue);\n }\n }, [key, initialValue]);\n\n return [store ? JSON.parse(store) : initialValue, setState];\n}\n\nexport function useSet(values) {\n const setRef = React.useRef(new Set(values));\n const [, reRender] = React.useReducer((x) => x + 1, 0);\n\n setRef.current.add = (...args) => {\n const res = Set.prototype.add.apply(setRef.current, args);\n reRender();\n\n return res;\n };\n\n setRef.current.clear = (...args) => {\n Set.prototype.clear.apply(setRef.current, args);\n reRender();\n };\n\n setRef.current.delete = (...args) => {\n const res = Set.prototype.delete.apply(setRef.current, args);\n reRender();\n\n return res;\n };\n\n return setRef.current;\n}\n\nexport function useThrottle(value, interval = 500) {\n const [throttledValue, setThrottledValue] = React.useState(value);\n const lastUpdated = React.useRef();\n\n React.useEffect(() => {\n const now = Date.now();\n\n if (now >= lastUpdated.current + interval) {\n lastUpdated.current = now;\n setThrottledValue(value);\n } else {\n const id = window.setTimeout(() => {\n lastUpdated.current = now;\n setThrottledValue(value);\n }, interval);\n\n return () => window.clearTimeout(id);\n }\n }, [value, interval]);\n\n return throttledValue;\n}\n\nexport function useToggle(initialValue) {\n const [on, setOn] = React.useState(initialValue);\n\n const handleToggle = React.useCallback((value) => {\n if (typeof value === \"boolean\") {\n return setOn(value);\n }\n\n return setOn((v) => !v);\n }, []);\n\n return [on, handleToggle];\n}\n\nconst useVisibilityChangeSubscribe = (callback) => {\n document.addEventListener(\"visibilitychange\", callback);\n\n return () => {\n document.removeEventListener(\"visibilitychange\", callback);\n };\n};\n\nconst getVisibilityChangeSnapshot = () => {\n return document.visibilityState;\n};\n\nconst getVisibilityChangeServerSnapshot = () => {\n throw Error(\"useVisibilityChange is a client-only hook\");\n};\n\nexport function useVisibilityChange() {\n const visibilityState = React.useSyncExternalStore(\n useVisibilityChangeSubscribe,\n getVisibilityChangeSnapshot,\n getVisibilityChangeServerSnapshot\n );\n\n return visibilityState === \"visible\";\n}\n\nexport function useWindowScroll() {\n const [state, setState] = React.useState({\n x: null,\n y: null,\n });\n\n const scrollTo = React.useCallback((...args) => {\n if (typeof args[0] === \"object\") {\n window.scrollTo(args[0]);\n } else if (typeof args[0] === \"number\" && typeof args[1] === \"number\") {\n window.scrollTo(args[0], args[1]);\n } else {\n throw new Error(\n `Invalid arguments passed to scrollTo. See here for more info. https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo`\n );\n }\n }, []);\n\n React.useLayoutEffect(() => {\n const handleScroll = () => {\n setState({ x: window.pageXOffset, y: window.pageYOffset });\n };\n\n handleScroll();\n window.addEventListener(\"scroll\", handleScroll);\n\n return () => {\n window.removeEventListener(\"scroll\", handleScroll);\n };\n }, []);\n\n return [state, scrollTo];\n}\n\nexport function useWindowSize() {\n const [size, setSize] = React.useState({\n width: null,\n height: null,\n });\n\n React.useLayoutEffect(() => {\n const handleResize = () => {\n setSize({\n width: window.innerWidth,\n height: window.innerHeight,\n });\n };\n\n handleResize();\n window.addEventListener(\"resize\", handleResize);\n\n return () => {\n window.removeEventListener(\"resize\", handleResize);\n };\n }, []);\n\n return size;\n}\n","import { scopes } from '../oauth.js';\nimport { useLocalStorage } from '@uidotdev/usehooks';\n\nconst STORAGE_KEY = 'tokens';\n\nconst ACCESS_TOKEN_KEY = 'accessToken';\nconst ACCESS_TOKEN_EXPIRE_KEY = 'accessTokenExpire';\nconst REFRESH_TOKEN_KEY = 'refreshToken';\n\nconst defaultTokensValue = {};\n\nfunction parseTokenResponse(tokenResponse) {\n if (tokenResponse.hasOwnProperty('error') && tokenResponse.hasOwnProperty('error_description')) {\n throw new Error(tokenResponse.error_description);\n }\n\n if (\n !tokenResponse.hasOwnProperty('access_token') ||\n !tokenResponse.hasOwnProperty('created_at') ||\n !tokenResponse.hasOwnProperty('expires_in') ||\n !tokenResponse.hasOwnProperty('refresh_token') ||\n !tokenResponse.hasOwnProperty('scope') ||\n !tokenResponse.hasOwnProperty('token_type') ||\n tokenResponse.token_type !== 'Bearer' ||\n tokenResponse.scope !== scopes\n ) {\n throw new Error('Incomplete response, missing fields');\n }\n\n return {\n [ACCESS_TOKEN_KEY]: tokenResponse.access_token,\n [ACCESS_TOKEN_EXPIRE_KEY]: (tokenResponse.created_at + tokenResponse.expires_in) * 1_000,\n [REFRESH_TOKEN_KEY]: tokenResponse.refresh_token,\n };\n}\n\nexport function useAuthStorage() {\n const [ tokens, setTokens ] = useLocalStorage(STORAGE_KEY, defaultTokensValue);\n\n function updateTokens(tokenResponse) {\n setTokens(parseTokenResponse(tokenResponse));\n }\n\n function clearTokens() {\n setTokens();\n }\n\n return {\n accessToken: tokens?.[ACCESS_TOKEN_KEY],\n accessTokenExpire: tokens?.[ACCESS_TOKEN_EXPIRE_KEY],\n refreshToken: tokens?.[REFRESH_TOKEN_KEY],\n updateTokens,\n clearTokens,\n };\n}\n\nfunction getStorageItem(key) {\n return JSON.parse(localStorage.getItem(STORAGE_KEY))?.[key];\n}\n\nfunction setStorageValue(value) {\n const key = STORAGE_KEY;\n const newValue = JSON.stringify(value || defaultTokensValue);\n localStorage.setItem(key, newValue);\n window.dispatchEvent(new StorageEvent('storage', {\n key,\n newValue,\n }));\n}\n\nexport function getAccessToken() {\n return getStorageItem(ACCESS_TOKEN_KEY);\n}\n\nfunction getAccessTokenExpire() {\n return getStorageItem(ACCESS_TOKEN_EXPIRE_KEY);\n}\n\nexport function isAccessTokenExpired() {\n const accessTokenExpire = getAccessTokenExpire();\n\n return typeof accessTokenExpire !== 'number' || accessTokenExpire < Date.now();\n}\n\nexport function getRefreshToken() {\n return getStorageItem(REFRESH_TOKEN_KEY);\n}\n\nexport function updateTokens(tokenResponse) {\n setStorageValue(parseTokenResponse(tokenResponse));\n}\n\nexport function clearTokens() {\n setStorageValue();\n}\n","import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\nimport { getAccessToken, isAccessTokenExpired } from '../hooks/useAuthStorage.js';\nimport { refreshTokenIfNeeded } from '../oauth.js';\n\nconst apiBaseUrl = import.meta.env.BACKEND_URL + 'api/';\nconst deviceApiBaseUrl = import.meta.env.DEVICE_BACKEND_URL + 'api/';\nconst mqttApiBaseUrl = import.meta.env.MQTT_BACKEND_URL;\n\nconst anonymousBaseQuery = fetchBaseQuery({\n baseUrl: apiBaseUrl,\n prepareHeaders: headers => {\n headers.set('accept', 'application/json');\n\n return headers;\n },\n});\n\nconst anonymousMqttBaseQuery = fetchBaseQuery({\n baseUrl: mqttApiBaseUrl,\n});\n\nconst authenticatedBaseQuery = fetchBaseQuery({\n baseUrl: apiBaseUrl,\n prepareHeaders: headers => {\n headers.set('accept', 'application/json');\n\n const token = getAccessToken();\n\n if (token) {\n headers.set('authorization', 'Bearer ' + token);\n }\n\n return headers;\n },\n});\n\nconst authenticatedDeviceBaseQuery = fetchBaseQuery({\n baseUrl: deviceApiBaseUrl,\n prepareHeaders: headers => {\n headers.set('accept', 'application/json');\n\n const token = getAccessToken();\n\n if (token) {\n headers.set('authorization', 'Bearer ' + token);\n }\n\n return headers;\n },\n});\n\nconst authenticatedBaseQueryWithReauth = async (args, api, extraOptions) => {\n if (isAccessTokenExpired()) {\n await refreshTokenIfNeeded();\n }\n\n let result = await authenticatedBaseQuery(args, api, extraOptions);\n\n if (result?.error?.status === 401 && await refreshTokenIfNeeded()) {\n return authenticatedBaseQuery(args, api, extraOptions);\n }\n\n return result;\n};\n\nconst authenticatedDeviceBaseQueryWithReauth = async (args, api, extraOptions) => {\n if (isAccessTokenExpired()) {\n await refreshTokenIfNeeded();\n }\n\n let result = await authenticatedDeviceBaseQuery(args, api, extraOptions);\n\n if (result?.error?.status === 401 && await refreshTokenIfNeeded()) {\n return authenticatedDeviceBaseQuery(args, api, extraOptions);\n }\n\n return result;\n};\n\nconst query = builder => url => builder.query({\n query: () => url,\n});\n\nexport const anonymousApiSlice = createApi({\n reducerPath: 'anonymousApi',\n baseQuery: anonymousBaseQuery,\n endpoints: builder => ({\n getPresentUsers: query(builder)('users/present'),\n }),\n});\n\nexport const anonymousMqttApiSlice = createApi({\n reducerPath: 'anonymousMqttApi',\n baseQuery: anonymousMqttBaseQuery,\n endpoints: builder => ({\n getStatus: query(builder)('status'),\n }),\n});\n\nexport const authenticatedApiSlice = createApi({\n reducerPath: 'authenticatedApi',\n baseQuery: authenticatedBaseQueryWithReauth,\n endpoints: builder => ({\n getCurrentUser: query(builder)('current_user'),\n }),\n});\n\nexport const authenticatedDeviceApiSlice = createApi({\n reducerPath: 'authenticatedDeviceApi',\n baseQuery: authenticatedDeviceBaseQueryWithReauth,\n endpoints: builder => ({\n getDevices: query(builder)('devices'),\n deviceAction: builder.mutation({\n query: params => ({\n url: 'device/' + params.deviceId + '/' + params.action,\n method: 'POST',\n }),\n }),\n getActionLog: builder.query({\n query: params => 'actionLog/' + params.offset + '/' + params.limit,\n }),\n }),\n});\n\nexport const {\n useGetPresentUsersQuery,\n} = anonymousApiSlice;\n\nexport const {\n useGetStatusQuery,\n} = anonymousMqttApiSlice;\n\nexport const {\n useGetCurrentUserQuery,\n} = authenticatedApiSlice;\n\nexport const {\n useGetDevicesQuery,\n useDeviceActionMutation,\n useGetActionLogQuery,\n} = authenticatedDeviceApiSlice;\n","import { configureStore } from '@reduxjs/toolkit';\nimport { setupListeners } from '@reduxjs/toolkit/query';\nimport {\n anonymousApiSlice,\n anonymousMqttApiSlice,\n authenticatedApiSlice,\n authenticatedDeviceApiSlice\n} from '../features/apiSlice';\n\nexport const store = configureStore({\n reducer: {\n [anonymousApiSlice.reducerPath]: anonymousApiSlice.reducer,\n [anonymousMqttApiSlice.reducerPath]: anonymousMqttApiSlice.reducer,\n [authenticatedApiSlice.reducerPath]: authenticatedApiSlice.reducer,\n [authenticatedDeviceApiSlice.reducerPath]: authenticatedDeviceApiSlice.reducer,\n },\n middleware: getDefaultMiddleware =>\n getDefaultMiddleware().concat(anonymousApiSlice.middleware).concat(anonymousMqttApiSlice.middleware)\n .concat(authenticatedApiSlice.middleware).concat(authenticatedDeviceApiSlice.middleware),\n});\n\nsetupListeners(store.dispatch);\n","/**\n * @remix-run/router v1.8.0\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n(function (Action) {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Action[\"Pop\"] = \"POP\";\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Action[\"Push\"] = \"PUSH\";\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\nconst PopStateEventType = \"popstate\";\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n let {\n initialEntries = [\"/\"],\n initialIndex,\n v5Compat = false\n } = options;\n let entries; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n let action = Action.Pop;\n let listener = null;\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation() {\n return entries[index];\n }\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n return location;\n }\n function createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n let history = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\"\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 1\n });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 0\n });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: nextLocation,\n delta\n });\n }\n },\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\n }\n };\n return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createBrowserLocation(window, globalHistory) {\n let {\n pathname,\n search,\n hash\n } = window.location;\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n function validateHashLocation(location, to) {\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n }\n return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location, index) {\n return {\n usr: location.state,\n key: location.key,\n idx: index\n };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = _extends({\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\"\n }, typeof to === \"string\" ? parsePath(to) : to, {\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: to && to.key || key || createKey()\n });\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nfunction createPath(_ref) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = _ref;\n if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nfunction parsePath(path) {\n let parsedPath = {};\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n if (path) {\n parsedPath.pathname = path;\n }\n }\n return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\n let {\n window = document.defaultView,\n v5Compat = false\n } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener = null;\n let index = getIndex();\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), \"\");\n }\n function getIndex() {\n let state = globalHistory.state || {\n idx: null\n };\n return state.idx;\n }\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: history.location,\n delta\n });\n }\n }\n function push(to, state) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 1\n });\n }\n }\n function replace(to, state) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 0\n });\n }\n }\n function createURL(to) {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base = window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n return new URL(href, base);\n }\n let history = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n }\n };\n return history;\n}\n//#endregion\n\nvar ResultType;\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\nfunction isIndexRoute(route) {\n return route.index === true;\n}\n// Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\nfunction convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n if (manifest === void 0) {\n manifest = {};\n }\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n invariant(!manifest[id], \"Found a route id collision on id \\\"\" + id + \"\\\". Route \" + \"id's must be globally unique within Data Router usages\");\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, mapRouteProperties(route), {\n id\n });\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {\n id,\n children: undefined\n });\n manifest[id] = pathOrLayoutRoute;\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);\n }\n return pathOrLayoutRoute;\n }\n });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n if (pathname == null) {\n return null;\n }\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname));\n }\n return matches;\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n if (parentPath === void 0) {\n parentPath = \"\";\n }\n let flattenRoute = (route, index, relativePath) => {\n let meta = {\n relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route\n };\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(meta.relativePath.startsWith(parentPath), \"Absolute route path \\\"\" + meta.relativePath + \"\\\" nested under path \" + (\"\\\"\" + parentPath + \"\\\" is not valid. An absolute child route path \") + \"must start with the combined path of all its parent routes.\");\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n // Add the children before adding this route to the array so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n };\n routes.forEach((route, index) => {\n var _route$path;\n // coarse-grain check for optional params\n if (route.path === \"\" || !((_route$path = route.path) != null && _route$path.includes(\"?\"))) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n return branches;\n}\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path) {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n let [first, ...rest] = segments;\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n let result = [];\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explodes _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\")));\n // Then if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n // for absolute paths, ensure `/` instead of empty segment\n return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\nfunction rankRouteBranches(branches) {\n branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n if (index) {\n initialScore += indexRouteValue;\n }\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n return siblings ?\n // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1] :\n // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\nfunction matchRouteBranch(branch, pathname) {\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end\n }, remainingPathname);\n if (!match) return null;\n Object.assign(matchedParams, match.params);\n let route = meta.route;\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n route\n });\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nfunction generatePath(originalPath, params) {\n if (params === void 0) {\n params = {};\n }\n let path = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(false, \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n path = path.replace(/\\*$/, \"/*\");\n }\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n const stringify = p => p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n const segments = path.split(/\\/+/).map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\";\n // Apply the splat\n return stringify(params[star]);\n }\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key];\n invariant(optional === \"?\" || param != null, \"Missing \\\":\" + key + \"\\\" param\");\n return stringify(param);\n }\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter(segment => !!segment);\n return prefix + segments.join(\"/\");\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n let match = pathname.match(matcher);\n if (!match) return null;\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params = paramNames.reduce((memo, paramName, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n }\n memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || \"\", paramName);\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n if (end === void 0) {\n end = true;\n }\n warning(path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"), \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n let paramNames = [];\n let regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:(\\w+)/g, (_, paramName) => {\n paramNames.push(paramName);\n return \"/([^\\\\/]+)\";\n });\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\n regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else ;\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, paramNames];\n}\nfunction safelyDecodeURI(value) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(false, \"The URL path \\\"\" + value + \"\\\" could not be decoded because it is is a \" + \"malformed URL segment. This is probably due to a bad percent \" + (\"encoding (\" + error + \").\"));\n return value;\n }\n}\nfunction safelyDecodeURIComponent(value, paramName) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(false, \"The value for the URL param \\\"\" + paramName + \"\\\" will not be decoded because\" + (\" the string \\\"\" + value + \"\\\" is a malformed URL segment. This is probably\") + (\" due to a bad percent encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n return pathname.slice(startIndex) || \"/\";\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\"\n } = typeof to === \"string\" ? parsePath(to) : to;\n let pathname = toPathname ? toPathname.startsWith(\"/\") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash)\n };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n relativeSegments.forEach(segment => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n return \"Cannot include a '\" + char + \"' character in a manually specified \" + (\"`to.\" + field + \"` field [\" + JSON.stringify(path) + \"]. Please separate it out to the \") + (\"`to.\" + dest + \"` field. Alternatively you may provide the full path as \") + \"a string in and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nfunction getPathContributingMatches(matches) {\n return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n/**\n * @private\n */\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n let to;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = _extends({}, toArg);\n invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n }\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from;\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n to.pathname = toSegments.join(\"/\");\n }\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n let path = resolvePath(to, from);\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n return path;\n}\n/**\n * @private\n */\nfunction getToPathname(to) {\n // Empty strings should be treated the same as / paths\n return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\n/**\n * @private\n */\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n return new Response(JSON.stringify(data), _extends({}, responseInit, {\n headers\n }));\n};\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n constructor(data, responseInit) {\n this.pendingKeysSet = new Set();\n this.subscribers = new Set();\n this.deferredKeys = [];\n invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\");\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref) => {\n let [key, value] = _ref;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n this.init = responseInit;\n }\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\n onSettle(promise, key, error, data) {\n if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n return Promise.reject(error);\n }\n this.pendingKeysSet.delete(key);\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\"Deferred data for key \\\"\" + key + \"\\\" resolved/rejected with `undefined`, \" + \"you must resolve/reject with a value or `null`.\");\n Object.defineProperty(promise, \"_error\", {\n get: () => undefinedError\n });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n this.emit(false, key);\n return Promise.reject(error);\n }\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n this.emit(false, key);\n return data;\n }\n emit(aborted, settledKey) {\n this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n }\n subscribe(fn) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n async resolveData(signal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n get unwrappedData() {\n invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n return Object.entries(this.data).reduce((acc, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\nconst defer = function defer(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n return new DeferredData(data, responseInit);\n};\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n return new Response(null, _extends({}, responseInit, {\n headers\n }));\n};\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirectDocument = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nclass ErrorResponse {\n constructor(status, statusText, data, internal) {\n if (internal === void 0) {\n internal = false;\n }\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nfunction isRouteErrorResponse(error) {\n return error != null && typeof error.status === \"number\" && typeof error.statusText === \"string\" && typeof error.internal === \"boolean\" && \"data\" in error;\n}\n\nconst validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nconst validMutationMethods = new Set(validMutationMethodsArr);\nconst validRequestMethodsArr = [\"get\", ...validMutationMethodsArr];\nconst validRequestMethods = new Set(validRequestMethodsArr);\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\nconst IDLE_NAVIGATION = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_BLOCKER = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined\n};\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst defaultMapRouteProperties = route => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary)\n});\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Create a router and listen to history POP navigations\n */\nfunction createRouter(init) {\n const routerWindow = init.window ? init.window : typeof window !== \"undefined\" ? window : undefined;\n const isBrowser = typeof routerWindow !== \"undefined\" && typeof routerWindow.document !== \"undefined\" && typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let mapRouteProperties;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Routes keyed by ID\n let manifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);\n let inFlightDataRoutes;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future = _extends({\n v7_normalizeFormMethod: false,\n v7_prependBasename: false\n }, init.future);\n // Cleanup function for history\n let unlistenHistory = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors = null;\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname\n });\n let {\n matches,\n route\n } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = {\n [route.id]: error\n };\n }\n let initialized =\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n !initialMatches.some(m => m.route.lazy) && (\n // And we have to either have no loaders or have been provided hydrationData\n !initialMatches.some(m => m.route.loader) || init.hydrationData != null);\n let router;\n let state = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n actionData: init.hydrationData && init.hydrationData.actionData || null,\n errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n fetchers: new Map(),\n blockers: new Map()\n };\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction = Action.Pop;\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes = [];\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads = [];\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(_ref => {\n let {\n action: historyAction,\n location,\n delta\n } = _ref;\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n warning(blockerFunctions.size === 0 || delta != null, \"You are trying to use a blocker on a POP navigation to a location \" + \"that was not created by @remix-run/router. This will fail silently in \" + \"production. This can happen if you are navigating outside the router \" + \"via `window.history.pushState`/`window.location.hash` instead of using \" + \"router navigation APIs. This can also happen if you are using \" + \"createHashRouter and the user manually changes the URL.\");\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction\n });\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return startNavigation(historyAction, location);\n });\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location);\n }\n return router;\n }\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n // Subscribe to state updates for the router\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n // Update our state and notify the calling context of the change\n function updateState(newState) {\n state = _extends({}, state, newState);\n subscribers.forEach(subscriber => subscriber(state));\n }\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(location, newState) {\n var _location$state, _location$state2;\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === \"loading\" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;\n let actionData;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === Action.Replace) {\n init.history.replace(location, location.state);\n }\n updateState(_extends({}, newState, {\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset,\n blockers\n }));\n // Reset stateful navigation vars\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n let historyAction = Action.Push;\n if (userReplace === true) {\n historyAction = Action.Replace;\n } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = Action.Replace;\n }\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction\n });\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace\n });\n }\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\n });\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\n }\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation\n });\n }\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(historyAction, location, opts) {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, {\n pathname: location.pathname\n });\n let {\n matches: notFoundMatches,\n route\n } = getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n });\n return;\n }\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a