// ==UserScript== // @name pixelplanet.fun picture overlay // @namespace https://github.com/Woyken/pixelplanet.fun-OverlayPicture // @version 1.1.14 // @description Add your picture as overlay to pixelplanet.fun // @author Woyken // @include https://pixelplanet.fun/* // @include https://fuckyouarkeros.fun/* // @grant none // @downloadURL https://woyken.github.io/pixelplanet.fun-OverlayPicture/pixelPlanetOverlay-loader.user.js // ==/UserScript== /**/ function _mergeNamespaces(n, m) { for (var i = 0; i < m.length; i++) { const e = m[i]; if (typeof e !== 'string' && !Array.isArray(e)) { for (const k in e) { if (k !== 'default' && !(k in n)) { const d = Object.getOwnPropertyDescriptor(e, k); if (d) { Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: () => e[k] }); } } } } } return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: 'Module' })); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a() { if (this instanceof a) { var args = [null]; args.push.apply(args, arguments); var Ctor = Function.bind.apply(f, args); return new Ctor(); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', { value: true }); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } var jsxRuntimeExports = {}; var jsxRuntime$1 = { get exports(){ return jsxRuntimeExports; }, set exports(v){ jsxRuntimeExports = v; }, }; var reactJsxRuntime_production_min = {}; var reactExports = {}; var react = { get exports(){ return reactExports; }, set exports(v){ reactExports = v; }, }; var react_production_min = {}; /** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var l$5=Symbol.for("react.element"),n$6=Symbol.for("react.portal"),p$7=Symbol.for("react.fragment"),q$6=Symbol.for("react.strict_mode"),r$5=Symbol.for("react.profiler"),t$5=Symbol.for("react.provider"),u$4=Symbol.for("react.context"),v$5=Symbol.for("react.forward_ref"),w$3=Symbol.for("react.suspense"),x$2=Symbol.for("react.memo"),y$2=Symbol.for("react.lazy"),z$3=Symbol.iterator;function A$3(a){if(null===a||"object"!==typeof a)return null;a=z$3&&a[z$3]||a["@@iterator"];return "function"===typeof a?a:null} var B$2={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$1=Object.assign,D$2={};function E$2(a,b,e){this.props=a;this.context=b;this.refs=D$2;this.updater=e||B$2;}E$2.prototype.isReactComponent={}; E$2.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E$2.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F$1(){}F$1.prototype=E$2.prototype;function G$2(a,b,e){this.props=a;this.context=b;this.refs=D$2;this.updater=e||B$2;}var H$2=G$2.prototype=new F$1; H$2.constructor=G$2;C$1(H$2,E$2.prototype);H$2.isPureReactComponent=!0;var I$2=Array.isArray,J=Object.prototype.hasOwnProperty,K$1={current:null},L$2={key:!0,ref:!0,__self:!0,__source:!0}; function M$2(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L$2.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1= level; } window$1.logLevel = 0; return level <= 0; }, log(a, ...args) { if (logger.isLogLevelEnabled(2 /* info */)) { console.log(a, ...args); } }, logWarn(a, ...args) { if (logger.isLogLevelEnabled(1 /* warn */)) { console.warn(a, ...args); } }, logError(a, ...args) { if (logger.isLogLevelEnabled(0 /* error */)) { console.error(a, ...args); } } }; function n$4(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$4(n)?3:0}function u$3(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$2(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?n.add(t):n[r]=t;}function c$2(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X$1&&n instanceof Map}function v$4(n){return q$4&&n instanceof Set}function p$5(n){return n.o||n.t}function l$3(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q$1];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h$4),Object.freeze(n),e&&i(n,(function(n,r){return d$2(r,!0)}),!0)),n}function h$4(){n$4(2);}function y$1(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b$2(r){var t=tn[r];return t||n$4(18,r),t}function m$4(n,r){tn[n]||(tn[n]=r);}function _$1(){return U$1}function j(n,r){r&&(b$2("Patches"),n.u=[],n.s=[],n.v=r);}function O$1(n){g$2(n),n.p.forEach(S$1),n.p=null;}function g$2(n){n===U$1&&(U$1=n.l);}function w$2(n){return U$1={p:[],l:U$1,h:n,m:!0,_:0}}function S$1(n){var r=n[Q$1];0===r.i||1===r.i?r.j():r.O=!0;}function P$1(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.g||b$2("ES5").S(e,r,o),o?(i[Q$1].P&&(O$1(e),n$4(4)),t$4(r)&&(r=M$1(e,r),e.l||x$1(e,r)),e.u&&b$2("Patches").M(i[Q$1].t,r,e.u,e.s)):r=M$1(e,i,[]),O$1(e),e.u&&e.v(e.u,e.s),r!==H$1?r:void 0}function M$1(n,r,t){if(y$1(r))return r;var e=r[Q$1];if(!e)return i(r,(function(i,o){return A$2(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x$1(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$3(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$2(n,e,o,r,i,t,a)})),x$1(n,o,!1),t&&n.u&&b$2("Patches").N(e,t,n.u,n.s);}return e.o}function A$2(e,i,o,a,c,s,v){if(r$4(c)){var p=M$1(e,c,s&&i&&3!==i.i&&!u$3(i.R,a)?s.concat(a):void 0);if(f$2(o,a,p),!r$4(p))return;e.m=!1;}else v&&o.add(c);if(t$4(c)&&!y$1(c)){if(!e.h.D&&e._<1)return;M$1(e,c),i&&i.A.l||x$1(e,c);}}function x$1(n,r,t){void 0===t&&(t=!1),!n.l&&n.h.D&&n.m&&d$2(r,t);}function z$2(n,r){var t=n[Q$1];return (t?p$5(t):n)[r]}function I$1(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$3(n){n.P||(n.P=!0,n.l&&k$3(n.l));}function E$1(n){n.o||(n.o=l$3(n.t));}function N$1(n,r,t){var e=s(r)?b$2("MapSet").F(r,t):v$4(r)?b$2("MapSet").T(r,t):n.g?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_$1(),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$2("ES5").J(r,t);return (t?t.A:_$1()).p.push(e),e}function R$1(e){return r$4(e)||n$4(22,e),function n(r){if(!t$4(r))return r;var e,u=r[Q$1],c=o(r);if(u){if(!u.P&&(u.i<4||!b$2("ES5").K(u)))return u.t;u.I=!0,e=D$1(r,c),u.I=!1;}else e=D$1(r,c);return i(e,(function(r,t){u&&a(u.t,r)===t||f$2(e,r,n(t));})),3===c?new Set(e):e}(e)}function D$1(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l$3(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$1];return en.get(r,n)},set:function(r){var t=this[Q$1];en.set(t,n,r);}},t}function e(n){for(var r=n.length-1;r>=0;r--){var t=n[r][Q$1];if(!t.P)switch(t.i){case 5:a(t)&&k$3(t);break;case 4:o(t)&&k$3(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$1){var a=r[o];if(void 0===a&&!u$3(r,o))return !0;var f=t[o],s=f&&f[Q$1];if(s?s.t!==a:!c$2(f,a))return !0}}var v=!!r[Q$1];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$2("Patches").$;return r$4(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce;an.produceWithPatches.bind(an);an.setAutoFreeze.bind(an);an.setUseProxies.bind(an);an.applyPatches.bind(an);an.createDraft.bind(an);an.finishDraft.bind(an); function _typeof$2(obj) { "@babel/helpers - typeof"; return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$2(obj); } function _toPrimitive(input, hint) { if (_typeof$2(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof$2(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof$2(key) === "symbol" ? key : String(key); } function _defineProperty$6(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$5(Object(source), !0).forEach(function (key) { _defineProperty$6(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js * * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes * during build. * @param {number} code */ function formatProdErrorMessage(code) { 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. '; } // Inlined version of the `symbol-observable` polyfill var $$observable = (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var randomString = function randomString() { return Math.random().toString(36).substring(7).split('').join('.'); }; var ActionTypes = { INIT: "@@redux/INIT" + randomString(), REPLACE: "@@redux/REPLACE" + randomString(), PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); } }; /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject$2(obj) { if (typeof obj !== 'object' || obj === null) return false; var proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto; } /** * @deprecated * * **We recommend using the `configureStore` method * of the `@reduxjs/toolkit` package**, which replaces `createStore`. * * Redux Toolkit is our recommended approach for writing Redux logic today, * including store setup, reducers, data fetching, and more. * * **For more details, please read this Redux docs page:** * **https://redux.js.org/introduction/why-rtk-is-redux-today** * * `configureStore` from Redux Toolkit is an improved version of `createStore` that * simplifies setup and helps avoid common bugs. * * You should not be using the `redux` core package by itself today, except for learning purposes. * The `createStore` method from the core `redux` package will not be removed, but we encourage * all users to migrate to using Redux Toolkit for all Redux code. * * If you want to use `createStore` without this visual deprecation warning, use * the `legacy_createStore` import instead: * * `import { legacy_createStore as createStore} from 'redux'` * */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { throw new Error(formatProdErrorMessage(0) ); } if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error(formatProdErrorMessage(1) ); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error(formatProdErrorMessage(2) ); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; /** * This makes a shallow copy of currentListeners so we can use * nextListeners as a temporary list while dispatching. * * This prevents any bugs around consumers calling * subscribe/unsubscribe in the middle of a dispatch. */ function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { if (isDispatching) { throw new Error(formatProdErrorMessage(3) ); } return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error(formatProdErrorMessage(4) ); } if (isDispatching) { throw new Error(formatProdErrorMessage(5) ); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } if (isDispatching) { throw new Error(formatProdErrorMessage(6) ); } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); currentListeners = null; }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!isPlainObject$2(action)) { throw new Error(formatProdErrorMessage(7) ); } if (typeof action.type === 'undefined') { throw new Error(formatProdErrorMessage(8) ); } if (isDispatching) { throw new Error(formatProdErrorMessage(9) ); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; listener(); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error(formatProdErrorMessage(10) ); } currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. // Any reducers that existed in both the new and old rootReducer // will receive the previous state. This effectively populates // the new state tree with any relevant data from the old one. dispatch({ type: ActionTypes.REPLACE }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/tc39/proposal-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object' || observer === null) { throw new Error(formatProdErrorMessage(11) ); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[$$observable] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[$$observable] = observable, _ref2; } function assertReducerShape(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error(formatProdErrorMessage(12) ); } if (typeof reducer(undefined, { type: ActionTypes.PROBE_UNKNOWN_ACTION() }) === 'undefined') { throw new Error(formatProdErrorMessage(13) ); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same var shapeAssertionError; try { assertReducerShape(finalReducers); } catch (e) { shapeAssertionError = e; } return function combination(state, action) { if (state === void 0) { state = {}; } if (shapeAssertionError) { throw shapeAssertionError; } var hasChanged = false; var nextState = {}; for (var _i = 0; _i < finalReducerKeys.length; _i++) { var _key = finalReducerKeys[_i]; var reducer = finalReducers[_key]; var previousStateForKey = state[_key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { action && action.type; throw new Error(formatProdErrorMessage(14) ); } nextState[_key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; return hasChanged ? nextState : state; }; } /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose$1() { for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(void 0, arguments)); }; }); } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function () { var store = createStore.apply(void 0, arguments); var _dispatch = function dispatch() { throw new Error(formatProdErrorMessage(15) ); }; var middlewareAPI = { getState: store.getState, dispatch: function dispatch() { return _dispatch.apply(void 0, arguments); } }; var chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = compose$1.apply(void 0, chain)(store.dispatch); return _objectSpread2(_objectSpread2({}, store), {}, { dispatch: _dispatch }); }; }; } // Cache implementation based on Erik Rasmussen's `lru-memoize`: // https://github.com/erikras/lru-memoize var NOT_FOUND = 'NOT_FOUND'; function createSingletonCache(equals) { var entry; return { get: function get(key) { if (entry && equals(entry.key, key)) { return entry.value; } return NOT_FOUND; }, put: function put(key, value) { entry = { key: key, value: value }; }, getEntries: function getEntries() { return entry ? [entry] : []; }, clear: function clear() { entry = undefined; } }; } function createLruCache(maxSize, equals) { var entries = []; function get(key) { var cacheIndex = entries.findIndex(function (entry) { return equals(key, entry.key); }); // We found a cached entry if (cacheIndex > -1) { var entry = entries[cacheIndex]; // Cached entry not at top of cache, move it to the top if (cacheIndex > 0) { entries.splice(cacheIndex, 1); entries.unshift(entry); } return entry.value; } // No entry found in cache, return sentinel return NOT_FOUND; } function put(key, value) { if (get(key) === NOT_FOUND) { // TODO Is unshift slow? entries.unshift({ key: key, value: value }); if (entries.length > maxSize) { entries.pop(); } } } function getEntries() { return entries; } function clear() { entries = []; } return { get: get, put: put, getEntries: getEntries, clear: clear }; } var defaultEqualityCheck = function defaultEqualityCheck(a, b) { return a === b; }; function createCacheKeyComparator(equalityCheck) { return function areArgumentsShallowlyEqual(prev, next) { if (prev === null || next === null || prev.length !== next.length) { return false; } // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible. var length = prev.length; for (var i = 0; i < length; i++) { if (!equalityCheck(prev[i], next[i])) { return false; } } return true; }; } // defaultMemoize now supports a configurable cache size with LRU behavior, // and optional comparison of the result value with existing values function defaultMemoize(func, equalityCheckOrOptions) { var providedOptions = typeof equalityCheckOrOptions === 'object' ? equalityCheckOrOptions : { equalityCheck: equalityCheckOrOptions }; var _providedOptions$equa = providedOptions.equalityCheck, equalityCheck = _providedOptions$equa === void 0 ? defaultEqualityCheck : _providedOptions$equa, _providedOptions$maxS = providedOptions.maxSize, maxSize = _providedOptions$maxS === void 0 ? 1 : _providedOptions$maxS, resultEqualityCheck = providedOptions.resultEqualityCheck; var comparator = createCacheKeyComparator(equalityCheck); var cache = maxSize === 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator); // we reference arguments instead of spreading them for performance reasons function memoized() { var value = cache.get(arguments); if (value === NOT_FOUND) { // @ts-ignore value = func.apply(null, arguments); if (resultEqualityCheck) { var entries = cache.getEntries(); var matchingEntry = entries.find(function (entry) { return resultEqualityCheck(entry.value, value); }); if (matchingEntry) { value = matchingEntry.value; } } cache.put(arguments, value); } return value; } memoized.clearCache = function () { return cache.clear(); }; return memoized; } function getDependencies(funcs) { var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs; if (!dependencies.every(function (dep) { return typeof dep === 'function'; })) { var dependencyTypes = dependencies.map(function (dep) { return typeof dep === 'function' ? "function " + (dep.name || 'unnamed') + "()" : typeof dep; }).join(', '); throw new Error("createSelector expects all input-selectors to be functions, but received the following types: [" + dependencyTypes + "]"); } return dependencies; } function createSelectorCreator(memoize) { for (var _len = arguments.length, memoizeOptionsFromArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { memoizeOptionsFromArgs[_key - 1] = arguments[_key]; } var createSelector = function createSelector() { for (var _len2 = arguments.length, funcs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { funcs[_key2] = arguments[_key2]; } var _recomputations = 0; var _lastResult; // Due to the intricacies of rest params, we can't do an optional arg after `...funcs`. // So, start by declaring the default value here. // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.) var directlyPassedOptions = { memoizeOptions: undefined }; // Normally, the result func or "output selector" is the last arg var resultFunc = funcs.pop(); // If the result func is actually an _object_, assume it's our options object if (typeof resultFunc === 'object') { directlyPassedOptions = resultFunc; // and pop the real result func off resultFunc = funcs.pop(); } if (typeof resultFunc !== 'function') { throw new Error("createSelector expects an output function after the inputs, but received: [" + typeof resultFunc + "]"); } // Determine which set of options we're using. Prefer options passed directly, // but fall back to options given to createSelectorCreator. var _directlyPassedOption = directlyPassedOptions, _directlyPassedOption2 = _directlyPassedOption.memoizeOptions, memoizeOptions = _directlyPassedOption2 === void 0 ? memoizeOptionsFromArgs : _directlyPassedOption2; // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer // is an array. In most libs I've looked at, it's an equality function or options object. // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full // user-provided array of options. Otherwise, it must be just the _first_ arg, and so // we wrap it in an array so we can apply it. var finalMemoizeOptions = Array.isArray(memoizeOptions) ? memoizeOptions : [memoizeOptions]; var dependencies = getDependencies(funcs); var memoizedResultFunc = memoize.apply(void 0, [function recomputationWrapper() { _recomputations++; // apply arguments instead of spreading for performance. return resultFunc.apply(null, arguments); }].concat(finalMemoizeOptions)); // If a selector is called with the exact same arguments we don't need to traverse our dependencies again. var selector = memoize(function dependenciesChecker() { var params = []; var length = dependencies.length; for (var i = 0; i < length; i++) { // apply arguments instead of spreading and mutate a local list of params for performance. // @ts-ignore params.push(dependencies[i].apply(null, arguments)); } // apply arguments instead of spreading for performance. _lastResult = memoizedResultFunc.apply(null, params); return _lastResult; }); Object.assign(selector, { resultFunc: resultFunc, memoizedResultFunc: memoizedResultFunc, dependencies: dependencies, lastResult: function lastResult() { return _lastResult; }, recomputations: function recomputations() { return _recomputations; }, resetRecomputations: function resetRecomputations() { return _recomputations = 0; } }); return selector; }; // @ts-ignore return createSelector; } var createSelector = /* #__PURE__ */createSelectorCreator(defaultMemoize); /** A function that accepts a potential "extra argument" value to be injected later, * and returns an instance of the thunk middleware that uses that value */ function createThunkMiddleware(extraArgument) { // Standard Redux middleware definition pattern: // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware var middleware = function middleware(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; return function (next) { return function (action) { // The thunk middleware looks for any functions that were passed to `store.dispatch`. // If this "action" is really a function, call it and return the result. if (typeof action === 'function') { // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg" return action(dispatch, getState, extraArgument); } // Otherwise, pass the action down the middleware chain as usual return next(action); }; }; }; return middleware; } var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version // with whatever "extra arg" they want to inject into their thunks thunk.withExtraArgument = createThunkMiddleware; const thunkMiddleware = thunk; var __extends = (globalThis && globalThis.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __generator$1 = (globalThis && globalThis.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { 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; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray$1 = (globalThis && globalThis.__spreadArray) || function (to, from) { for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i]; return to; }; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; }; var __spreadValues = function (a, b) { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) { var prop = _c[_i]; if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); }; var __async = function (__this, __arguments, generator) { return new Promise(function (resolve, reject) { var fulfilled = function (value) { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = function (value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); }; step((generator = generator.apply(__this, __arguments)).next()); }); }; var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () { if (arguments.length === 0) return void 0; if (typeof arguments[0] === "object") return compose$1; return compose$1.apply(null, arguments); }; // src/isPlainObject.ts function isPlainObject$1(value) { if (typeof value !== "object" || value === null) return false; var proto = Object.getPrototypeOf(value); if (proto === null) return true; var baseProto = proto; while (Object.getPrototypeOf(baseProto) !== null) { baseProto = Object.getPrototypeOf(baseProto); } return proto === baseProto; } var MiddlewareArray = /** @class */ (function (_super) { __extends(MiddlewareArray, _super); function MiddlewareArray() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var _this = _super.apply(this, args) || this; Object.setPrototypeOf(_this, MiddlewareArray.prototype); return _this; } Object.defineProperty(MiddlewareArray, Symbol.species, { get: function () { return MiddlewareArray; }, enumerable: false, configurable: true }); MiddlewareArray.prototype.concat = function () { var arr = []; for (var _i = 0; _i < arguments.length; _i++) { arr[_i] = arguments[_i]; } return _super.prototype.concat.apply(this, arr); }; MiddlewareArray.prototype.prepend = function () { var arr = []; for (var _i = 0; _i < arguments.length; _i++) { arr[_i] = arguments[_i]; } if (arr.length === 1 && Array.isArray(arr[0])) { return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray$1([void 0], arr[0].concat(this))))(); } return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray$1([void 0], arr.concat(this))))(); }; return MiddlewareArray; }(Array)); function freezeDraftable(val) { return t$4(val) ? fn(val, function () { }) : val; } // src/getDefaultMiddleware.ts function isBoolean(x) { return typeof x === "boolean"; } function curryGetDefaultMiddleware() { return function curriedGetDefaultMiddleware(options) { return getDefaultMiddleware(options); }; } function getDefaultMiddleware(options) { if (options === void 0) { options = {}; } var _c = options.thunk, thunk = _c === void 0 ? true : _c; options.immutableCheck; options.serializableCheck; var middlewareArray = new MiddlewareArray(); if (thunk) { if (isBoolean(thunk)) { middlewareArray.push(thunkMiddleware); } else { middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument)); } } return middlewareArray; } // src/configureStore.ts var IS_PRODUCTION = "production" === "production"; function configureStore(options) { var curriedGetDefaultMiddleware = curryGetDefaultMiddleware(); 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; var rootReducer; if (typeof reducer === "function") { rootReducer = reducer; } else if (isPlainObject$1(reducer)) { rootReducer = combineReducers(reducer); } else { throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers'); } var finalMiddleware = middleware; if (typeof finalMiddleware === "function") { finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware); } var middlewareEnhancer = applyMiddleware.apply(void 0, finalMiddleware); var finalCompose = compose$1; if (devTools) { finalCompose = composeWithDevTools(__spreadValues({ trace: !IS_PRODUCTION }, typeof devTools === "object" && devTools)); } var storeEnhancers = [middlewareEnhancer]; if (Array.isArray(enhancers)) { storeEnhancers = __spreadArray$1([middlewareEnhancer], enhancers); } else if (typeof enhancers === "function") { storeEnhancers = enhancers(storeEnhancers); } var composedEnhancer = finalCompose.apply(void 0, storeEnhancers); return createStore(rootReducer, preloadedState, composedEnhancer); } // src/createAction.ts function createAction(type, prepareAction) { function actionCreator() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (prepareAction) { var prepared = prepareAction.apply(void 0, args); if (!prepared) { throw new Error("prepareAction did not return an object"); } return __spreadValues(__spreadValues({ type: type, payload: prepared.payload }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error }); } return { type: type, payload: args[0] }; } actionCreator.toString = function () { return "" + type; }; actionCreator.type = type; actionCreator.match = function (action) { return action.type === type; }; return actionCreator; } // src/mapBuilders.ts function executeReducerBuilderCallback(builderCallback) { var actionsMap = {}; var actionMatchers = []; var defaultCaseReducer; var builder = { addCase: function (typeOrActionCreator, reducer) { var type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type; if (type in actionsMap) { throw new Error("addCase cannot be called with two reducers for the same action type"); } actionsMap[type] = reducer; return builder; }, addMatcher: function (matcher, reducer) { actionMatchers.push({ matcher: matcher, reducer: reducer }); return builder; }, addDefaultCase: function (reducer) { defaultCaseReducer = reducer; return builder; } }; builderCallback(builder); return [actionsMap, actionMatchers, defaultCaseReducer]; } // src/createReducer.ts function isStateFunction(x) { return typeof x === "function"; } function createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) { if (actionMatchers === void 0) { actionMatchers = []; } var _c = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _c[0], finalActionMatchers = _c[1], finalDefaultCaseReducer = _c[2]; var getInitialState; if (isStateFunction(initialState)) { getInitialState = function () { return freezeDraftable(initialState()); }; } else { var frozenInitialState_1 = freezeDraftable(initialState); getInitialState = function () { return frozenInitialState_1; }; } function reducer(state, action) { if (state === void 0) { state = getInitialState(); } var caseReducers = __spreadArray$1([ actionsMap[action.type] ], finalActionMatchers.filter(function (_c) { var matcher = _c.matcher; return matcher(action); }).map(function (_c) { var reducer2 = _c.reducer; return reducer2; })); if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) { caseReducers = [finalDefaultCaseReducer]; } return caseReducers.reduce(function (previousState, caseReducer) { if (caseReducer) { if (r$4(previousState)) { var draft = previousState; var result = caseReducer(draft, action); if (result === void 0) { return previousState; } return result; } else if (!t$4(previousState)) { var result = caseReducer(previousState, action); if (result === void 0) { if (previousState === null) { return previousState; } throw Error("A case reducer on a non-draftable value must not return undefined"); } return result; } else { return fn(previousState, function (draft) { return caseReducer(draft, action); }); } } return previousState; }, state); } reducer.getInitialState = getInitialState; return reducer; } function getType2(slice, actionKey) { return slice + "/" + actionKey; } function createSlice(options) { var name = options.name; if (!name) { throw new Error("`name` is a required option for createSlice"); } if (typeof process !== "undefined" && "production" === "development") { if (options.initialState === void 0) { console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`"); } } var initialState = typeof options.initialState == "function" ? options.initialState : freezeDraftable(options.initialState); var reducers = options.reducers || {}; var reducerNames = Object.keys(reducers); var sliceCaseReducersByName = {}; var sliceCaseReducersByType = {}; var actionCreators = {}; reducerNames.forEach(function (reducerName) { var maybeReducerWithPrepare = reducers[reducerName]; var type = getType2(name, reducerName); var caseReducer; var prepareCallback; if ("reducer" in maybeReducerWithPrepare) { caseReducer = maybeReducerWithPrepare.reducer; prepareCallback = maybeReducerWithPrepare.prepare; } else { caseReducer = maybeReducerWithPrepare; } sliceCaseReducersByName[reducerName] = caseReducer; sliceCaseReducersByType[type] = caseReducer; actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type); }); function buildReducer() { 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; var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType); return createReducer(initialState, function (builder) { for (var key in finalCaseReducers) { builder.addCase(key, finalCaseReducers[key]); } for (var _i = 0, actionMatchers_1 = actionMatchers; _i < actionMatchers_1.length; _i++) { var m = actionMatchers_1[_i]; builder.addMatcher(m.matcher, m.reducer); } if (defaultCaseReducer) { builder.addDefaultCase(defaultCaseReducer); } }); } var _reducer; return { name: name, reducer: function (state, action) { if (!_reducer) _reducer = buildReducer(); return _reducer(state, action); }, actions: actionCreators, caseReducers: sliceCaseReducersByName, getInitialState: function () { if (!_reducer) _reducer = buildReducer(); return _reducer.getInitialState(); } }; } // src/nanoid.ts var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"; var nanoid = function (size) { if (size === void 0) { size = 21; } var id = ""; var i = size; while (i--) { id += urlAlphabet[Math.random() * 64 | 0]; } return id; }; // src/createAsyncThunk.ts var commonProperties = [ "name", "message", "stack", "code" ]; var RejectWithValue = /** @class */ (function () { function RejectWithValue(payload, meta) { this.payload = payload; this.meta = meta; } return RejectWithValue; }()); var FulfillWithMeta = /** @class */ (function () { function FulfillWithMeta(payload, meta) { this.payload = payload; this.meta = meta; } return FulfillWithMeta; }()); var miniSerializeError = function (value) { if (typeof value === "object" && value !== null) { var simpleError = {}; for (var _i = 0, commonProperties_1 = commonProperties; _i < commonProperties_1.length; _i++) { var property = commonProperties_1[_i]; if (typeof value[property] === "string") { simpleError[property] = value[property]; } } return simpleError; } return { message: String(value) }; }; var createAsyncThunk = (function () { function createAsyncThunk2(typePrefix, payloadCreator, options) { var fulfilled = createAction(typePrefix + "/fulfilled", function (payload, requestId, arg, meta) { return ({ payload: payload, meta: __spreadProps(__spreadValues({}, meta || {}), { arg: arg, requestId: requestId, requestStatus: "fulfilled" }) }); }); var pending = createAction(typePrefix + "/pending", function (requestId, arg, meta) { return ({ payload: void 0, meta: __spreadProps(__spreadValues({}, meta || {}), { arg: arg, requestId: requestId, requestStatus: "pending" }) }); }); var rejected = createAction(typePrefix + "/rejected", function (error, requestId, arg, payload, meta) { return ({ payload: payload, error: (options && options.serializeError || miniSerializeError)(error || "Rejected"), meta: __spreadProps(__spreadValues({}, meta || {}), { arg: arg, requestId: requestId, rejectedWithValue: !!payload, requestStatus: "rejected", aborted: (error == null ? void 0 : error.name) === "AbortError", condition: (error == null ? void 0 : error.name) === "ConditionError" }) }); }); var AC = typeof AbortController !== "undefined" ? AbortController : /** @class */ (function () { function class_1() { this.signal = { aborted: false, addEventListener: function () { }, dispatchEvent: function () { return false; }, onabort: function () { }, removeEventListener: function () { }, reason: void 0, throwIfAborted: function () { } }; } class_1.prototype.abort = function () { }; return class_1; }()); function actionCreator(arg) { return function (dispatch, getState, extra) { var requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid(); var abortController = new AC(); var abortReason; function abort(reason) { abortReason = reason; abortController.abort(); } var promise2 = function () { return __async(this, null, function () { var _a, _b, finalAction, conditionResult, abortedPromise, err_1, skipDispatch; return __generator$1(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 4, , 5]); conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState: getState, extra: extra }); if (!isThenable(conditionResult)) return [3 /*break*/, 2]; return [4 /*yield*/, conditionResult]; case 1: conditionResult = _c.sent(); _c.label = 2; case 2: if (conditionResult === false || abortController.signal.aborted) { throw { name: "ConditionError", message: "Aborted due to condition callback returning false." }; } abortedPromise = new Promise(function (_, reject) { return abortController.signal.addEventListener("abort", function () { return reject({ name: "AbortError", message: abortReason || "Aborted" }); }); }); 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 }))); return [4 /*yield*/, Promise.race([ abortedPromise, Promise.resolve(payloadCreator(arg, { dispatch: dispatch, getState: getState, extra: extra, requestId: requestId, signal: abortController.signal, abort: abort, rejectWithValue: function (value, meta) { return new RejectWithValue(value, meta); }, fulfillWithValue: function (value, meta) { return new FulfillWithMeta(value, meta); } })).then(function (result) { if (result instanceof RejectWithValue) { throw result; } if (result instanceof FulfillWithMeta) { return fulfilled(result.payload, requestId, arg, result.meta); } return fulfilled(result, requestId, arg); }) ])]; case 3: finalAction = _c.sent(); return [3 /*break*/, 5]; case 4: err_1 = _c.sent(); finalAction = err_1 instanceof RejectWithValue ? rejected(null, requestId, arg, err_1.payload, err_1.meta) : rejected(err_1, requestId, arg); return [3 /*break*/, 5]; case 5: skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition; if (!skipDispatch) { dispatch(finalAction); } return [2 /*return*/, finalAction]; } }); }); }(); return Object.assign(promise2, { abort: abort, requestId: requestId, arg: arg, unwrap: function () { return promise2.then(unwrapResult); } }); }; } return Object.assign(actionCreator, { pending: pending, rejected: rejected, fulfilled: fulfilled, typePrefix: typePrefix }); } createAsyncThunk2.withTypes = function () { return createAsyncThunk2; }; return createAsyncThunk2; })(); function unwrapResult(action) { if (action.meta && action.meta.rejectedWithValue) { throw action.payload; } if (action.error) { throw action.error; } return action.payload; } function isThenable(value) { return value !== null && typeof value === "object" && typeof value.then === "function"; } // src/tsHelpers.ts var hasMatchFunction = function (v) { return v && typeof v.match === "function"; }; // src/matchers.ts var matches = function (matcher, action) { if (hasMatchFunction(matcher)) { return matcher.match(action); } else { return matcher(action); } }; function isAnyOf() { var matchers = []; for (var _i = 0; _i < arguments.length; _i++) { matchers[_i] = arguments[_i]; } return function (action) { return matchers.some(function (matcher) { return matches(matcher, action); }); }; } // src/listenerMiddleware/utils.ts var assertFunction = function (func, expected) { if (typeof func !== "function") { throw new TypeError(expected + " is not a function"); } }; var noop$2 = function () { }; var catchRejection = function (promise2, onError) { if (onError === void 0) { onError = noop$2; } promise2.catch(onError); return promise2; }; var addAbortSignalListener = function (abortSignal, callback) { abortSignal.addEventListener("abort", callback, { once: true }); return function () { return abortSignal.removeEventListener("abort", callback); }; }; var abortControllerWithReason = function (abortController, reason) { var signal = abortController.signal; if (signal.aborted) { return; } if (!("reason" in signal)) { Object.defineProperty(signal, "reason", { enumerable: true, value: reason, configurable: true, writable: true }); } abortController.abort(reason); }; // src/listenerMiddleware/exceptions.ts var task = "task"; var listener = "listener"; var completed = "completed"; var cancelled = "cancelled"; var taskCancelled = "task-" + cancelled; var taskCompleted = "task-" + completed; var listenerCancelled = listener + "-" + cancelled; var listenerCompleted = listener + "-" + completed; var TaskAbortError = /** @class */ (function () { function TaskAbortError(code) { this.code = code; this.name = "TaskAbortError"; this.message = task + " " + cancelled + " (reason: " + code + ")"; } return TaskAbortError; }()); // src/listenerMiddleware/task.ts var validateActive = function (signal) { if (signal.aborted) { throw new TaskAbortError(signal.reason); } }; function raceWithSignal(signal, promise2) { var cleanup = noop$2; return new Promise(function (resolve, reject) { var notifyRejection = function () { return reject(new TaskAbortError(signal.reason)); }; if (signal.aborted) { notifyRejection(); return; } cleanup = addAbortSignalListener(signal, notifyRejection); promise2.finally(function () { return cleanup(); }).then(resolve, reject); }).finally(function () { cleanup = noop$2; }); } var runTask = function (task2, cleanUp) { return __async(void 0, null, function () { var value, error_1; return __generator$1(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 3, 4, 5]); return [4 /*yield*/, Promise.resolve()]; case 1: _c.sent(); return [4 /*yield*/, task2()]; case 2: value = _c.sent(); return [2 /*return*/, { status: "ok", value: value }]; case 3: error_1 = _c.sent(); return [2 /*return*/, { status: error_1 instanceof TaskAbortError ? "cancelled" : "rejected", error: error_1 }]; case 4: cleanUp == null ? void 0 : cleanUp(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; var createPause = function (signal) { return function (promise2) { return catchRejection(raceWithSignal(signal, promise2).then(function (output) { validateActive(signal); return output; })); }; }; var createDelay = function (signal) { var pause = createPause(signal); return function (timeoutMs) { return pause(new Promise(function (resolve) { return setTimeout(resolve, timeoutMs); })); }; }; // src/listenerMiddleware/index.ts var assign$1 = Object.assign; var INTERNAL_NIL_TOKEN = {}; var alm = "listenerMiddleware"; var createFork = function (parentAbortSignal) { var linkControllers = function (controller) { return addAbortSignalListener(parentAbortSignal, function () { return abortControllerWithReason(controller, parentAbortSignal.reason); }); }; return function (taskExecutor) { assertFunction(taskExecutor, "taskExecutor"); var childAbortController = new AbortController(); linkControllers(childAbortController); var result = runTask(function () { return __async(void 0, null, function () { var result2; return __generator$1(this, function (_c) { switch (_c.label) { case 0: validateActive(parentAbortSignal); validateActive(childAbortController.signal); return [4 /*yield*/, taskExecutor({ pause: createPause(childAbortController.signal), delay: createDelay(childAbortController.signal), signal: childAbortController.signal })]; case 1: result2 = _c.sent(); validateActive(childAbortController.signal); return [2 /*return*/, result2]; } }); }); }, function () { return abortControllerWithReason(childAbortController, taskCompleted); }); return { result: createPause(parentAbortSignal)(result), cancel: function () { abortControllerWithReason(childAbortController, taskCancelled); } }; }; }; var createTakePattern = function (startListening, signal) { var take = function (predicate, timeout) { return __async(void 0, null, function () { var unsubscribe, tuplePromise, promises, output; return __generator$1(this, function (_c) { switch (_c.label) { case 0: validateActive(signal); unsubscribe = function () { }; tuplePromise = new Promise(function (resolve, reject) { var stopListening = startListening({ predicate: predicate, effect: function (action, listenerApi) { listenerApi.unsubscribe(); resolve([ action, listenerApi.getState(), listenerApi.getOriginalState() ]); } }); unsubscribe = function () { stopListening(); reject(); }; }); promises = [ tuplePromise ]; if (timeout != null) { promises.push(new Promise(function (resolve) { return setTimeout(resolve, timeout, null); })); } _c.label = 1; case 1: _c.trys.push([1, , 3, 4]); return [4 /*yield*/, raceWithSignal(signal, Promise.race(promises))]; case 2: output = _c.sent(); validateActive(signal); return [2 /*return*/, output]; case 3: unsubscribe(); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; return function (predicate, timeout) { return catchRejection(take(predicate, timeout)); }; }; var getListenerEntryPropsFrom = function (options) { var type = options.type, actionCreator = options.actionCreator, matcher = options.matcher, predicate = options.predicate, effect = options.effect; if (type) { predicate = createAction(type).match; } else if (actionCreator) { type = actionCreator.type; predicate = actionCreator.match; } else if (matcher) { predicate = matcher; } else if (predicate) ; else { throw new Error("Creating or removing a listener requires one of the known fields for matching an action"); } assertFunction(effect, "options.listener"); return { predicate: predicate, type: type, effect: effect }; }; var createListenerEntry = function (options) { var _c = getListenerEntryPropsFrom(options), type = _c.type, predicate = _c.predicate, effect = _c.effect; var id = nanoid(); var entry = { id: id, effect: effect, type: type, predicate: predicate, pending: new Set(), unsubscribe: function () { throw new Error("Unsubscribe not initialized"); } }; return entry; }; var cancelActiveListeners = function (entry) { entry.pending.forEach(function (controller) { abortControllerWithReason(controller, listenerCancelled); }); }; var createClearListenerMiddleware = function (listenerMap) { return function () { listenerMap.forEach(cancelActiveListeners); listenerMap.clear(); }; }; var safelyNotifyError = function (errorHandler, errorToNotify, errorInfo) { try { errorHandler(errorToNotify, errorInfo); } catch (errorHandlerError) { setTimeout(function () { throw errorHandlerError; }, 0); } }; var addListener = createAction(alm + "/add"); var clearAllListeners = createAction(alm + "/removeAll"); var removeListener = createAction(alm + "/remove"); var defaultErrorHandler = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } console.error.apply(console, __spreadArray$1([alm + "/error"], args)); }; function createListenerMiddleware(middlewareOptions) { var _this = this; if (middlewareOptions === void 0) { middlewareOptions = {}; } var listenerMap = new Map(); var extra = middlewareOptions.extra, _c = middlewareOptions.onError, onError = _c === void 0 ? defaultErrorHandler : _c; assertFunction(onError, "onError"); var insertEntry = function (entry) { entry.unsubscribe = function () { return listenerMap.delete(entry.id); }; listenerMap.set(entry.id, entry); return function (cancelOptions) { entry.unsubscribe(); if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) { cancelActiveListeners(entry); } }; }; var findListenerEntry = function (comparator) { for (var _i = 0, _c = Array.from(listenerMap.values()); _i < _c.length; _i++) { var entry = _c[_i]; if (comparator(entry)) { return entry; } } return void 0; }; var startListening = function (options) { var entry = findListenerEntry(function (existingEntry) { return existingEntry.effect === options.effect; }); if (!entry) { entry = createListenerEntry(options); } return insertEntry(entry); }; var stopListening = function (options) { var _c = getListenerEntryPropsFrom(options), type = _c.type, effect = _c.effect, predicate = _c.predicate; var entry = findListenerEntry(function (entry2) { var matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate; return matchPredicateOrType && entry2.effect === effect; }); if (entry) { entry.unsubscribe(); if (options.cancelActive) { cancelActiveListeners(entry); } } return !!entry; }; var notifyListener = function (entry, action, api, getOriginalState) { return __async(_this, null, function () { var internalTaskController, take, listenerError_1; return __generator$1(this, function (_c) { switch (_c.label) { case 0: internalTaskController = new AbortController(); take = createTakePattern(startListening, internalTaskController.signal); _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); entry.pending.add(internalTaskController); return [4 /*yield*/, Promise.resolve(entry.effect(action, assign$1({}, api, { getOriginalState: getOriginalState, condition: function (predicate, timeout) { return take(predicate, timeout).then(Boolean); }, take: take, delay: createDelay(internalTaskController.signal), pause: createPause(internalTaskController.signal), extra: extra, signal: internalTaskController.signal, fork: createFork(internalTaskController.signal), unsubscribe: entry.unsubscribe, subscribe: function () { listenerMap.set(entry.id, entry); }, cancelActiveListeners: function () { entry.pending.forEach(function (controller, _, set) { if (controller !== internalTaskController) { abortControllerWithReason(controller, listenerCancelled); set.delete(controller); } }); } })))]; case 2: _c.sent(); return [3 /*break*/, 5]; case 3: listenerError_1 = _c.sent(); if (!(listenerError_1 instanceof TaskAbortError)) { safelyNotifyError(onError, listenerError_1, { raisedBy: "effect" }); } return [3 /*break*/, 5]; case 4: abortControllerWithReason(internalTaskController, listenerCompleted); entry.pending.delete(internalTaskController); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; var clearListenerMiddleware = createClearListenerMiddleware(listenerMap); var middleware = function (api) { return function (next) { return function (action) { if (addListener.match(action)) { return startListening(action.payload); } if (clearAllListeners.match(action)) { clearListenerMiddleware(); return; } if (removeListener.match(action)) { return stopListening(action.payload); } var originalState = api.getState(); var getOriginalState = function () { if (originalState === INTERNAL_NIL_TOKEN) { throw new Error(alm + ": getOriginalState can only be called synchronously"); } return originalState; }; var result; try { result = next(action); if (listenerMap.size > 0) { var currentState = api.getState(); var listenerEntries = Array.from(listenerMap.values()); for (var _i = 0, listenerEntries_1 = listenerEntries; _i < listenerEntries_1.length; _i++) { var entry = listenerEntries_1[_i]; var runListener = false; try { runListener = entry.predicate(action, currentState, originalState); } catch (predicateError) { runListener = false; safelyNotifyError(onError, predicateError, { raisedBy: "predicate" }); } if (!runListener) { continue; } notifyListener(entry, action, api, getOriginalState); } } } finally { originalState = INTERNAL_NIL_TOKEN; } return result; }; }; }; return { middleware: middleware, startListening: startListening, stopListening: stopListening, clearListeners: clearListenerMiddleware }; } var promise; 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 () { throw err; }, 0); }); }; // src/index.ts F(); const initialState$7 = { gameGui: { hoverPixel: { x: 0, y: 0 }, viewScale: 1, viewCenter: { x: 0, y: 0 }, waitDate: new Date() }, canvas: { palette: [], reservedColorCount: 0, id: 0, canvasSize: 1, selectedColor: 0, maxTimeoutMs: 100, timeoutOnBaseMs: 100, timeoutOnPlacedMs: 100, latestPixelReturnCooldownMs: 0 } }; const gameSlice = createSlice({ initialState: initialState$7, name: "game", reducers: { setHoverPixel: (state, action) => { state.gameGui.hoverPixel = action.payload; }, setViewScale: (state, action) => { state.gameGui.viewScale = action.payload; }, setViewCenter: (state, action) => { state.gameGui.viewCenter = action.payload; }, setPalette: (state, action) => { state.canvas.palette = action.payload; }, setReservedColorCount: (state, action) => { state.canvas.reservedColorCount = action.payload; }, setCanvasId: (state, action) => { state.canvas.id = action.payload; }, setCanvasSize: (state, action) => { state.canvas.canvasSize = action.payload; }, setSelectedColor: (state, action) => { state.canvas.selectedColor = action.payload; }, setWaitDate: (state, action) => { state.gameGui.waitDate = action.payload; }, setMaxTimeoutMs: (state, action) => { state.canvas.maxTimeoutMs = action.payload; }, setTimeoutOnBaseMs: (state, action) => { state.canvas.timeoutOnBaseMs = action.payload; }, setTimeoutOnPlacedMs: (state, action) => { state.canvas.timeoutOnPlacedMs = action.payload; }, setLatestPixelReturnCooldown: (state, action) => { state.canvas.latestPixelReturnCooldownMs = action.payload; } } }); createSelector((state) => state.game.canvas.selectedColor, (currentSelectedColor) => currentSelectedColor); const selectHoverPixel = createSelector((state) => state.game.gameGui.hoverPixel, (hoverPixel) => hoverPixel); const selectCanvasReservedColorCount = createSelector((state) => state.game.canvas.reservedColorCount, (reservedColorCount) => reservedColorCount); const selectCanvasPalette = createSelector((state) => state.game.canvas.palette, (palette) => palette); const selectCanvasId = createSelector((state) => state.game.canvas.id, (id) => id); createSelector((state) => state.game.canvas.maxTimeoutMs, (maxTimeoutMs) => maxTimeoutMs); createSelector((state) => state.game.canvas.timeoutOnBaseMs, (timeoutOnBaseMs) => timeoutOnBaseMs); createSelector((state) => state.game.canvas.timeoutOnPlacedMs, (timeoutOnPlacedMs) => timeoutOnPlacedMs); createSelector((state) => state.game.canvas.latestPixelReturnCooldownMs, (latestPixelReturnCooldownMs) => latestPixelReturnCooldownMs); const selectCanvasUserPalette = createSelector(selectCanvasReservedColorCount, selectCanvasPalette, (reservedColorCount, palette) => { return palette.slice(reservedColorCount); }); const selectGameViewCenter = createSelector((state) => state.game.gameGui.viewCenter, (viewCenter) => viewCenter); const selectGameViewScale = createSelector((state) => state.game.gameGui.viewScale, (viewScale) => viewScale); createSelector((state) => state.game.gameGui.waitDate, (waitDate) => waitDate); const selectCanvasSize = createSelector((state) => state.game.canvas.canvasSize, (canvasSize) => canvasSize); const colorConverter = { getClosestColorFromPalette(gamePalette, reservedOffset, r, g, b) { const idx = this.convertActualColorFromPalette(gamePalette, reservedOffset, r, g, b); return this.getActualColorFromPalette(gamePalette, idx); }, convertActualColorFromPalette(gamePalette, reservedOffset, r, g, b) { const resultColorIdx = gamePalette.map((color, i) => { if (i < reservedOffset) return void 0; const difference = Math.sqrt((r - color[0]) ** 2 + (g - color[1]) ** 2 + (b - color[2]) ** 2); return { difference, color, index: i }; }).filter((a) => !!a).map((a) => a).sort((aa, bb) => aa.difference - bb.difference)[0]?.index; if (resultColorIdx === void 0) throw new Error(`Color not found ${r}, ${g}, ${b} from ${JSON.stringify(gamePalette)}`); return resultColorIdx; }, getActualColorFromPalette(gamePalette, color) { const colorData = gamePalette[color]; if (!colorData) return null; return [colorData[0], colorData[1], colorData[2]]; }, areColorsEqual(gamePalette, c1, c2) { if (c1 === c2) { return true; } const color1 = gamePalette[c1]; const color2 = gamePalette[c2]; if (!color1 || !color2) return c1 === c2; let areEqual = true; areEqual = areEqual && color1[0] === color2[0]; areEqual = areEqual && color1[1] === color2[1]; areEqual = areEqual && color1[2] === color2[2]; return areEqual; }, parseColor(colorStr) { const r = parseInt(colorStr.substr(1, 2), 16); const g = parseInt(colorStr.substr(3, 2), 16); const b = parseInt(colorStr.substr(5, 2), 16); return [r, g, b]; } }; var shimExports = {}; var shim = { get exports(){ return shimExports; }, set exports(v){ shimExports = v; }, }; var useSyncExternalStoreShim_production_min = {}; /** * @license React * use-sync-external-store-shim.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var e$2=reactExports;function h$3(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k$2="function"===typeof Object.is?Object.is:h$3,l$2=e$2.useState,m$3=e$2.useEffect,n$3=e$2.useLayoutEffect,p$4=e$2.useDebugValue;function q$3(a,b){var d=b(),f=l$2({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n$3(function(){c.value=d;c.getSnapshot=b;r$3(c)&&g({inst:c});},[a,d,b]);m$3(function(){r$3(c)&&g({inst:c});return a(function(){r$3(c)&&g({inst:c});})},[a]);p$4(d);return d} function r$3(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k$2(a,d)}catch(f){return !0}}function t$3(a,b){return b()}var u$2="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t$3:q$3;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e$2.useSyncExternalStore?e$2.useSyncExternalStore:u$2; (function (module) { { module.exports = useSyncExternalStoreShim_production_min; } } (shim)); var withSelectorExports = {}; var withSelector = { get exports(){ return withSelectorExports; }, set exports(v){ withSelectorExports = v; }, }; var withSelector_production_min = {}; /** * @license React * use-sync-external-store-shim/with-selector.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var h$2=reactExports,n$2=shimExports;function p$3(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q$2="function"===typeof Object.is?Object.is:p$3,r$2=n$2.useSyncExternalStore,t$2=h$2.useRef,u$1=h$2.useEffect,v$3=h$2.useMemo,w$1=h$2.useDebugValue; withSelector_production_min.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t$2(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f;}else f=c.current;c=v$3(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q$2(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return [function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r$2(a,c[0],c[1]); u$1(function(){f.hasValue=!0;f.value=d;},[d]);w$1(d);return d}; (function (module) { { module.exports = withSelector_production_min; } } (withSelector)); var reactDomExports = {}; var reactDom = { get exports(){ return reactDomExports; }, set exports(v){ reactDomExports = v; }, }; var reactDom_production_min = {}; var schedulerExports = {}; var scheduler = { get exports(){ return schedulerExports; }, set exports(v){ schedulerExports = v; }, }; var scheduler_production_min = {}; /** * @license React * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function (exports) { function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; } (scheduler_production_min)); (function (module) { { module.exports = scheduler_production_min; } } (scheduler)); /** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var aa=reactExports,ca=schedulerExports;function p$2(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return !1}function v$2(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z$1={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z$1[a]=new v$2(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z$1[b]=new v$2(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z$1[a]=new v$2(a,2,!1,a.toLowerCase(),null,!1,!1);}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z$1[a]=new v$2(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z$1[a]=new v$2(a,3,!1,a.toLowerCase(),null,!1,!1);}); ["checked","multiple","muted","selected"].forEach(function(a){z$1[a]=new v$2(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z$1[a]=new v$2(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z$1[a]=new v$2(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z$1[a]=new v$2(a,5,!1,a.toLowerCase(),null,!1,!1);});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra, sa);z$1[b]=new v$2(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z$1[b]=new v$2(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z$1[b]=new v$2(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z$1[a]=new v$2(a,1,!1,a.toLowerCase(),null,!1,!1);}); z$1.xlinkHref=new v$2("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z$1[a]=new v$2(a,1,!1,a.toLowerCase(),null,!0,!0);}); function ta(a,b,c,d){var e=z$1.hasOwnProperty(b)?z$1[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ma(a):""} function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return ""}} function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return "Fragment";case wa:return "Portal";case Aa:return "Profiler";case za:return "StrictMode";case Ea:return "Suspense";case Fa:return "SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return (a.displayName||"Context")+".Consumer";case Ba:return (a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName|| b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null} function Ra(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return "Offscreen"; case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return ""}} function Ta(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker= null;delete a[b];}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a));}function Wa(a){if(!a)return !1;var b=a._valueTracker;if(!b)return !0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}} function Ya(a,b){var c=b.checked;return A$1({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1);} function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);} function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);} function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var eb=Array.isArray; function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;} var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a];});});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"} function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var tb=A$1({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p$2(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p$2(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p$2(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p$2(62));}} function vb(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return !1;default:return !0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null; function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p$2(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b));}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a;}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304; function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)));}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b} function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c;}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1; function ge(a,b){switch(a){case "keyup":return -1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return !0;default:return !1}}function he(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case "compositionend":return he(b);case "keypress":if(32!==b.which)return null;fe=!0;return ee;case "textInput":return a=b.data,a===ee&&fe?null:a;default:return null}} function ke(a,b){if(ie)return "compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=Je(c);}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=Xa(a.document);}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c, d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1; function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--);}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b;}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H);}function ag(a,b,c){if(H.current!==Vf)throw Error(p$2(168));G(H,b);G(Wf,c);}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p$2(108,Ra(a)||"Unknown",e));return A$1({},c,d)} function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return !0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p$2(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c);}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a);}function ig(a){fg=!0;hg(a);} function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x;}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x;}if(n.done)return c(e, m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k= f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h);}return g(a);case wa:a:{for(l=f.key;null!== d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=zh(f,a.mode,h);d.return=a;a=d;}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d): (c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p$2(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a);}E(Eh);G(Eh,b);}function Jh(){E(Eh);E(Fh);E(Gh);} function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c));}function Lh(a){Fh.current===a&&(E(Eh),E(Fh));}var M=Uf(0); function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Nh=[]; function Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b();}finally{C=c,Qh.transition=d;}}function Fi(){return di().memoizedState} function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d);}} function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else {var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d));}} function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}} var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308, 4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return [d.memoizedState,a]},useRef:function(a){var b= ci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p$2(407));c=c();}else {c=b();if(null===R)throw Error(p$2(349));0!==(Rh&30)||ni(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d, f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0\x3c/script>",a=a.removeChild(a.firstChild)): "string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);}else {if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering= b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p$2(156,b.tag));} function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p$2(340));Ig();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(), null;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){W(a,b,d);}else c.current=null;}function Nj(a,b,c){try{c();}catch(d){W(a,b,d);}}var Oj=!1; function Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+= q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y;}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode;}q=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break; case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w;}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p$2(163));}}catch(F){W(b,b.return,F);}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return;}n=Oj;Oj=!1;return n} function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f);}e=e.next;}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag} function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling;} function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling;}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling;} function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c);}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0; Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next;}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount();}catch(h){W(c,b,h);}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!== c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c);}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f;}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else {a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p$2(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b);}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c));}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c);} function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p$2(314));}null!==d&&d.delete(b);Zk(a,c);}var Wk; Wk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1;}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue= null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p$2(306, d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p$2(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState= f,b.memoizedState=f,b.flags&256){e=Ki(Error(p$2(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p$2(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c);}b=b.child;}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32), hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps; g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return, c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p$2(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}Yi(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c), b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p$2(156,b.tag));};function Gk(a,b){return ac(a,b)} function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return !(!a||!a.isReactComponent)} function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2} function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11; break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p$2(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a} function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData= null;}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3 batch = newBatch; // Supply a getter just to skip dealing with ESM bindings const getBatch = () => batch; const ReactReduxContext = /*#__PURE__*/reactExports.createContext(null); /** * A hook to access the value of the `ReactReduxContext`. This is a low-level * hook that you should usually not need to call directly. * * @returns {any} the value of the `ReactReduxContext` * * @example * * import React from 'react' * import { useReduxContext } from 'react-redux' * * export const CounterComponent = () => { * const { store } = useReduxContext() * return
{store.getState()}
* } */ function useReduxContext() { const contextValue = reactExports.useContext(ReactReduxContext); return contextValue; } const notInitialized = () => { throw new Error('uSES not initialized!'); }; let useSyncExternalStoreWithSelector = notInitialized; const initializeUseSelector = fn => { useSyncExternalStoreWithSelector = fn; }; const refEquality = (a, b) => a === b; /** * Hook factory, which creates a `useSelector` hook bound to a given context. * * @param {React.Context} [context=ReactReduxContext] Context passed to your ``. * @returns {Function} A `useSelector` hook bound to the specified context. */ function createSelectorHook(context = ReactReduxContext) { const useReduxContext$1 = context === ReactReduxContext ? useReduxContext : () => reactExports.useContext(context); return function useSelector(selector, equalityFn = refEquality) { const { store, subscription, getServerState } = useReduxContext$1(); const selectedState = useSyncExternalStoreWithSelector(subscription.addNestedSub, store.getState, getServerState || store.getState, selector, equalityFn); reactExports.useDebugValue(selectedState); return selectedState; }; } /** * A hook to access the redux store's state. This hook takes a selector function * as an argument. The selector is called with the store state. * * This hook takes an optional equality comparison function as the second parameter * that allows you to customize the way the selected state is compared to determine * whether the component needs to be re-rendered. * * @param {Function} selector the selector function * @param {Function=} equalityFn the function that will be used to determine equality * * @returns {any} the selected state * * @example * * import React from 'react' * import { useSelector } from 'react-redux' * * export const CounterComponent = () => { * const counter = useSelector(state => state.counter) * return
{counter}
* } */ const useSelector = /*#__PURE__*/createSelectorHook(); function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose$2(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var reactIsExports$1 = {}; var reactIs$2 = { get exports(){ return reactIsExports$1; }, set exports(v){ reactIsExports$1 = v; }, }; var reactIs_production_min$1 = {}; /** @license React v16.13.1 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var b$1="function"===typeof Symbol&&Symbol.for,c$1=b$1?Symbol.for("react.element"):60103,d$1=b$1?Symbol.for("react.portal"):60106,e$1=b$1?Symbol.for("react.fragment"):60107,f$1=b$1?Symbol.for("react.strict_mode"):60108,g$1=b$1?Symbol.for("react.profiler"):60114,h$1=b$1?Symbol.for("react.provider"):60109,k$1=b$1?Symbol.for("react.context"):60110,l$1=b$1?Symbol.for("react.async_mode"):60111,m$2=b$1?Symbol.for("react.concurrent_mode"):60111,n$1=b$1?Symbol.for("react.forward_ref"):60112,p$1=b$1?Symbol.for("react.suspense"):60113,q$1=b$1? Symbol.for("react.suspense_list"):60120,r$1=b$1?Symbol.for("react.memo"):60115,t$1=b$1?Symbol.for("react.lazy"):60116,v$1=b$1?Symbol.for("react.block"):60121,w=b$1?Symbol.for("react.fundamental"):60117,x=b$1?Symbol.for("react.responder"):60118,y=b$1?Symbol.for("react.scope"):60119; function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c$1:switch(a=a.type,a){case l$1:case m$2:case e$1:case g$1:case f$1:case p$1:return a;default:switch(a=a&&a.$$typeof,a){case k$1:case n$1:case t$1:case r$1:case h$1:return a;default:return u}}case d$1:return u}}}function A(a){return z(a)===m$2}reactIs_production_min$1.AsyncMode=l$1;reactIs_production_min$1.ConcurrentMode=m$2;reactIs_production_min$1.ContextConsumer=k$1;reactIs_production_min$1.ContextProvider=h$1;reactIs_production_min$1.Element=c$1;reactIs_production_min$1.ForwardRef=n$1;reactIs_production_min$1.Fragment=e$1;reactIs_production_min$1.Lazy=t$1;reactIs_production_min$1.Memo=r$1;reactIs_production_min$1.Portal=d$1; reactIs_production_min$1.Profiler=g$1;reactIs_production_min$1.StrictMode=f$1;reactIs_production_min$1.Suspense=p$1;reactIs_production_min$1.isAsyncMode=function(a){return A(a)||z(a)===l$1};reactIs_production_min$1.isConcurrentMode=A;reactIs_production_min$1.isContextConsumer=function(a){return z(a)===k$1};reactIs_production_min$1.isContextProvider=function(a){return z(a)===h$1};reactIs_production_min$1.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c$1};reactIs_production_min$1.isForwardRef=function(a){return z(a)===n$1};reactIs_production_min$1.isFragment=function(a){return z(a)===e$1};reactIs_production_min$1.isLazy=function(a){return z(a)===t$1}; reactIs_production_min$1.isMemo=function(a){return z(a)===r$1};reactIs_production_min$1.isPortal=function(a){return z(a)===d$1};reactIs_production_min$1.isProfiler=function(a){return z(a)===g$1};reactIs_production_min$1.isStrictMode=function(a){return z(a)===f$1};reactIs_production_min$1.isSuspense=function(a){return z(a)===p$1}; reactIs_production_min$1.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e$1||a===m$2||a===g$1||a===f$1||a===p$1||a===q$1||"object"===typeof a&&null!==a&&(a.$$typeof===t$1||a.$$typeof===r$1||a.$$typeof===h$1||a.$$typeof===k$1||a.$$typeof===n$1||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v$1)};reactIs_production_min$1.typeOf=z; (function (module) { { module.exports = reactIs_production_min$1; } } (reactIs$2)); var reactIs$1 = reactIsExports$1; var FORWARD_REF_STATICS = { '$$typeof': true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { '$$typeof': true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = {}; TYPE_STATICS[reactIs$1.ForwardRef] = FORWARD_REF_STATICS; TYPE_STATICS[reactIs$1.Memo] = MEMO_STATICS; var reactIsExports = {}; var reactIs = { get exports(){ return reactIsExports; }, set exports(v){ reactIsExports = v; }, }; var reactIs_production_min = {}; /** * @license React * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var b=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m$1=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference"); function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m$1:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=g;reactIs_production_min.Element=b;reactIs_production_min.ForwardRef=l;reactIs_production_min.Fragment=d;reactIs_production_min.Lazy=q;reactIs_production_min.Memo=p;reactIs_production_min.Portal=c;reactIs_production_min.Profiler=f;reactIs_production_min.StrictMode=e;reactIs_production_min.Suspense=m$1; reactIs_production_min.SuspenseList=n;reactIs_production_min.isAsyncMode=function(){return !1};reactIs_production_min.isConcurrentMode=function(){return !1};reactIs_production_min.isContextConsumer=function(a){return v(a)===h};reactIs_production_min.isContextProvider=function(a){return v(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return v(a)===l};reactIs_production_min.isFragment=function(a){return v(a)===d};reactIs_production_min.isLazy=function(a){return v(a)===q};reactIs_production_min.isMemo=function(a){return v(a)===p}; reactIs_production_min.isPortal=function(a){return v(a)===c};reactIs_production_min.isProfiler=function(a){return v(a)===f};reactIs_production_min.isStrictMode=function(a){return v(a)===e};reactIs_production_min.isSuspense=function(a){return v(a)===m$1};reactIs_production_min.isSuspenseList=function(a){return v(a)===n}; reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m$1||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?!0:!1};reactIs_production_min.typeOf=v; (function (module) { { module.exports = reactIs_production_min; } } (reactIs)); // well as nesting subscriptions of descendant components, so that we can ensure the // ancestor components re-render before descendants function createListenerCollection() { const batch = getBatch(); let first = null; let last = null; return { clear() { first = null; last = null; }, notify() { batch(() => { let listener = first; while (listener) { listener.callback(); listener = listener.next; } }); }, get() { let listeners = []; let listener = first; while (listener) { listeners.push(listener); listener = listener.next; } return listeners; }, subscribe(callback) { let isSubscribed = true; let listener = last = { callback, next: null, prev: last }; if (listener.prev) { listener.prev.next = listener; } else { first = listener; } return function unsubscribe() { if (!isSubscribed || first === null) return; isSubscribed = false; if (listener.next) { listener.next.prev = listener.prev; } else { last = listener.prev; } if (listener.prev) { listener.prev.next = listener.next; } else { first = listener.next; } }; } }; } const nullListeners = { notify() {}, get: () => [] }; function createSubscription(store, parentSub) { let unsubscribe; let listeners = nullListeners; function addNestedSub(listener) { trySubscribe(); return listeners.subscribe(listener); } function notifyNestedSubs() { listeners.notify(); } function handleChangeWrapper() { if (subscription.onStateChange) { subscription.onStateChange(); } } function isSubscribed() { return Boolean(unsubscribe); } function trySubscribe() { if (!unsubscribe) { unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper); listeners = createListenerCollection(); } } function tryUnsubscribe() { if (unsubscribe) { unsubscribe(); unsubscribe = undefined; listeners.clear(); listeners = nullListeners; } } const subscription = { addNestedSub, notifyNestedSubs, handleChangeWrapper, isSubscribed, trySubscribe, tryUnsubscribe, getListeners: () => listeners }; return subscription; } // To get around it, we can conditionally useEffect on the server (no-op) and // useLayoutEffect in the browser. We need useLayoutEffect to ensure the store // subscription callback always has the selector from the latest render commit // available, otherwise a store update may happen between render and the effect, // which may cause missed updates; we also must ensure the store subscription // is created synchronously, otherwise a store update may occur before the // subscription is created and an inconsistent state may be observed // Matches logic in React's `shared/ExecutionEnvironment` file const canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); const useIsomorphicLayoutEffect = canUseDOM ? reactExports.useLayoutEffect : reactExports.useEffect; function Provider({ store, context, children, serverState }) { const contextValue = reactExports.useMemo(() => { const subscription = createSubscription(store); return { store, subscription, getServerState: serverState ? () => serverState : undefined }; }, [store, serverState]); const previousState = reactExports.useMemo(() => store.getState(), [store]); useIsomorphicLayoutEffect(() => { const { subscription } = contextValue; subscription.onStateChange = subscription.notifyNestedSubs; subscription.trySubscribe(); if (previousState !== store.getState()) { subscription.notifyNestedSubs(); } return () => { subscription.tryUnsubscribe(); subscription.onStateChange = undefined; }; }, [contextValue, previousState]); const Context = context || ReactReduxContext; // @ts-ignore 'AnyAction' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype return /*#__PURE__*/React.createElement(Context.Provider, { value: contextValue }, children); } /** * Hook factory, which creates a `useStore` hook bound to a given context. * * @param {React.Context} [context=ReactReduxContext] Context passed to your ``. * @returns {Function} A `useStore` hook bound to the specified context. */ function createStoreHook(context = ReactReduxContext) { const useReduxContext$1 = // @ts-ignore context === ReactReduxContext ? useReduxContext : () => reactExports.useContext(context); return function useStore() { const { store } = useReduxContext$1(); // @ts-ignore return store; }; } /** * A hook to access the redux store. * * @returns {any} the redux store * * @example * * import React from 'react' * import { useStore } from 'react-redux' * * export const ExampleComponent = () => { * const store = useStore() * return
{store.getState()}
* } */ const useStore = /*#__PURE__*/createStoreHook(); /** * Hook factory, which creates a `useDispatch` hook bound to a given context. * * @param {React.Context} [context=ReactReduxContext] Context passed to your ``. * @returns {Function} A `useDispatch` hook bound to the specified context. */ function createDispatchHook(context = ReactReduxContext) { const useStore$1 = // @ts-ignore context === ReactReduxContext ? useStore : createStoreHook(context); return function useDispatch() { const store = useStore$1(); // @ts-ignore return store.dispatch; }; } /** * A hook to access the redux `dispatch` function. * * @returns {any|function} redux store's `dispatch` function * * @example * * import React, { useCallback } from 'react' * import { useDispatch } from 'react-redux' * * export const CounterComponent = ({ value }) => { * const dispatch = useDispatch() * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), []) * return ( *
* {value} * *
* ) * } */ const useDispatch = /*#__PURE__*/createDispatchHook(); // The primary entry point assumes we're working with standard ReactDOM/RN, but initializeUseSelector(withSelectorExports.useSyncExternalStoreWithSelector); // with standard React renderers (ReactDOM, React Native) setBatch(reactDomExports.unstable_batchedUpdates); const useAppDispatch = () => useDispatch(); const useAppSelector = useSelector; /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ const proxyMarker = Symbol("Comlink.proxy"); const createEndpoint = Symbol("Comlink.endpoint"); const releaseProxy = Symbol("Comlink.releaseProxy"); const finalizer = Symbol("Comlink.finalizer"); const throwMarker = Symbol("Comlink.thrown"); const isObject$1 = (val) => (typeof val === "object" && val !== null) || typeof val === "function"; /** * Internal transfer handle to handle objects marked to proxy. */ const proxyTransferHandler = { canHandle: (val) => isObject$1(val) && val[proxyMarker], serialize(obj) { const { port1, port2 } = new MessageChannel(); expose(obj, port1); return [port2, [port2]]; }, deserialize(port) { port.start(); return wrap(port); }, }; /** * Internal transfer handler to handle thrown exceptions. */ const throwTransferHandler = { canHandle: (value) => isObject$1(value) && throwMarker in value, serialize({ value }) { let serialized; if (value instanceof Error) { serialized = { isError: true, value: { message: value.message, name: value.name, stack: value.stack, }, }; } else { serialized = { isError: false, value }; } return [serialized, []]; }, deserialize(serialized) { if (serialized.isError) { throw Object.assign(new Error(serialized.value.message), serialized.value); } throw serialized.value; }, }; /** * Allows customizing the serialization of certain values. */ const transferHandlers = new Map([ ["proxy", proxyTransferHandler], ["throw", throwTransferHandler], ]); function isAllowedOrigin(allowedOrigins, origin) { for (const allowedOrigin of allowedOrigins) { if (origin === allowedOrigin || allowedOrigin === "*") { return true; } if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) { return true; } } return false; } function expose(obj, ep = self, allowedOrigins = ["*"]) { ep.addEventListener("message", function callback(ev) { if (!ev || !ev.data) { return; } if (!isAllowedOrigin(allowedOrigins, ev.origin)) { console.warn(`Invalid origin '${ev.origin}' for comlink proxy`); return; } const { id, type, path } = Object.assign({ path: [] }, ev.data); const argumentList = (ev.data.argumentList || []).map(fromWireValue); let returnValue; try { const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj); const rawValue = path.reduce((obj, prop) => obj[prop], obj); switch (type) { case "GET" /* MessageType.GET */: { returnValue = rawValue; } break; case "SET" /* MessageType.SET */: { parent[path.slice(-1)[0]] = fromWireValue(ev.data.value); returnValue = true; } break; case "APPLY" /* MessageType.APPLY */: { returnValue = rawValue.apply(parent, argumentList); } break; case "CONSTRUCT" /* MessageType.CONSTRUCT */: { const value = new rawValue(...argumentList); returnValue = proxy(value); } break; case "ENDPOINT" /* MessageType.ENDPOINT */: { const { port1, port2 } = new MessageChannel(); expose(obj, port2); returnValue = transfer(port1, [port1]); } break; case "RELEASE" /* MessageType.RELEASE */: { returnValue = undefined; } break; default: return; } } catch (value) { returnValue = { value, [throwMarker]: 0 }; } Promise.resolve(returnValue) .catch((value) => { return { value, [throwMarker]: 0 }; }) .then((returnValue) => { const [wireValue, transferables] = toWireValue(returnValue); ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables); if (type === "RELEASE" /* MessageType.RELEASE */) { // detach and deactive after sending release response above. ep.removeEventListener("message", callback); closeEndPoint(ep); if (finalizer in obj && typeof obj[finalizer] === "function") { obj[finalizer](); } } }) .catch((error) => { // Send Serialization Error To Caller const [wireValue, transferables] = toWireValue({ value: new TypeError("Unserializable return value"), [throwMarker]: 0, }); ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables); }); }); if (ep.start) { ep.start(); } } function isMessagePort(endpoint) { return endpoint.constructor.name === "MessagePort"; } function closeEndPoint(endpoint) { if (isMessagePort(endpoint)) endpoint.close(); } function wrap(ep, target) { return createProxy(ep, [], target); } function throwIfProxyReleased(isReleased) { if (isReleased) { throw new Error("Proxy has been released and is not useable"); } } function releaseEndpoint(ep) { return requestResponseMessage(ep, { type: "RELEASE" /* MessageType.RELEASE */, }).then(() => { closeEndPoint(ep); }); } const proxyCounter = new WeakMap(); const proxyFinalizers = "FinalizationRegistry" in self && new FinalizationRegistry((ep) => { const newCount = (proxyCounter.get(ep) || 0) - 1; proxyCounter.set(ep, newCount); if (newCount === 0) { releaseEndpoint(ep); } }); function registerProxy(proxy, ep) { const newCount = (proxyCounter.get(ep) || 0) + 1; proxyCounter.set(ep, newCount); if (proxyFinalizers) { proxyFinalizers.register(proxy, ep, proxy); } } function unregisterProxy(proxy) { if (proxyFinalizers) { proxyFinalizers.unregister(proxy); } } function createProxy(ep, path = [], target = function () { }) { let isProxyReleased = false; const proxy = new Proxy(target, { get(_target, prop) { throwIfProxyReleased(isProxyReleased); if (prop === releaseProxy) { return () => { unregisterProxy(proxy); releaseEndpoint(ep); isProxyReleased = true; }; } if (prop === "then") { if (path.length === 0) { return { then: () => proxy }; } const r = requestResponseMessage(ep, { type: "GET" /* MessageType.GET */, path: path.map((p) => p.toString()), }).then(fromWireValue); return r.then.bind(r); } return createProxy(ep, [...path, prop]); }, set(_target, prop, rawValue) { throwIfProxyReleased(isProxyReleased); // FIXME: ES6 Proxy Handler `set` methods are supposed to return a // boolean. To show good will, we return true asynchronously ¯\_(ツ)_/¯ const [value, transferables] = toWireValue(rawValue); return requestResponseMessage(ep, { type: "SET" /* MessageType.SET */, path: [...path, prop].map((p) => p.toString()), value, }, transferables).then(fromWireValue); }, apply(_target, _thisArg, rawArgumentList) { throwIfProxyReleased(isProxyReleased); const last = path[path.length - 1]; if (last === createEndpoint) { return requestResponseMessage(ep, { type: "ENDPOINT" /* MessageType.ENDPOINT */, }).then(fromWireValue); } // We just pretend that `bind()` didn’t happen. if (last === "bind") { return createProxy(ep, path.slice(0, -1)); } const [argumentList, transferables] = processArguments(rawArgumentList); return requestResponseMessage(ep, { type: "APPLY" /* MessageType.APPLY */, path: path.map((p) => p.toString()), argumentList, }, transferables).then(fromWireValue); }, construct(_target, rawArgumentList) { throwIfProxyReleased(isProxyReleased); const [argumentList, transferables] = processArguments(rawArgumentList); return requestResponseMessage(ep, { type: "CONSTRUCT" /* MessageType.CONSTRUCT */, path: path.map((p) => p.toString()), argumentList, }, transferables).then(fromWireValue); }, }); registerProxy(proxy, ep); return proxy; } function myFlat(arr) { return Array.prototype.concat.apply([], arr); } function processArguments(argumentList) { const processed = argumentList.map(toWireValue); return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))]; } const transferCache = new WeakMap(); function transfer(obj, transfers) { transferCache.set(obj, transfers); return obj; } function proxy(obj) { return Object.assign(obj, { [proxyMarker]: true }); } function toWireValue(value) { for (const [name, handler] of transferHandlers) { if (handler.canHandle(value)) { const [serializedValue, transferables] = handler.serialize(value); return [ { type: "HANDLER" /* WireValueType.HANDLER */, name, value: serializedValue, }, transferables, ]; } } return [ { type: "RAW" /* WireValueType.RAW */, value, }, transferCache.get(value) || [], ]; } function fromWireValue(value) { switch (value.type) { case "HANDLER" /* WireValueType.HANDLER */: return transferHandlers.get(value.name).deserialize(value.value); case "RAW" /* WireValueType.RAW */: return value.value; } } function requestResponseMessage(ep, msg, transfers) { return new Promise((resolve) => { const id = generateUUID(); ep.addEventListener("message", function l(ev) { if (!ev.data || !ev.data.id || ev.data.id !== id) { return; } ep.removeEventListener("message", l); resolve(ev.data); }); if (ep.start) { ep.start(); } ep.postMessage(Object.assign({ id }, msg), transfers); }); } function generateUUID() { return new Array(4) .fill(0) .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)) .join("-"); } const encodedJs = "KGZ1bmN0aW9uICgpIHsKICAgICd1c2Ugc3RyaWN0JzsKCiAgICAvKioKICAgICAqIEBsaWNlbnNlCiAgICAgKiBDb3B5cmlnaHQgMjAxOSBHb29nbGUgTExDCiAgICAgKiBTUERYLUxpY2Vuc2UtSWRlbnRpZmllcjogQXBhY2hlLTIuMAogICAgICovCiAgICBjb25zdCBwcm94eU1hcmtlciA9IFN5bWJvbCgiQ29tbGluay5wcm94eSIpOwogICAgY29uc3QgY3JlYXRlRW5kcG9pbnQgPSBTeW1ib2woIkNvbWxpbmsuZW5kcG9pbnQiKTsKICAgIGNvbnN0IHJlbGVhc2VQcm94eSA9IFN5bWJvbCgiQ29tbGluay5yZWxlYXNlUHJveHkiKTsKICAgIGNvbnN0IGZpbmFsaXplciA9IFN5bWJvbCgiQ29tbGluay5maW5hbGl6ZXIiKTsKICAgIGNvbnN0IHRocm93TWFya2VyID0gU3ltYm9sKCJDb21saW5rLnRocm93biIpOwogICAgY29uc3QgaXNPYmplY3QgPSAodmFsKSA9PiAodHlwZW9mIHZhbCA9PT0gIm9iamVjdCIgJiYgdmFsICE9PSBudWxsKSB8fCB0eXBlb2YgdmFsID09PSAiZnVuY3Rpb24iOwogICAgLyoqCiAgICAgKiBJbnRlcm5hbCB0cmFuc2ZlciBoYW5kbGUgdG8gaGFuZGxlIG9iamVjdHMgbWFya2VkIHRvIHByb3h5LgogICAgICovCiAgICBjb25zdCBwcm94eVRyYW5zZmVySGFuZGxlciA9IHsKICAgICAgICBjYW5IYW5kbGU6ICh2YWwpID0+IGlzT2JqZWN0KHZhbCkgJiYgdmFsW3Byb3h5TWFya2VyXSwKICAgICAgICBzZXJpYWxpemUob2JqKSB7CiAgICAgICAgICAgIGNvbnN0IHsgcG9ydDEsIHBvcnQyIH0gPSBuZXcgTWVzc2FnZUNoYW5uZWwoKTsKICAgICAgICAgICAgZXhwb3NlKG9iaiwgcG9ydDEpOwogICAgICAgICAgICByZXR1cm4gW3BvcnQyLCBbcG9ydDJdXTsKICAgICAgICB9LAogICAgICAgIGRlc2VyaWFsaXplKHBvcnQpIHsKICAgICAgICAgICAgcG9ydC5zdGFydCgpOwogICAgICAgICAgICByZXR1cm4gd3JhcChwb3J0KTsKICAgICAgICB9LAogICAgfTsKICAgIC8qKgogICAgICogSW50ZXJuYWwgdHJhbnNmZXIgaGFuZGxlciB0byBoYW5kbGUgdGhyb3duIGV4Y2VwdGlvbnMuCiAgICAgKi8KICAgIGNvbnN0IHRocm93VHJhbnNmZXJIYW5kbGVyID0gewogICAgICAgIGNhbkhhbmRsZTogKHZhbHVlKSA9PiBpc09iamVjdCh2YWx1ZSkgJiYgdGhyb3dNYXJrZXIgaW4gdmFsdWUsCiAgICAgICAgc2VyaWFsaXplKHsgdmFsdWUgfSkgewogICAgICAgICAgICBsZXQgc2VyaWFsaXplZDsKICAgICAgICAgICAgaWYgKHZhbHVlIGluc3RhbmNlb2YgRXJyb3IpIHsKICAgICAgICAgICAgICAgIHNlcmlhbGl6ZWQgPSB7CiAgICAgICAgICAgICAgICAgICAgaXNFcnJvcjogdHJ1ZSwKICAgICAgICAgICAgICAgICAgICB2YWx1ZTogewogICAgICAgICAgICAgICAgICAgICAgICBtZXNzYWdlOiB2YWx1ZS5tZXNzYWdlLAogICAgICAgICAgICAgICAgICAgICAgICBuYW1lOiB2YWx1ZS5uYW1lLAogICAgICAgICAgICAgICAgICAgICAgICBzdGFjazogdmFsdWUuc3RhY2ssCiAgICAgICAgICAgICAgICAgICAgfSwKICAgICAgICAgICAgICAgIH07CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBzZXJpYWxpemVkID0geyBpc0Vycm9yOiBmYWxzZSwgdmFsdWUgfTsKICAgICAgICAgICAgfQogICAgICAgICAgICByZXR1cm4gW3NlcmlhbGl6ZWQsIFtdXTsKICAgICAgICB9LAogICAgICAgIGRlc2VyaWFsaXplKHNlcmlhbGl6ZWQpIHsKICAgICAgICAgICAgaWYgKHNlcmlhbGl6ZWQuaXNFcnJvcikgewogICAgICAgICAgICAgICAgdGhyb3cgT2JqZWN0LmFzc2lnbihuZXcgRXJyb3Ioc2VyaWFsaXplZC52YWx1ZS5tZXNzYWdlKSwgc2VyaWFsaXplZC52YWx1ZSk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgdGhyb3cgc2VyaWFsaXplZC52YWx1ZTsKICAgICAgICB9LAogICAgfTsKICAgIC8qKgogICAgICogQWxsb3dzIGN1c3RvbWl6aW5nIHRoZSBzZXJpYWxpemF0aW9uIG9mIGNlcnRhaW4gdmFsdWVzLgogICAgICovCiAgICBjb25zdCB0cmFuc2ZlckhhbmRsZXJzID0gbmV3IE1hcChbCiAgICAgICAgWyJwcm94eSIsIHByb3h5VHJhbnNmZXJIYW5kbGVyXSwKICAgICAgICBbInRocm93IiwgdGhyb3dUcmFuc2ZlckhhbmRsZXJdLAogICAgXSk7CiAgICBmdW5jdGlvbiBpc0FsbG93ZWRPcmlnaW4oYWxsb3dlZE9yaWdpbnMsIG9yaWdpbikgewogICAgICAgIGZvciAoY29uc3QgYWxsb3dlZE9yaWdpbiBvZiBhbGxvd2VkT3JpZ2lucykgewogICAgICAgICAgICBpZiAob3JpZ2luID09PSBhbGxvd2VkT3JpZ2luIHx8IGFsbG93ZWRPcmlnaW4gPT09ICIqIikgewogICAgICAgICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGFsbG93ZWRPcmlnaW4gaW5zdGFuY2VvZiBSZWdFeHAgJiYgYWxsb3dlZE9yaWdpbi50ZXN0KG9yaWdpbikpIHsKICAgICAgICAgICAgICAgIHJldHVybiB0cnVlOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIHJldHVybiBmYWxzZTsKICAgIH0KICAgIGZ1bmN0aW9uIGV4cG9zZShvYmosIGVwID0gc2VsZiwgYWxsb3dlZE9yaWdpbnMgPSBbIioiXSkgewogICAgICAgIGVwLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLCBmdW5jdGlvbiBjYWxsYmFjayhldikgewogICAgICAgICAgICBpZiAoIWV2IHx8ICFldi5kYXRhKSB7CiAgICAgICAgICAgICAgICByZXR1cm47CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKCFpc0FsbG93ZWRPcmlnaW4oYWxsb3dlZE9yaWdpbnMsIGV2Lm9yaWdpbikpIHsKICAgICAgICAgICAgICAgIGNvbnNvbGUud2FybihgSW52YWxpZCBvcmlnaW4gJyR7ZXYub3JpZ2lufScgZm9yIGNvbWxpbmsgcHJveHlgKTsKICAgICAgICAgICAgICAgIHJldHVybjsKICAgICAgICAgICAgfQogICAgICAgICAgICBjb25zdCB7IGlkLCB0eXBlLCBwYXRoIH0gPSBPYmplY3QuYXNzaWduKHsgcGF0aDogW10gfSwgZXYuZGF0YSk7CiAgICAgICAgICAgIGNvbnN0IGFyZ3VtZW50TGlzdCA9IChldi5kYXRhLmFyZ3VtZW50TGlzdCB8fCBbXSkubWFwKGZyb21XaXJlVmFsdWUpOwogICAgICAgICAgICBsZXQgcmV0dXJuVmFsdWU7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgICBjb25zdCBwYXJlbnQgPSBwYXRoLnNsaWNlKDAsIC0xKS5yZWR1Y2UoKG9iaiwgcHJvcCkgPT4gb2JqW3Byb3BdLCBvYmopOwogICAgICAgICAgICAgICAgY29uc3QgcmF3VmFsdWUgPSBwYXRoLnJlZHVjZSgob2JqLCBwcm9wKSA9PiBvYmpbcHJvcF0sIG9iaik7CiAgICAgICAgICAgICAgICBzd2l0Y2ggKHR5cGUpIHsKICAgICAgICAgICAgICAgICAgICBjYXNlICJHRVQiIC8qIE1lc3NhZ2VUeXBlLkdFVCAqLzoKICAgICAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuVmFsdWUgPSByYXdWYWx1ZTsKICAgICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICAgICAgICBjYXNlICJTRVQiIC8qIE1lc3NhZ2VUeXBlLlNFVCAqLzoKICAgICAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgICAgICAgcGFyZW50W3BhdGguc2xpY2UoLTEpWzBdXSA9IGZyb21XaXJlVmFsdWUoZXYuZGF0YS52YWx1ZSk7CiAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm5WYWx1ZSA9IHRydWU7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgICAgY2FzZSAiQVBQTFkiIC8qIE1lc3NhZ2VUeXBlLkFQUExZICovOgogICAgICAgICAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm5WYWx1ZSA9IHJhd1ZhbHVlLmFwcGx5KHBhcmVudCwgYXJndW1lbnRMaXN0KTsKICAgICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICAgICAgICBjYXNlICJDT05TVFJVQ1QiIC8qIE1lc3NhZ2VUeXBlLkNPTlNUUlVDVCAqLzoKICAgICAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgICAgICAgY29uc3QgdmFsdWUgPSBuZXcgcmF3VmFsdWUoLi4uYXJndW1lbnRMaXN0KTsKICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVyblZhbHVlID0gcHJveHkodmFsdWUpOwogICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICAgICAgICAgIGNhc2UgIkVORFBPSU5UIiAvKiBNZXNzYWdlVHlwZS5FTkRQT0lOVCAqLzoKICAgICAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgICAgICAgY29uc3QgeyBwb3J0MSwgcG9ydDIgfSA9IG5ldyBNZXNzYWdlQ2hhbm5lbCgpOwogICAgICAgICAgICAgICAgICAgICAgICAgICAgZXhwb3NlKG9iaiwgcG9ydDIpOwogICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuVmFsdWUgPSB0cmFuc2Zlcihwb3J0MSwgW3BvcnQxXSk7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgICAgY2FzZSAiUkVMRUFTRSIgLyogTWVzc2FnZVR5cGUuUkVMRUFTRSAqLzoKICAgICAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuVmFsdWUgPSB1bmRlZmluZWQ7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGNhdGNoICh2YWx1ZSkgewogICAgICAgICAgICAgICAgcmV0dXJuVmFsdWUgPSB7IHZhbHVlLCBbdGhyb3dNYXJrZXJdOiAwIH07CiAgICAgICAgICAgIH0KICAgICAgICAgICAgUHJvbWlzZS5yZXNvbHZlKHJldHVyblZhbHVlKQogICAgICAgICAgICAgICAgLmNhdGNoKCh2YWx1ZSkgPT4gewogICAgICAgICAgICAgICAgcmV0dXJuIHsgdmFsdWUsIFt0aHJvd01hcmtlcl06IDAgfTsKICAgICAgICAgICAgfSkKICAgICAgICAgICAgICAgIC50aGVuKChyZXR1cm5WYWx1ZSkgPT4gewogICAgICAgICAgICAgICAgY29uc3QgW3dpcmVWYWx1ZSwgdHJhbnNmZXJhYmxlc10gPSB0b1dpcmVWYWx1ZShyZXR1cm5WYWx1ZSk7CiAgICAgICAgICAgICAgICBlcC5wb3N0TWVzc2FnZShPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sIHdpcmVWYWx1ZSksIHsgaWQgfSksIHRyYW5zZmVyYWJsZXMpOwogICAgICAgICAgICAgICAgaWYgKHR5cGUgPT09ICJSRUxFQVNFIiAvKiBNZXNzYWdlVHlwZS5SRUxFQVNFICovKSB7CiAgICAgICAgICAgICAgICAgICAgLy8gZGV0YWNoIGFuZCBkZWFjdGl2ZSBhZnRlciBzZW5kaW5nIHJlbGVhc2UgcmVzcG9uc2UgYWJvdmUuCiAgICAgICAgICAgICAgICAgICAgZXAucmVtb3ZlRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsIGNhbGxiYWNrKTsKICAgICAgICAgICAgICAgICAgICBjbG9zZUVuZFBvaW50KGVwKTsKICAgICAgICAgICAgICAgICAgICBpZiAoZmluYWxpemVyIGluIG9iaiAmJiB0eXBlb2Ygb2JqW2ZpbmFsaXplcl0gPT09ICJmdW5jdGlvbiIpIHsKICAgICAgICAgICAgICAgICAgICAgICAgb2JqW2ZpbmFsaXplcl0oKTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0pCiAgICAgICAgICAgICAgICAuY2F0Y2goKGVycm9yKSA9PiB7CiAgICAgICAgICAgICAgICAvLyBTZW5kIFNlcmlhbGl6YXRpb24gRXJyb3IgVG8gQ2FsbGVyCiAgICAgICAgICAgICAgICBjb25zdCBbd2lyZVZhbHVlLCB0cmFuc2ZlcmFibGVzXSA9IHRvV2lyZVZhbHVlKHsKICAgICAgICAgICAgICAgICAgICB2YWx1ZTogbmV3IFR5cGVFcnJvcigiVW5zZXJpYWxpemFibGUgcmV0dXJuIHZhbHVlIiksCiAgICAgICAgICAgICAgICAgICAgW3Rocm93TWFya2VyXTogMCwKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgZXAucG9zdE1lc3NhZ2UoT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LCB3aXJlVmFsdWUpLCB7IGlkIH0pLCB0cmFuc2ZlcmFibGVzKTsKICAgICAgICAgICAgfSk7CiAgICAgICAgfSk7CiAgICAgICAgaWYgKGVwLnN0YXJ0KSB7CiAgICAgICAgICAgIGVwLnN0YXJ0KCk7CiAgICAgICAgfQogICAgfQogICAgZnVuY3Rpb24gaXNNZXNzYWdlUG9ydChlbmRwb2ludCkgewogICAgICAgIHJldHVybiBlbmRwb2ludC5jb25zdHJ1Y3Rvci5uYW1lID09PSAiTWVzc2FnZVBvcnQiOwogICAgfQogICAgZnVuY3Rpb24gY2xvc2VFbmRQb2ludChlbmRwb2ludCkgewogICAgICAgIGlmIChpc01lc3NhZ2VQb3J0KGVuZHBvaW50KSkKICAgICAgICAgICAgZW5kcG9pbnQuY2xvc2UoKTsKICAgIH0KICAgIGZ1bmN0aW9uIHdyYXAoZXAsIHRhcmdldCkgewogICAgICAgIHJldHVybiBjcmVhdGVQcm94eShlcCwgW10sIHRhcmdldCk7CiAgICB9CiAgICBmdW5jdGlvbiB0aHJvd0lmUHJveHlSZWxlYXNlZChpc1JlbGVhc2VkKSB7CiAgICAgICAgaWYgKGlzUmVsZWFzZWQpIHsKICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCJQcm94eSBoYXMgYmVlbiByZWxlYXNlZCBhbmQgaXMgbm90IHVzZWFibGUiKTsKICAgICAgICB9CiAgICB9CiAgICBmdW5jdGlvbiByZWxlYXNlRW5kcG9pbnQoZXApIHsKICAgICAgICByZXR1cm4gcmVxdWVzdFJlc3BvbnNlTWVzc2FnZShlcCwgewogICAgICAgICAgICB0eXBlOiAiUkVMRUFTRSIgLyogTWVzc2FnZVR5cGUuUkVMRUFTRSAqLywKICAgICAgICB9KS50aGVuKCgpID0+IHsKICAgICAgICAgICAgY2xvc2VFbmRQb2ludChlcCk7CiAgICAgICAgfSk7CiAgICB9CiAgICBjb25zdCBwcm94eUNvdW50ZXIgPSBuZXcgV2Vha01hcCgpOwogICAgY29uc3QgcHJveHlGaW5hbGl6ZXJzID0gIkZpbmFsaXphdGlvblJlZ2lzdHJ5IiBpbiBzZWxmICYmCiAgICAgICAgbmV3IEZpbmFsaXphdGlvblJlZ2lzdHJ5KChlcCkgPT4gewogICAgICAgICAgICBjb25zdCBuZXdDb3VudCA9IChwcm94eUNvdW50ZXIuZ2V0KGVwKSB8fCAwKSAtIDE7CiAgICAgICAgICAgIHByb3h5Q291bnRlci5zZXQoZXAsIG5ld0NvdW50KTsKICAgICAgICAgICAgaWYgKG5ld0NvdW50ID09PSAwKSB7CiAgICAgICAgICAgICAgICByZWxlYXNlRW5kcG9pbnQoZXApOwogICAgICAgICAgICB9CiAgICAgICAgfSk7CiAgICBmdW5jdGlvbiByZWdpc3RlclByb3h5KHByb3h5LCBlcCkgewogICAgICAgIGNvbnN0IG5ld0NvdW50ID0gKHByb3h5Q291bnRlci5nZXQoZXApIHx8IDApICsgMTsKICAgICAgICBwcm94eUNvdW50ZXIuc2V0KGVwLCBuZXdDb3VudCk7CiAgICAgICAgaWYgKHByb3h5RmluYWxpemVycykgewogICAgICAgICAgICBwcm94eUZpbmFsaXplcnMucmVnaXN0ZXIocHJveHksIGVwLCBwcm94eSk7CiAgICAgICAgfQogICAgfQogICAgZnVuY3Rpb24gdW5yZWdpc3RlclByb3h5KHByb3h5KSB7CiAgICAgICAgaWYgKHByb3h5RmluYWxpemVycykgewogICAgICAgICAgICBwcm94eUZpbmFsaXplcnMudW5yZWdpc3Rlcihwcm94eSk7CiAgICAgICAgfQogICAgfQogICAgZnVuY3Rpb24gY3JlYXRlUHJveHkoZXAsIHBhdGggPSBbXSwgdGFyZ2V0ID0gZnVuY3Rpb24gKCkgeyB9KSB7CiAgICAgICAgbGV0IGlzUHJveHlSZWxlYXNlZCA9IGZhbHNlOwogICAgICAgIGNvbnN0IHByb3h5ID0gbmV3IFByb3h5KHRhcmdldCwgewogICAgICAgICAgICBnZXQoX3RhcmdldCwgcHJvcCkgewogICAgICAgICAgICAgICAgdGhyb3dJZlByb3h5UmVsZWFzZWQoaXNQcm94eVJlbGVhc2VkKTsKICAgICAgICAgICAgICAgIGlmIChwcm9wID09PSByZWxlYXNlUHJveHkpIHsKICAgICAgICAgICAgICAgICAgICByZXR1cm4gKCkgPT4gewogICAgICAgICAgICAgICAgICAgICAgICB1bnJlZ2lzdGVyUHJveHkocHJveHkpOwogICAgICAgICAgICAgICAgICAgICAgICByZWxlYXNlRW5kcG9pbnQoZXApOwogICAgICAgICAgICAgICAgICAgICAgICBpc1Byb3h5UmVsZWFzZWQgPSB0cnVlOwogICAgICAgICAgICAgICAgICAgIH07CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBpZiAocHJvcCA9PT0gInRoZW4iKSB7CiAgICAgICAgICAgICAgICAgICAgaWYgKHBhdGgubGVuZ3RoID09PSAwKSB7CiAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB7IHRoZW46ICgpID0+IHByb3h5IH07CiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgIGNvbnN0IHIgPSByZXF1ZXN0UmVzcG9uc2VNZXNzYWdlKGVwLCB7CiAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJHRVQiIC8qIE1lc3NhZ2VUeXBlLkdFVCAqLywKICAgICAgICAgICAgICAgICAgICAgICAgcGF0aDogcGF0aC5tYXAoKHApID0+IHAudG9TdHJpbmcoKSksCiAgICAgICAgICAgICAgICAgICAgfSkudGhlbihmcm9tV2lyZVZhbHVlKTsKICAgICAgICAgICAgICAgICAgICByZXR1cm4gci50aGVuLmJpbmQocik7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICByZXR1cm4gY3JlYXRlUHJveHkoZXAsIFsuLi5wYXRoLCBwcm9wXSk7CiAgICAgICAgICAgIH0sCiAgICAgICAgICAgIHNldChfdGFyZ2V0LCBwcm9wLCByYXdWYWx1ZSkgewogICAgICAgICAgICAgICAgdGhyb3dJZlByb3h5UmVsZWFzZWQoaXNQcm94eVJlbGVhc2VkKTsKICAgICAgICAgICAgICAgIC8vIEZJWE1FOiBFUzYgUHJveHkgSGFuZGxlciBgc2V0YCBtZXRob2RzIGFyZSBzdXBwb3NlZCB0byByZXR1cm4gYQogICAgICAgICAgICAgICAgLy8gYm9vbGVhbi4gVG8gc2hvdyBnb29kIHdpbGwsIHdlIHJldHVybiB0cnVlIGFzeW5jaHJvbm91c2x5IMKvXF8o44OEKV8vwq8KICAgICAgICAgICAgICAgIGNvbnN0IFt2YWx1ZSwgdHJhbnNmZXJhYmxlc10gPSB0b1dpcmVWYWx1ZShyYXdWYWx1ZSk7CiAgICAgICAgICAgICAgICByZXR1cm4gcmVxdWVzdFJlc3BvbnNlTWVzc2FnZShlcCwgewogICAgICAgICAgICAgICAgICAgIHR5cGU6ICJTRVQiIC8qIE1lc3NhZ2VUeXBlLlNFVCAqLywKICAgICAgICAgICAgICAgICAgICBwYXRoOiBbLi4ucGF0aCwgcHJvcF0ubWFwKChwKSA9PiBwLnRvU3RyaW5nKCkpLAogICAgICAgICAgICAgICAgICAgIHZhbHVlLAogICAgICAgICAgICAgICAgfSwgdHJhbnNmZXJhYmxlcykudGhlbihmcm9tV2lyZVZhbHVlKTsKICAgICAgICAgICAgfSwKICAgICAgICAgICAgYXBwbHkoX3RhcmdldCwgX3RoaXNBcmcsIHJhd0FyZ3VtZW50TGlzdCkgewogICAgICAgICAgICAgICAgdGhyb3dJZlByb3h5UmVsZWFzZWQoaXNQcm94eVJlbGVhc2VkKTsKICAgICAgICAgICAgICAgIGNvbnN0IGxhc3QgPSBwYXRoW3BhdGgubGVuZ3RoIC0gMV07CiAgICAgICAgICAgICAgICBpZiAobGFzdCA9PT0gY3JlYXRlRW5kcG9pbnQpIHsKICAgICAgICAgICAgICAgICAgICByZXR1cm4gcmVxdWVzdFJlc3BvbnNlTWVzc2FnZShlcCwgewogICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAiRU5EUE9JTlQiIC8qIE1lc3NhZ2VUeXBlLkVORFBPSU5UICovLAogICAgICAgICAgICAgICAgICAgIH0pLnRoZW4oZnJvbVdpcmVWYWx1ZSk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAvLyBXZSBqdXN0IHByZXRlbmQgdGhhdCBgYmluZCgpYCBkaWRu4oCZdCBoYXBwZW4uCiAgICAgICAgICAgICAgICBpZiAobGFzdCA9PT0gImJpbmQiKSB7CiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGNyZWF0ZVByb3h5KGVwLCBwYXRoLnNsaWNlKDAsIC0xKSk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBjb25zdCBbYXJndW1lbnRMaXN0LCB0cmFuc2ZlcmFibGVzXSA9IHByb2Nlc3NBcmd1bWVudHMocmF3QXJndW1lbnRMaXN0KTsKICAgICAgICAgICAgICAgIHJldHVybiByZXF1ZXN0UmVzcG9uc2VNZXNzYWdlKGVwLCB7CiAgICAgICAgICAgICAgICAgICAgdHlwZTogIkFQUExZIiAvKiBNZXNzYWdlVHlwZS5BUFBMWSAqLywKICAgICAgICAgICAgICAgICAgICBwYXRoOiBwYXRoLm1hcCgocCkgPT4gcC50b1N0cmluZygpKSwKICAgICAgICAgICAgICAgICAgICBhcmd1bWVudExpc3QsCiAgICAgICAgICAgICAgICB9LCB0cmFuc2ZlcmFibGVzKS50aGVuKGZyb21XaXJlVmFsdWUpOwogICAgICAgICAgICB9LAogICAgICAgICAgICBjb25zdHJ1Y3QoX3RhcmdldCwgcmF3QXJndW1lbnRMaXN0KSB7CiAgICAgICAgICAgICAgICB0aHJvd0lmUHJveHlSZWxlYXNlZChpc1Byb3h5UmVsZWFzZWQpOwogICAgICAgICAgICAgICAgY29uc3QgW2FyZ3VtZW50TGlzdCwgdHJhbnNmZXJhYmxlc10gPSBwcm9jZXNzQXJndW1lbnRzKHJhd0FyZ3VtZW50TGlzdCk7CiAgICAgICAgICAgICAgICByZXR1cm4gcmVxdWVzdFJlc3BvbnNlTWVzc2FnZShlcCwgewogICAgICAgICAgICAgICAgICAgIHR5cGU6ICJDT05TVFJVQ1QiIC8qIE1lc3NhZ2VUeXBlLkNPTlNUUlVDVCAqLywKICAgICAgICAgICAgICAgICAgICBwYXRoOiBwYXRoLm1hcCgocCkgPT4gcC50b1N0cmluZygpKSwKICAgICAgICAgICAgICAgICAgICBhcmd1bWVudExpc3QsCiAgICAgICAgICAgICAgICB9LCB0cmFuc2ZlcmFibGVzKS50aGVuKGZyb21XaXJlVmFsdWUpOwogICAgICAgICAgICB9LAogICAgICAgIH0pOwogICAgICAgIHJlZ2lzdGVyUHJveHkocHJveHksIGVwKTsKICAgICAgICByZXR1cm4gcHJveHk7CiAgICB9CiAgICBmdW5jdGlvbiBteUZsYXQoYXJyKSB7CiAgICAgICAgcmV0dXJuIEFycmF5LnByb3RvdHlwZS5jb25jYXQuYXBwbHkoW10sIGFycik7CiAgICB9CiAgICBmdW5jdGlvbiBwcm9jZXNzQXJndW1lbnRzKGFyZ3VtZW50TGlzdCkgewogICAgICAgIGNvbnN0IHByb2Nlc3NlZCA9IGFyZ3VtZW50TGlzdC5tYXAodG9XaXJlVmFsdWUpOwogICAgICAgIHJldHVybiBbcHJvY2Vzc2VkLm1hcCgodikgPT4gdlswXSksIG15RmxhdChwcm9jZXNzZWQubWFwKCh2KSA9PiB2WzFdKSldOwogICAgfQogICAgY29uc3QgdHJhbnNmZXJDYWNoZSA9IG5ldyBXZWFrTWFwKCk7CiAgICBmdW5jdGlvbiB0cmFuc2ZlcihvYmosIHRyYW5zZmVycykgewogICAgICAgIHRyYW5zZmVyQ2FjaGUuc2V0KG9iaiwgdHJhbnNmZXJzKTsKICAgICAgICByZXR1cm4gb2JqOwogICAgfQogICAgZnVuY3Rpb24gcHJveHkob2JqKSB7CiAgICAgICAgcmV0dXJuIE9iamVjdC5hc3NpZ24ob2JqLCB7IFtwcm94eU1hcmtlcl06IHRydWUgfSk7CiAgICB9CiAgICBmdW5jdGlvbiB0b1dpcmVWYWx1ZSh2YWx1ZSkgewogICAgICAgIGZvciAoY29uc3QgW25hbWUsIGhhbmRsZXJdIG9mIHRyYW5zZmVySGFuZGxlcnMpIHsKICAgICAgICAgICAgaWYgKGhhbmRsZXIuY2FuSGFuZGxlKHZhbHVlKSkgewogICAgICAgICAgICAgICAgY29uc3QgW3NlcmlhbGl6ZWRWYWx1ZSwgdHJhbnNmZXJhYmxlc10gPSBoYW5kbGVyLnNlcmlhbGl6ZSh2YWx1ZSk7CiAgICAgICAgICAgICAgICByZXR1cm4gWwogICAgICAgICAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgICAgICAgICAgdHlwZTogIkhBTkRMRVIiIC8qIFdpcmVWYWx1ZVR5cGUuSEFORExFUiAqLywKICAgICAgICAgICAgICAgICAgICAgICAgbmFtZSwKICAgICAgICAgICAgICAgICAgICAgICAgdmFsdWU6IHNlcmlhbGl6ZWRWYWx1ZSwKICAgICAgICAgICAgICAgICAgICB9LAogICAgICAgICAgICAgICAgICAgIHRyYW5zZmVyYWJsZXMsCiAgICAgICAgICAgICAgICBdOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIHJldHVybiBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIHR5cGU6ICJSQVciIC8qIFdpcmVWYWx1ZVR5cGUuUkFXICovLAogICAgICAgICAgICAgICAgdmFsdWUsCiAgICAgICAgICAgIH0sCiAgICAgICAgICAgIHRyYW5zZmVyQ2FjaGUuZ2V0KHZhbHVlKSB8fCBbXSwKICAgICAgICBdOwogICAgfQogICAgZnVuY3Rpb24gZnJvbVdpcmVWYWx1ZSh2YWx1ZSkgewogICAgICAgIHN3aXRjaCAodmFsdWUudHlwZSkgewogICAgICAgICAgICBjYXNlICJIQU5ETEVSIiAvKiBXaXJlVmFsdWVUeXBlLkhBTkRMRVIgKi86CiAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNmZXJIYW5kbGVycy5nZXQodmFsdWUubmFtZSkuZGVzZXJpYWxpemUodmFsdWUudmFsdWUpOwogICAgICAgICAgICBjYXNlICJSQVciIC8qIFdpcmVWYWx1ZVR5cGUuUkFXICovOgogICAgICAgICAgICAgICAgcmV0dXJuIHZhbHVlLnZhbHVlOwogICAgICAgIH0KICAgIH0KICAgIGZ1bmN0aW9uIHJlcXVlc3RSZXNwb25zZU1lc3NhZ2UoZXAsIG1zZywgdHJhbnNmZXJzKSB7CiAgICAgICAgcmV0dXJuIG5ldyBQcm9taXNlKChyZXNvbHZlKSA9PiB7CiAgICAgICAgICAgIGNvbnN0IGlkID0gZ2VuZXJhdGVVVUlEKCk7CiAgICAgICAgICAgIGVwLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLCBmdW5jdGlvbiBsKGV2KSB7CiAgICAgICAgICAgICAgICBpZiAoIWV2LmRhdGEgfHwgIWV2LmRhdGEuaWQgfHwgZXYuZGF0YS5pZCAhPT0gaWQpIHsKICAgICAgICAgICAgICAgICAgICByZXR1cm47CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBlcC5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIiwgbCk7CiAgICAgICAgICAgICAgICByZXNvbHZlKGV2LmRhdGEpOwogICAgICAgICAgICB9KTsKICAgICAgICAgICAgaWYgKGVwLnN0YXJ0KSB7CiAgICAgICAgICAgICAgICBlcC5zdGFydCgpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVwLnBvc3RNZXNzYWdlKE9iamVjdC5hc3NpZ24oeyBpZCB9LCBtc2cpLCB0cmFuc2ZlcnMpOwogICAgICAgIH0pOwogICAgfQogICAgZnVuY3Rpb24gZ2VuZXJhdGVVVUlEKCkgewogICAgICAgIHJldHVybiBuZXcgQXJyYXkoNCkKICAgICAgICAgICAgLmZpbGwoMCkKICAgICAgICAgICAgLm1hcCgoKSA9PiBNYXRoLmZsb29yKE1hdGgucmFuZG9tKCkgKiBOdW1iZXIuTUFYX1NBRkVfSU5URUdFUikudG9TdHJpbmcoMTYpKQogICAgICAgICAgICAuam9pbigiLSIpOwogICAgfQoKICAgIGNvbnN0IGNvbG9yQ29udmVydGVyID0gewogICAgICBnZXRDbG9zZXN0Q29sb3JGcm9tUGFsZXR0ZShnYW1lUGFsZXR0ZSwgcmVzZXJ2ZWRPZmZzZXQsIHIsIGcsIGIpIHsKICAgICAgICBjb25zdCBpZHggPSB0aGlzLmNvbnZlcnRBY3R1YWxDb2xvckZyb21QYWxldHRlKGdhbWVQYWxldHRlLCByZXNlcnZlZE9mZnNldCwgciwgZywgYik7CiAgICAgICAgcmV0dXJuIHRoaXMuZ2V0QWN0dWFsQ29sb3JGcm9tUGFsZXR0ZShnYW1lUGFsZXR0ZSwgaWR4KTsKICAgICAgfSwKICAgICAgY29udmVydEFjdHVhbENvbG9yRnJvbVBhbGV0dGUoZ2FtZVBhbGV0dGUsIHJlc2VydmVkT2Zmc2V0LCByLCBnLCBiKSB7CiAgICAgICAgY29uc3QgcmVzdWx0Q29sb3JJZHggPSBnYW1lUGFsZXR0ZS5tYXAoKGNvbG9yLCBpKSA9PiB7CiAgICAgICAgICBpZiAoaSA8IHJlc2VydmVkT2Zmc2V0KQogICAgICAgICAgICByZXR1cm4gdm9pZCAwOwogICAgICAgICAgY29uc3QgZGlmZmVyZW5jZSA9IE1hdGguc3FydCgociAtIGNvbG9yWzBdKSAqKiAyICsgKGcgLSBjb2xvclsxXSkgKiogMiArIChiIC0gY29sb3JbMl0pICoqIDIpOwogICAgICAgICAgcmV0dXJuIHsKICAgICAgICAgICAgZGlmZmVyZW5jZSwKICAgICAgICAgICAgY29sb3IsCiAgICAgICAgICAgIGluZGV4OiBpCiAgICAgICAgICB9OwogICAgICAgIH0pLmZpbHRlcigoYSkgPT4gISFhKS5tYXAoKGEpID0+IGEpLnNvcnQoKGFhLCBiYikgPT4gYWEuZGlmZmVyZW5jZSAtIGJiLmRpZmZlcmVuY2UpWzBdPy5pbmRleDsKICAgICAgICBpZiAocmVzdWx0Q29sb3JJZHggPT09IHZvaWQgMCkKICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgQ29sb3Igbm90IGZvdW5kICR7cn0sICR7Z30sICR7Yn0gZnJvbSAke0pTT04uc3RyaW5naWZ5KGdhbWVQYWxldHRlKX1gKTsKICAgICAgICByZXR1cm4gcmVzdWx0Q29sb3JJZHg7CiAgICAgIH0sCiAgICAgIGdldEFjdHVhbENvbG9yRnJvbVBhbGV0dGUoZ2FtZVBhbGV0dGUsIGNvbG9yKSB7CiAgICAgICAgY29uc3QgY29sb3JEYXRhID0gZ2FtZVBhbGV0dGVbY29sb3JdOwogICAgICAgIGlmICghY29sb3JEYXRhKQogICAgICAgICAgcmV0dXJuIG51bGw7CiAgICAgICAgcmV0dXJuIFtjb2xvckRhdGFbMF0sIGNvbG9yRGF0YVsxXSwgY29sb3JEYXRhWzJdXTsKICAgICAgfSwKICAgICAgYXJlQ29sb3JzRXF1YWwoZ2FtZVBhbGV0dGUsIGMxLCBjMikgewogICAgICAgIGlmIChjMSA9PT0gYzIpIHsKICAgICAgICAgIHJldHVybiB0cnVlOwogICAgICAgIH0KICAgICAgICBjb25zdCBjb2xvcjEgPSBnYW1lUGFsZXR0ZVtjMV07CiAgICAgICAgY29uc3QgY29sb3IyID0gZ2FtZVBhbGV0dGVbYzJdOwogICAgICAgIGlmICghY29sb3IxIHx8ICFjb2xvcjIpCiAgICAgICAgICByZXR1cm4gYzEgPT09IGMyOwogICAgICAgIGxldCBhcmVFcXVhbCA9IHRydWU7CiAgICAgICAgYXJlRXF1YWwgPSBhcmVFcXVhbCAmJiBjb2xvcjFbMF0gPT09IGNvbG9yMlswXTsKICAgICAgICBhcmVFcXVhbCA9IGFyZUVxdWFsICYmIGNvbG9yMVsxXSA9PT0gY29sb3IyWzFdOwogICAgICAgIGFyZUVxdWFsID0gYXJlRXF1YWwgJiYgY29sb3IxWzJdID09PSBjb2xvcjJbMl07CiAgICAgICAgcmV0dXJuIGFyZUVxdWFsOwogICAgICB9LAogICAgICBwYXJzZUNvbG9yKGNvbG9yU3RyKSB7CiAgICAgICAgY29uc3QgciA9IHBhcnNlSW50KGNvbG9yU3RyLnN1YnN0cigxLCAyKSwgMTYpOwogICAgICAgIGNvbnN0IGcgPSBwYXJzZUludChjb2xvclN0ci5zdWJzdHIoMywgMiksIDE2KTsKICAgICAgICBjb25zdCBiID0gcGFyc2VJbnQoY29sb3JTdHIuc3Vic3RyKDUsIDIpLCAxNik7CiAgICAgICAgcmV0dXJuIFtyLCBnLCBiXTsKICAgICAgfQogICAgfTsKCiAgICBjb25zdCBwaWN0dXJlQ29udmVydGVyID0gewogICAgICBhc3luYyBpc0ltYWdlVmFsaWRDb3JzKHVybCkgewogICAgICAgIHRyeSB7CiAgICAgICAgICBjb25zdCByZXNwb25zZSA9IGF3YWl0IGZldGNoKHVybCk7CiAgICAgICAgfSBjYXRjaCAoZXJyb3IpIHsKICAgICAgICAgIHJldHVybiBmYWxzZTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgIH0sCiAgICAgIGFzeW5jIGFwcGx5TW9kaWZpY2F0aW9uc1RvSW1hZ2VEYXRhKGNvbG9yUGFsZXR0ZSwgaW1hZ2VEYXRhLCBtb2RpZmllckNvbnZlcnRDb2xvcnMsIGJyaWdodGVuQnksIG1vZGlmaWVyU21vbFBpeGVscykgewogICAgICAgIHJldHVybiBuZXcgUHJvbWlzZSgocmVzb2x2ZSkgPT4gewogICAgICAgICAgY29uc3Qgb3V0SW1hZ2VEYXRhID0gbmV3IEltYWdlRGF0YShpbWFnZURhdGEud2lkdGgsIGltYWdlRGF0YS5oZWlnaHQpOwogICAgICAgICAgb3V0SW1hZ2VEYXRhLmRhdGEuc2V0KGltYWdlRGF0YS5kYXRhKTsKICAgICAgICAgIGlmIChtb2RpZmllckNvbnZlcnRDb2xvcnMpIHsKICAgICAgICAgICAgZm9yIChsZXQgeSA9IDA7IHkgPCBvdXRJbWFnZURhdGEuaGVpZ2h0OyB5KyspIHsKICAgICAgICAgICAgICBmb3IgKGxldCB4ID0gMDsgeCA8IG91dEltYWdlRGF0YS53aWR0aDsgeCsrKSB7CiAgICAgICAgICAgICAgICBjb25zdCBpZHggPSBvdXRJbWFnZURhdGEud2lkdGggKiB5ICsgeCA8PCAyOwogICAgICAgICAgICAgICAgY29uc3Qgb3JpZ2luYWxSID0gaW1hZ2VEYXRhLmRhdGFbaWR4ICsgMF0gPz8gMDsKICAgICAgICAgICAgICAgIGNvbnN0IG9yaWdpbmFsRyA9IGltYWdlRGF0YS5kYXRhW2lkeCArIDFdID8/IDA7CiAgICAgICAgICAgICAgICBjb25zdCBvcmlnaW5hbEIgPSBpbWFnZURhdGEuZGF0YVtpZHggKyAyXSA/PyAwOwogICAgICAgICAgICAgICAgY29uc3Qgb3JpZ2luYWxBID0gaW1hZ2VEYXRhLmRhdGFbaWR4ICsgM10gPz8gMDsKICAgICAgICAgICAgICAgIGNvbnN0IHIgPSBNYXRoLm1pbihvcmlnaW5hbFIgKyBicmlnaHRlbkJ5LCAyNTUpOwogICAgICAgICAgICAgICAgY29uc3QgZyA9IE1hdGgubWluKG9yaWdpbmFsRyArIGJyaWdodGVuQnksIDI1NSk7CiAgICAgICAgICAgICAgICBjb25zdCBiID0gTWF0aC5taW4ob3JpZ2luYWxCICsgYnJpZ2h0ZW5CeSwgMjU1KTsKICAgICAgICAgICAgICAgIGNvbnN0IHJlc3VsdEFyciA9IGNvbG9yQ29udmVydGVyLmdldENsb3Nlc3RDb2xvckZyb21QYWxldHRlKGNvbG9yUGFsZXR0ZSwgMCwgciwgZywgYik7CiAgICAgICAgICAgICAgICBpZiAoIXJlc3VsdEFycikgOyBlbHNlIHsKICAgICAgICAgICAgICAgICAgY29uc3QgW2NvbnZlcnRlZFIsIGNvbnZlcnRlZEcsIGNvbnZlcnRlZEJdID0gcmVzdWx0QXJyOwogICAgICAgICAgICAgICAgICBvdXRJbWFnZURhdGEuZGF0YVtpZHggKyAwXSA9IGNvbnZlcnRlZFI7CiAgICAgICAgICAgICAgICAgIG91dEltYWdlRGF0YS5kYXRhW2lkeCArIDFdID0gY29udmVydGVkRzsKICAgICAgICAgICAgICAgICAgb3V0SW1hZ2VEYXRhLmRhdGFbaWR4ICsgMl0gPSBjb252ZXJ0ZWRCOwogICAgICAgICAgICAgICAgICBvdXRJbWFnZURhdGEuZGF0YVtpZHggKyAzXSA9IG9yaWdpbmFsQSA+IDMwID8gMjU1IDogMDsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGlmIChtb2RpZmllclNtb2xQaXhlbHMpIHsKICAgICAgICAgICAgY29uc3Qgc21vbFBpeGVsc011bHRpcGxpZXIgPSAzOwogICAgICAgICAgICBjb25zdCBzbW9sUGl4ZWxzSW1hZ2VEYXRhID0gbmV3IEltYWdlRGF0YShvdXRJbWFnZURhdGEud2lkdGggKiBzbW9sUGl4ZWxzTXVsdGlwbGllciwgb3V0SW1hZ2VEYXRhLmhlaWdodCAqIHNtb2xQaXhlbHNNdWx0aXBsaWVyKTsKICAgICAgICAgICAgZm9yIChsZXQgb3V0WSA9IDA7IG91dFkgPCBvdXRJbWFnZURhdGEuaGVpZ2h0OyBvdXRZKyspIHsKICAgICAgICAgICAgICBmb3IgKGxldCBvdXRYID0gMDsgb3V0WCA8IG91dEltYWdlRGF0YS53aWR0aDsgb3V0WCsrKSB7CiAgICAgICAgICAgICAgICBjb25zdCBvdXRJZHggPSBvdXRJbWFnZURhdGEud2lkdGggKiBvdXRZICsgb3V0WCA8PCAyOwogICAgICAgICAgICAgICAgY29uc3Qgb3V0UiA9IG91dEltYWdlRGF0YS5kYXRhW291dElkeCArIDBdID8/IDA7CiAgICAgICAgICAgICAgICBjb25zdCBvdXRHID0gb3V0SW1hZ2VEYXRhLmRhdGFbb3V0SWR4ICsgMV0gPz8gMDsKICAgICAgICAgICAgICAgIGNvbnN0IG91dEIgPSBvdXRJbWFnZURhdGEuZGF0YVtvdXRJZHggKyAyXSA/PyAwOwogICAgICAgICAgICAgICAgY29uc3Qgb3V0QSA9IG91dEltYWdlRGF0YS5kYXRhW291dElkeCArIDNdID8/IDA7CiAgICAgICAgICAgICAgICBjb25zdCBzbW9sWCA9IG91dFggKiBzbW9sUGl4ZWxzTXVsdGlwbGllciArIE1hdGguZmxvb3Ioc21vbFBpeGVsc011bHRpcGxpZXIgLyAyKTsKICAgICAgICAgICAgICAgIGNvbnN0IHNtb2xZID0gb3V0WSAqIHNtb2xQaXhlbHNNdWx0aXBsaWVyICsgTWF0aC5mbG9vcihzbW9sUGl4ZWxzTXVsdGlwbGllciAvIDIpOwogICAgICAgICAgICAgICAgY29uc3Qgc21vbElkeCA9IHNtb2xZICogc21vbFBpeGVsc0ltYWdlRGF0YS53aWR0aCArIHNtb2xYIDw8IDI7CiAgICAgICAgICAgICAgICBzbW9sUGl4ZWxzSW1hZ2VEYXRhLmRhdGFbc21vbElkeCArIDBdID0gb3V0UjsKICAgICAgICAgICAgICAgIHNtb2xQaXhlbHNJbWFnZURhdGEuZGF0YVtzbW9sSWR4ICsgMV0gPSBvdXRHOwogICAgICAgICAgICAgICAgc21vbFBpeGVsc0ltYWdlRGF0YS5kYXRhW3Ntb2xJZHggKyAyXSA9IG91dEI7CiAgICAgICAgICAgICAgICBzbW9sUGl4ZWxzSW1hZ2VEYXRhLmRhdGFbc21vbElkeCArIDNdID0gb3V0QTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgcmVzb2x2ZShzbW9sUGl4ZWxzSW1hZ2VEYXRhKTsKICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgfQogICAgICAgICAgcmVzb2x2ZShvdXRJbWFnZURhdGEpOwogICAgICAgIH0pOwogICAgICB9CiAgICB9OwoKICAgIGV4cG9zZShwaWN0dXJlQ29udmVydGVyKTsKCn0pKCk7Cg=="; const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" }); function WorkerWrapper() { const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob); try { return objURL ? new Worker(objURL) : new Worker("data:application/javascript;base64," + encodedJs); } finally { objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL); } } const worker = new WorkerWrapper(); const pictureConverterApi = wrap(worker); async function tryReadingImageData(url, abortSignal) { try { return await loadImageDrawOnCanvasGetData(url, abortSignal); } catch (error) { logger.logError(`Error loading image: url: ${url} ${error}`); return void 0; } } async function loadImageDrawOnCanvasGetData(url, abortSignal) { const img = new Image(); const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); if (!ctx) throw new Error("Can't get context"); const clearCallbacks = () => { img.onload = null; img.onerror = null; img.src = ""; abortSignal.onabort = null; }; const imageData = await new Promise((resolve, reject) => { img.onerror = () => { reject(new Error("Image load error")); clearCallbacks(); }; img.onload = () => { canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); try { resolve(ctx.getImageData(0, 0, img.width, img.height)); } catch (error) { if (!window.location.protocol.startsWith("http")) reject(error); fetch(url, { signal: abortSignal }).then((response) => response.blob()).then((blob) => new File([blob], "image.png", { type: "image/png" })).then((file) => loadImageDrawOnCanvasGetData(URL.createObjectURL(file), abortSignal).finally(() => URL.revokeObjectURL(url))).then(resolve); } }; abortSignal.onabort = () => { reject(new Error("Aborted")); clearCallbacks(); }; img.src = url; }); clearCallbacks(); return imageData; } function delay(timeout) { return new Promise((resolve) => { setTimeout(resolve, timeout); }); } const setInputImageAction = createAsyncThunk("imageProcessing/setInputImage", async (input, { dispatch, getState }) => { await dispatch(clearInputImageAction()); const file = typeof input !== "string" ? input : void 0; const url = typeof input === "string" ? input : void 0; return { file, url }; }); const clearInputImageAction = createAsyncThunk("imageProcessing/clearInputImage", async (_, { dispatch, getState }) => { dispatch(clearOutputImageAction()); }); const clearOutputImageAction = createAsyncThunk("imageProcessing/clearOutputImage", async (_, { getState }) => { getState().processedImages.outputImage.abortController?.abort(); }); function useReadingInputImageProcess() { const inputFile = useAppSelector(selectInputFile); const inputUrl = useAppSelector(selectInputUrl); const dispatch = useAppDispatch(); reactExports.useEffect(() => { dispatch(startNewImageReadingProcess()); }, [inputFile, inputUrl]); } const startNewImageReadingProcess = createAsyncThunk("imageProcessing/startNewImageReadingProcess", async (_, { dispatch, getState }) => { const url = selectInputUrl(getState()); const file = selectInputFile(getState()); const abortController = new AbortController(); if (url) return tryReadingImageData(url, abortController.signal); if (file != null) { const fileUrl = URL.createObjectURL(file); delay(0).then(() => URL.revokeObjectURL(fileUrl)); return tryReadingImageData(fileUrl, abortController.signal); } return void 0; }); const startProcessingOutputImage = createAsyncThunk("imageProcessing/startProcessingOutputImage", async (_, { getState }) => { const palette = selectCanvasUserPalette(getState()); const modifierShouldConvertColors = selectModifierShouldConvertColors(getState()); const modifierImageBrightness = selectModifierImageBrightness(getState()); const modifierSmolPixels = selectModifierSmolPixels(getState()); const inputImageData = selectInputImageData(getState()); if (inputImageData == null) throw new Error("Can't process output image without input image data"); const abortController = new AbortController(); const outImageData = await new Promise((resolve, reject) => { abortController.signal.onabort = () => reject(new Error("aborted")); pictureConverterApi.applyModificationsToImageData(palette, inputImageData, modifierShouldConvertColors, modifierImageBrightness, modifierSmolPixels).then((imageData) => { resolve(imageData); }).catch((error) => { reject(error); }); }); return { outImageData, abortController }; }); const loadSavedConfigurations = createAsyncThunk("imageProcessing/loadSavedConfigurations", async (_, { dispatch, getState }) => { return JSON.parse(localStorage.getItem("OverlaySavedConfigurationsv2") || "[]"); }); const initialState$6 = { savedConfigs: [], overlayEnabled: true, overlayImage: { inputImage: {} }, placementConfiguration: { yOffset: 0, xOffset: 0, transparency: 92, isFollowMouseActive: false, autoSelectColor: false }, modifications: { imageBrightness: 0, shouldConvertColors: false, smolPixels: false }, isBotModalVisible: false, browserWindow: { innerWidth: 100, innerHeight: 100 } }; const overlaySlice = createSlice({ initialState: initialState$6, name: "overlay", reducers: { setPlacementXOffset: (state, action) => { state.placementConfiguration.xOffset = action.payload; }, setPlacementYOffset: (state, action) => { state.placementConfiguration.yOffset = action.payload; }, setPlacementTransparency: (state, action) => { state.placementConfiguration.transparency = action.payload; }, togglePlacementFollowMouse: (state) => { state.placementConfiguration.isFollowMouseActive = !state.placementConfiguration.isFollowMouseActive; }, setPlacementIsFollowMouseActive: (state, action) => { state.placementConfiguration.isFollowMouseActive = action.payload; }, setPlacementAutoSelectColor: (state, action) => { state.placementConfiguration.autoSelectColor = action.payload; }, setModifierImageBrightness: (state, action) => { state.modifications.imageBrightness = action.payload; }, setModifierShouldConvertColors: (state, action) => { state.modifications.shouldConvertColors = action.payload; }, setModifierSmolPixels: (state, action) => { state.modifications.smolPixels = action.payload; }, setOverlayEnabled: (state, action) => { state.overlayEnabled = action.payload; }, setWindowSize: (state, action) => { state.browserWindow = action.payload; }, saveConfiguration: (state, action) => { const savedConfigurations = state.savedConfigs; const existingConfiguration = savedConfigurations.find((c) => c.imageUrl === action.payload.imageUrl); if (existingConfiguration != null) { existingConfiguration.modifiers = action.payload.modifiers; existingConfiguration.placementConfiguration = action.payload.placementConfiguration; } else { savedConfigurations.push(action.payload); } }, removeSavedConfig: (state, action) => { const savedConfigurations = state.savedConfigs; const existingConfiguration = savedConfigurations.find((c) => c.imageUrl === action.payload); if (existingConfiguration) { savedConfigurations.splice(savedConfigurations.indexOf(existingConfiguration), 1); } } }, extraReducers: (builder) => { builder.addCase(setInputImageAction.fulfilled, (state, action) => { state.overlayImage.inputImage.url = action.payload.url; state.overlayImage.inputImage.file = action.payload.file; }); builder.addCase(clearInputImageAction.fulfilled, (state) => { state.overlayImage.inputImage.file = void 0; state.overlayImage.inputImage.url = void 0; }); builder.addCase(loadSavedConfigurations.fulfilled, (state, action) => { state.savedConfigs = action.payload; }); } }); const selectInputUrl = createSelector((state) => state.overlay.overlayImage.inputImage.url, (url) => url); const selectInputImageData = createSelector((state) => state.processedImages.inputImage.loadedImage.imageData, (imageData) => imageData); const selectIsModificationsAvailable = createSelector(selectInputImageData, (inputImageData) => { return !!inputImageData; }); const selectInputFile = createSelector((state) => state.overlay.overlayImage.inputImage.file, (file) => file); const selectFileName = createSelector(selectInputFile, selectInputUrl, (file, url) => { const fileName = file?.name ?? url?.split("/").pop(); if (fileName) { return { fileName, fileExtension: fileName.split(".").pop(), fileNameWithoutExtension: fileName.split(".").slice(0, -1).join(".") }; } return void 0; }); const selectShouldShowPlacementConfiguration = createSelector(selectInputFile, selectInputUrl, (file, url) => file || url); const selectPlacementXOffset = createSelector((state) => state.overlay.placementConfiguration.xOffset, (xOffset) => xOffset); const selectPlacementYOffset = createSelector((state) => state.overlay.placementConfiguration.yOffset, (yOffset) => yOffset); const selectPlacementTransparency = createSelector((state) => state.overlay.placementConfiguration.transparency, (transparency) => transparency); const selectPlacementIsFollowMouseActive = createSelector((state) => state.overlay.placementConfiguration.isFollowMouseActive, (isFollowMouseActive) => isFollowMouseActive); const selectPlacementAutoSelectColor = createSelector((state) => state.overlay.placementConfiguration.autoSelectColor, (autoSelectColor) => autoSelectColor); const selectModifierImageBrightness = createSelector((state) => state.overlay.modifications.imageBrightness, (imageBrightness) => imageBrightness); const selectModifierShouldConvertColors = createSelector((state) => state.overlay.modifications.shouldConvertColors, (shouldConvertColors) => shouldConvertColors); const selectModifierSmolPixels = createSelector((state) => state.overlay.modifications.smolPixels, (smolPixels) => smolPixels); const selectIsOverlayEnabled = createSelector((state) => state.overlay.overlayEnabled, (overlayEnabled) => overlayEnabled); const selectInputImageLoadingStatus = createSelector((state) => state.processedImages.inputImage.loadedImage.status, (status) => status); const selectIsOutputImageProcessing = createSelector((state) => state.processedImages.outputImage.isProcessing, (isProcessing) => isProcessing); const selectOutputImageData = createSelector((state) => state.processedImages.outputImage.isProcessing, (state) => state.processedImages.outputImage.imageData, (state) => state.processedImages.outputImage.abortController, (isProcessing, imageData, abortController) => { if (!isProcessing && imageData) { return imageData; } return void 0; }); const selectRenderImageData = createSelector(selectOutputImageData, selectInputImageData, (outputImageData, inputImageData) => { return outputImageData || inputImageData; }); const selectShouldShowImageFromData = createSelector(selectRenderImageData, (imageData) => !!imageData); const selectShouldShowImageFromUrl = createSelector(selectShouldShowImageFromData, selectInputFile, selectInputUrl, (shouldShowImageFromData, file, url) => { if (shouldShowImageFromData) return false; if (file || url) return true; return false; }); createSelector(selectInputUrl, selectOutputImageData, (url, imageData) => { return imageData || url; }); const selectWindowSize = createSelector((state) => state.overlay.browserWindow.innerHeight, (state) => state.overlay.browserWindow.innerWidth, (innerHeight, innerWidth) => { return { innerHeight, innerWidth }; }); const selectOverlayOffsetCoordsOnScreen = createSelector(selectWindowSize, selectGameViewCenter, selectPlacementXOffset, selectPlacementYOffset, selectGameViewScale, (windowSize, gameViewCenter, xOffset, yOffset, viewScale) => { const leftOffset = windowSize.innerWidth / 2 - (gameViewCenter.x - xOffset) * viewScale; const topOffset = windowSize.innerHeight / 2 - (gameViewCenter.y - yOffset) * viewScale; return { leftOffset, topOffset }; }); const selectCurrentHoverPixelOnOutputImageColorIndexInPalette = createSelector(selectPlacementAutoSelectColor, selectModifierSmolPixels, selectHoverPixel, selectPlacementXOffset, selectPlacementYOffset, selectRenderImageData, selectCanvasPalette, selectCanvasReservedColorCount, (autoSelectColor, modifierSmolPixels, hoverPixel, placementXOffset, placementYOffset, renderImageData, palette, reservedColorCount) => { if (!autoSelectColor) return void 0; if (!renderImageData) return void 0; const smolPixelsCanvasSizeModifier = modifierSmolPixels ? 3 : 1; const smolPixelsCanvasExtraOffsetToMiddle = Math.floor(smolPixelsCanvasSizeModifier / 2); const offsetXInImage = (hoverPixel.x - placementXOffset) * smolPixelsCanvasSizeModifier + smolPixelsCanvasExtraOffsetToMiddle; const offsetYInImage = (hoverPixel.y - placementYOffset) * smolPixelsCanvasSizeModifier + smolPixelsCanvasExtraOffsetToMiddle; if (offsetXInImage < 0 || offsetXInImage >= renderImageData.width || offsetYInImage < 0 || offsetYInImage >= renderImageData.height) return void 0; const idx = renderImageData.width * offsetYInImage + offsetXInImage << 2; const r = renderImageData.data[idx + 0]; const g = renderImageData.data[idx + 1]; const b = renderImageData.data[idx + 2]; const a = renderImageData.data[idx + 3]; if (r == null || g == null || b == null || a == null) return void 0; if (a < 30) return void 0; const colorIndex = colorConverter.convertActualColorFromPalette(palette, reservedColorCount, r, g, b); return colorIndex; }); const selectSavedConfigurations = createSelector((state) => state.overlay.savedConfigs, (savedConfigurations) => savedConfigurations); const selectCurrentStateAsConfiguration = createSelector(selectInputUrl, selectPlacementXOffset, selectPlacementYOffset, selectPlacementTransparency, selectPlacementAutoSelectColor, selectModifierImageBrightness, selectModifierShouldConvertColors, (inputUrl, xOffset, yOffset, transparency, autoSelectColor, imageBrightness, shouldConvertColors) => { if (!inputUrl) return void 0; return { imageUrl: inputUrl, modifiers: { autoSelectColor, imageBrightness, shouldConvertColors }, placementConfiguration: { xOffset, yOffset, transparency } }; }); function commonjsRequire(path) { throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); } var localforageExports = {}; var localforage$1 = { get exports(){ return localforageExports; }, set exports(v){ localforageExports = v; }, }; /*! localForage -- Offline Storage, Improved Version 1.10.0 https://localforage.github.io/localForage (c) 2013-2017 Mozilla, Apache License 2.0 */ (function (module, exports) { (function(f){{module.exports=f();}})(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var scriptEl = global.document.createElement('script'); scriptEl.onreadystatechange = function () { nextTick(); scriptEl.onreadystatechange = null; scriptEl.parentNode.removeChild(scriptEl); scriptEl = null; }; global.document.documentElement.appendChild(scriptEl); }; } else { scheduleDrain = function () { setTimeout(nextTick, 0); }; } } var draining; var queue = []; //named nextTick for less confusing stack traces function nextTick() { draining = true; var i, oldQueue; var len = queue.length; while (len) { oldQueue = queue; queue = []; i = -1; while (++i < len) { oldQueue[i](); } len = queue.length; } draining = false; } module.exports = immediate; function immediate(task) { if (queue.push(task) === 1 && !draining) { scheduleDrain(); } } }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); },{}],2:[function(_dereq_,module,exports){ var immediate = _dereq_(1); /* istanbul ignore next */ function INTERNAL() {} var handlers = {}; var REJECTED = ['REJECTED']; var FULFILLED = ['FULFILLED']; var PENDING = ['PENDING']; module.exports = Promise; function Promise(resolver) { if (typeof resolver !== 'function') { throw new TypeError('resolver must be a function'); } this.state = PENDING; this.queue = []; this.outcome = void 0; if (resolver !== INTERNAL) { safelyResolveThenable(this, resolver); } } Promise.prototype["catch"] = function (onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function (onFulfilled, onRejected) { if (typeof onFulfilled !== 'function' && this.state === FULFILLED || typeof onRejected !== 'function' && this.state === REJECTED) { return this; } var promise = new this.constructor(INTERNAL); if (this.state !== PENDING) { var resolver = this.state === FULFILLED ? onFulfilled : onRejected; unwrap(promise, resolver, this.outcome); } else { this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); } return promise; }; function QueueItem(promise, onFulfilled, onRejected) { this.promise = promise; if (typeof onFulfilled === 'function') { this.onFulfilled = onFulfilled; this.callFulfilled = this.otherCallFulfilled; } if (typeof onRejected === 'function') { this.onRejected = onRejected; this.callRejected = this.otherCallRejected; } } QueueItem.prototype.callFulfilled = function (value) { handlers.resolve(this.promise, value); }; QueueItem.prototype.otherCallFulfilled = function (value) { unwrap(this.promise, this.onFulfilled, value); }; QueueItem.prototype.callRejected = function (value) { handlers.reject(this.promise, value); }; QueueItem.prototype.otherCallRejected = function (value) { unwrap(this.promise, this.onRejected, value); }; function unwrap(promise, func, value) { immediate(function () { var returnValue; try { returnValue = func(value); } catch (e) { return handlers.reject(promise, e); } if (returnValue === promise) { handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); } else { handlers.resolve(promise, returnValue); } }); } handlers.resolve = function (self, value) { var result = tryCatch(getThen, value); if (result.status === 'error') { return handlers.reject(self, result.value); } var thenable = result.value; if (thenable) { safelyResolveThenable(self, thenable); } else { self.state = FULFILLED; self.outcome = value; var i = -1; var len = self.queue.length; while (++i < len) { self.queue[i].callFulfilled(value); } } return self; }; handlers.reject = function (self, error) { self.state = REJECTED; self.outcome = error; var i = -1; var len = self.queue.length; while (++i < len) { self.queue[i].callRejected(error); } return self; }; function getThen(obj) { // Make sure we only access the accessor once as required by the spec var then = obj && obj.then; if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') { return function appyThen() { then.apply(obj, arguments); }; } } function safelyResolveThenable(self, thenable) { // Either fulfill, reject or reject with error var called = false; function onError(value) { if (called) { return; } called = true; handlers.reject(self, value); } function onSuccess(value) { if (called) { return; } called = true; handlers.resolve(self, value); } function tryToUnwrap() { thenable(onSuccess, onError); } var result = tryCatch(tryToUnwrap); if (result.status === 'error') { onError(result.value); } } function tryCatch(func, value) { var out = {}; try { out.value = func(value); out.status = 'success'; } catch (e) { out.status = 'error'; out.value = e; } return out; } Promise.resolve = resolve; function resolve(value) { if (value instanceof this) { return value; } return handlers.resolve(new this(INTERNAL), value); } Promise.reject = reject; function reject(reason) { var promise = new this(INTERNAL); return handlers.reject(promise, reason); } Promise.all = all; function all(iterable) { var self = this; if (Object.prototype.toString.call(iterable) !== '[object Array]') { return this.reject(new TypeError('must be an array')); } var len = iterable.length; var called = false; if (!len) { return this.resolve([]); } var values = new Array(len); var resolved = 0; var i = -1; var promise = new this(INTERNAL); while (++i < len) { allResolver(iterable[i], i); } return promise; function allResolver(value, i) { self.resolve(value).then(resolveFromAll, function (error) { if (!called) { called = true; handlers.reject(promise, error); } }); function resolveFromAll(outValue) { values[i] = outValue; if (++resolved === len && !called) { called = true; handlers.resolve(promise, values); } } } } Promise.race = race; function race(iterable) { var self = this; if (Object.prototype.toString.call(iterable) !== '[object Array]') { return this.reject(new TypeError('must be an array')); } var len = iterable.length; var called = false; if (!len) { return this.resolve([]); } var i = -1; var promise = new this(INTERNAL); while (++i < len) { resolver(iterable[i]); } return promise; function resolver(value) { self.resolve(value).then(function (response) { if (!called) { called = true; handlers.resolve(promise, response); } }, function (error) { if (!called) { called = true; handlers.reject(promise, error); } }); } } },{"1":1}],3:[function(_dereq_,module,exports){ (function (global){ if (typeof global.Promise !== 'function') { global.Promise = _dereq_(2); } }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); },{"2":2}],4:[function(_dereq_,module,exports){ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function getIDB() { /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ try { if (typeof indexedDB !== 'undefined') { return indexedDB; } if (typeof webkitIndexedDB !== 'undefined') { return webkitIndexedDB; } if (typeof mozIndexedDB !== 'undefined') { return mozIndexedDB; } if (typeof OIndexedDB !== 'undefined') { return OIndexedDB; } if (typeof msIndexedDB !== 'undefined') { return msIndexedDB; } } catch (e) { return; } } var idb = getIDB(); function isIndexedDBValid() { try { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. if (!idb || !idb.open) { return false; } // We mimic PouchDB here; // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1; // Safari <10.1 does not meet our requirements for IDB support // (see: https://github.com/pouchdb/pouchdb/issues/5572). // Safari 10.1 shipped with fetch, we can use that to detect it. // Note: this creates issues with `window.fetch` polyfills and // overrides; see: // https://github.com/localForage/localForage/issues/856 return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' && // some outdated implementations of IDB that appear on Samsung // and HTC Android devices <4.4 are missing IDBKeyRange // See: https://github.com/mozilla/localForage/issues/128 // See: https://github.com/mozilla/localForage/issues/272 typeof IDBKeyRange !== 'undefined'; } catch (e) { return false; } } // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function createBlob(parts, properties) { /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder; var builder = new Builder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // This is CommonJS because lie is an external dependency, so Rollup // can just ignore it. if (typeof Promise === 'undefined') { // In the "nopromises" build this will just throw if you don't have // a global promise object, but it would throw anyway later. _dereq_(3); } var Promise$1 = Promise; function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } function executeTwoCallbacks(promise, callback, errorCallback) { if (typeof callback === 'function') { promise.then(callback); } if (typeof errorCallback === 'function') { promise["catch"](errorCallback); } } function normalizeKey(key) { // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } return key; } function getCallback() { if (arguments.length && typeof arguments[arguments.length - 1] === 'function') { return arguments[arguments.length - 1]; } } // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs = void 0; var dbContexts = {}; var toString = Object.prototype.toString; // Transaction Modes var READ_ONLY = 'readonly'; var READ_WRITE = 'readwrite'; // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // // Blobs are not supported in all versions of IndexedDB, notably // Chrome <37 and Android <5. In those versions, storing a blob will throw. // // Various other blob bugs exist in Chrome v37-42 (inclusive). // Detecting them is expensive and confusing to users, and Chrome 37-42 // is at very low usage worldwide, so we do a hacky userAgent check instead. // // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // // Code borrowed from PouchDB. See: // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js // function _checkBlobSupportWithoutCaching(idb) { return new Promise$1(function (resolve) { var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); var blob = createBlob(['']); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.onabort = function (e) { // If the transaction aborts now its due to not being able to // write to the database, likely due to the disk being full e.preventDefault(); e.stopPropagation(); resolve(false); }; txn.oncomplete = function () { var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); var matchedEdge = navigator.userAgent.match(/Edge\//); // MS Edge pretends to be Chrome 42: // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); }; })["catch"](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise$1.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } function _deferReadiness(dbInfo) { var dbContext = dbContexts[dbInfo.name]; // Create a deferred object representing the current database operation. var deferredOperation = {}; deferredOperation.promise = new Promise$1(function (resolve, reject) { deferredOperation.resolve = resolve; deferredOperation.reject = reject; }); // Enqueue the deferred operation. dbContext.deferredOperations.push(deferredOperation); // Chain its promise to the database readiness. if (!dbContext.dbReady) { dbContext.dbReady = deferredOperation.promise; } else { dbContext.dbReady = dbContext.dbReady.then(function () { return deferredOperation.promise; }); } } function _advanceReadiness(dbInfo) { var dbContext = dbContexts[dbInfo.name]; // Dequeue a deferred operation. var deferredOperation = dbContext.deferredOperations.pop(); // Resolve its promise (which is part of the database readiness // chain of promises). if (deferredOperation) { deferredOperation.resolve(); return deferredOperation.promise; } } function _rejectReadiness(dbInfo, err) { var dbContext = dbContexts[dbInfo.name]; // Dequeue a deferred operation. var deferredOperation = dbContext.deferredOperations.pop(); // Reject its promise (which is part of the database readiness // chain of promises). if (deferredOperation) { deferredOperation.reject(err); return deferredOperation.promise; } } function _getConnection(dbInfo, upgradeNeeded) { return new Promise$1(function (resolve, reject) { dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); if (dbInfo.db) { if (upgradeNeeded) { _deferReadiness(dbInfo); dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = idb.open.apply(idb, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function (e) { e.preventDefault(); reject(openreq.error); }; openreq.onsuccess = function () { var db = openreq.result; db.onversionchange = function (e) { // Triggered when the database is modified (e.g. adding an objectStore) or // deleted (even when initiated by other sessions in different tabs). // Closing the connection here prevents those operations from being blocked. // If the database is accessed again later by this instance, the connection // will be reopened or the database recreated as needed. e.target.close(); }; resolve(db); _advanceReadiness(dbInfo); }; }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise$1(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Specialize the default `ready()` function by making it dependent // on the current database operations. Thus, the driver will be actually // ready when it's been initialized (default) *and* there are no pending // operations on the database (initiated by some other instances). function _fullyReady(callback) { var self = this; var promise = self._initReady().then(function () { var dbContext = dbContexts[self._dbInfo.name]; if (dbContext && dbContext.dbReady) { return dbContext.dbReady; } }); executeTwoCallbacks(promise, callback, callback); return promise; } // Try to establish a new db connection to replace the // current one which is broken (i.e. experiencing // InvalidStateError while creating a transaction). function _tryReconnect(dbInfo) { _deferReadiness(dbInfo); var dbContext = dbContexts[dbInfo.name]; var forages = dbContext.forages; for (var i = 0; i < forages.length; i++) { var forage = forages[i]; if (forage._dbInfo.db) { forage._dbInfo.db.close(); forage._dbInfo.db = null; } } dbInfo.db = null; return _getOriginalConnection(dbInfo).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { // store the latest db reference // in case the db was upgraded dbInfo.db = dbContext.db = db; for (var i = 0; i < forages.length; i++) { forages[i]._dbInfo.db = db; } })["catch"](function (err) { _rejectReadiness(dbInfo, err); throw err; }); } // FF doesn't like Promises (micro-tasks) and IDDB store operations, // so we have to do it with callbacks function createTransaction(dbInfo, mode, callback, retries) { if (retries === undefined) { retries = 1; } try { var tx = dbInfo.db.transaction(dbInfo.storeName, mode); callback(null, tx); } catch (err) { if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) { return Promise$1.resolve().then(function () { if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { // increase the db version, to create the new ObjectStore if (dbInfo.db) { dbInfo.version = dbInfo.db.version + 1; } // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } }).then(function () { return _tryReconnect(dbInfo).then(function () { createTransaction(dbInfo, mode, callback, retries - 1); }); })["catch"](callback); } callback(err); } } function createDbContext() { return { // Running localForages sharing a database. forages: [], // Shared database. db: null, // Database readiness (promise). dbReady: null, // Deferred operations on the database. deferredOperations: [] }; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = createDbContext(); // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(self); // Replace the default `ready()` function with the specialized one. if (!self._initReady) { self._initReady = self.ready; self.ready = _fullyReady; } // Create an array of initialization states of the related localForages. var initPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise$1.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== self) { // Don't wait for itself... initPromises.push(forage._initReady()["catch"](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise$1.all(initPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k = 0; k < forages.length; k++) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function getItem(key, callback) { var self = this; key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); // when the iterator callback returns any // (non-`undefined`) value, then we stop // the iteration immediately if (result !== void 0) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; if (toString.call(value) === '[object Blob]') { return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { if (blobSupport) { return value; } return _encodeBlob(value); }); } return value; }).then(function (value) { createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `.delete()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store["delete"](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var advanced = false; var req = store.openKeyCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.openKeyCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor["continue"](); }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function dropInstance(options, callback) { callback = getCallback.apply(this, arguments); var currentConfig = this.config(); options = typeof options !== 'function' && options || {}; if (!options.name) { options.name = options.name || currentConfig.name; options.storeName = options.storeName || currentConfig.storeName; } var self = this; var promise; if (!options.name) { promise = Promise$1.reject('Invalid arguments'); } else { var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db; var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) { var dbContext = dbContexts[options.name]; var forages = dbContext.forages; dbContext.db = db; for (var i = 0; i < forages.length; i++) { forages[i]._dbInfo.db = db; } return db; }); if (!options.storeName) { promise = dbPromise.then(function (db) { _deferReadiness(options); var dbContext = dbContexts[options.name]; var forages = dbContext.forages; db.close(); for (var i = 0; i < forages.length; i++) { var forage = forages[i]; forage._dbInfo.db = null; } var dropDBPromise = new Promise$1(function (resolve, reject) { var req = idb.deleteDatabase(options.name); req.onerror = function () { var db = req.result; if (db) { db.close(); } reject(req.error); }; req.onblocked = function () { // Closing all open connections in onversionchange handler should prevent this situation, but if // we do get here, it just means the request remains pending - eventually it will succeed or error console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed'); }; req.onsuccess = function () { var db = req.result; if (db) { db.close(); } resolve(db); }; }); return dropDBPromise.then(function (db) { dbContext.db = db; for (var i = 0; i < forages.length; i++) { var _forage = forages[i]; _advanceReadiness(_forage._dbInfo); } })["catch"](function (err) { (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); throw err; }); }); } else { promise = dbPromise.then(function (db) { if (!db.objectStoreNames.contains(options.storeName)) { return; } var newVersion = db.version + 1; _deferReadiness(options); var dbContext = dbContexts[options.name]; var forages = dbContext.forages; db.close(); for (var i = 0; i < forages.length; i++) { var forage = forages[i]; forage._dbInfo.db = null; forage._dbInfo.version = newVersion; } var dropObjectPromise = new Promise$1(function (resolve, reject) { var req = idb.open(options.name, newVersion); req.onerror = function (err) { var db = req.result; db.close(); reject(err); }; req.onupgradeneeded = function () { var db = req.result; db.deleteObjectStore(options.storeName); }; req.onsuccess = function () { var db = req.result; db.close(); resolve(db); }; }); return dropObjectPromise.then(function (db) { dbContext.db = db; for (var j = 0; j < forages.length; j++) { var _forage2 = forages[j]; _forage2._dbInfo.db = db; _advanceReadiness(_forage2._dbInfo); } })["catch"](function (err) { (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); throw err; }); }); } } executeCallback(promise, callback); return promise; } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, _support: isIndexedDBValid(), iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys, dropInstance: dropInstance }; function isWebSQLValid() { return typeof openDatabase === 'function'; } // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; var toString$1 = Object.prototype.toString; function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueType = ''; if (value) { valueType = toString$1.call(value); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueType === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueType === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueType === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueType === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueType === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueType === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueType === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueType === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueType === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueType === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ function createDbTable(t, dbInfo, callback, errorCallback) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback); } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage$1(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise$1(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return reject(e); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { createDbTable(t, dbInfo, function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }, reject); }); dbInfo.serializer = localforageSerializer; return dbInfoPromise; } function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { t.executeSql(sqlStatement, args, callback, function (t, error) { if (error.code === error.SYNTAX_ERR) { t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) { if (!results.rows.length) { // if the table is missing (was deleted) // re-create it table and retry createDbTable(t, dbInfo, function () { t.executeSql(sqlStatement, args, callback, errorCallback); }, errorCallback); } else { errorCallback(t, error); } }, errorCallback); } else { errorCallback(t, error); } }, errorCallback); } function getItem$1(key, callback) { var self = this; key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function iterate$1(iterator, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function _setItem(key, value, callback, retriesLeft) { var self = this; key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // Try to re-run the transaction. if (retriesLeft > 0) { resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1])); return; } reject(sqlError); } }); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function setItem$1(key, value, callback) { return _setItem.apply(this, [key, value, callback, 1]); } function removeItem$1(key, callback) { var self = this; key = normalizeKey(key); var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear$1(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length$1(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key$1(n, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } function keys$1(callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })["catch"](reject); }); executeCallback(promise, callback); return promise; } // https://www.w3.org/TR/webdatabase/#databases // > There is no way to enumerate or delete the databases available for an origin from this API. function getAllStoreNames(db) { return new Promise$1(function (resolve, reject) { db.transaction(function (t) { t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) { var storeNames = []; for (var i = 0; i < results.rows.length; i++) { storeNames.push(results.rows.item(i).name); } resolve({ db: db, storeNames: storeNames }); }, function (t, error) { reject(error); }); }, function (sqlError) { reject(sqlError); }); }); } function dropInstance$1(options, callback) { callback = getCallback.apply(this, arguments); var currentConfig = this.config(); options = typeof options !== 'function' && options || {}; if (!options.name) { options.name = options.name || currentConfig.name; options.storeName = options.storeName || currentConfig.storeName; } var self = this; var promise; if (!options.name) { promise = Promise$1.reject('Invalid arguments'); } else { promise = new Promise$1(function (resolve) { var db; if (options.name === currentConfig.name) { // use the db reference of the current instance db = self._dbInfo.db; } else { db = openDatabase(options.name, '', '', 0); } if (!options.storeName) { // drop all database tables resolve(getAllStoreNames(db)); } else { resolve({ db: db, storeNames: [options.storeName] }); } }).then(function (operationInfo) { return new Promise$1(function (resolve, reject) { operationInfo.db.transaction(function (t) { function dropTable(storeName) { return new Promise$1(function (resolve, reject) { t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); } var operations = []; for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) { operations.push(dropTable(operationInfo.storeNames[i])); } Promise$1.all(operations).then(function () { resolve(); })["catch"](function (e) { reject(e); }); }, function (sqlError) { reject(sqlError); }); }); }); } executeCallback(promise, callback); return promise; } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage$1, _support: isWebSQLValid(), iterate: iterate$1, getItem: getItem$1, setItem: setItem$1, removeItem: removeItem$1, clear: clear$1, length: length$1, key: key$1, keys: keys$1, dropInstance: dropInstance$1 }; function isLocalStorageValid() { try { return typeof localStorage !== 'undefined' && 'setItem' in localStorage && // in IE8 typeof localStorage.setItem === 'object' !!localStorage.setItem; } catch (e) { return false; } } function _getKeyPrefix(options, defaultConfig) { var keyPrefix = options.name + '/'; if (options.storeName !== defaultConfig.storeName) { keyPrefix += options.storeName + '/'; } return keyPrefix; } // Check if localStorage throws when saving an item function checkIfLocalStorageThrows() { var localStorageTestKey = '_localforage_support_test'; try { localStorage.setItem(localStorageTestKey, true); localStorage.removeItem(localStorageTestKey); return false; } catch (e) { return true; } } // Check if localStorage is usable and allows to save an item // This method checks if localStorage is usable in Safari Private Browsing // mode, or in any other case where the available quota for localStorage // is 0 and there wasn't any saved items yet. function _isLocalStorageUsable() { return !checkIfLocalStorageThrows() || localStorage.length > 0; } // Config the localStorage backend, using options set in the config. function _initStorage$2(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig); if (!_isLocalStorageUsable()) { return Promise$1.reject(); } self._dbInfo = dbInfo; dbInfo.serializer = localforageSerializer; return Promise$1.resolve(); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear$2(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem$2(key, callback) { var self = this; key = normalizeKey(key); var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate$2(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key$2(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys$2(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { var itemKey = localStorage.key(i); if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { keys.push(itemKey.substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length$2(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem$2(key, callback) { var self = this; key = normalizeKey(key); var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem$2(key, value, callback) { var self = this; key = normalizeKey(key); var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise$1(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function dropInstance$2(options, callback) { callback = getCallback.apply(this, arguments); options = typeof options !== 'function' && options || {}; if (!options.name) { var currentConfig = this.config(); options.name = options.name || currentConfig.name; options.storeName = options.storeName || currentConfig.storeName; } var self = this; var promise; if (!options.name) { promise = Promise$1.reject('Invalid arguments'); } else { promise = new Promise$1(function (resolve) { if (!options.storeName) { resolve(options.name + '/'); } else { resolve(_getKeyPrefix(options, self._defaultConfig)); } }).then(function (keyPrefix) { for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); } executeCallback(promise, callback); return promise; } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage$2, _support: isLocalStorageValid(), iterate: iterate$2, getItem: getItem$2, setItem: setItem$2, removeItem: removeItem$2, clear: clear$2, length: length$2, key: key$2, keys: keys$2, dropInstance: dropInstance$2 }; var sameValue = function sameValue(x, y) { return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); }; var includes = function includes(array, searchElement) { var len = array.length; var i = 0; while (i < len) { if (sameValue(array[i], searchElement)) { return true; } i++; } return false; }; var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; // Drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var DefinedDrivers = {}; var DriverSupport = {}; var DefaultDrivers = { INDEXEDDB: asyncStorage, WEBSQL: webSQLStorage, LOCALSTORAGE: localStorageWrapper }; var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; var OptionalDriverMethods = ['dropInstance']; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods); var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var _key in arg) { if (arg.hasOwnProperty(_key)) { if (isArray(arg[_key])) { arguments[0][_key] = arg[_key].slice(); } else { arguments[0][_key] = arg[_key]; } } } } } return arguments[0]; } var LocalForage = function () { function LocalForage(options) { _classCallCheck(this, LocalForage); for (var driverTypeKey in DefaultDrivers) { if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { var driver = DefaultDrivers[driverTypeKey]; var driverName = driver._driver; this[driverTypeKey] = driverName; if (!DefinedDrivers[driverName]) { // we don't need to wait for the promise, // since the default drivers can be defined // in a blocking manner this.defineDriver(driver); } } } this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver)["catch"](function () {}); } // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } if (i === 'version' && typeof options[i] !== 'number') { return new Error('Database version must be a number.'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { return this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise$1(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } var driverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0, len = driverMethods.length; i < len; i++) { var driverMethodName = driverMethods[i]; // when the property is there, // it should be a method even when optional var isRequired = !includes(OptionalDriverMethods, driverMethodName); if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') { reject(complianceError); return; } } var configureMissingMethods = function configureMissingMethods() { var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { return function () { var error = new Error('Method ' + methodName + ' is not implemented by the current driver'); var promise = Promise$1.reject(error); executeCallback(promise, arguments[arguments.length - 1]); return promise; }; }; for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) { var optionalDriverMethod = OptionalDriverMethods[_i]; if (!driverObject[optionalDriverMethod]) { driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); } } }; configureMissingMethods(); var setDriverSupport = function setDriverSupport(support) { if (DefinedDrivers[driverName]) { console.info('Redefining LocalForage driver: ' + driverName); } DefinedDrivers[driverName] = driverObject; DriverSupport[driverName] = support; // don't use a then, so that we can define // drivers that have simple _support methods // in a blocking manner resolve(); }; if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { driverObject._support().then(setDriverSupport, reject); } else { setDriverSupport(!!driverObject._support); } } else { setDriverSupport(true); } } catch (e) { reject(e); } }); executeTwoCallbacks(promise, callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.')); executeTwoCallbacks(getDriverPromise, callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = Promise$1.resolve(localforageSerializer); executeTwoCallbacks(serializerPromise, callback); return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); executeTwoCallbacks(promise, callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function extendSelfWithDriver(driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise$1.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () { return Promise$1.resolve(); }) : Promise$1.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })["catch"](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise$1.reject(error); return self._driverSet; }); executeTwoCallbacks(this._driverSet, callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!DriverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0, len = LibraryMethods.length; i < len; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; }(); // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localforage_js = new LocalForage(); module.exports = localforage_js; },{"3":3}]},{},[4])(4) }); } (localforage$1)); const localforage = localforageExports; var KEY_PREFIX = 'persist:'; var FLUSH = 'persist/FLUSH'; var REHYDRATE = 'persist/REHYDRATE'; var PAUSE = 'persist/PAUSE'; var PERSIST = 'persist/PERSIST'; var PURGE = 'persist/PURGE'; var REGISTER = 'persist/REGISTER'; var DEFAULT_VERSION = -1; function _typeof$1(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); } function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(source, true).forEach(function (key) { _defineProperty$5(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty$5(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /* autoMergeLevel1: - merges 1 level of substate - skips substate if already modified */ function autoMergeLevel1(inboundState, originalState, reducedState, _ref) { _ref.debug; var newState = _objectSpread$4({}, reducedState); // only rehydrate if inboundState exists and is an object if (inboundState && _typeof$1(inboundState) === 'object') { Object.keys(inboundState).forEach(function (key) { // ignore _persist data if (key === '_persist') return; // if reducer modifies substate, skip auto rehydration if (originalState[key] !== reducedState[key]) { return; } // otherwise hard set the new value newState[key] = inboundState[key]; }); } return newState; } // @TODO remove once flow < 0.63 support is no longer required. function createPersistoid(config) { // defaults var blacklist = config.blacklist || null; var whitelist = config.whitelist || null; var transforms = config.transforms || []; var throttle = config.throttle || 0; var storageKey = "".concat(config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX).concat(config.key); var storage = config.storage; var serialize; if (config.serialize === false) { serialize = function serialize(x) { return x; }; } else if (typeof config.serialize === 'function') { serialize = config.serialize; } else { serialize = defaultSerialize; } var writeFailHandler = config.writeFailHandler || null; // initialize stateful values var lastState = {}; var stagedState = {}; var keysToProcess = []; var timeIterator = null; var writePromise = null; var update = function update(state) { // add any changed keys to the queue Object.keys(state).forEach(function (key) { if (!passWhitelistBlacklist(key)) return; // is keyspace ignored? noop if (lastState[key] === state[key]) return; // value unchanged? noop if (keysToProcess.indexOf(key) !== -1) return; // is key already queued? noop keysToProcess.push(key); // add key to queue }); //if any key is missing in the new state which was present in the lastState, //add it for processing too Object.keys(lastState).forEach(function (key) { if (state[key] === undefined && passWhitelistBlacklist(key) && keysToProcess.indexOf(key) === -1 && lastState[key] !== undefined) { keysToProcess.push(key); } }); // start the time iterator if not running (read: throttle) if (timeIterator === null) { timeIterator = setInterval(processNextKey, throttle); } lastState = state; }; function processNextKey() { if (keysToProcess.length === 0) { if (timeIterator) clearInterval(timeIterator); timeIterator = null; return; } var key = keysToProcess.shift(); var endState = transforms.reduce(function (subState, transformer) { return transformer.in(subState, key, lastState); }, lastState[key]); if (endState !== undefined) { try { stagedState[key] = serialize(endState); } catch (err) { console.error('redux-persist/createPersistoid: error serializing state', err); } } else { //if the endState is undefined, no need to persist the existing serialized content delete stagedState[key]; } if (keysToProcess.length === 0) { writeStagedState(); } } function writeStagedState() { // cleanup any removed keys just before write. Object.keys(stagedState).forEach(function (key) { if (lastState[key] === undefined) { delete stagedState[key]; } }); writePromise = storage.setItem(storageKey, serialize(stagedState)).catch(onWriteFail); } function passWhitelistBlacklist(key) { if (whitelist && whitelist.indexOf(key) === -1 && key !== '_persist') return false; if (blacklist && blacklist.indexOf(key) !== -1) return false; return true; } function onWriteFail(err) { // @TODO add fail handlers (typically storage full) if (writeFailHandler) writeFailHandler(err); if (err && "production" !== 'production') { console.error('Error storing data', err); } } var flush = function flush() { while (keysToProcess.length !== 0) { processNextKey(); } return writePromise || Promise.resolve(); }; // return `persistoid` return { update: update, flush: flush }; } // @NOTE in the future this may be exposed via config function defaultSerialize(data) { return JSON.stringify(data); } function getStoredState(config) { var transforms = config.transforms || []; var storageKey = "".concat(config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX).concat(config.key); var storage = config.storage; config.debug; var deserialize; if (config.deserialize === false) { deserialize = function deserialize(x) { return x; }; } else if (typeof config.deserialize === 'function') { deserialize = config.deserialize; } else { deserialize = defaultDeserialize; } return storage.getItem(storageKey).then(function (serialized) { if (!serialized) return undefined;else { try { var state = {}; var rawState = deserialize(serialized); Object.keys(rawState).forEach(function (key) { state[key] = transforms.reduceRight(function (subState, transformer) { return transformer.out(subState, key, rawState); }, deserialize(rawState[key])); }); return state; } catch (err) { throw err; } } }); } function defaultDeserialize(serial) { return JSON.parse(serial); } function purgeStoredState(config) { var storage = config.storage; var storageKey = "".concat(config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX).concat(config.key); return storage.removeItem(storageKey, warnIfRemoveError); } function warnIfRemoveError(err) { if (err && "production" !== 'production') { console.error('redux-persist/purgeStoredState: Error purging data stored state', err); } } function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(source, true).forEach(function (key) { _defineProperty$4(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties$1(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose$1(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose$1(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var DEFAULT_TIMEOUT = 5000; /* @TODO add validation / handling for: - persisting a reducer which has nested _persist - handling actions that fire before reydrate is called */ function persistReducer(config, baseReducer) { var version = config.version !== undefined ? config.version : DEFAULT_VERSION; config.debug || false; var stateReconciler = config.stateReconciler === undefined ? autoMergeLevel1 : config.stateReconciler; var getStoredState$1 = config.getStoredState || getStoredState; var timeout = config.timeout !== undefined ? config.timeout : DEFAULT_TIMEOUT; var _persistoid = null; var _purge = false; var _paused = true; var conditionalUpdate = function conditionalUpdate(state) { // update the persistoid only if we are rehydrated and not paused state._persist.rehydrated && _persistoid && !_paused && _persistoid.update(state); return state; }; return function (state, action) { var _ref = state || {}, _persist = _ref._persist, rest = _objectWithoutProperties$1(_ref, ["_persist"]); // $FlowIgnore need to update State type var restState = rest; if (action.type === PERSIST) { var _sealed = false; var _rehydrate = function _rehydrate(payload, err) { if (!_sealed) { action.rehydrate(config.key, payload, err); _sealed = true; } }; timeout && setTimeout(function () { !_sealed && _rehydrate(undefined, new Error("redux-persist: persist timed out for persist key \"".concat(config.key, "\""))); }, timeout); // @NOTE PERSIST resumes if paused. _paused = false; // @NOTE only ever create persistoid once, ensure we call it at least once, even if _persist has already been set if (!_persistoid) _persistoid = createPersistoid(config); // @NOTE PERSIST can be called multiple times, noop after the first if (_persist) { // We still need to call the base reducer because there might be nested // uses of persistReducer which need to be aware of the PERSIST action return _objectSpread$3({}, baseReducer(restState, action), { _persist: _persist }); } if (typeof action.rehydrate !== 'function' || typeof action.register !== 'function') throw new Error('redux-persist: either rehydrate or register is not a function on the PERSIST action. This can happen if the action is being replayed. This is an unexplored use case, please open an issue and we will figure out a resolution.'); action.register(config.key); getStoredState$1(config).then(function (restoredState) { var migrate = config.migrate || function (s, v) { return Promise.resolve(s); }; migrate(restoredState, version).then(function (migratedState) { _rehydrate(migratedState); }, function (migrateErr) { _rehydrate(undefined, migrateErr); }); }, function (err) { _rehydrate(undefined, err); }); return _objectSpread$3({}, baseReducer(restState, action), { _persist: { version: version, rehydrated: false } }); } else if (action.type === PURGE) { _purge = true; action.result(purgeStoredState(config)); return _objectSpread$3({}, baseReducer(restState, action), { _persist: _persist }); } else if (action.type === FLUSH) { action.result(_persistoid && _persistoid.flush()); return _objectSpread$3({}, baseReducer(restState, action), { _persist: _persist }); } else if (action.type === PAUSE) { _paused = true; } else if (action.type === REHYDRATE) { // noop on restState if purging if (_purge) return _objectSpread$3({}, restState, { _persist: _objectSpread$3({}, _persist, { rehydrated: true }) // @NOTE if key does not match, will continue to default else below }); if (action.key === config.key) { var reducedState = baseReducer(restState, action); var inboundState = action.payload; // only reconcile state if stateReconciler and inboundState are both defined var reconciledRest = stateReconciler !== false && inboundState !== undefined ? stateReconciler(inboundState, state, reducedState, config) : reducedState; var _newState = _objectSpread$3({}, reconciledRest, { _persist: _objectSpread$3({}, _persist, { rehydrated: true }) }); return conditionalUpdate(_newState); } } // if we have not already handled PERSIST, straight passthrough if (!_persist) return baseReducer(state, action); // run base reducer: // is state modified ? return original : return updated var newState = baseReducer(restState, action); if (newState === restState) return state; return conditionalUpdate(_objectSpread$3({}, newState, { _persist: _persist })); }; } function _toConsumableArray$2(arr) { return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _nonIterableSpread$2(); } function _nonIterableSpread$2() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray$2(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles$2(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(source, true).forEach(function (key) { _defineProperty$3(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var initialState$5 = { registry: [], bootstrapped: false }; var persistorReducer = function persistorReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$5; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case REGISTER: return _objectSpread$2({}, state, { registry: [].concat(_toConsumableArray$2(state.registry), [action.key]) }); case REHYDRATE: var firstIndex = state.registry.indexOf(action.key); var registry = _toConsumableArray$2(state.registry); registry.splice(firstIndex, 1); return _objectSpread$2({}, state, { registry: registry, bootstrapped: registry.length === 0 }); default: return state; } }; function persistStore(store, options, cb) { var boostrappedCb = cb || false; var _pStore = createStore(persistorReducer, initialState$5, options && options.enhancer ? options.enhancer : undefined); var register = function register(key) { _pStore.dispatch({ type: REGISTER, key: key }); }; var rehydrate = function rehydrate(key, payload, err) { var rehydrateAction = { type: REHYDRATE, payload: payload, err: err, key: key // dispatch to `store` to rehydrate and `persistor` to track result }; store.dispatch(rehydrateAction); _pStore.dispatch(rehydrateAction); if (boostrappedCb && persistor.getState().bootstrapped) { boostrappedCb(); boostrappedCb = false; } }; var persistor = _objectSpread$2({}, _pStore, { purge: function purge() { var results = []; store.dispatch({ type: PURGE, result: function result(purgeResult) { results.push(purgeResult); } }); return Promise.all(results); }, flush: function flush() { var results = []; store.dispatch({ type: FLUSH, result: function result(flushResult) { results.push(flushResult); } }); return Promise.all(results); }, pause: function pause() { store.dispatch({ type: PAUSE }); }, persist: function persist() { store.dispatch({ type: PERSIST, register: register, rehydrate: rehydrate }); } }); if (!(options && options.manualPersist)) { persistor.persist(); } return persistor; } const initialState$4 = { chunks: [] }; const chunkDataSlice = createSlice({ initialState: initialState$4, name: "chunkData", reducers: { addChunk: (state, action) => { state.chunks.push(action.payload); }, setPixel: (state, action) => { const { chunkX, chunkY, pixels } = action.payload; const chunk = state.chunks.find((x) => x.chunkX === chunkX && x.chunkY === chunkY); if (!chunk || chunk.fetching) return; pixels.forEach((p) => { chunk.chunkData.set([p.color], p.offsetInChunk); }); } }, extraReducers: (builder) => { builder.addCase(fetchChunkDataAction.pending, (state, action) => { const foundChunk = state.chunks.some((x) => x.chunkX === action.meta.arg.chunkX && x.chunkY === action.meta.arg.chunkY); if (!foundChunk) { state.chunks.push({ chunkX: action.meta.arg.chunkX, chunkY: action.meta.arg.chunkY, fetching: true }); return; } state.chunks = state.chunks.map((c) => { if (c.chunkX === action.meta.arg.chunkX && c.chunkY === action.meta.arg.chunkY) { return { chunkX: action.meta.arg.chunkX, chunkY: action.meta.arg.chunkY, fetching: true }; } return c; }); }); builder.addCase(fetchChunkDataAction.fulfilled, (state, action) => { const foundChunk = state.chunks.some((x) => x.chunkX === action.meta.arg.chunkX && x.chunkY === action.meta.arg.chunkY); if (!foundChunk) { state.chunks.push({ chunkX: action.meta.arg.chunkX, chunkY: action.meta.arg.chunkY, chunkData: action.payload, fetching: false }); return; } state.chunks = state.chunks.map((chunk) => { if (chunk.chunkX === action.meta.arg.chunkX && chunk.chunkY === action.meta.arg.chunkY) { return { chunkX: action.meta.arg.chunkX, chunkY: action.meta.arg.chunkY, fetching: false, chunkData: action.payload }; } return chunk; }); }); builder.addCase(fetchChunkDataAction.rejected, (state, action) => { state.chunks = state.chunks.filter((x) => x.chunkX !== action.meta.arg.chunkX && x.chunkY !== action.meta.arg.chunkY); }); } }); const fetchChunkDataAction = createAsyncThunk("chunkData/fetchChunkData", async (chunkCoords, { getState }) => { const canvasId = selectCanvasId(getState()); const chunkData = await fetch(`/chunks/${canvasId}/${chunkCoords.chunkX}/${chunkCoords.chunkY}.bmp`).then((x) => x.arrayBuffer()).then((x) => new Uint8Array(x)); return chunkData; }); function isStringOrNumber(value) { return typeof value === 'string' || typeof value === 'number'; } var FlatObjectCache = /*#__PURE__*/function () { function FlatObjectCache() { this._cache = {}; } var _proto = FlatObjectCache.prototype; _proto.set = function set(key, selectorFn) { this._cache[key] = selectorFn; }; _proto.get = function get(key) { return this._cache[key]; }; _proto.remove = function remove(key) { delete this._cache[key]; }; _proto.clear = function clear() { this._cache = {}; }; _proto.isValidCacheKey = function isValidCacheKey(cacheKey) { return isStringOrNumber(cacheKey); }; return FlatObjectCache; }(); var defaultCacheCreator = FlatObjectCache; var defaultCacheKeyValidator = function defaultCacheKeyValidator() { return true; }; function createCachedSelector() { for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } return function (polymorphicOptions, legacyOptions) { if (legacyOptions) { throw new Error('[re-reselect] "options" as second argument is not supported anymore. Please provide an option object as single argument.'); } var options = typeof polymorphicOptions === 'function' ? { keySelector: polymorphicOptions } : Object.assign({}, polymorphicOptions); // https://github.com/reduxjs/reselect/blob/v4.0.0/src/index.js#L54 var recomputations = 0; var resultFunc = funcs.pop(); var dependencies = Array.isArray(funcs[0]) ? funcs[0] : [].concat(funcs); var resultFuncWithRecomputations = function resultFuncWithRecomputations() { recomputations++; return resultFunc.apply(void 0, arguments); }; funcs.push(resultFuncWithRecomputations); var cache = options.cacheObject || new defaultCacheCreator(); var selectorCreator = options.selectorCreator || createSelector; var isValidCacheKey = cache.isValidCacheKey || defaultCacheKeyValidator; if (options.keySelectorCreator) { options.keySelector = options.keySelectorCreator({ keySelector: options.keySelector, inputSelectors: dependencies, resultFunc: resultFunc }); } // Application receives this function var selector = function selector() { var cacheKey = options.keySelector.apply(options, arguments); if (isValidCacheKey(cacheKey)) { var cacheResponse = cache.get(cacheKey); if (cacheResponse === undefined) { cacheResponse = selectorCreator.apply(void 0, funcs); cache.set(cacheKey, cacheResponse); } return cacheResponse.apply(void 0, arguments); } console.warn("[re-reselect] Invalid cache key \"" + cacheKey + "\" has been returned by keySelector function."); return undefined; }; // Further selector methods selector.getMatchingSelector = function () { var cacheKey = options.keySelector.apply(options, arguments); // @NOTE It might update cache hit count in LRU-like caches return cache.get(cacheKey); }; selector.removeMatchingSelector = function () { var cacheKey = options.keySelector.apply(options, arguments); cache.remove(cacheKey); }; selector.clearCache = function () { cache.clear(); }; selector.resultFunc = resultFunc; selector.dependencies = dependencies; selector.cache = cache; selector.recomputations = function () { return recomputations; }; selector.resetRecomputations = function () { return recomputations = 0; }; selector.keySelector = options.keySelector; return selector; }; } function gameCoordsToScreen(gameCoords, windowSize, viewCenter, viewScale) { const gameCoordsOffsetX = gameCoords.x - viewCenter.x; const gameCoordsOffsetY = gameCoords.y - viewCenter.y; const screenCoordsX = windowSize.width / 2 + gameCoordsOffsetX * viewScale; const screenCoordsY = windowSize.height / 2 + gameCoordsOffsetY * viewScale; return { clientX: Math.floor(screenCoordsX), clientY: Math.floor(screenCoordsY) }; } const initialState$3 = { pixelsToPlaceQueue: {}, pixelPlaceQueueEnabled: false }; const pixelPlacementSlice = createSlice({ initialState: initialState$3, name: "pixelPlacement", reducers: { addPixelsToPlaceQueue: (state, action) => { action.payload.pixels.forEach(({ coord, color }) => { const pixelId = coord.x + action.payload.canvasSize / 2 + (coord.y + action.payload.canvasSize / 2) * action.payload.canvasSize; state.pixelsToPlaceQueue[pixelId] = { coord, color }; }); }, removePixelsFromPlaceQueue: (state, action) => { action.payload.pixels.forEach(({ coord }) => { const pixelId = coord.x + action.payload.canvasSize / 2 + (coord.y + action.payload.canvasSize / 2) * action.payload.canvasSize; delete state.pixelsToPlaceQueue[pixelId]; }); }, setPixelPlaceQueueEnabled: (state, action) => { state.pixelPlaceQueueEnabled = action.payload; } } }); const selectPixelPlaceQueueEnabled = createSelector((state) => state.pixelPlacement.pixelPlaceQueueEnabled, (pixelPlaceQueueEnabled) => pixelPlaceQueueEnabled); const selectPixelsToPlaceQueue = createSelector((state) => state.pixelPlacement.pixelsToPlaceQueue, (pixelsToPlaceQueue) => pixelsToPlaceQueue); const selectPixelsToPlaceIds = createSelector((state) => state.pixelPlacement.pixelsToPlaceQueue, (pixelsToPlaceQueue) => Object.keys(pixelsToPlaceQueue).map((key) => parseInt(key, 10))); createSelector(selectPixelsToPlaceIds, selectPixelsToPlaceQueue, (pixelsToPlaceIds, pixelsToPlaceQueue) => { const first = pixelsToPlaceIds[0]; if (!first) return void 0; return pixelsToPlaceQueue[first]; }); const splitRenderCanvasSize$1 = 1024; const selectRenderCanvasCoords = createCachedSelector(selectCanvasSize, (_, renderCanvasId) => renderCanvasId, (canvasSize, renderCanvasId) => { const splitCanvasesWidth = Math.ceil(canvasSize / splitRenderCanvasSize$1); const renderCanvasXCorner = Math.floor(renderCanvasId % splitCanvasesWidth) * splitRenderCanvasSize$1 - canvasSize / 2; const renderCanvasYCorner = Math.floor(renderCanvasId / splitCanvasesWidth) * splitRenderCanvasSize$1 - canvasSize / 2; return { renderCanvasXCorner, renderCanvasYCorner }; })((_, renderCanvasId) => renderCanvasId); const selectPixelIdsToPlaceByRenderCanvasId = createSelector(selectPixelsToPlaceIds, selectCanvasSize, (pixelsToPlaceIds, canvasSize) => { const splitCanvasesWidth = Math.ceil(canvasSize / splitRenderCanvasSize$1); const dict = pixelsToPlaceIds.reduce((acc, pixelId) => { const x = pixelId % canvasSize; const y = Math.floor(pixelId / canvasSize); const splitRenderCanvasX = Math.floor(x / splitRenderCanvasSize$1); const splitRenderCanvasY = Math.floor(y / splitRenderCanvasSize$1); const splitRenderCanvasId = splitRenderCanvasX + splitRenderCanvasY * splitCanvasesWidth; const foundAccumulator = acc[splitRenderCanvasId]; if (!foundAccumulator) { acc[splitRenderCanvasId] = [pixelId]; return acc; } foundAccumulator.push(pixelId); return acc; }, {}); return dict; }); const selectMainCanvasTopLeftScreenCoords = createSelector(selectCanvasSize, selectWindowSize, selectGameViewCenter, selectGameViewScale, (canvasSize, windowSize, gameViewCenter, gameViewScale) => { return gameCoordsToScreen({ x: -canvasSize / 2, y: -canvasSize / 2 }, { height: windowSize.innerHeight, width: windowSize.innerWidth }, gameViewCenter, gameViewScale); }); const selectPixelsToPlaceRenderCanvasIds = createSelector(selectPixelIdsToPlaceByRenderCanvasId, (pixelIdsToPlaceByRenderCanvasId) => Object.keys(pixelIdsToPlaceByRenderCanvasId).map((key) => parseInt(key, 10))); const selectPixelsToPlaceBySplitRenderCanvasId = createCachedSelector(selectPixelIdsToPlaceByRenderCanvasId, selectPixelsToPlaceQueue, selectCanvasSize, (_, renderCanvasId) => renderCanvasId, (pixelIdsToPlaceByRenderCanvasId, pixelsToPlaceQueue, canvasSize, renderCanvasId) => { const splitCanvasesWidth = Math.ceil(canvasSize / splitRenderCanvasSize$1); const splitRenderCanvasX = Math.floor(renderCanvasId % splitCanvasesWidth); const splitRenderCanvasY = Math.floor(renderCanvasId / splitCanvasesWidth); const splitRenderCanvasId = splitRenderCanvasX + splitRenderCanvasY * splitCanvasesWidth; const pixelIdsToPlace = pixelIdsToPlaceByRenderCanvasId[splitRenderCanvasId]; if (!pixelIdsToPlace) return []; return pixelIdsToPlace.map((pixelId) => pixelsToPlaceQueue[pixelId]).filter((pixel) => !!pixel).map((pixel) => pixel); })((_, renderCanvasId) => renderCanvasId); const initialState$2 = { inputImage: { loadedImage: { status: "none" } }, outputImage: { isProcessing: false } }; const processedImagesSlice = createSlice({ initialState: initialState$2, name: "processedImages", reducers: {}, extraReducers: (builder) => { builder.addCase(startNewImageReadingProcess.pending, (state) => { state.inputImage.loadedImage.status = "loading"; state.inputImage.loadedImage.error = void 0; }); builder.addCase(startNewImageReadingProcess.fulfilled, (state, action) => { state.inputImage.loadedImage.status = "loaded"; state.inputImage.loadedImage.imageData = action.payload; }); builder.addCase(startNewImageReadingProcess.rejected, (state, action) => { state.inputImage.loadedImage.status = "error"; state.inputImage.loadedImage.error = action.error.message; }); builder.addCase(clearInputImageAction.fulfilled, (state) => { state.inputImage.loadedImage.status = "none"; state.inputImage.loadedImage.error = void 0; state.inputImage.loadedImage.imageData = void 0; }); builder.addCase(startProcessingOutputImage.pending, (state) => { state.outputImage.isProcessing = true; }); builder.addCase(startProcessingOutputImage.fulfilled, (state, action) => { state.outputImage.isProcessing = false; state.outputImage.imageData = action.payload.outImageData; state.outputImage.abortController = action.payload.abortController; }); builder.addCase(clearOutputImageAction.fulfilled, (state) => { state.outputImage.imageData = void 0; state.outputImage.abortController = void 0; state.outputImage.isProcessing = false; }); } }); const listenerMiddleware = createListenerMiddleware(); const startAppListening = listenerMiddleware.startListening; const reduxPersistedStorage = localforage.createInstance({ name: "picture_overlay", storeName: "redux_persisted" }); const commonPersistReducerParams = { serialize: false, deserialize: false, storage: reduxPersistedStorage }; const persistedOverlayReducer = persistReducer({ ...commonPersistReducerParams, key: "overlay" }, overlaySlice.reducer); function configureAppStore() { return configureStore({ reducer: { overlay: persistedOverlayReducer, game: gameSlice.reducer, chunkData: chunkDataSlice.reducer, pixelPlacement: pixelPlacementSlice.reducer, processedImages: processedImagesSlice.reducer }, devTools: false, middleware(getDefaultMiddleware) { return getDefaultMiddleware().concat([listenerMiddleware.middleware]); } }); } const store = configureAppStore(); const persistor = persistStore(store); function isStoreFromRedux(store) { if (typeof store !== "object") return false; if (!store.dispatch) return false; if (!store.getState) return false; if (!store.subscribe) return false; return true; } function getStoreFromReactInternalEl(el) { if (el.tag !== 0 || !el.child) return void 0; if (el.child.tag !== 10) return void 0; if (!el.child.memoizedProps) return void 0; const childStore = el.child.memoizedProps?.value?.store; if (!isStoreFromRedux(childStore)) return void 0; const parentStore = el.memoizedProps?.store; if (!isStoreFromRedux(parentStore)) return void 0; if (childStore !== parentStore) return void 0; return parentStore; } function findReactRootContainerEl() { return document.getElementById("app"); } function findStoreInRoot(el) { const reactContainerName = Object.keys(el).filter((k) => k.startsWith("__reactContainer"))[0]; if (!reactContainerName) throw new Error("couldn't find internal react root"); const root = el[reactContainerName]; let checkedReactInternalElement = root; while (checkedReactInternalElement.child) { const store = getStoreFromReactInternalEl(checkedReactInternalElement); if (store) return store; checkedReactInternalElement = checkedReactInternalElement.child; } return void 0; } function findPageReduxStore() { const reactRootEl = findReactRootContainerEl(); if (!reactRootEl) throw new Error("Couldn't find React root container"); const store = findStoreInRoot(reactRootEl); if (!store) throw new Error("Couldn't find Redux store"); return store; } const usePageReduxStoreSelector = (selector) => { const store = usePageReduxStore(); const [selectedResult, setSelectedResult] = reactExports.useState(); reactExports.useEffect(() => { if (!store) return void 0; setSelectedResult(selector(store.getState())); const unsubscribe = store.subscribe(() => { setSelectedResult(selector(store.getState())); }); return () => unsubscribe(); }, [store, selector]); return selectedResult; }; const usePageReduxStoreDispatch = () => { const store = usePageReduxStore(); if (!store) return void 0; return store.dispatch; }; function pageReduxStoreSelectColorAction(colorIndex) { return { type: "SELECT_COLOR", color: colorIndex }; } function setViewCoordinates(view) { return { type: "SET_VIEW_COORDINATES", view }; } function usePageReduxStore() { const [pageReduxStore, setPageReduxStore] = reactExports.useState(); reactExports.useEffect(() => { let timeout; try { setPageReduxStore(findPageReduxStore()); } catch (error) { logger.log("Error while finding redux store", error, "retrying in 1 second"); timeout = setTimeout(() => { setPageReduxStore(findPageReduxStore()); }, 1e3); } return () => { if (timeout) clearTimeout(timeout); }; }, [setPageReduxStore]); return pageReduxStore; } const selectPageStatePixelWaitDate = createSelector((state) => state.user.wait, (pixelWaitDate) => pixelWaitDate); const selectPageStateCurrentSelectedColor = createSelector((state) => state.canvas.selectedColor, (currentSelectedColor) => currentSelectedColor); const selectPageStateHoverPixel = createSelector((state) => state.canvas.hover?.[0], (state) => state.canvas.hover?.[1], (hoverPixelX, hoverPixelY) => { if (hoverPixelX == null || hoverPixelY == null) return void 0; return { x: hoverPixelX, y: hoverPixelY }; }); createSelector((state) => state.canvas.view[2], (viewScale) => viewScale); const selectPageStateCanvasViewCenter = createSelector((state) => state.canvas.view[0], (state) => state.canvas.view[1], (viewX, viewY) => { if (viewX == null || viewY == null) return void 0; return { x: viewX, y: viewY }; }); const selectPageStateRoundedCanvasViewCenter = createSelector(selectPageStateCanvasViewCenter, (view) => view ? { x: Math.round(view.x), y: Math.round(view.y) } : void 0); const selectPageStateCanvasPalette = createSelector((state) => state.canvas.palette.abgr, (paletteAbgr) => { return Array.from(new Uint32Array(paletteAbgr)).map((abgr) => { const b = (abgr & 16711680) >>> 16; const g = (abgr & 65280) >>> 8; const r = abgr & 255; return [r, g, b]; }); }); const selectPageStateCanvasReservedColors = createSelector((state) => state.canvas.clrIgnore, (reservedColors) => reservedColors); const selectPageStateCanvasId = createSelector((state) => state.canvas.canvasId, (canvasId) => canvasId); const selectPageStateCanvasSize = createSelector((state) => state.canvas.canvasSize, (size) => size); const selectPageStateCanvasMaxTimeoutMs = createSelector((state) => state.canvas.canvases[state.canvas.canvasId]?.cds, (canvasMaxTimeout) => canvasMaxTimeout); const selectPageStateCanvasTimeoutOnBaseMs = createSelector((state) => state.canvas.canvases[state.canvas.canvasId]?.bcd, (canvasTimeoutOnBase) => canvasTimeoutOnBase); const selectPaseStateCanvasTimeoutOnPlacedMs = createSelector((state) => state.canvas.canvases[state.canvas.canvasId]?.pcd, (canvasTimeoutOnPlaced) => canvasTimeoutOnPlaced); function executeAllHooks(retryCounter = 0) { try { hookForAutoSelectColor(); hookForHoverPixel(); } catch (error) { if (retryCounter > 5) { logger.logError("failed to executeAllHooks multiple times. Rethrowing exception", error); throw error; } const retryInMs = (retryCounter + 1) * 1e3; logger.log("failed to executeAllHooks", error, "retrying in", retryInMs); setTimeout(() => { executeAllHooks(retryCounter + 1); }, retryInMs); } } function hookForAutoSelectColor() { const pageStore = findPageReduxStore(); const pageDispatch = pageStore.dispatch; let lastColorIndex; store.subscribe(() => { const colorIndex = selectCurrentHoverPixelOnOutputImageColorIndexInPalette(store.getState()); if (colorIndex !== void 0 && colorIndex !== lastColorIndex) { lastColorIndex = colorIndex; pageDispatch(pageReduxStoreSelectColorAction(colorIndex)); } }); } function hookForHoverPixel() { const pageStore = findPageReduxStore(); let lastHoverPixel; pageStore.subscribe(() => { let hoverPixel = selectPageStateHoverPixel(pageStore.getState()); if (hoverPixel) { if (hoverPixel !== lastHoverPixel) { lastHoverPixel = hoverPixel; store.dispatch(gameSlice.actions.setHoverPixel(hoverPixel)); } return; } hoverPixel = selectPageStateRoundedCanvasViewCenter(pageStore.getState()); if (hoverPixel) { if (hoverPixel !== lastHoverPixel) { lastHoverPixel = hoverPixel; store.dispatch(gameSlice.actions.setHoverPixel(hoverPixel)); } } }); } var createRoot; var m = reactDomExports; { createRoot = m.createRoot; m.hydrateRoot; } function _setPrototypeOf$1(o, p) { _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$1(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf$1(subClass, superClass); } var changedArray = function changedArray(a, b) { if (a === void 0) { a = []; } if (b === void 0) { b = []; } return a.length !== b.length || a.some(function (item, index) { return !Object.is(item, b[index]); }); }; var initialState$1 = { error: null }; var ErrorBoundary = /*#__PURE__*/function (_React$Component) { _inheritsLoose(ErrorBoundary, _React$Component); function ErrorBoundary() { var _this; for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) { _args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this; _this.state = initialState$1; _this.resetErrorBoundary = function () { var _this$props; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args); _this.reset(); }; return _this; } ErrorBoundary.getDerivedStateFromError = function getDerivedStateFromError(error) { return { error: error }; }; var _proto = ErrorBoundary.prototype; _proto.reset = function reset() { this.setState(initialState$1); }; _proto.componentDidCatch = function componentDidCatch(error, info) { var _this$props$onError, _this$props2; (_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) { var error = this.state.error; var resetKeys = this.props.resetKeys; // There's an edge case where if the thing that triggered the error // happens to *also* be in the resetKeys array, we'd end up resetting // the error boundary immediately. This would likely trigger a second // error to be thrown. // So we make sure that we don't check the resetKeys on the first call // of cDU after the error is set if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) { var _this$props$onResetKe, _this$props3; (_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys); this.reset(); } }; _proto.render = function render() { var error = this.state.error; var _this$props4 = this.props, fallbackRender = _this$props4.fallbackRender, FallbackComponent = _this$props4.FallbackComponent, fallback = _this$props4.fallback; if (error !== null) { var _props = { error: error, resetErrorBoundary: this.resetErrorBoundary }; if ( /*#__PURE__*/reactExports.isValidElement(fallback)) { return fallback; } else if (typeof fallbackRender === 'function') { return fallbackRender(_props); } else if (FallbackComponent) { return /*#__PURE__*/reactExports.createElement(FallbackComponent, _props); } else { throw new Error('react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop'); } } return this.props.children; }; return ErrorBoundary; }(reactExports.Component); function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized$1(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized$1(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var PersistGate = /*#__PURE__*/ function (_PureComponent) { _inherits(PersistGate, _PureComponent); function PersistGate() { var _getPrototypeOf2; var _this; _classCallCheck(this, PersistGate); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(PersistGate)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty$2(_assertThisInitialized$1(_this), "state", { bootstrapped: false }); _defineProperty$2(_assertThisInitialized$1(_this), "_unsubscribe", void 0); _defineProperty$2(_assertThisInitialized$1(_this), "handlePersistorState", function () { var persistor = _this.props.persistor; var _persistor$getState = persistor.getState(), bootstrapped = _persistor$getState.bootstrapped; if (bootstrapped) { if (_this.props.onBeforeLift) { Promise.resolve(_this.props.onBeforeLift()).finally(function () { return _this.setState({ bootstrapped: true }); }); } else { _this.setState({ bootstrapped: true }); } _this._unsubscribe && _this._unsubscribe(); } }); return _this; } _createClass(PersistGate, [{ key: "componentDidMount", value: function componentDidMount() { this._unsubscribe = this.props.persistor.subscribe(this.handlePersistorState); this.handlePersistorState(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this._unsubscribe && this._unsubscribe(); } }, { key: "render", value: function render() { if (typeof this.props.children === 'function') { return this.props.children(this.state.bootstrapped); } return this.state.bootstrapped ? this.props.children : this.props.loading; } }]); return PersistGate; }(reactExports.PureComponent); _defineProperty$2(PersistGate, "defaultProps", { children: null, loading: null }); /** * Exports a boolean value reporting whether is client side or server side by checking on the window object */ const isClient = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Exports a boolean value reporting whether the given API is supported or not */ const isApiSupported = (api) => (typeof window !== 'undefined' ? api in window : false); const cache = new Map(); /** * A tiny wrapper around console.warn that makes sure the message is only displayed once. * Used mainly to avoid polluting server side logs * @param message */ const warnOnce = (message) => { if (cache.has(message)) return; cache.set(message, true); // eslint-disable-next-line no-console console.warn(message); }; const errorMessage = 'matchMedia is not supported, this could happen both because window.matchMedia is not supported by' + ' your current browser or you\'re using the useMediaQuery hook whilst server side rendering.'; /** * Accepts a media query string then uses the * [window.matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) API to determine if it * matches with the current document.
* It also monitor the document changes to detect when it matches or stops matching the media query.
* Returns the validity state of the given media query. * */ const useMediaQuery = (mediaQuery) => { if (!isClient || !isApiSupported('matchMedia')) { warnOnce(errorMessage); return false; } const [isVerified, setIsVerified] = reactExports.useState(!!window.matchMedia(mediaQuery).matches); reactExports.useEffect(() => { const mediaQueryList = window.matchMedia(mediaQuery); const documentChangeHandler = () => setIsVerified(!!mediaQueryList.matches); try { mediaQueryList.addEventListener('change', documentChangeHandler); } catch (e) { // Safari isn't supporting mediaQueryList.addEventListener mediaQueryList.addListener(documentChangeHandler); } documentChangeHandler(); return () => { try { mediaQueryList.removeEventListener('change', documentChangeHandler); } catch (e) { // Safari isn't supporting mediaQueryList.removeEventListener mediaQueryList.removeListener(documentChangeHandler); } }; }, [mediaQuery]); return isVerified; }; /* eslint-disable @typescript-eslint/no-explicit-any */ const objectFromEntries = !Object .fromEntries ? (entries) => { if (!entries || !entries[Symbol.iterator]) { throw new Error("Object.fromEntries() requires a single iterable argument"); } const o = {}; Object.keys(entries).forEach(key => { const [k, v] = entries[key]; o[k] = v; }); return o; } : Object.fromEntries; /** Object.keys() with types */ function objectKeys(o) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return Object.keys(o); } /** https://docs.tsafe.dev/assert */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function assert(condition, msg) { if (!condition) { throw new Error(msg); } } /* eslint-disable @typescript-eslint/no-explicit-any */ /** https://docs.tsafe.dev/typeguard */ function typeGuard(_value, isMatched) { return isMatched; } /** Copy pasted from * https://github.com/emotion-js/emotion/blob/23f43ab9f24d44219b0b007a00f4ac681fe8712e/packages/react/src/class-names.js#L17-L63 **/ const classnames = (args) => { const len = args.length; let i = 0; let cls = ""; for (; i < len; i++) { const arg = args[i]; if (arg == null) continue; let toAdd; switch (typeof arg) { case "boolean": break; case "object": { if (Array.isArray(arg)) { toAdd = classnames(arg); } else { assert(!typeGuard(arg, false)); toAdd = ""; for (const k in arg) { if (arg[k] && k) { toAdd && (toAdd += " "); toAdd += k; } } } break; } default: { toAdd = arg; } } if (toAdd) { cls && (cls += " "); cls += toAdd; } } return cls; }; /* eslint-disable */ // Inspired by https://github.com/garycourt/murmurhash-js // Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86 function murmur2(str) { // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. // const m = 0x5bd1e995; // const r = 24; // Initialize the hash var h = 0; // Mix 4 bytes at a time into the hash var k, i = 0, len = str.length; for (; len >= 4; ++i, len -= 4) { k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24; k = /* Math.imul(k, m): */ (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16); k ^= /* k >>> r: */ k >>> 24; h = /* Math.imul(k, m): */ (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^ /* Math.imul(h, m): */ (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16); } // Handle the last few bytes of the input array switch (len) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= str.charCodeAt(i) & 0xff; h = /* Math.imul(h, m): */ (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16); } // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >>> 13; h = /* Math.imul(h, m): */ (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16); return ((h ^ h >>> 15) >>> 0).toString(36); } var unitlessKeys = { animationIterationCount: 1, borderImageOutset: 1, borderImageSlice: 1, borderImageWidth: 1, boxFlex: 1, boxFlexGroup: 1, boxOrdinalGroup: 1, columnCount: 1, columns: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, flexOrder: 1, gridRow: 1, gridRowEnd: 1, gridRowSpan: 1, gridRowStart: 1, gridColumn: 1, gridColumnEnd: 1, gridColumnSpan: 1, gridColumnStart: 1, msGridRow: 1, msGridRowSpan: 1, msGridColumn: 1, msGridColumnSpan: 1, fontWeight: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, tabSize: 1, widows: 1, zIndex: 1, zoom: 1, WebkitLineClamp: 1, // SVG-related properties fillOpacity: 1, floodOpacity: 1, stopOpacity: 1, strokeDasharray: 1, strokeDashoffset: 1, strokeMiterlimit: 1, strokeOpacity: 1, strokeWidth: 1 }; function memoize$1(fn) { var cache = Object.create(null); return function (arg) { if (cache[arg] === undefined) cache[arg] = fn(arg); return cache[arg]; }; } var hyphenateRegex = /[A-Z]|^ms/g; var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g; var isCustomProperty = function isCustomProperty(property) { return property.charCodeAt(1) === 45; }; var isProcessableValue = function isProcessableValue(value) { return value != null && typeof value !== 'boolean'; }; var processStyleName = /* #__PURE__ */memoize$1(function (styleName) { return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase(); }); var processStyleValue = function processStyleValue(key, value) { switch (key) { case 'animation': case 'animationName': { if (typeof value === 'string') { return value.replace(animationRegex, function (match, p1, p2) { cursor = { name: p1, styles: p2, next: cursor }; return p1; }); } } } if (unitlessKeys[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) { return value + 'px'; } return value; }; var noComponentSelectorMessage = 'Component selectors can only be used in conjunction with ' + '@emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware ' + 'compiler transform.'; function handleInterpolation(mergedProps, registered, interpolation) { if (interpolation == null) { return ''; } if (interpolation.__emotion_styles !== undefined) { return interpolation; } switch (typeof interpolation) { case 'boolean': { return ''; } case 'object': { if (interpolation.anim === 1) { cursor = { name: interpolation.name, styles: interpolation.styles, next: cursor }; return interpolation.name; } if (interpolation.styles !== undefined) { var next = interpolation.next; if (next !== undefined) { // not the most efficient thing ever but this is a pretty rare case // and there will be very few iterations of this generally while (next !== undefined) { cursor = { name: next.name, styles: next.styles, next: cursor }; next = next.next; } } var styles = interpolation.styles + ";"; return styles; } return createStringFromObject(mergedProps, registered, interpolation); } case 'function': { if (mergedProps !== undefined) { var previousCursor = cursor; var result = interpolation(mergedProps); cursor = previousCursor; return handleInterpolation(mergedProps, registered, result); } break; } } // finalize string values (regular strings and functions interpolated into css calls) if (registered == null) { return interpolation; } var cached = registered[interpolation]; return cached !== undefined ? cached : interpolation; } function createStringFromObject(mergedProps, registered, obj) { var string = ''; if (Array.isArray(obj)) { for (var i = 0; i < obj.length; i++) { string += handleInterpolation(mergedProps, registered, obj[i]) + ";"; } } else { for (var _key in obj) { var value = obj[_key]; if (typeof value !== 'object') { if (registered != null && registered[value] !== undefined) { string += _key + "{" + registered[value] + "}"; } else if (isProcessableValue(value)) { string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";"; } } else { if (_key === 'NO_COMPONENT_SELECTOR' && "production" !== 'production') { throw new Error(noComponentSelectorMessage); } if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) { for (var _i = 0; _i < value.length; _i++) { if (isProcessableValue(value[_i])) { string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";"; } } } else { var interpolated = handleInterpolation(mergedProps, registered, value); switch (_key) { case 'animation': case 'animationName': { string += processStyleName(_key) + ":" + interpolated + ";"; break; } default: { string += _key + "{" + interpolated + "}"; } } } } } } return string; } var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g; // keyframes are stored on the SerializedStyles object as a linked list var cursor; var serializeStyles = function serializeStyles(args, registered, mergedProps) { if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) { return args[0]; } var stringMode = true; var styles = ''; cursor = undefined; var strings = args[0]; if (strings == null || strings.raw === undefined) { stringMode = false; styles += handleInterpolation(mergedProps, registered, strings); } else { styles += strings[0]; } // we start at 1 since we've already handled the first arg for (var i = 1; i < args.length; i++) { styles += handleInterpolation(mergedProps, registered, args[i]); if (stringMode) { styles += strings[i]; } } labelPattern.lastIndex = 0; var identifierName = ''; var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5 while ((match = labelPattern.exec(styles)) !== null) { identifierName += '-' + // $FlowFixMe we know it's not null match[1]; } var name = murmur2(styles) + identifierName; return { name: name, styles: styles, next: cursor }; }; var isBrowser = "object" !== 'undefined'; function getRegisteredStyles(registered, registeredStyles, classNames) { var rawClassName = ''; classNames.split(' ').forEach(function (className) { if (registered[className] !== undefined) { registeredStyles.push(registered[className] + ";"); } else { rawClassName += className + " "; } }); return rawClassName; } var registerStyles = function registerStyles(cache, serialized, isStringTag) { var className = cache.key + "-" + serialized.name; if ( // we only need to add the styles to the registered cache if the // class name could be used further down // the tree but if it's a string tag, we know it won't // so we don't have to add it to registered cache. // this improves memory usage since we can avoid storing the whole style string (isStringTag === false || // we need to always store it if we're in compat mode and // in node since emotion-server relies on whether a style is in // the registered cache to know whether a style is global or not // also, note that this check will be dead code eliminated in the browser isBrowser === false ) && cache.registered[className] === undefined) { cache.registered[className] = serialized.styles; } }; var insertStyles = function insertStyles(cache, serialized, isStringTag) { registerStyles(cache, serialized, isStringTag); var className = cache.key + "-" + serialized.name; if (cache.inserted[serialized.name] === undefined) { var current = serialized; do { cache.insert(serialized === current ? "." + className : '', current, cache.sheet, true); current = current.next; } while (current !== undefined); } }; /** Like react's useMemo but with guarantee that the fn * won't be invoked again if deps hasn't change */ function useGuaranteedMemo(fn, deps) { const ref = reactExports.useRef(); if (!ref.current || deps.length !== ref.current.prevDeps.length || ref.current.prevDeps.map((v, i) => v === deps[i]).indexOf(false) >= 0) { ref.current = { "v": fn(), "prevDeps": [...deps], }; } return ref.current.v; } function matchCSSObject(arg) { return (arg instanceof Object && !("styles" in arg) && !("length" in arg) && !("__emotion_styles" in arg)); } const { createCssAndCx } = (() => { function merge(registered, css, className) { const registeredStyles = []; const rawClassName = getRegisteredStyles(registered, registeredStyles, className); if (registeredStyles.length < 2) { return className; } return rawClassName + css(registeredStyles); } function createCssAndCx(params) { const { cache } = params; const css = (...args) => { const serialized = serializeStyles(args, cache.registered); insertStyles(cache, serialized, false); const className = `${cache.key}-${serialized.name}`; scope: { const arg = args[0]; if (!matchCSSObject(arg)) { break scope; } increaseSpecificityToTakePrecedenceOverMediaQueries.saveClassNameCSSObjectMapping(cache, className, arg); } return className; }; const cx = (...args) => { const className = classnames(args); const feat27FixedClassnames = increaseSpecificityToTakePrecedenceOverMediaQueries.fixClassName(cache, className, css); return merge(cache.registered, css, feat27FixedClassnames); //return merge(cache.registered, css, className); }; return { css, cx }; } return { createCssAndCx }; })(); function createUseCssAndCx(params) { const { useCache } = params; function useCssAndCx() { const cache = useCache(); const { css, cx } = useGuaranteedMemo(() => createCssAndCx({ cache }), [cache]); return { css, cx }; } return { useCssAndCx }; } // https://github.com/garronej/tss-react/issues/27 const increaseSpecificityToTakePrecedenceOverMediaQueries = (() => { const cssObjectMapByCache = new WeakMap(); return { "saveClassNameCSSObjectMapping": (cache, className, cssObject) => { let cssObjectMap = cssObjectMapByCache.get(cache); if (cssObjectMap === undefined) { cssObjectMap = new Map(); cssObjectMapByCache.set(cache, cssObjectMap); } cssObjectMap.set(className, cssObject); }, "fixClassName": (() => { function fix(classNameCSSObjects) { let isThereAnyMediaQueriesInPreviousClasses = false; return classNameCSSObjects.map(([className, cssObject]) => { if (cssObject === undefined) { return className; } let out; if (!isThereAnyMediaQueriesInPreviousClasses) { out = className; for (const key in cssObject) { if (key.startsWith("@media")) { isThereAnyMediaQueriesInPreviousClasses = true; break; } } } else { out = { "&&": cssObject, }; } return out; }); } return (cache, className, css) => { const cssObjectMap = cssObjectMapByCache.get(cache); return classnames(fix(className .split(" ") .map(className => [ className, cssObjectMap === null || cssObjectMap === void 0 ? void 0 : cssObjectMap.get(className), ])).map(classNameOrCSSObject => typeof classNameOrCSSObject === "string" ? classNameOrCSSObject : css(classNameOrCSSObject))); }; })(), }; })(); /* eslint-disable @typescript-eslint/no-explicit-any */ /** * useEffect( * ()=> { ... }, * [ { "foo": "bar" } ] * ) * => The callback will be invoked every render. * because { "foo": "bar" } is a new instance every render. * * useEffect( * ()=> { ... }, * [ getDependencyArrayRef({ "foo": "bar" }) ] * ); * => The callback will only be invoked once. * * The optimization will be enabled only if obj is * of the form Record * overwise the object is returned (the function is the identity function). */ function getDependencyArrayRef(obj) { if (!(obj instanceof Object) || typeof obj === "function") { return obj; } const arr = []; for (const key in obj) { const value = obj[key]; const typeofValue = typeof value; if (!(typeofValue === "string" || (typeofValue === "number" && !isNaN(value)) || typeofValue === "boolean" || value === undefined || value === null)) { return obj; } arr.push(`${key}:${typeofValue}_${value}`); } return "xSqLiJdLMd9s" + arr.join("|"); } /* eslint-disable @typescript-eslint/ban-types */ function mergeClasses(classesFromUseStyles, classesFromProps, cx) { //NOTE: We use this test to be resilient in case classesFromProps is not of the expected type. if (!(classesFromProps instanceof Object)) { return classesFromUseStyles; } const out = {}; objectKeys(classesFromUseStyles).forEach(ruleName => (out[ruleName] = cx(classesFromUseStyles[ruleName], classesFromProps[ruleName]))); objectKeys(classesFromProps).forEach(ruleName => { if (ruleName in classesFromUseStyles) { return; } const className = classesFromProps[ruleName]; //...Same here, that why we don't do className === undefined if (typeof className !== "string") { return; } out[ruleName] = className; }); return out; } /* Based off glamor's StyleSheet, thanks Sunil ❤️ high performance StyleSheet for css-in-js systems - uses multiple style tags behind the scenes for millions of rules - uses `insertRule` for appending in production for *much* faster performance // usage import { StyleSheet } from '@emotion/sheet' let styleSheet = new StyleSheet({ key: '', container: document.head }) styleSheet.insert('#box { border: 1px solid red; }') - appends a css rule into the stylesheet styleSheet.flush() - empties the stylesheet of all its contents */ // $FlowFixMe function sheetForTag(tag) { if (tag.sheet) { // $FlowFixMe return tag.sheet; } // this weirdness brought to you by firefox /* istanbul ignore next */ for (var i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].ownerNode === tag) { // $FlowFixMe return document.styleSheets[i]; } } } function createStyleElement(options) { var tag = document.createElement('style'); tag.setAttribute('data-emotion', options.key); if (options.nonce !== undefined) { tag.setAttribute('nonce', options.nonce); } tag.appendChild(document.createTextNode('')); tag.setAttribute('data-s', ''); return tag; } var StyleSheet = /*#__PURE__*/function () { // Using Node instead of HTMLElement since container may be a ShadowRoot function StyleSheet(options) { var _this = this; this._insertTag = function (tag) { var before; if (_this.tags.length === 0) { if (_this.insertionPoint) { before = _this.insertionPoint.nextSibling; } else if (_this.prepend) { before = _this.container.firstChild; } else { before = _this.before; } } else { before = _this.tags[_this.tags.length - 1].nextSibling; } _this.container.insertBefore(tag, before); _this.tags.push(tag); }; this.isSpeedy = options.speedy === undefined ? "production" === 'production' : options.speedy; this.tags = []; this.ctr = 0; this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets this.key = options.key; this.container = options.container; this.prepend = options.prepend; this.insertionPoint = options.insertionPoint; this.before = null; } var _proto = StyleSheet.prototype; _proto.hydrate = function hydrate(nodes) { nodes.forEach(this._insertTag); }; _proto.insert = function insert(rule) { // the max length is how many rules we have per style tag, it's 65000 in speedy mode // it's 1 in dev because we insert source maps that map a single rule to a location // and you can only have one source map per style tag if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) { this._insertTag(createStyleElement(this)); } var tag = this.tags[this.tags.length - 1]; if (this.isSpeedy) { var sheet = sheetForTag(tag); try { // this is the ultrafast version, works across browsers // the big drawback is that the css won't be editable in devtools sheet.insertRule(rule, sheet.cssRules.length); } catch (e) { } } else { tag.appendChild(document.createTextNode(rule)); } this.ctr++; }; _proto.flush = function flush() { // $FlowFixMe this.tags.forEach(function (tag) { return tag.parentNode && tag.parentNode.removeChild(tag); }); this.tags = []; this.ctr = 0; }; return StyleSheet; }(); var MS = '-ms-'; var MOZ = '-moz-'; var WEBKIT = '-webkit-'; var COMMENT = 'comm'; var RULESET = 'rule'; var DECLARATION = 'decl'; var IMPORT = '@import'; var KEYFRAMES = '@keyframes'; /** * @param {number} * @return {number} */ var abs = Math.abs; /** * @param {number} * @return {string} */ var from = String.fromCharCode; /** * @param {object} * @return {object} */ var assign = Object.assign; /** * @param {string} value * @param {number} length * @return {number} */ function hash$2 (value, length) { return charat(value, 0) ^ 45 ? (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3) : 0 } /** * @param {string} value * @return {string} */ function trim (value) { return value.trim() } /** * @param {string} value * @param {RegExp} pattern * @return {string?} */ function match (value, pattern) { return (value = pattern.exec(value)) ? value[0] : value } /** * @param {string} value * @param {(string|RegExp)} pattern * @param {string} replacement * @return {string} */ function replace (value, pattern, replacement) { return value.replace(pattern, replacement) } /** * @param {string} value * @param {string} search * @return {number} */ function indexof (value, search) { return value.indexOf(search) } /** * @param {string} value * @param {number} index * @return {number} */ function charat (value, index) { return value.charCodeAt(index) | 0 } /** * @param {string} value * @param {number} begin * @param {number} end * @return {string} */ function substr (value, begin, end) { return value.slice(begin, end) } /** * @param {string} value * @return {number} */ function strlen (value) { return value.length } /** * @param {any[]} value * @return {number} */ function sizeof (value) { return value.length } /** * @param {any} value * @param {any[]} array * @return {any} */ function append (value, array) { return array.push(value), value } /** * @param {string[]} array * @param {function} callback * @return {string} */ function combine (array, callback) { return array.map(callback).join('') } var line = 1; var column = 1; var length = 0; var position = 0; var character = 0; var characters = ''; /** * @param {string} value * @param {object | null} root * @param {object | null} parent * @param {string} type * @param {string[] | string} props * @param {object[] | string} children * @param {number} length */ function node (value, root, parent, type, props, children, length) { return {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''} } /** * @param {object} root * @param {object} props * @return {object} */ function copy (root, props) { return assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props) } /** * @return {number} */ function char () { return character } /** * @return {number} */ function prev () { character = position > 0 ? charat(characters, --position) : 0; if (column--, character === 10) column = 1, line--; return character } /** * @return {number} */ function next () { character = position < length ? charat(characters, position++) : 0; if (column++, character === 10) column = 1, line++; return character } /** * @return {number} */ function peek () { return charat(characters, position) } /** * @return {number} */ function caret () { return position } /** * @param {number} begin * @param {number} end * @return {string} */ function slice$1 (begin, end) { return substr(characters, begin, end) } /** * @param {number} type * @return {number} */ function token (type) { switch (type) { // \0 \t \n \r \s whitespace token case 0: case 9: case 10: case 13: case 32: return 5 // ! + , / > @ ~ isolate token case 33: case 43: case 44: case 47: case 62: case 64: case 126: // ; { } breakpoint token case 59: case 123: case 125: return 4 // : accompanied token case 58: return 3 // " ' ( [ opening delimit token case 34: case 39: case 40: case 91: return 2 // ) ] closing delimit token case 41: case 93: return 1 } return 0 } /** * @param {string} value * @return {any[]} */ function alloc (value) { return line = column = 1, length = strlen(characters = value), position = 0, [] } /** * @param {any} value * @return {any} */ function dealloc (value) { return characters = '', value } /** * @param {number} type * @return {string} */ function delimit (type) { return trim(slice$1(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type))) } /** * @param {number} type * @return {string} */ function whitespace (type) { while (character = peek()) if (character < 33) next(); else break return token(type) > 2 || token(character) > 3 ? '' : ' ' } /** * @param {number} index * @param {number} count * @return {string} */ function escaping (index, count) { while (--count && next()) // not 0-9 A-F a-f if (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97)) break return slice$1(index, caret() + (count < 6 && peek() == 32 && next() == 32)) } /** * @param {number} type * @return {number} */ function delimiter (type) { while (next()) switch (character) { // ] ) " ' case type: return position // " ' case 34: case 39: if (type !== 34 && type !== 39) delimiter(character); break // ( case 40: if (type === 41) delimiter(type); break // \ case 92: next(); break } return position } /** * @param {number} type * @param {number} index * @return {number} */ function commenter (type, index) { while (next()) // // if (type + character === 47 + 10) break // /* else if (type + character === 42 + 42 && peek() === 47) break return '/*' + slice$1(index, position - 1) + '*' + from(type === 47 ? type : next()) } /** * @param {number} index * @return {string} */ function identifier (index) { while (!token(peek())) next(); return slice$1(index, position) } /** * @param {string} value * @return {object[]} */ function compile (value) { return dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value)) } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {string[]} rule * @param {string[]} rules * @param {string[]} rulesets * @param {number[]} pseudo * @param {number[]} points * @param {string[]} declarations * @return {object} */ function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) { var index = 0; var offset = 0; var length = pseudo; var atrule = 0; var property = 0; var previous = 0; var variable = 1; var scanning = 1; var ampersand = 1; var character = 0; var type = ''; var props = rules; var children = rulesets; var reference = rule; var characters = type; while (scanning) switch (previous = character, character = next()) { // ( case 40: if (previous != 108 && charat(characters, length - 1) == 58) { if (indexof(characters += replace(delimit(character), '&', '&\f'), '&\f') != -1) ampersand = -1; break } // " ' [ case 34: case 39: case 91: characters += delimit(character); break // \t \n \r \s case 9: case 10: case 13: case 32: characters += whitespace(previous); break // \ case 92: characters += escaping(caret() - 1, 7); continue // / case 47: switch (peek()) { case 42: case 47: append(comment(commenter(next(), caret()), root, parent), declarations); break default: characters += '/'; } break // { case 123 * variable: points[index++] = strlen(characters) * ampersand; // } ; \0 case 125 * variable: case 59: case 0: switch (character) { // \0 } case 0: case 125: scanning = 0; // ; case 59 + offset: if (property > 0 && (strlen(characters) - length)) append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations); break // @ ; case 59: characters += ';'; // { rule/at-rule default: append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets); if (character === 123) if (offset === 0) parse(characters, root, reference, reference, props, rulesets, length, points, children); else switch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) { // d m s case 100: case 109: case 115: parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children); break default: parse(characters, reference, reference, reference, [''], children, 0, points, children); } } index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo; break // : case 58: length = 1 + strlen(characters), property = previous; default: if (variable < 1) if (character == 123) --variable; else if (character == 125 && variable++ == 0 && prev() == 125) continue switch (characters += from(character), character * variable) { // & case 38: ampersand = offset > 0 ? 1 : (characters += '\f', -1); break // , case 44: points[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1; break // @ case 64: // - if (peek() === 45) characters += delimit(next()); atrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++; break // - case 45: if (previous === 45 && strlen(characters) == 2) variable = 0; } } return rulesets } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {number} index * @param {number} offset * @param {string[]} rules * @param {number[]} points * @param {string} type * @param {string[]} props * @param {string[]} children * @param {number} length * @return {object} */ function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) { var post = offset - 1; var rule = offset === 0 ? rules : ['']; var size = sizeof(rule); for (var i = 0, j = 0, k = 0; i < index; ++i) for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x) if (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\f/g, rule[x]))) props[k++] = z; return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length) } /** * @param {number} value * @param {object} root * @param {object?} parent * @return {object} */ function comment (value, root, parent) { return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0) } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {number} length * @return {object} */ function declaration (value, root, parent, length) { return node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length) } /** * @param {object[]} children * @param {function} callback * @return {string} */ function serialize (children, callback) { var output = ''; var length = sizeof(children); for (var i = 0; i < length; i++) output += callback(children[i], i, children, callback) || ''; return output } /** * @param {object} element * @param {number} index * @param {object[]} children * @param {function} callback * @return {string} */ function stringify (element, index, children, callback) { switch (element.type) { case IMPORT: case DECLARATION: return element.return = element.return || element.value case COMMENT: return '' case KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}' case RULESET: element.value = element.props.join(','); } return strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : '' } /** * @param {function[]} collection * @return {function} */ function middleware (collection) { var length = sizeof(collection); return function (element, index, children, callback) { var output = ''; for (var i = 0; i < length; i++) output += collection[i](element, index, children, callback) || ''; return output } } /** * @param {function} callback * @return {function} */ function rulesheet (callback) { return function (element) { if (!element.root) if (element = element.return) callback(element); } } var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) { var previous = 0; var character = 0; while (true) { previous = character; character = peek(); // &\f if (previous === 38 && character === 12) { points[index] = 1; } if (token(character)) { break; } next(); } return slice$1(begin, position); }; var toRules = function toRules(parsed, points) { // pretend we've started with a comma var index = -1; var character = 44; do { switch (token(character)) { case 0: // &\f if (character === 38 && peek() === 12) { // this is not 100% correct, we don't account for literal sequences here - like for example quoted strings // stylis inserts \f after & to know when & where it should replace this sequence with the context selector // and when it should just concatenate the outer and inner selectors // it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here points[index] = 1; } parsed[index] += identifierWithPointTracking(position - 1, points, index); break; case 2: parsed[index] += delimit(character); break; case 4: // comma if (character === 44) { // colon parsed[++index] = peek() === 58 ? '&\f' : ''; points[index] = parsed[index].length; break; } // fallthrough default: parsed[index] += from(character); } } while (character = next()); return parsed; }; var getRules = function getRules(value, points) { return dealloc(toRules(alloc(value), points)); }; // WeakSet would be more appropriate, but only WeakMap is supported in IE11 var fixedElements = /* #__PURE__ */new WeakMap(); var compat = function compat(element) { if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo // negative .length indicates that this rule has been already prefixed element.length < 1) { return; } var value = element.value, parent = element.parent; var isImplicitRule = element.column === parent.column && element.line === parent.line; while (parent.type !== 'rule') { parent = parent.parent; if (!parent) return; } // short-circuit for the simplest case if (element.props.length === 1 && value.charCodeAt(0) !== 58 /* colon */ && !fixedElements.get(parent)) { return; } // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level) // then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent" if (isImplicitRule) { return; } fixedElements.set(element, true); var points = []; var rules = getRules(value, points); var parentRules = parent.props; for (var i = 0, k = 0; i < rules.length; i++) { for (var j = 0; j < parentRules.length; j++, k++) { element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i]; } } }; var removeLabel = function removeLabel(element) { if (element.type === 'decl') { var value = element.value; if ( // charcode for l value.charCodeAt(0) === 108 && // charcode for b value.charCodeAt(2) === 98) { // this ignores label element["return"] = ''; element.value = ''; } } }; /* eslint-disable no-fallthrough */ function prefix(value, length) { switch (hash$2(value, length)) { // color-adjust case 5103: return WEBKIT + 'print-' + value + value; // animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function) case 5737: case 4201: case 3177: case 3433: case 1641: case 4457: case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break case 5572: case 6356: case 5844: case 3191: case 6645: case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite, case 6391: case 5879: case 5623: case 6135: case 4599: case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width) case 4215: case 6389: case 5109: case 5365: case 5621: case 3829: return WEBKIT + value + value; // appearance, user-select, transform, hyphens, text-size-adjust case 5349: case 4246: case 4810: case 6968: case 2756: return WEBKIT + value + MOZ + value + MS + value + value; // flex, flex-direction case 6828: case 4268: return WEBKIT + value + MS + value + value; // order case 6165: return WEBKIT + value + MS + 'flex-' + value + value; // align-items case 5187: return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value; // align-self case 5443: return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value; // align-content case 4675: return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value; // flex-shrink case 5548: return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value; // flex-basis case 5292: return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value; // flex-grow case 6060: return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value; // transition case 4554: return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value; // cursor case 6187: return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value; // background, background-image case 5495: case 3959: return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1'); // justify-content case 4968: return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value; // (margin|padding)-inline-(start|end) case 4095: case 3583: case 4068: case 2532: return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value; // (min|max)?(width|height|inline-size|block-size) case 8116: case 7059: case 5753: case 5535: case 5445: case 5701: case 4933: case 4677: case 5533: case 5789: case 5021: case 4765: // stretch, max-content, min-content, fill-available if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) { // (m)ax-content, (m)in-content case 109: // - if (charat(value, length + 4) !== 45) break; // (f)ill-available, (f)it-content case 102: return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value; // (s)tretch case 115: return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value; } break; // position: sticky case 4949: // (s)ticky? if (charat(value, length + 1) !== 115) break; // display: (flex|inline-flex) case 6444: switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) { // stic(k)y case 107: return replace(value, ':', ':' + WEBKIT) + value; // (inline-)?fl(e)x case 101: return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value; } break; // writing-mode case 5936: switch (charat(value, length + 11)) { // vertical-l(r) case 114: return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value; // vertical-r(l) case 108: return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value; // horizontal(-)tb case 45: return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value; } return WEBKIT + value + MS + value + value; } return value; } var prefixer = function prefixer(element, index, children, callback) { if (element.length > -1) if (!element["return"]) switch (element.type) { case DECLARATION: element["return"] = prefix(element.value, element.length); break; case KEYFRAMES: return serialize([copy(element, { value: replace(element.value, '@', '@' + WEBKIT) })], callback); case RULESET: if (element.length) return combine(element.props, function (value) { switch (match(value, /(::plac\w+|:read-\w+)/)) { // :read-(only|write) case ':read-only': case ':read-write': return serialize([copy(element, { props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')] })], callback); // :placeholder case '::placeholder': return serialize([copy(element, { props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')] }), copy(element, { props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')] }), copy(element, { props: [replace(value, /:(plac\w+)/, MS + 'input-$1')] })], callback); } return ''; }); } }; var defaultStylisPlugins = [prefixer]; var createCache = function createCache(options) { var key = options.key; if ( key === 'css') { var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration // document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be) // note this very very intentionally targets all style elements regardless of the key to ensure // that creating a cache works inside of render of a React component Array.prototype.forEach.call(ssrStyles, function (node) { // we want to only move elements which have a space in the data-emotion attribute value // because that indicates that it is an Emotion 11 server-side rendered style elements // while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector // Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes) // so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles // will not result in the Emotion 10 styles being destroyed var dataEmotionAttribute = node.getAttribute('data-emotion'); if (dataEmotionAttribute.indexOf(' ') === -1) { return; } document.head.appendChild(node); node.setAttribute('data-s', ''); }); } var stylisPlugins = options.stylisPlugins || defaultStylisPlugins; var inserted = {}; var container; var nodesToHydrate = []; { container = options.container || document.head; Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which // means that the style elements we're looking at are only Emotion 11 server-rendered style elements document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) { var attrib = node.getAttribute("data-emotion").split(' '); // $FlowFixMe for (var i = 1; i < attrib.length; i++) { inserted[attrib[i]] = true; } nodesToHydrate.push(node); }); } var _insert; var omnipresentPlugins = [compat, removeLabel]; { var currentSheet; var finalizingPlugins = [stringify, rulesheet(function (rule) { currentSheet.insert(rule); })]; var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins)); var stylis = function stylis(styles) { return serialize(compile(styles), serializer); }; _insert = function insert(selector, serialized, sheet, shouldCache) { currentSheet = sheet; stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles); if (shouldCache) { cache.inserted[serialized.name] = true; } }; } var cache = { key: key, sheet: new StyleSheet({ key: key, container: container, nonce: options.nonce, speedy: options.speedy, prepend: options.prepend, insertionPoint: options.insertionPoint }), nonce: options.nonce, inserted: inserted, registered: {}, insert: _insert }; cache.sheet.hydrate(nodesToHydrate); return cache; }; var syncFallback = function syncFallback(create) { return create(); }; var useInsertionEffect = React$1['useInsertion' + 'Effect'] ? React$1['useInsertion' + 'Effect'] : false; var useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback; var useInsertionEffectWithLayoutFallback = useInsertionEffect || reactExports.useLayoutEffect; var EmotionCacheContext = /* #__PURE__ */reactExports.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case // because this module is primarily intended for the browser and node // but it's also required in react native and similar environments sometimes // and we could have a special build just for that // but this is much easier and the native packages // might use a different theme context in the future anyway typeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache({ key: 'css' }) : null); EmotionCacheContext.Provider; var __unsafe_useEmotionCache = function useEmotionCache() { return reactExports.useContext(EmotionCacheContext); }; var withEmotionCache = function withEmotionCache(func) { // $FlowFixMe return /*#__PURE__*/reactExports.forwardRef(function (props, ref) { // the cache will never be null in the browser var cache = reactExports.useContext(EmotionCacheContext); return func(props, cache, ref); }); }; var ThemeContext$2 = /* #__PURE__ */reactExports.createContext({}); // initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild // initial client-side render from SSR, use place of hydrating tag var Global = /* #__PURE__ */withEmotionCache(function (props, cache) { var styles = props.styles; var serialized = serializeStyles([styles], undefined, reactExports.useContext(ThemeContext$2)); // but it is based on a constant that will never change at runtime // it's effectively like having two implementations and switching them out // so it's not actually breaking anything var sheetRef = reactExports.useRef(); useInsertionEffectWithLayoutFallback(function () { var key = cache.key + "-global"; // use case of https://github.com/emotion-js/emotion/issues/2675 var sheet = new cache.sheet.constructor({ key: key, nonce: cache.sheet.nonce, container: cache.sheet.container, speedy: cache.sheet.isSpeedy }); var rehydrating = false; // $FlowFixMe var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]"); if (cache.sheet.tags.length) { sheet.before = cache.sheet.tags[0]; } if (node !== null) { rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other s node.setAttribute('data-emotion', key); sheet.hydrate([node]); } sheetRef.current = [sheet, rehydrating]; return function () { sheet.flush(); }; }, [cache]); useInsertionEffectWithLayoutFallback(function () { var sheetRefCurrent = sheetRef.current; var sheet = sheetRefCurrent[0], rehydrating = sheetRefCurrent[1]; if (rehydrating) { sheetRefCurrent[1] = false; return; } if (serialized.next !== undefined) { // insert keyframes insertStyles(cache, serialized.next, true); } if (sheet.tags.length) { // if this doesn't exist then it will be null so the style element will be appended var element = sheet.tags[sheet.tags.length - 1].nextElementSibling; sheet.before = element; sheet.flush(); } cache.insert("", serialized, sheet, false); }, [cache, serialized.name]); return null; }); function css() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return serializeStyles(args); } var keyframes = function keyframes() { var insertable = css.apply(void 0, arguments); var name = "animation-" + insertable.name; // $FlowFixMe return { name: name, styles: "@keyframes " + name + "{" + insertable.styles + "}", anim: 1, toString: function toString() { return "_EMO_" + this.name + "_" + this.styles + "_EMO_"; } }; }; let counter = 0; function createMakeStyles(params) { const { useTheme, cache: cacheProvidedAtInception } = params; function useCache() { var _a; const contextualCache = __unsafe_useEmotionCache(); const cacheExplicitlyProvidedForTss = useCacheProvidedByProvider(); const cacheToBeUsed = (_a = cacheProvidedAtInception !== null && cacheProvidedAtInception !== void 0 ? cacheProvidedAtInception : cacheExplicitlyProvidedForTss) !== null && _a !== void 0 ? _a : contextualCache; if (cacheToBeUsed === null) { throw new Error([ "In order to get SSR working with tss-react you need to explicitly provide an Emotion cache.", "MUI users be aware: This is not an error strictly related to tss-react, with or without tss-react,", "MUI needs an Emotion cache to be provided for SSR to work.", "Here is the MUI documentation related to SSR setup: https://mui.com/material-ui/guides/server-rendering/", "TSS provides helper that makes the process of setting up SSR easier: https://docs.tss-react.dev/ssr", ].join("\n")); } return cacheToBeUsed; } const { useCssAndCx } = createUseCssAndCx({ useCache }); /** returns useStyle. */ function makeStyles(params) { const { name: nameOrWrappedName, uniqId = counter++ } = params !== null && params !== void 0 ? params : {}; const name = typeof nameOrWrappedName !== "object" ? nameOrWrappedName : Object.keys(nameOrWrappedName)[0]; return function (cssObjectByRuleNameOrGetCssObjectByRuleName) { const getCssObjectByRuleName = typeof cssObjectByRuleNameOrGetCssObjectByRuleName === "function" ? cssObjectByRuleNameOrGetCssObjectByRuleName : () => cssObjectByRuleNameOrGetCssObjectByRuleName; return function useStyles(params, styleOverrides) { var _a, _b; const theme = useTheme(); const { css, cx } = useCssAndCx(); const cache = useCache(); let classes = reactExports.useMemo(() => { const refClassesCache = {}; const refClasses = typeof Proxy !== "undefined" && new Proxy({}, { "get": (_target, propertyKey) => { if (typeof propertyKey === "symbol") { assert(false); } return (refClassesCache[propertyKey] = `${cache.key}-${uniqId}${name !== undefined ? `-${name}` : ""}-${propertyKey}-ref`); }, }); const cssObjectByRuleName = getCssObjectByRuleName(theme, params, refClasses || {}); const classes = objectFromEntries(objectKeys(cssObjectByRuleName).map(ruleName => { const cssObject = cssObjectByRuleName[ruleName]; if (!cssObject.label) { cssObject.label = `${name !== undefined ? `${name}-` : ""}${ruleName}`; } return [ ruleName, `${css(cssObject)}${typeGuard(ruleName, ruleName in refClassesCache) ? ` ${refClassesCache[ruleName]}` : ""}`, ]; })); objectKeys(refClassesCache).forEach(ruleName => { if (ruleName in classes) { return; } classes[ruleName] = refClassesCache[ruleName]; }); return classes; }, [cache, css, cx, theme, getDependencyArrayRef(params)]); const propsClasses = styleOverrides === null || styleOverrides === void 0 ? void 0 : styleOverrides.props.classes; classes = reactExports.useMemo(() => mergeClasses(classes, propsClasses, cx), [classes, getDependencyArrayRef(propsClasses), cx]); { let cssObjectByRuleNameOrGetCssObjectByRuleName = undefined; try { cssObjectByRuleNameOrGetCssObjectByRuleName = name !== undefined ? (_b = (_a = theme.components) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b.styleOverrides : undefined; // eslint-disable-next-line no-empty } catch (_c) { } const themeClasses = reactExports.useMemo(() => { if (!cssObjectByRuleNameOrGetCssObjectByRuleName) { return undefined; } const themeClasses = {}; for (const ruleName in cssObjectByRuleNameOrGetCssObjectByRuleName) { const cssObjectOrGetCssObject = cssObjectByRuleNameOrGetCssObjectByRuleName[ruleName]; if (!(cssObjectOrGetCssObject instanceof Object)) { continue; } themeClasses[ruleName] = css(typeof cssObjectOrGetCssObject === "function" ? cssObjectOrGetCssObject(Object.assign({ theme, "ownerState": styleOverrides === null || styleOverrides === void 0 ? void 0 : styleOverrides.ownerState }, styleOverrides === null || styleOverrides === void 0 ? void 0 : styleOverrides.props)) : cssObjectOrGetCssObject); } return themeClasses; }, [ cssObjectByRuleNameOrGetCssObjectByRuleName === undefined ? undefined : JSON.stringify(cssObjectByRuleNameOrGetCssObjectByRuleName), getDependencyArrayRef(styleOverrides === null || styleOverrides === void 0 ? void 0 : styleOverrides.props), getDependencyArrayRef(styleOverrides === null || styleOverrides === void 0 ? void 0 : styleOverrides.ownerState), css, ]); classes = reactExports.useMemo(() => mergeClasses(classes, themeClasses, cx), [classes, themeClasses, cx]); } return { classes, theme, css, cx, }; }; }; } function useStyles() { const theme = useTheme(); const { css, cx } = useCssAndCx(); return { theme, css, cx }; } return { makeStyles, useStyles }; } const reactContext = reactExports.createContext(undefined); function useCacheProvidedByProvider() { const cacheExplicitlyProvidedForTss = reactExports.useContext(reactContext); return cacheExplicitlyProvidedForTss; } /** @see */ function capitalize$1(str) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (str.charAt(0).toUpperCase() + str.slice(1)); } var __rest = (globalThis && globalThis.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; function createWithStyles(params) { const { useTheme, cache } = params; const { makeStyles } = createMakeStyles({ useTheme, cache }); function withStyles(Component, cssObjectByRuleNameOrGetCssObjectByRuleName, params) { const Component_ = typeof Component === "string" ? (() => { const tag = Component; const Out = function (_a) { var { children } = _a, props = __rest(_a, ["children"]); return reactExports.createElement(tag, props, children); }; Object.defineProperty(Out, "name", { "value": capitalize$1(tag), }); return Out; })() : Component; /** * Get component name for wrapping * @see https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging */ const name = (() => { { const { name: nameOrWrappedName } = params !== null && params !== void 0 ? params : {}; if (nameOrWrappedName !== undefined) { return typeof nameOrWrappedName !== "object" ? nameOrWrappedName : Object.keys(nameOrWrappedName)[0]; } } { const displayName = Component_.displayName; if (typeof displayName === "string" && displayName !== "") { return displayName; } } { const { name } = Component_; if (name) { return name; } } })(); const useStyles = makeStyles(Object.assign(Object.assign({}, params), { name }))(typeof cssObjectByRuleNameOrGetCssObjectByRuleName === "function" ? (theme, props, classes) => incorporateMediaQueries(cssObjectByRuleNameOrGetCssObjectByRuleName(theme, props, classes)) : incorporateMediaQueries(cssObjectByRuleNameOrGetCssObjectByRuleName)); function getHasNonRootClasses(classes) { for (const name in classes) { if (name === "root") { continue; } return true; } return false; } // eslint-disable-next-line @typescript-eslint/no-explicit-any const Out = reactExports.forwardRef(function (props, ref) { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { className, classes: _classes } = props, rest = __rest(props, ["className", "classes"]); const { classes, cx } = useStyles(props, { props }); return (React.createElement(Component_, Object.assign({ ref: ref, className: getHasNonRootClasses(classes) ? className : cx(classes.root, className) }, (typeof Component === "string" ? {} : { classes }), rest))); }); if (name !== undefined) { Out.displayName = `${capitalize$1(name)}WithStyles`; Object.defineProperty(Out, "name", { "value": Out.displayName }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any return Out; } return { withStyles }; } function incorporateMediaQueries(cssObjectByRuleNameWithMediaQueries) { const cssObjectByRuleName = {}; const cssObjectByRuleNameWithMediaQueriesByMediaQuery = {}; Object.keys(cssObjectByRuleNameWithMediaQueries).forEach(ruleNameOrMediaQuery => ((ruleNameOrMediaQuery.startsWith("@media") ? cssObjectByRuleNameWithMediaQueriesByMediaQuery : cssObjectByRuleName)[ruleNameOrMediaQuery] = cssObjectByRuleNameWithMediaQueries[ruleNameOrMediaQuery])); Object.keys(cssObjectByRuleNameWithMediaQueriesByMediaQuery).forEach(mediaQuery => { const cssObjectByRuleNameBis = cssObjectByRuleNameWithMediaQueriesByMediaQuery[mediaQuery]; Object.keys(cssObjectByRuleNameBis).forEach(ruleName => { var _a; return (cssObjectByRuleName[ruleName] = Object.assign(Object.assign({}, ((_a = cssObjectByRuleName[ruleName]) !== null && _a !== void 0 ? _a : {})), { [mediaQuery]: cssObjectByRuleNameBis[ruleName] })); }); }); return cssObjectByRuleName; } function GlobalStyles$2(props) { const { styles } = props; return React.createElement(Global, { styles: css(styles) }); } /** @see */ function createMakeAndWithStyles(params) { return Object.assign(Object.assign({}, createMakeStyles(params)), createWithStyles(params)); } const common = { black: '#000', white: '#fff' }; const common$1 = common; const red = { 50: '#ffebee', 100: '#ffcdd2', 200: '#ef9a9a', 300: '#e57373', 400: '#ef5350', 500: '#f44336', 600: '#e53935', 700: '#d32f2f', 800: '#c62828', 900: '#b71c1c', A100: '#ff8a80', A200: '#ff5252', A400: '#ff1744', A700: '#d50000' }; const red$1 = red; const purple = { 50: '#f3e5f5', 100: '#e1bee7', 200: '#ce93d8', 300: '#ba68c8', 400: '#ab47bc', 500: '#9c27b0', 600: '#8e24aa', 700: '#7b1fa2', 800: '#6a1b9a', 900: '#4a148c', A100: '#ea80fc', A200: '#e040fb', A400: '#d500f9', A700: '#aa00ff' }; const purple$1 = purple; const blue = { 50: '#e3f2fd', 100: '#bbdefb', 200: '#90caf9', 300: '#64b5f6', 400: '#42a5f5', 500: '#2196f3', 600: '#1e88e5', 700: '#1976d2', 800: '#1565c0', 900: '#0d47a1', A100: '#82b1ff', A200: '#448aff', A400: '#2979ff', A700: '#2962ff' }; const blue$1 = blue; const lightBlue = { 50: '#e1f5fe', 100: '#b3e5fc', 200: '#81d4fa', 300: '#4fc3f7', 400: '#29b6f6', 500: '#03a9f4', 600: '#039be5', 700: '#0288d1', 800: '#0277bd', 900: '#01579b', A100: '#80d8ff', A200: '#40c4ff', A400: '#00b0ff', A700: '#0091ea' }; const lightBlue$1 = lightBlue; const green = { 50: '#e8f5e9', 100: '#c8e6c9', 200: '#a5d6a7', 300: '#81c784', 400: '#66bb6a', 500: '#4caf50', 600: '#43a047', 700: '#388e3c', 800: '#2e7d32', 900: '#1b5e20', A100: '#b9f6ca', A200: '#69f0ae', A400: '#00e676', A700: '#00c853' }; const green$1 = green; const orange = { 50: '#fff3e0', 100: '#ffe0b2', 200: '#ffcc80', 300: '#ffb74d', 400: '#ffa726', 500: '#ff9800', 600: '#fb8c00', 700: '#f57c00', 800: '#ef6c00', 900: '#e65100', A100: '#ffd180', A200: '#ffab40', A400: '#ff9100', A700: '#ff6d00' }; const orange$1 = orange; const grey = { 50: '#fafafa', 100: '#f5f5f5', 200: '#eeeeee', 300: '#e0e0e0', 400: '#bdbdbd', 500: '#9e9e9e', 600: '#757575', 700: '#616161', 800: '#424242', 900: '#212121', A100: '#f5f5f5', A200: '#eeeeee', A400: '#bdbdbd', A700: '#616161' }; const grey$1 = grey; function isPlainObject(item) { return item !== null && typeof item === 'object' && item.constructor === Object; } function deepClone(source) { if (!isPlainObject(source)) { return source; } const output = {}; Object.keys(source).forEach(key => { output[key] = deepClone(source[key]); }); return output; } function deepmerge(target, source, options = { clone: true }) { const output = options.clone ? _extends({}, target) : target; if (isPlainObject(target) && isPlainObject(source)) { Object.keys(source).forEach(key => { // Avoid prototype pollution if (key === '__proto__') { return; } if (isPlainObject(source[key]) && key in target && isPlainObject(target[key])) { // Since `output` is a clone of `target` and we have narrowed `target` in this block we can cast to the same type. output[key] = deepmerge(target[key], source[key], options); } else if (options.clone) { output[key] = isPlainObject(source[key]) ? deepClone(source[key]) : source[key]; } else { output[key] = source[key]; } }); } return output; } var propTypesExports = {}; var propTypes = { get exports(){ return propTypesExports; }, set exports(v){ propTypesExports = v; }, }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = ReactPropTypesSecret_1; function emptyFunction() {} function emptyFunctionWithReset() {} emptyFunctionWithReset.resetWarningCache = emptyFunction; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bigint: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, elementType: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim, checkPropTypes: emptyFunctionWithReset, resetWarningCache: emptyFunction }; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod propTypes.exports = factoryWithThrowingShims(); } /** * WARNING: Don't import this directly. * Use `MuiError` from `@mui/utils/macros/MuiError.macro` instead. * @param {number} code */ function formatMuiErrorMessage(code) { // Apply babel-plugin-transform-template-literals in loose mode // loose mode is safe iff we're concatenating primitives // see https://babeljs.io/docs/en/babel-plugin-transform-template-literals#loose /* eslint-disable prefer-template */ let url = 'https://mui.com/production-error/?code=' + code; for (let i = 1; i < arguments.length; i += 1) { // rest params over-transpile for this case // eslint-disable-next-line prefer-rest-params url += '&args[]=' + encodeURIComponent(arguments[i]); } return 'Minified MUI error #' + code + '; visit ' + url + ' for the full message.'; /* eslint-enable prefer-template */ } // It should to be noted that this function isn't equivalent to `text-transform: capitalize`. // // A strict capitalization should uppercase the first letter of each word in the sentence. // We only handle the first word. function capitalize(string) { if (typeof string !== 'string') { throw new Error(formatMuiErrorMessage(7)); } return string.charAt(0).toUpperCase() + string.slice(1); } /** * Safe chained function. * * Will only create a new function if needed, * otherwise will pass back existing functions or null. */ function createChainedFunction(...funcs) { return funcs.reduce((acc, func) => { if (func == null) { return acc; } return function chainedFunction(...args) { acc.apply(this, args); func.apply(this, args); }; }, () => {}); } // Corresponds to 10 frames at 60 Hz. // A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B. function debounce$1(func, wait = 166) { let timeout; function debounced(...args) { const later = () => { func.apply(this, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); } debounced.clear = () => { clearTimeout(timeout); }; return debounced; } function deprecatedPropType(validator, reason) { { return () => null; } } function isMuiElement(element, muiNames) { return /*#__PURE__*/reactExports.isValidElement(element) && muiNames.indexOf(element.type.muiName) !== -1; } function ownerDocument(node) { return node && node.ownerDocument || document; } function ownerWindow(node) { const doc = ownerDocument(node); return doc.defaultView || window; } function requirePropFactory(componentNameInError, Component) { { return () => null; } } /** * TODO v5: consider making it private * * passes {value} to {ref} * * WARNING: Be sure to only call this inside a callback that is passed as a ref. * Otherwise, make sure to cleanup the previous {ref} if it changes. See * https://github.com/mui/material-ui/issues/13539 * * Useful if you want to expose the ref of an inner component to the public API * while still using it inside the component. * @param ref A ref callback or ref object. If anything falsy, this is a no-op. */ function setRef(ref, value) { if (typeof ref === 'function') { ref(value); } else if (ref) { ref.current = value; } } const useEnhancedEffect = typeof window !== 'undefined' ? reactExports.useLayoutEffect : reactExports.useEffect; const useEnhancedEffect$1 = useEnhancedEffect; let globalId = 0; function useGlobalId(idOverride) { const [defaultId, setDefaultId] = reactExports.useState(idOverride); const id = idOverride || defaultId; reactExports.useEffect(() => { if (defaultId == null) { // Fallback to this default id when possible. // Use the incrementing value for client-side rendering only. // We can't use it server-side. // If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem globalId += 1; setDefaultId(`mui-${globalId}`); } }, [defaultId]); return id; } // eslint-disable-next-line no-useless-concat -- Workaround for https://github.com/webpack/webpack/issues/14814 const maybeReactUseId = React$1['useId' + '']; /** * * @example
* @param idOverride * @returns {string} */ function useId(idOverride) { if (maybeReactUseId !== undefined) { const reactId = maybeReactUseId(); return idOverride != null ? idOverride : reactId; } // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime. return useGlobalId(idOverride); } function unsupportedProp(props, propName, componentName, location, propFullName) { { return null; } } /* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */ function useControlled({ controlled, default: defaultProp, name, state = 'value' }) { // isControlled is ignored in the hook dependency lists as it should never change. const { current: isControlled } = reactExports.useRef(controlled !== undefined); const [valueState, setValue] = reactExports.useState(defaultProp); const value = isControlled ? controlled : valueState; const setValueIfUncontrolled = reactExports.useCallback(newValue => { if (!isControlled) { setValue(newValue); } }, []); return [value, setValueIfUncontrolled]; } /** * https://github.com/facebook/react/issues/14099#issuecomment-440013892 */ function useEventCallback(fn) { const ref = reactExports.useRef(fn); useEnhancedEffect$1(() => { ref.current = fn; }); return reactExports.useCallback((...args) => // @ts-expect-error hide `this` // tslint:disable-next-line:ban-comma-operator (0, ref.current)(...args), []); } function useForkRef(...refs) { /** * This will create a new function if the refs passed to this hook change and are all defined. * This means react will call the old forkRef with `null` and the new forkRef * with the ref. Cleanup naturally emerges from this behavior. */ return reactExports.useMemo(() => { if (refs.every(ref => ref == null)) { return null; } return instance => { refs.forEach(ref => { setRef(ref, instance); }); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, refs); } // based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js let hadKeyboardEvent = true; let hadFocusVisibleRecently = false; let hadFocusVisibleRecentlyTimeout; const inputTypesWhitelist = { text: true, search: true, url: true, tel: true, email: true, password: true, number: true, date: true, month: true, week: true, time: true, datetime: true, 'datetime-local': true }; /** * Computes whether the given element should automatically trigger the * `focus-visible` class being added, i.e. whether it should always match * `:focus-visible` when focused. * @param {Element} node * @returns {boolean} */ function focusTriggersKeyboardModality(node) { const { type, tagName } = node; if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) { return true; } if (tagName === 'TEXTAREA' && !node.readOnly) { return true; } if (node.isContentEditable) { return true; } return false; } /** * Keep track of our keyboard modality state with `hadKeyboardEvent`. * If the most recent user interaction was via the keyboard; * and the key press did not include a meta, alt/option, or control key; * then the modality is keyboard. Otherwise, the modality is not keyboard. * @param {KeyboardEvent} event */ function handleKeyDown(event) { if (event.metaKey || event.altKey || event.ctrlKey) { return; } hadKeyboardEvent = true; } /** * If at any point a user clicks with a pointing device, ensure that we change * the modality away from keyboard. * This avoids the situation where a user presses a key on an already focused * element, and then clicks on a different element, focusing it with a * pointing device, while we still think we're in keyboard modality. */ function handlePointerDown() { hadKeyboardEvent = false; } function handleVisibilityChange() { if (this.visibilityState === 'hidden') { // If the tab becomes active again, the browser will handle calling focus // on the element (Safari actually calls it twice). // If this tab change caused a blur on an element with focus-visible, // re-apply the class when the user switches back to the tab. if (hadFocusVisibleRecently) { hadKeyboardEvent = true; } } } function prepare(doc) { doc.addEventListener('keydown', handleKeyDown, true); doc.addEventListener('mousedown', handlePointerDown, true); doc.addEventListener('pointerdown', handlePointerDown, true); doc.addEventListener('touchstart', handlePointerDown, true); doc.addEventListener('visibilitychange', handleVisibilityChange, true); } function isFocusVisible(event) { const { target } = event; try { return target.matches(':focus-visible'); } catch (error) { // Browsers not implementing :focus-visible will throw a SyntaxError. // We use our own heuristic for those browsers. // Rethrow might be better if it's not the expected error but do we really // want to crash if focus-visible malfunctioned? } // No need for validFocusTarget check. The user does that by attaching it to // focusable events only. return hadKeyboardEvent || focusTriggersKeyboardModality(target); } function useIsFocusVisible() { const ref = reactExports.useCallback(node => { if (node != null) { prepare(node.ownerDocument); } }, []); const isFocusVisibleRef = reactExports.useRef(false); /** * Should be called if a blur event is fired */ function handleBlurVisible() { // checking against potential state variable does not suffice if we focus and blur synchronously. // React wouldn't have time to trigger a re-render so `focusVisible` would be stale. // Ideally we would adjust `isFocusVisible(event)` to look at `relatedTarget` for blur events. // This doesn't work in IE11 due to https://github.com/facebook/react/issues/3751 // TODO: check again if React releases their internal changes to focus event handling (https://github.com/facebook/react/pull/19186). if (isFocusVisibleRef.current) { // To detect a tab/window switch, we look for a blur event followed // rapidly by a visibility change. // If we don't see a visibility change within 100ms, it's probably a // regular focus change. hadFocusVisibleRecently = true; window.clearTimeout(hadFocusVisibleRecentlyTimeout); hadFocusVisibleRecentlyTimeout = window.setTimeout(() => { hadFocusVisibleRecently = false; }, 100); isFocusVisibleRef.current = false; return true; } return false; } /** * Should be called if a blur event is fired */ function handleFocusVisible(event) { if (isFocusVisible(event)) { isFocusVisibleRef.current = true; return true; } return false; } return { isFocusVisibleRef, onFocus: handleFocusVisible, onBlur: handleBlurVisible, ref }; } // A change of the browser zoom change the scrollbar size. // Credit https://github.com/twbs/bootstrap/blob/488fd8afc535ca3a6ad4dc581f5e89217b6a36ac/js/src/util/scrollbar.js#L14-L18 function getScrollbarSize(doc) { // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes const documentWidth = doc.documentElement.clientWidth; return Math.abs(window.innerWidth - documentWidth); } const visuallyHidden = { border: 0, clip: 'rect(0 0 0 0)', height: '1px', margin: -1, overflow: 'hidden', padding: 0, position: 'absolute', whiteSpace: 'nowrap', width: '1px' }; const visuallyHidden$1 = visuallyHidden; /** * Add keys, values of `defaultProps` that does not exist in `props` * @param {object} defaultProps * @param {object} props * @returns {object} resolved props */ function resolveProps(defaultProps, props) { const output = _extends({}, props); Object.keys(defaultProps).forEach(propName => { if (propName.toString().match(/^(components|slots)$/)) { output[propName] = _extends({}, defaultProps[propName], output[propName]); } else if (propName.toString().match(/^(componentsProps|slotProps)$/)) { const defaultSlotProps = defaultProps[propName] || {}; const slotProps = props[propName]; output[propName] = {}; if (!slotProps || !Object.keys(slotProps)) { // Reduce the iteration if the slot props is empty output[propName] = defaultSlotProps; } else if (!defaultSlotProps || !Object.keys(defaultSlotProps)) { // Reduce the iteration if the default slot props is empty output[propName] = slotProps; } else { output[propName] = _extends({}, slotProps); Object.keys(defaultSlotProps).forEach(slotPropName => { output[propName][slotPropName] = resolveProps(defaultSlotProps[slotPropName], slotProps[slotPropName]); }); } } else if (output[propName] === undefined) { output[propName] = defaultProps[propName]; } }); return output; } function composeClasses(slots, getUtilityClass, classes) { const output = {}; Object.keys(slots).forEach( // `Objet.keys(slots)` can't be wider than `T` because we infer `T` from `slots`. // @ts-expect-error https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208 slot => { output[slot] = slots[slot].reduce((acc, key) => { if (key) { acc.push(getUtilityClass(key)); if (classes && classes[key]) { acc.push(classes[key]); } } return acc; }, []).join(' '); }); return output; } const defaultGenerator = componentName => componentName; const createClassNameGenerator = () => { let generate = defaultGenerator; return { configure(generator) { generate = generator; }, generate(componentName) { return generate(componentName); }, reset() { generate = defaultGenerator; } }; }; const ClassNameGenerator = createClassNameGenerator(); const ClassNameGenerator$1 = ClassNameGenerator; const globalStateClassesMapping = { active: 'active', checked: 'checked', completed: 'completed', disabled: 'disabled', error: 'error', expanded: 'expanded', focused: 'focused', focusVisible: 'focusVisible', required: 'required', selected: 'selected' }; function generateUtilityClass(componentName, slot, globalStatePrefix = 'Mui') { const globalStateClass = globalStateClassesMapping[slot]; return globalStateClass ? `${globalStatePrefix}-${globalStateClass}` : `${ClassNameGenerator$1.generate(componentName)}-${slot}`; } function generateUtilityClasses(componentName, slots, globalStatePrefix = 'Mui') { const result = {}; slots.forEach(slot => { result[slot] = generateUtilityClass(componentName, slot, globalStatePrefix); }); return result; } var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 var isPropValid = /* #__PURE__ */memoize$1(function (prop) { return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 /* o */ && prop.charCodeAt(1) === 110 /* n */ && prop.charCodeAt(2) < 91; } /* Z+1 */ ); var testOmitPropsOnStringTag = isPropValid; var testOmitPropsOnComponent = function testOmitPropsOnComponent(key) { return key !== 'theme'; }; var getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) { return typeof tag === 'string' && // 96 is one less than the char code // for "a" so this is checking that // it's a lowercase character tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent; }; var composeShouldForwardProps = function composeShouldForwardProps(tag, options, isReal) { var shouldForwardProp; if (options) { var optionsShouldForwardProp = options.shouldForwardProp; shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName) { return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName); } : optionsShouldForwardProp; } if (typeof shouldForwardProp !== 'function' && isReal) { shouldForwardProp = tag.__emotion_forwardProp; } return shouldForwardProp; }; var Insertion = function Insertion(_ref) { var cache = _ref.cache, serialized = _ref.serialized, isStringTag = _ref.isStringTag; registerStyles(cache, serialized, isStringTag); useInsertionEffectAlwaysWithSyncFallback(function () { return insertStyles(cache, serialized, isStringTag); }); return null; }; var createStyled$1 = function createStyled(tag, options) { var isReal = tag.__emotion_real === tag; var baseTag = isReal && tag.__emotion_base || tag; var identifierName; var targetClassName; if (options !== undefined) { identifierName = options.label; targetClassName = options.target; } var shouldForwardProp = composeShouldForwardProps(tag, options, isReal); var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag); var shouldUseAs = !defaultShouldForwardProp('as'); return function () { var args = arguments; var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : []; if (identifierName !== undefined) { styles.push("label:" + identifierName + ";"); } if (args[0] == null || args[0].raw === undefined) { styles.push.apply(styles, args); } else { styles.push(args[0][0]); var len = args.length; var i = 1; for (; i < len; i++) { styles.push(args[i], args[0][i]); } } // $FlowFixMe: we need to cast StatelessFunctionalComponent to our PrivateStyledComponent class var Styled = withEmotionCache(function (props, cache, ref) { var FinalTag = shouldUseAs && props.as || baseTag; var className = ''; var classInterpolations = []; var mergedProps = props; if (props.theme == null) { mergedProps = {}; for (var key in props) { mergedProps[key] = props[key]; } mergedProps.theme = reactExports.useContext(ThemeContext$2); } if (typeof props.className === 'string') { className = getRegisteredStyles(cache.registered, classInterpolations, props.className); } else if (props.className != null) { className = props.className + " "; } var serialized = serializeStyles(styles.concat(classInterpolations), cache.registered, mergedProps); className += cache.key + "-" + serialized.name; if (targetClassName !== undefined) { className += " " + targetClassName; } var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp; var newProps = {}; for (var _key in props) { if (shouldUseAs && _key === 'as') continue; if ( // $FlowFixMe finalShouldForwardProp(_key)) { newProps[_key] = props[_key]; } } newProps.className = className; newProps.ref = ref; return /*#__PURE__*/reactExports.createElement(reactExports.Fragment, null, /*#__PURE__*/reactExports.createElement(Insertion, { cache: cache, serialized: serialized, isStringTag: typeof FinalTag === 'string' }), /*#__PURE__*/reactExports.createElement(FinalTag, newProps)); }); Styled.displayName = identifierName !== undefined ? identifierName : "Styled(" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + ")"; Styled.defaultProps = tag.defaultProps; Styled.__emotion_real = Styled; Styled.__emotion_base = baseTag; Styled.__emotion_styles = styles; Styled.__emotion_forwardProp = shouldForwardProp; Object.defineProperty(Styled, 'toString', { value: function value() { if (targetClassName === undefined && "production" !== 'production') { return 'NO_COMPONENT_SELECTOR'; } // $FlowFixMe: coerce undefined to string return "." + targetClassName; } }); Styled.withComponent = function (nextTag, nextOptions) { return createStyled(nextTag, _extends({}, options, nextOptions, { shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true) })).apply(void 0, styles); }; return Styled; }; }; var tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; var newStyled = createStyled$1.bind(); tags.forEach(function (tagName) { // $FlowFixMe: we can ignore this because its exposed type is defined by the CreateStyled type newStyled[tagName] = newStyled(tagName); }); const emStyled = newStyled; function isEmpty$4(obj) { return obj === undefined || obj === null || Object.keys(obj).length === 0; } function GlobalStyles$1(props) { const { styles, defaultTheme = {} } = props; const globalStyles = typeof styles === 'function' ? themeInput => styles(isEmpty$4(themeInput) ? defaultTheme : themeInput) : styles; return /*#__PURE__*/jsx(Global, { styles: globalStyles }); } /** @license MUI v5.11.0 * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ function styled$2(tag, options) { const stylesFactory = emStyled(tag, options); return stylesFactory; } // eslint-disable-next-line @typescript-eslint/naming-convention const internal_processStyles = (tag, processor) => { // Emotion attaches all the styles as `__emotion_styles`. // Ref: https://github.com/emotion-js/emotion/blob/16d971d0da229596d6bcc39d282ba9753c9ee7cf/packages/styled/src/base.js#L186 if (Array.isArray(tag.__emotion_styles)) { tag.__emotion_styles = processor(tag.__emotion_styles); } }; function merge(acc, item) { if (!item) { return acc; } return deepmerge(acc, item, { clone: false // No need to clone deep, it's way faster. }); } // The breakpoint **start** at this value. // For instance with the first breakpoint xs: [xs, sm[. const values$1 = { xs: 0, // phone sm: 600, // tablet md: 900, // small laptop lg: 1200, // desktop xl: 1536 // large screen }; const defaultBreakpoints = { // Sorted ASC by size. That's important. // It can't be configured as it's used statically for propTypes. keys: ['xs', 'sm', 'md', 'lg', 'xl'], up: key => `@media (min-width:${values$1[key]}px)` }; function handleBreakpoints(props, propValue, styleFromPropValue) { const theme = props.theme || {}; if (Array.isArray(propValue)) { const themeBreakpoints = theme.breakpoints || defaultBreakpoints; return propValue.reduce((acc, item, index) => { acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]); return acc; }, {}); } if (typeof propValue === 'object') { const themeBreakpoints = theme.breakpoints || defaultBreakpoints; return Object.keys(propValue).reduce((acc, breakpoint) => { // key is breakpoint if (Object.keys(themeBreakpoints.values || values$1).indexOf(breakpoint) !== -1) { const mediaKey = themeBreakpoints.up(breakpoint); acc[mediaKey] = styleFromPropValue(propValue[breakpoint], breakpoint); } else { const cssKey = breakpoint; acc[cssKey] = propValue[cssKey]; } return acc; }, {}); } const output = styleFromPropValue(propValue); return output; } function createEmptyBreakpointObject(breakpointsInput = {}) { var _breakpointsInput$key; const breakpointsInOrder = (_breakpointsInput$key = breakpointsInput.keys) == null ? void 0 : _breakpointsInput$key.reduce((acc, key) => { const breakpointStyleKey = breakpointsInput.up(key); acc[breakpointStyleKey] = {}; return acc; }, {}); return breakpointsInOrder || {}; } function removeUnusedBreakpoints(breakpointKeys, style) { return breakpointKeys.reduce((acc, key) => { const breakpointOutput = acc[key]; const isBreakpointUnused = !breakpointOutput || Object.keys(breakpointOutput).length === 0; if (isBreakpointUnused) { delete acc[key]; } return acc; }, style); } function getPath(obj, path, checkVars = true) { if (!path || typeof path !== 'string') { return null; } // Check if CSS variables are used if (obj && obj.vars && checkVars) { const val = `vars.${path}`.split('.').reduce((acc, item) => acc && acc[item] ? acc[item] : null, obj); if (val != null) { return val; } } return path.split('.').reduce((acc, item) => { if (acc && acc[item] != null) { return acc[item]; } return null; }, obj); } function getStyleValue$1(themeMapping, transform, propValueFinal, userValue = propValueFinal) { let value; if (typeof themeMapping === 'function') { value = themeMapping(propValueFinal); } else if (Array.isArray(themeMapping)) { value = themeMapping[propValueFinal] || userValue; } else { value = getPath(themeMapping, propValueFinal) || userValue; } if (transform) { value = transform(value, userValue, themeMapping); } return value; } function style$1(options) { const { prop, cssProperty = options.prop, themeKey, transform } = options; // false positive // eslint-disable-next-line react/function-component-definition const fn = props => { if (props[prop] == null) { return null; } const propValue = props[prop]; const theme = props.theme; const themeMapping = getPath(theme, themeKey) || {}; const styleFromPropValue = propValueFinal => { let value = getStyleValue$1(themeMapping, transform, propValueFinal); if (propValueFinal === value && typeof propValueFinal === 'string') { // Haven't found value value = getStyleValue$1(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal); } if (cssProperty === false) { return value; } return { [cssProperty]: value }; }; return handleBreakpoints(props, propValue, styleFromPropValue); }; fn.propTypes = {}; fn.filterProps = [prop]; return fn; } function compose(...styles) { const handlers = styles.reduce((acc, style) => { style.filterProps.forEach(prop => { acc[prop] = style; }); return acc; }, {}); // false positive // eslint-disable-next-line react/function-component-definition const fn = props => { return Object.keys(props).reduce((acc, prop) => { if (handlers[prop]) { return merge(acc, handlers[prop](props)); } return acc; }, {}); }; fn.propTypes = {}; fn.filterProps = styles.reduce((acc, style) => acc.concat(style.filterProps), []); return fn; } function memoize(fn) { const cache = {}; return arg => { if (cache[arg] === undefined) { cache[arg] = fn(arg); } return cache[arg]; }; } const properties = { m: 'margin', p: 'padding' }; const directions = { t: 'Top', r: 'Right', b: 'Bottom', l: 'Left', x: ['Left', 'Right'], y: ['Top', 'Bottom'] }; const aliases = { marginX: 'mx', marginY: 'my', paddingX: 'px', paddingY: 'py' }; // memoize() impact: // From 300,000 ops/sec // To 350,000 ops/sec const getCssProperties = memoize(prop => { // It's not a shorthand notation. if (prop.length > 2) { if (aliases[prop]) { prop = aliases[prop]; } else { return [prop]; } } const [a, b] = prop.split(''); const property = properties[a]; const direction = directions[b] || ''; return Array.isArray(direction) ? direction.map(dir => property + dir) : [property + direction]; }); const marginKeys = ['m', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'marginInline', 'marginInlineStart', 'marginInlineEnd', 'marginBlock', 'marginBlockStart', 'marginBlockEnd']; const paddingKeys = ['p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY', 'paddingInline', 'paddingInlineStart', 'paddingInlineEnd', 'paddingBlock', 'paddingBlockStart', 'paddingBlockEnd']; [...marginKeys, ...paddingKeys]; function createUnaryUnit(theme, themeKey, defaultValue, propName) { var _getPath; const themeSpacing = (_getPath = getPath(theme, themeKey, false)) != null ? _getPath : defaultValue; if (typeof themeSpacing === 'number') { return abs => { if (typeof abs === 'string') { return abs; } return themeSpacing * abs; }; } if (Array.isArray(themeSpacing)) { return abs => { if (typeof abs === 'string') { return abs; } return themeSpacing[abs]; }; } if (typeof themeSpacing === 'function') { return themeSpacing; } return () => undefined; } function createUnarySpacing(theme) { return createUnaryUnit(theme, 'spacing', 8); } function getValue(transformer, propValue) { if (typeof propValue === 'string' || propValue == null) { return propValue; } const abs = Math.abs(propValue); const transformed = transformer(abs); if (propValue >= 0) { return transformed; } if (typeof transformed === 'number') { return -transformed; } return `-${transformed}`; } function getStyleFromPropValue(cssProperties, transformer) { return propValue => cssProperties.reduce((acc, cssProperty) => { acc[cssProperty] = getValue(transformer, propValue); return acc; }, {}); } function resolveCssProperty(props, keys, prop, transformer) { // Using a hash computation over an array iteration could be faster, but with only 28 items, // it's doesn't worth the bundle size. if (keys.indexOf(prop) === -1) { return null; } const cssProperties = getCssProperties(prop); const styleFromPropValue = getStyleFromPropValue(cssProperties, transformer); const propValue = props[prop]; return handleBreakpoints(props, propValue, styleFromPropValue); } function style(props, keys) { const transformer = createUnarySpacing(props.theme); return Object.keys(props).map(prop => resolveCssProperty(props, keys, prop, transformer)).reduce(merge, {}); } function margin(props) { return style(props, marginKeys); } margin.propTypes = {}; margin.filterProps = marginKeys; function padding(props) { return style(props, paddingKeys); } padding.propTypes = {}; padding.filterProps = paddingKeys; function borderTransform(value) { if (typeof value !== 'number') { return value; } return `${value}px solid`; } const border = style$1({ prop: 'border', themeKey: 'borders', transform: borderTransform }); const borderTop = style$1({ prop: 'borderTop', themeKey: 'borders', transform: borderTransform }); const borderRight = style$1({ prop: 'borderRight', themeKey: 'borders', transform: borderTransform }); const borderBottom = style$1({ prop: 'borderBottom', themeKey: 'borders', transform: borderTransform }); const borderLeft = style$1({ prop: 'borderLeft', themeKey: 'borders', transform: borderTransform }); const borderColor = style$1({ prop: 'borderColor', themeKey: 'palette' }); const borderTopColor = style$1({ prop: 'borderTopColor', themeKey: 'palette' }); const borderRightColor = style$1({ prop: 'borderRightColor', themeKey: 'palette' }); const borderBottomColor = style$1({ prop: 'borderBottomColor', themeKey: 'palette' }); const borderLeftColor = style$1({ prop: 'borderLeftColor', themeKey: 'palette' }); // false positive // eslint-disable-next-line react/function-component-definition const borderRadius = props => { if (props.borderRadius !== undefined && props.borderRadius !== null) { const transformer = createUnaryUnit(props.theme, 'shape.borderRadius', 4); const styleFromPropValue = propValue => ({ borderRadius: getValue(transformer, propValue) }); return handleBreakpoints(props, props.borderRadius, styleFromPropValue); } return null; }; borderRadius.propTypes = {}; borderRadius.filterProps = ['borderRadius']; compose(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderTopColor, borderRightColor, borderBottomColor, borderLeftColor, borderRadius); // false positive // eslint-disable-next-line react/function-component-definition const gap = props => { if (props.gap !== undefined && props.gap !== null) { const transformer = createUnaryUnit(props.theme, 'spacing', 8); const styleFromPropValue = propValue => ({ gap: getValue(transformer, propValue) }); return handleBreakpoints(props, props.gap, styleFromPropValue); } return null; }; gap.propTypes = {}; gap.filterProps = ['gap']; // false positive // eslint-disable-next-line react/function-component-definition const columnGap = props => { if (props.columnGap !== undefined && props.columnGap !== null) { const transformer = createUnaryUnit(props.theme, 'spacing', 8); const styleFromPropValue = propValue => ({ columnGap: getValue(transformer, propValue) }); return handleBreakpoints(props, props.columnGap, styleFromPropValue); } return null; }; columnGap.propTypes = {}; columnGap.filterProps = ['columnGap']; // false positive // eslint-disable-next-line react/function-component-definition const rowGap = props => { if (props.rowGap !== undefined && props.rowGap !== null) { const transformer = createUnaryUnit(props.theme, 'spacing', 8); const styleFromPropValue = propValue => ({ rowGap: getValue(transformer, propValue) }); return handleBreakpoints(props, props.rowGap, styleFromPropValue); } return null; }; rowGap.propTypes = {}; rowGap.filterProps = ['rowGap']; const gridColumn = style$1({ prop: 'gridColumn' }); const gridRow = style$1({ prop: 'gridRow' }); const gridAutoFlow = style$1({ prop: 'gridAutoFlow' }); const gridAutoColumns = style$1({ prop: 'gridAutoColumns' }); const gridAutoRows = style$1({ prop: 'gridAutoRows' }); const gridTemplateColumns = style$1({ prop: 'gridTemplateColumns' }); const gridTemplateRows = style$1({ prop: 'gridTemplateRows' }); const gridTemplateAreas = style$1({ prop: 'gridTemplateAreas' }); const gridArea = style$1({ prop: 'gridArea' }); compose(gap, columnGap, rowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea); function paletteTransform(value, userValue) { if (userValue === 'grey') { return userValue; } return value; } const color = style$1({ prop: 'color', themeKey: 'palette', transform: paletteTransform }); const bgcolor = style$1({ prop: 'bgcolor', cssProperty: 'backgroundColor', themeKey: 'palette', transform: paletteTransform }); const backgroundColor = style$1({ prop: 'backgroundColor', themeKey: 'palette', transform: paletteTransform }); compose(color, bgcolor, backgroundColor); function sizingTransform(value) { return value <= 1 && value !== 0 ? `${value * 100}%` : value; } const width = style$1({ prop: 'width', transform: sizingTransform }); const maxWidth = props => { if (props.maxWidth !== undefined && props.maxWidth !== null) { const styleFromPropValue = propValue => { var _props$theme, _props$theme$breakpoi, _props$theme$breakpoi2; const breakpoint = ((_props$theme = props.theme) == null ? void 0 : (_props$theme$breakpoi = _props$theme.breakpoints) == null ? void 0 : (_props$theme$breakpoi2 = _props$theme$breakpoi.values) == null ? void 0 : _props$theme$breakpoi2[propValue]) || values$1[propValue]; return { maxWidth: breakpoint || sizingTransform(propValue) }; }; return handleBreakpoints(props, props.maxWidth, styleFromPropValue); } return null; }; maxWidth.filterProps = ['maxWidth']; const minWidth = style$1({ prop: 'minWidth', transform: sizingTransform }); const height = style$1({ prop: 'height', transform: sizingTransform }); const maxHeight = style$1({ prop: 'maxHeight', transform: sizingTransform }); const minHeight = style$1({ prop: 'minHeight', transform: sizingTransform }); style$1({ prop: 'size', cssProperty: 'width', transform: sizingTransform }); style$1({ prop: 'size', cssProperty: 'height', transform: sizingTransform }); const boxSizing = style$1({ prop: 'boxSizing' }); compose(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing); const defaultSxConfig = { // borders border: { themeKey: 'borders', transform: borderTransform }, borderTop: { themeKey: 'borders', transform: borderTransform }, borderRight: { themeKey: 'borders', transform: borderTransform }, borderBottom: { themeKey: 'borders', transform: borderTransform }, borderLeft: { themeKey: 'borders', transform: borderTransform }, borderColor: { themeKey: 'palette' }, borderTopColor: { themeKey: 'palette' }, borderRightColor: { themeKey: 'palette' }, borderBottomColor: { themeKey: 'palette' }, borderLeftColor: { themeKey: 'palette' }, borderRadius: { themeKey: 'shape.borderRadius', style: borderRadius }, // palette color: { themeKey: 'palette', transform: paletteTransform }, bgcolor: { themeKey: 'palette', cssProperty: 'backgroundColor', transform: paletteTransform }, backgroundColor: { themeKey: 'palette', transform: paletteTransform }, // spacing p: { style: padding }, pt: { style: padding }, pr: { style: padding }, pb: { style: padding }, pl: { style: padding }, px: { style: padding }, py: { style: padding }, padding: { style: padding }, paddingTop: { style: padding }, paddingRight: { style: padding }, paddingBottom: { style: padding }, paddingLeft: { style: padding }, paddingX: { style: padding }, paddingY: { style: padding }, paddingInline: { style: padding }, paddingInlineStart: { style: padding }, paddingInlineEnd: { style: padding }, paddingBlock: { style: padding }, paddingBlockStart: { style: padding }, paddingBlockEnd: { style: padding }, m: { style: margin }, mt: { style: margin }, mr: { style: margin }, mb: { style: margin }, ml: { style: margin }, mx: { style: margin }, my: { style: margin }, margin: { style: margin }, marginTop: { style: margin }, marginRight: { style: margin }, marginBottom: { style: margin }, marginLeft: { style: margin }, marginX: { style: margin }, marginY: { style: margin }, marginInline: { style: margin }, marginInlineStart: { style: margin }, marginInlineEnd: { style: margin }, marginBlock: { style: margin }, marginBlockStart: { style: margin }, marginBlockEnd: { style: margin }, // display displayPrint: { cssProperty: false, transform: value => ({ '@media print': { display: value } }) }, display: {}, overflow: {}, textOverflow: {}, visibility: {}, whiteSpace: {}, // flexbox flexBasis: {}, flexDirection: {}, flexWrap: {}, justifyContent: {}, alignItems: {}, alignContent: {}, order: {}, flex: {}, flexGrow: {}, flexShrink: {}, alignSelf: {}, justifyItems: {}, justifySelf: {}, // grid gap: { style: gap }, rowGap: { style: rowGap }, columnGap: { style: columnGap }, gridColumn: {}, gridRow: {}, gridAutoFlow: {}, gridAutoColumns: {}, gridAutoRows: {}, gridTemplateColumns: {}, gridTemplateRows: {}, gridTemplateAreas: {}, gridArea: {}, // positions position: {}, zIndex: { themeKey: 'zIndex' }, top: {}, right: {}, bottom: {}, left: {}, // shadows boxShadow: { themeKey: 'shadows' }, // sizing width: { transform: sizingTransform }, maxWidth: { style: maxWidth }, minWidth: { transform: sizingTransform }, height: { transform: sizingTransform }, maxHeight: { transform: sizingTransform }, minHeight: { transform: sizingTransform }, boxSizing: {}, // typography fontFamily: { themeKey: 'typography' }, fontSize: { themeKey: 'typography' }, fontStyle: { themeKey: 'typography' }, fontWeight: { themeKey: 'typography' }, letterSpacing: {}, textTransform: {}, lineHeight: {}, textAlign: {}, typography: { cssProperty: false, themeKey: 'typography' } }; const defaultSxConfig$1 = defaultSxConfig; function objectsHaveSameKeys(...objects) { const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []); const union = new Set(allKeys); return objects.every(object => union.size === Object.keys(object).length); } function callIfFn(maybeFn, arg) { return typeof maybeFn === 'function' ? maybeFn(arg) : maybeFn; } // eslint-disable-next-line @typescript-eslint/naming-convention function unstable_createStyleFunctionSx() { function getThemeValue(prop, val, theme, config) { const props = { [prop]: val, theme }; const options = config[prop]; if (!options) { return { [prop]: val }; } const { cssProperty = prop, themeKey, transform, style } = options; if (val == null) { return null; } const themeMapping = getPath(theme, themeKey) || {}; if (style) { return style(props); } const styleFromPropValue = propValueFinal => { let value = getStyleValue$1(themeMapping, transform, propValueFinal); if (propValueFinal === value && typeof propValueFinal === 'string') { // Haven't found value value = getStyleValue$1(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal); } if (cssProperty === false) { return value; } return { [cssProperty]: value }; }; return handleBreakpoints(props, val, styleFromPropValue); } function styleFunctionSx(props) { var _theme$unstable_sxCon; const { sx, theme = {} } = props || {}; if (!sx) { return null; // Emotion & styled-components will neglect null } const config = (_theme$unstable_sxCon = theme.unstable_sxConfig) != null ? _theme$unstable_sxCon : defaultSxConfig$1; /* * Receive `sxInput` as object or callback * and then recursively check keys & values to create media query object styles. * (the result will be used in `styled`) */ function traverse(sxInput) { let sxObject = sxInput; if (typeof sxInput === 'function') { sxObject = sxInput(theme); } else if (typeof sxInput !== 'object') { // value return sxInput; } if (!sxObject) { return null; } const emptyBreakpoints = createEmptyBreakpointObject(theme.breakpoints); const breakpointsKeys = Object.keys(emptyBreakpoints); let css = emptyBreakpoints; Object.keys(sxObject).forEach(styleKey => { const value = callIfFn(sxObject[styleKey], theme); if (value !== null && value !== undefined) { if (typeof value === 'object') { if (config[styleKey]) { css = merge(css, getThemeValue(styleKey, value, theme, config)); } else { const breakpointsValues = handleBreakpoints({ theme }, value, x => ({ [styleKey]: x })); if (objectsHaveSameKeys(breakpointsValues, value)) { css[styleKey] = styleFunctionSx({ sx: value, theme }); } else { css = merge(css, breakpointsValues); } } } else { css = merge(css, getThemeValue(styleKey, value, theme, config)); } } }); return removeUnusedBreakpoints(breakpointsKeys, css); } return Array.isArray(sx) ? sx.map(traverse) : traverse(sx); } return styleFunctionSx; } const styleFunctionSx = unstable_createStyleFunctionSx(); styleFunctionSx.filterProps = ['sx']; const styleFunctionSx$1 = styleFunctionSx; const _excluded$S = ["sx"]; const splitProps = props => { var _props$theme$unstable, _props$theme; const result = { systemProps: {}, otherProps: {} }; const config = (_props$theme$unstable = props == null ? void 0 : (_props$theme = props.theme) == null ? void 0 : _props$theme.unstable_sxConfig) != null ? _props$theme$unstable : defaultSxConfig$1; Object.keys(props).forEach(prop => { if (config[prop]) { result.systemProps[prop] = props[prop]; } else { result.otherProps[prop] = props[prop]; } }); return result; }; function extendSxProp(props) { const { sx: inSx } = props, other = _objectWithoutPropertiesLoose$2(props, _excluded$S); const { systemProps, otherProps } = splitProps(other); let finalSx; if (Array.isArray(inSx)) { finalSx = [systemProps, ...inSx]; } else if (typeof inSx === 'function') { finalSx = (...args) => { const result = inSx(...args); if (!isPlainObject(result)) { return systemProps; } return _extends({}, systemProps, result); }; } else { finalSx = _extends({}, systemProps, inSx); } return _extends({}, otherProps, { sx: finalSx }); } function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t { const breakpointsAsArray = Object.keys(values).map(key => ({ key, val: values[key] })) || []; // Sort in ascending order breakpointsAsArray.sort((breakpoint1, breakpoint2) => breakpoint1.val - breakpoint2.val); return breakpointsAsArray.reduce((acc, obj) => { return _extends({}, acc, { [obj.key]: obj.val }); }, {}); }; // Keep in mind that @media is inclusive by the CSS specification. function createBreakpoints(breakpoints) { const { // The breakpoint **start** at this value. // For instance with the first breakpoint xs: [xs, sm). values = { xs: 0, // phone sm: 600, // tablet md: 900, // small laptop lg: 1200, // desktop xl: 1536 // large screen }, unit = 'px', step = 5 } = breakpoints, other = _objectWithoutPropertiesLoose$2(breakpoints, _excluded$R); const sortedValues = sortBreakpointsValues(values); const keys = Object.keys(sortedValues); function up(key) { const value = typeof values[key] === 'number' ? values[key] : key; return `@media (min-width:${value}${unit})`; } function down(key) { const value = typeof values[key] === 'number' ? values[key] : key; return `@media (max-width:${value - step / 100}${unit})`; } function between(start, end) { const endIndex = keys.indexOf(end); return `@media (min-width:${typeof values[start] === 'number' ? values[start] : start}${unit}) and ` + `(max-width:${(endIndex !== -1 && typeof values[keys[endIndex]] === 'number' ? values[keys[endIndex]] : end) - step / 100}${unit})`; } function only(key) { if (keys.indexOf(key) + 1 < keys.length) { return between(key, keys[keys.indexOf(key) + 1]); } return up(key); } function not(key) { // handle first and last key separately, for better readability const keyIndex = keys.indexOf(key); if (keyIndex === 0) { return up(keys[1]); } if (keyIndex === keys.length - 1) { return down(keys[keyIndex]); } return between(key, keys[keys.indexOf(key) + 1]).replace('@media', '@media not all and'); } return _extends({ keys, values: sortedValues, up, down, between, only, not, unit }, other); } const shape = { borderRadius: 4 }; const shape$1 = shape; /* tslint:enable:unified-signatures */ function createSpacing(spacingInput = 8) { // Already transformed. if (spacingInput.mui) { return spacingInput; } // Material Design layouts are visually balanced. Most measurements align to an 8dp grid, which aligns both spacing and the overall layout. // Smaller components, such as icons, can align to a 4dp grid. // https://m2.material.io/design/layout/understanding-layout.html const transform = createUnarySpacing({ spacing: spacingInput }); const spacing = (...argsInput) => { const args = argsInput.length === 0 ? [1] : argsInput; return args.map(argument => { const output = transform(argument); return typeof output === 'number' ? `${output}px` : output; }).join(' '); }; spacing.mui = true; return spacing; } const _excluded$Q = ["breakpoints", "palette", "spacing", "shape"]; function createTheme$1(options = {}, ...args) { const { breakpoints: breakpointsInput = {}, palette: paletteInput = {}, spacing: spacingInput, shape: shapeInput = {} } = options, other = _objectWithoutPropertiesLoose$2(options, _excluded$Q); const breakpoints = createBreakpoints(breakpointsInput); const spacing = createSpacing(spacingInput); let muiTheme = deepmerge({ breakpoints, direction: 'ltr', components: {}, // Inject component definitions. palette: _extends({ mode: 'light' }, paletteInput), spacing, shape: _extends({}, shape$1, shapeInput) }, other); muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme); muiTheme.unstable_sxConfig = _extends({}, defaultSxConfig$1, other == null ? void 0 : other.unstable_sxConfig); muiTheme.unstable_sx = function sx(props) { return styleFunctionSx$1({ sx: props, theme: this }); }; return muiTheme; } const ThemeContext = /*#__PURE__*/reactExports.createContext(null); const ThemeContext$1 = ThemeContext; function useTheme$3() { const theme = reactExports.useContext(ThemeContext$1); return theme; } const hasSymbol = typeof Symbol === 'function' && Symbol.for; const nested = hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__'; function mergeOuterLocalTheme(outerTheme, localTheme) { if (typeof localTheme === 'function') { const mergedTheme = localTheme(outerTheme); return mergedTheme; } return _extends({}, outerTheme, localTheme); } /** * This component takes a `theme` prop. * It makes the `theme` available down the React tree thanks to React context. * This component should preferably be used at **the root of your component tree**. */ function ThemeProvider$1(props) { const { children, theme: localTheme } = props; const outerTheme = useTheme$3(); const theme = reactExports.useMemo(() => { const output = outerTheme === null ? localTheme : mergeOuterLocalTheme(outerTheme, localTheme); if (output != null) { output[nested] = outerTheme !== null; } return output; }, [localTheme, outerTheme]); return /*#__PURE__*/jsx(ThemeContext$1.Provider, { value: theme, children: children }); } function isObjectEmpty(obj) { return Object.keys(obj).length === 0; } function useTheme$2(defaultTheme = null) { const contextTheme = useTheme$3(); return !contextTheme || isObjectEmpty(contextTheme) ? defaultTheme : contextTheme; } const systemDefaultTheme$1 = createTheme$1(); function useTheme$1(defaultTheme = systemDefaultTheme$1) { return useTheme$2(defaultTheme); } const _excluded$P = ["className", "component"]; function createBox(options = {}) { const { defaultTheme, defaultClassName = 'MuiBox-root', generateClassName } = options; const BoxRoot = styled$2('div', { shouldForwardProp: prop => prop !== 'theme' && prop !== 'sx' && prop !== 'as' })(styleFunctionSx$1); const Box = /*#__PURE__*/reactExports.forwardRef(function Box(inProps, ref) { const theme = useTheme$1(defaultTheme); const _extendSxProp = extendSxProp(inProps), { className, component = 'div' } = _extendSxProp, other = _objectWithoutPropertiesLoose$2(_extendSxProp, _excluded$P); return /*#__PURE__*/jsx(BoxRoot, _extends({ as: component, ref: ref, className: clsx(className, generateClassName ? generateClassName(defaultClassName) : defaultClassName), theme: theme }, other)); }); return Box; } const _excluded$O = ["variant"]; function isEmpty$3(string) { return string.length === 0; } /** * Generates string classKey based on the properties provided. It starts with the * variant if defined, and then it appends all other properties in alphabetical order. * @param {object} props - the properties for which the classKey should be created. */ function propsToClassKey(props) { const { variant } = props, other = _objectWithoutPropertiesLoose$2(props, _excluded$O); let classKey = variant || ''; Object.keys(other).sort().forEach(key => { if (key === 'color') { classKey += isEmpty$3(classKey) ? props[key] : capitalize(props[key]); } else { classKey += `${isEmpty$3(classKey) ? key : capitalize(key)}${capitalize(props[key].toString())}`; } }); return classKey; } const _excluded$N = ["name", "slot", "skipVariantsResolver", "skipSx", "overridesResolver"], _excluded2$4 = ["theme"], _excluded3$1 = ["theme"]; function isEmpty$2(obj) { return Object.keys(obj).length === 0; } // https://github.com/emotion-js/emotion/blob/26ded6109fcd8ca9875cc2ce4564fee678a3f3c5/packages/styled/src/utils.js#L40 function isStringTag(tag) { return typeof tag === 'string' && // 96 is one less than the char code // for "a" so this is checking that // it's a lowercase character tag.charCodeAt(0) > 96; } const getStyleOverrides = (name, theme) => { if (theme.components && theme.components[name] && theme.components[name].styleOverrides) { return theme.components[name].styleOverrides; } return null; }; const getVariantStyles = (name, theme) => { let variants = []; if (theme && theme.components && theme.components[name] && theme.components[name].variants) { variants = theme.components[name].variants; } const variantsStyles = {}; variants.forEach(definition => { const key = propsToClassKey(definition.props); variantsStyles[key] = definition.style; }); return variantsStyles; }; const variantsResolver = (props, styles, theme, name) => { var _theme$components, _theme$components$nam; const { ownerState = {} } = props; const variantsStyles = []; const themeVariants = theme == null ? void 0 : (_theme$components = theme.components) == null ? void 0 : (_theme$components$nam = _theme$components[name]) == null ? void 0 : _theme$components$nam.variants; if (themeVariants) { themeVariants.forEach(themeVariant => { let isMatch = true; Object.keys(themeVariant.props).forEach(key => { if (ownerState[key] !== themeVariant.props[key] && props[key] !== themeVariant.props[key]) { isMatch = false; } }); if (isMatch) { variantsStyles.push(styles[propsToClassKey(themeVariant.props)]); } }); } return variantsStyles; }; // Update /system/styled/#api in case if this changes function shouldForwardProp(prop) { return prop !== 'ownerState' && prop !== 'theme' && prop !== 'sx' && prop !== 'as'; } const systemDefaultTheme = createTheme$1(); function createStyled(input = {}) { const { defaultTheme = systemDefaultTheme, rootShouldForwardProp = shouldForwardProp, slotShouldForwardProp = shouldForwardProp } = input; const systemSx = props => { const theme = isEmpty$2(props.theme) ? defaultTheme : props.theme; return styleFunctionSx$1(_extends({}, props, { theme })); }; systemSx.__mui_systemSx = true; return (tag, inputOptions = {}) => { // Filter out the `sx` style function from the previous styled component to prevent unnecessary styles generated by the composite components. internal_processStyles(tag, styles => styles.filter(style => !(style != null && style.__mui_systemSx))); const { name: componentName, slot: componentSlot, skipVariantsResolver: inputSkipVariantsResolver, skipSx: inputSkipSx, overridesResolver } = inputOptions, options = _objectWithoutPropertiesLoose$2(inputOptions, _excluded$N); // if skipVariantsResolver option is defined, take the value, otherwise, true for root and false for other slots. const skipVariantsResolver = inputSkipVariantsResolver !== undefined ? inputSkipVariantsResolver : componentSlot && componentSlot !== 'Root' || false; const skipSx = inputSkipSx || false; let label; let shouldForwardPropOption = shouldForwardProp; if (componentSlot === 'Root') { shouldForwardPropOption = rootShouldForwardProp; } else if (componentSlot) { // any other slot specified shouldForwardPropOption = slotShouldForwardProp; } else if (isStringTag(tag)) { // for string (html) tag, preserve the behavior in emotion & styled-components. shouldForwardPropOption = undefined; } const defaultStyledResolver = styled$2(tag, _extends({ shouldForwardProp: shouldForwardPropOption, label }, options)); const muiStyledResolver = (styleArg, ...expressions) => { const expressionsWithDefaultTheme = expressions ? expressions.map(stylesArg => { // On the server Emotion doesn't use React.forwardRef for creating components, so the created // component stays as a function. This condition makes sure that we do not interpolate functions // which are basically components used as a selectors. return typeof stylesArg === 'function' && stylesArg.__emotion_real !== stylesArg ? _ref => { let { theme: themeInput } = _ref, other = _objectWithoutPropertiesLoose$2(_ref, _excluded2$4); return stylesArg(_extends({ theme: isEmpty$2(themeInput) ? defaultTheme : themeInput }, other)); } : stylesArg; }) : []; let transformedStyleArg = styleArg; if (componentName && overridesResolver) { expressionsWithDefaultTheme.push(props => { const theme = isEmpty$2(props.theme) ? defaultTheme : props.theme; const styleOverrides = getStyleOverrides(componentName, theme); if (styleOverrides) { const resolvedStyleOverrides = {}; Object.entries(styleOverrides).forEach(([slotKey, slotStyle]) => { resolvedStyleOverrides[slotKey] = typeof slotStyle === 'function' ? slotStyle(_extends({}, props, { theme })) : slotStyle; }); return overridesResolver(props, resolvedStyleOverrides); } return null; }); } if (componentName && !skipVariantsResolver) { expressionsWithDefaultTheme.push(props => { const theme = isEmpty$2(props.theme) ? defaultTheme : props.theme; return variantsResolver(props, getVariantStyles(componentName, theme), theme, componentName); }); } if (!skipSx) { expressionsWithDefaultTheme.push(systemSx); } const numOfCustomFnsApplied = expressionsWithDefaultTheme.length - expressions.length; if (Array.isArray(styleArg) && numOfCustomFnsApplied > 0) { const placeholders = new Array(numOfCustomFnsApplied).fill(''); // If the type is array, than we need to add placeholders in the template for the overrides, variants and the sx styles. transformedStyleArg = [...styleArg, ...placeholders]; transformedStyleArg.raw = [...styleArg.raw, ...placeholders]; } else if (typeof styleArg === 'function' && // On the server Emotion doesn't use React.forwardRef for creating components, so the created // component stays as a function. This condition makes sure that we do not interpolate functions // which are basically components used as a selectors. styleArg.__emotion_real !== styleArg) { // If the type is function, we need to define the default theme. transformedStyleArg = _ref2 => { let { theme: themeInput } = _ref2, other = _objectWithoutPropertiesLoose$2(_ref2, _excluded3$1); return styleArg(_extends({ theme: isEmpty$2(themeInput) ? defaultTheme : themeInput }, other)); }; } const Component = defaultStyledResolver(transformedStyleArg, ...expressionsWithDefaultTheme); return Component; }; if (defaultStyledResolver.withConfig) { muiStyledResolver.withConfig = defaultStyledResolver.withConfig; } return muiStyledResolver; }; } function getThemeProps(params) { const { theme, name, props } = params; if (!theme || !theme.components || !theme.components[name] || !theme.components[name].defaultProps) { return props; } return resolveProps(theme.components[name].defaultProps, props); } function useThemeProps$1({ props, name, defaultTheme }) { const theme = useTheme$1(defaultTheme); const mergedProps = getThemeProps({ theme, name, props }); return mergedProps; } /** * Returns a number whose value is limited to the given range. * @param {number} value The value to be clamped * @param {number} min The lower boundary of the output range * @param {number} max The upper boundary of the output range * @returns {number} A number in the range [min, max] */ function clamp$2(value, min = 0, max = 1) { return Math.min(Math.max(min, value), max); } /** * Converts a color from CSS hex format to CSS rgb format. * @param {string} color - Hex color, i.e. #nnn or #nnnnnn * @returns {string} A CSS rgb color string */ function hexToRgb(color) { color = color.slice(1); const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g'); let colors = color.match(re); if (colors && colors[0].length === 1) { colors = colors.map(n => n + n); } return colors ? `rgb${colors.length === 4 ? 'a' : ''}(${colors.map((n, index) => { return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000; }).join(', ')})` : ''; } /** * Returns an object with the type and values of a color. * * Note: Does not support rgb % values. * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color() * @returns {object} - A MUI color object: {type: string, values: number[]} */ function decomposeColor(color) { // Idempotent if (color.type) { return color; } if (color.charAt(0) === '#') { return decomposeColor(hexToRgb(color)); } const marker = color.indexOf('('); const type = color.substring(0, marker); if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) { throw new Error(formatMuiErrorMessage(9, color)); } let values = color.substring(marker + 1, color.length - 1); let colorSpace; if (type === 'color') { values = values.split(' '); colorSpace = values.shift(); if (values.length === 4 && values[3].charAt(0) === '/') { values[3] = values[3].slice(1); } if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) { throw new Error(formatMuiErrorMessage(10, colorSpace)); } } else { values = values.split(','); } values = values.map(value => parseFloat(value)); return { type, values, colorSpace }; } /** * Converts a color object with type and values to a string. * @param {object} color - Decomposed color * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla', 'color' * @param {array} color.values - [n,n,n] or [n,n,n,n] * @returns {string} A CSS color string */ function recomposeColor(color) { const { type, colorSpace } = color; let { values } = color; if (type.indexOf('rgb') !== -1) { // Only convert the first 3 values to int (i.e. not alpha) values = values.map((n, i) => i < 3 ? parseInt(n, 10) : n); } else if (type.indexOf('hsl') !== -1) { values[1] = `${values[1]}%`; values[2] = `${values[2]}%`; } if (type.indexOf('color') !== -1) { values = `${colorSpace} ${values.join(' ')}`; } else { values = `${values.join(', ')}`; } return `${type}(${values})`; } /** * Converts a color from hsl format to rgb format. * @param {string} color - HSL color values * @returns {string} rgb color values */ function hslToRgb(color) { color = decomposeColor(color); const { values } = color; const h = values[0]; const s = values[1] / 100; const l = values[2] / 100; const a = s * Math.min(l, 1 - l); const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); let type = 'rgb'; const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)]; if (color.type === 'hsla') { type += 'a'; rgb.push(values[3]); } return recomposeColor({ type, values: rgb }); } /** * The relative brightness of any point in a color space, * normalized to 0 for darkest black and 1 for lightest white. * * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color() * @returns {number} The relative brightness of the color in the range 0 - 1 */ function getLuminance(color) { color = decomposeColor(color); let rgb = color.type === 'hsl' || color.type === 'hsla' ? decomposeColor(hslToRgb(color)).values : color.values; rgb = rgb.map(val => { if (color.type !== 'color') { val /= 255; // normalized } return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4; }); // Truncate at 3 digits return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3)); } /** * Calculates the contrast ratio between two colors. * * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @returns {number} A contrast ratio value in the range 0 - 21. */ function getContrastRatio(foreground, background) { const lumA = getLuminance(foreground); const lumB = getLuminance(background); return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05); } /** * Sets the absolute transparency of a color. * Any existing alpha values are overwritten. * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color() * @param {number} value - value to set the alpha channel to in the range 0 - 1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function alpha(color, value) { color = decomposeColor(color); value = clamp$2(value); if (color.type === 'rgb' || color.type === 'hsl') { color.type += 'a'; } if (color.type === 'color') { color.values[3] = `/${value}`; } else { color.values[3] = value; } return recomposeColor(color); } /** * Darkens a color. * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color() * @param {number} coefficient - multiplier in the range 0 - 1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function darken(color, coefficient) { color = decomposeColor(color); coefficient = clamp$2(coefficient); if (color.type.indexOf('hsl') !== -1) { color.values[2] *= 1 - coefficient; } else if (color.type.indexOf('rgb') !== -1 || color.type.indexOf('color') !== -1) { for (let i = 0; i < 3; i += 1) { color.values[i] *= 1 - coefficient; } } return recomposeColor(color); } /** * Lightens a color. * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color() * @param {number} coefficient - multiplier in the range 0 - 1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function lighten(color, coefficient) { color = decomposeColor(color); coefficient = clamp$2(coefficient); if (color.type.indexOf('hsl') !== -1) { color.values[2] += (100 - color.values[2]) * coefficient; } else if (color.type.indexOf('rgb') !== -1) { for (let i = 0; i < 3; i += 1) { color.values[i] += (255 - color.values[i]) * coefficient; } } else if (color.type.indexOf('color') !== -1) { for (let i = 0; i < 3; i += 1) { color.values[i] += (1 - color.values[i]) * coefficient; } } return recomposeColor(color); } const EMPTY_THEME = {}; function InnerThemeProvider(props) { const theme = useTheme$1(); return /*#__PURE__*/jsx(ThemeContext$2.Provider, { value: typeof theme === 'object' ? theme : EMPTY_THEME, children: props.children }); } /** * This component makes the `theme` available down the React tree. * It should preferably be used at **the root of your component tree**. */ function ThemeProvider(props) { const { children, theme: localTheme } = props; return /*#__PURE__*/jsx(ThemeProvider$1, { theme: localTheme, children: /*#__PURE__*/jsx(InnerThemeProvider, { children: children }) }); } function createMixins(breakpoints, mixins) { return _extends({ toolbar: { minHeight: 56, [breakpoints.up('xs')]: { '@media (orientation: landscape)': { minHeight: 48 } }, [breakpoints.up('sm')]: { minHeight: 64 } } }, mixins); } const _excluded$M = ["mode", "contrastThreshold", "tonalOffset"]; const light = { // The colors used to style the text. text: { // The most important text. primary: 'rgba(0, 0, 0, 0.87)', // Secondary text. secondary: 'rgba(0, 0, 0, 0.6)', // Disabled text have even lower visual prominence. disabled: 'rgba(0, 0, 0, 0.38)' }, // The color used to divide different elements. divider: 'rgba(0, 0, 0, 0.12)', // The background colors used to style the surfaces. // Consistency between these values is important. background: { paper: common$1.white, default: common$1.white }, // The colors used to style the action elements. action: { // The color of an active action like an icon button. active: 'rgba(0, 0, 0, 0.54)', // The color of an hovered action. hover: 'rgba(0, 0, 0, 0.04)', hoverOpacity: 0.04, // The color of a selected action. selected: 'rgba(0, 0, 0, 0.08)', selectedOpacity: 0.08, // The color of a disabled action. disabled: 'rgba(0, 0, 0, 0.26)', // The background color of a disabled action. disabledBackground: 'rgba(0, 0, 0, 0.12)', disabledOpacity: 0.38, focus: 'rgba(0, 0, 0, 0.12)', focusOpacity: 0.12, activatedOpacity: 0.12 } }; const dark = { text: { primary: common$1.white, secondary: 'rgba(255, 255, 255, 0.7)', disabled: 'rgba(255, 255, 255, 0.5)', icon: 'rgba(255, 255, 255, 0.5)' }, divider: 'rgba(255, 255, 255, 0.12)', background: { paper: '#121212', default: '#121212' }, action: { active: common$1.white, hover: 'rgba(255, 255, 255, 0.08)', hoverOpacity: 0.08, selected: 'rgba(255, 255, 255, 0.16)', selectedOpacity: 0.16, disabled: 'rgba(255, 255, 255, 0.3)', disabledBackground: 'rgba(255, 255, 255, 0.12)', disabledOpacity: 0.38, focus: 'rgba(255, 255, 255, 0.12)', focusOpacity: 0.12, activatedOpacity: 0.24 } }; function addLightOrDark(intent, direction, shade, tonalOffset) { const tonalOffsetLight = tonalOffset.light || tonalOffset; const tonalOffsetDark = tonalOffset.dark || tonalOffset * 1.5; if (!intent[direction]) { if (intent.hasOwnProperty(shade)) { intent[direction] = intent[shade]; } else if (direction === 'light') { intent.light = lighten(intent.main, tonalOffsetLight); } else if (direction === 'dark') { intent.dark = darken(intent.main, tonalOffsetDark); } } } function getDefaultPrimary(mode = 'light') { if (mode === 'dark') { return { main: blue$1[200], light: blue$1[50], dark: blue$1[400] }; } return { main: blue$1[700], light: blue$1[400], dark: blue$1[800] }; } function getDefaultSecondary(mode = 'light') { if (mode === 'dark') { return { main: purple$1[200], light: purple$1[50], dark: purple$1[400] }; } return { main: purple$1[500], light: purple$1[300], dark: purple$1[700] }; } function getDefaultError(mode = 'light') { if (mode === 'dark') { return { main: red$1[500], light: red$1[300], dark: red$1[700] }; } return { main: red$1[700], light: red$1[400], dark: red$1[800] }; } function getDefaultInfo(mode = 'light') { if (mode === 'dark') { return { main: lightBlue$1[400], light: lightBlue$1[300], dark: lightBlue$1[700] }; } return { main: lightBlue$1[700], light: lightBlue$1[500], dark: lightBlue$1[900] }; } function getDefaultSuccess(mode = 'light') { if (mode === 'dark') { return { main: green$1[400], light: green$1[300], dark: green$1[700] }; } return { main: green$1[800], light: green$1[500], dark: green$1[900] }; } function getDefaultWarning(mode = 'light') { if (mode === 'dark') { return { main: orange$1[400], light: orange$1[300], dark: orange$1[700] }; } return { main: '#ed6c02', // closest to orange[800] that pass 3:1. light: orange$1[500], dark: orange$1[900] }; } function createPalette(palette) { const { mode = 'light', contrastThreshold = 3, tonalOffset = 0.2 } = palette, other = _objectWithoutPropertiesLoose$2(palette, _excluded$M); const primary = palette.primary || getDefaultPrimary(mode); const secondary = palette.secondary || getDefaultSecondary(mode); const error = palette.error || getDefaultError(mode); const info = palette.info || getDefaultInfo(mode); const success = palette.success || getDefaultSuccess(mode); const warning = palette.warning || getDefaultWarning(mode); // Use the same logic as // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59 // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54 function getContrastText(background) { const contrastText = getContrastRatio(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary; return contrastText; } const augmentColor = ({ color, name, mainShade = 500, lightShade = 300, darkShade = 700 }) => { color = _extends({}, color); if (!color.main && color[mainShade]) { color.main = color[mainShade]; } if (!color.hasOwnProperty('main')) { throw new Error(formatMuiErrorMessage(11, name ? ` (${name})` : '', mainShade)); } if (typeof color.main !== 'string') { throw new Error(formatMuiErrorMessage(12, name ? ` (${name})` : '', JSON.stringify(color.main))); } addLightOrDark(color, 'light', lightShade, tonalOffset); addLightOrDark(color, 'dark', darkShade, tonalOffset); if (!color.contrastText) { color.contrastText = getContrastText(color.main); } return color; }; const modes = { dark, light }; const paletteOutput = deepmerge(_extends({ // A collection of common colors. common: _extends({}, common$1), // prevent mutable object. // The palette mode, can be light or dark. mode, // The colors used to represent primary interface elements for a user. primary: augmentColor({ color: primary, name: 'primary' }), // The colors used to represent secondary interface elements for a user. secondary: augmentColor({ color: secondary, name: 'secondary', mainShade: 'A400', lightShade: 'A200', darkShade: 'A700' }), // The colors used to represent interface elements that the user should be made aware of. error: augmentColor({ color: error, name: 'error' }), // The colors used to represent potentially dangerous actions or important messages. warning: augmentColor({ color: warning, name: 'warning' }), // The colors used to present information to the user that is neutral and not necessarily important. info: augmentColor({ color: info, name: 'info' }), // The colors used to indicate the successful completion of an action that user triggered. success: augmentColor({ color: success, name: 'success' }), // The grey colors. grey: grey$1, // Used by `getContrastText()` to maximize the contrast between // the background and the text. contrastThreshold, // Takes a background color and returns the text color that maximizes the contrast. getContrastText, // Generate a rich color object. augmentColor, // Used by the functions below to shift a color's luminance by approximately // two indexes within its tonal palette. // E.g., shift from Red 500 to Red 300 or Red 700. tonalOffset }, modes[mode]), other); return paletteOutput; } const _excluded$L = ["fontFamily", "fontSize", "fontWeightLight", "fontWeightRegular", "fontWeightMedium", "fontWeightBold", "htmlFontSize", "allVariants", "pxToRem"]; function round$2(value) { return Math.round(value * 1e5) / 1e5; } const caseAllCaps = { textTransform: 'uppercase' }; const defaultFontFamily = '"Roboto", "Helvetica", "Arial", sans-serif'; /** * @see @link{https://m2.material.io/design/typography/the-type-system.html} * @see @link{https://m2.material.io/design/typography/understanding-typography.html} */ function createTypography(palette, typography) { const _ref = typeof typography === 'function' ? typography(palette) : typography, { fontFamily = defaultFontFamily, // The default font size of the Material Specification. fontSize = 14, // px fontWeightLight = 300, fontWeightRegular = 400, fontWeightMedium = 500, fontWeightBold = 700, // Tell MUI what's the font-size on the html element. // 16px is the default font-size used by browsers. htmlFontSize = 16, // Apply the CSS properties to all the variants. allVariants, pxToRem: pxToRem2 } = _ref, other = _objectWithoutPropertiesLoose$2(_ref, _excluded$L); const coef = fontSize / 14; const pxToRem = pxToRem2 || (size => `${size / htmlFontSize * coef}rem`); const buildVariant = (fontWeight, size, lineHeight, letterSpacing, casing) => _extends({ fontFamily, fontWeight, fontSize: pxToRem(size), // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/ lineHeight }, fontFamily === defaultFontFamily ? { letterSpacing: `${round$2(letterSpacing / size)}em` } : {}, casing, allVariants); const variants = { h1: buildVariant(fontWeightLight, 96, 1.167, -1.5), h2: buildVariant(fontWeightLight, 60, 1.2, -0.5), h3: buildVariant(fontWeightRegular, 48, 1.167, 0), h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25), h5: buildVariant(fontWeightRegular, 24, 1.334, 0), h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15), subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15), subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1), body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15), body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15), button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps), caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4), overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps) }; return deepmerge(_extends({ htmlFontSize, pxToRem, fontFamily, fontSize, fontWeightLight, fontWeightRegular, fontWeightMedium, fontWeightBold }, variants), other, { clone: false // No need to clone deep }); } const shadowKeyUmbraOpacity = 0.2; const shadowKeyPenumbraOpacity = 0.14; const shadowAmbientShadowOpacity = 0.12; function createShadow(...px) { return [`${px[0]}px ${px[1]}px ${px[2]}px ${px[3]}px rgba(0,0,0,${shadowKeyUmbraOpacity})`, `${px[4]}px ${px[5]}px ${px[6]}px ${px[7]}px rgba(0,0,0,${shadowKeyPenumbraOpacity})`, `${px[8]}px ${px[9]}px ${px[10]}px ${px[11]}px rgba(0,0,0,${shadowAmbientShadowOpacity})`].join(','); } // Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss const shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)]; const shadows$1 = shadows; const _excluded$K = ["duration", "easing", "delay"]; // Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves // to learn the context in which each easing should be used. const easing = { // This is the most common easing curve. easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)', // Objects enter the screen at full velocity from off-screen and // slowly decelerate to a resting point. easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)', // Objects leave the screen at full velocity. They do not decelerate when off-screen. easeIn: 'cubic-bezier(0.4, 0, 1, 1)', // The sharp curve is used by objects that may return to the screen at any time. sharp: 'cubic-bezier(0.4, 0, 0.6, 1)' }; // Follow https://m2.material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations // to learn when use what timing const duration = { shortest: 150, shorter: 200, short: 250, // most basic recommended timing standard: 300, // this is to be used in complex animations complex: 375, // recommended when something is entering screen enteringScreen: 225, // recommended when something is leaving screen leavingScreen: 195 }; function formatMs(milliseconds) { return `${Math.round(milliseconds)}ms`; } function getAutoHeightDuration(height) { if (!height) { return 0; } const constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10 return Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10); } function createTransitions(inputTransitions) { const mergedEasing = _extends({}, easing, inputTransitions.easing); const mergedDuration = _extends({}, duration, inputTransitions.duration); const create = (props = ['all'], options = {}) => { const { duration: durationOption = mergedDuration.standard, easing: easingOption = mergedEasing.easeInOut, delay = 0 } = options; _objectWithoutPropertiesLoose$2(options, _excluded$K); return (Array.isArray(props) ? props : [props]).map(animatedProp => `${animatedProp} ${typeof durationOption === 'string' ? durationOption : formatMs(durationOption)} ${easingOption} ${typeof delay === 'string' ? delay : formatMs(delay)}`).join(','); }; return _extends({ getAutoHeightDuration, create }, inputTransitions, { easing: mergedEasing, duration: mergedDuration }); } // We need to centralize the zIndex definitions as they work // like global values in the browser. const zIndex = { mobileStepper: 1000, fab: 1050, speedDial: 1050, appBar: 1100, drawer: 1200, modal: 1300, snackbar: 1400, tooltip: 1500 }; const zIndex$1 = zIndex; const _excluded$J = ["breakpoints", "mixins", "spacing", "palette", "transitions", "typography", "shape"]; function createTheme(options = {}, ...args) { const { mixins: mixinsInput = {}, palette: paletteInput = {}, transitions: transitionsInput = {}, typography: typographyInput = {} } = options, other = _objectWithoutPropertiesLoose$2(options, _excluded$J); if (options.vars) { throw new Error(formatMuiErrorMessage(18)); } const palette = createPalette(paletteInput); const systemTheme = createTheme$1(options); let muiTheme = deepmerge(systemTheme, { mixins: createMixins(systemTheme.breakpoints, mixinsInput), palette, // Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol. shadows: shadows$1.slice(), typography: createTypography(palette, typographyInput), transitions: createTransitions(transitionsInput), zIndex: _extends({}, zIndex$1) }); muiTheme = deepmerge(muiTheme, other); muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme); muiTheme.unstable_sxConfig = _extends({}, defaultSxConfig$1, other == null ? void 0 : other.unstable_sxConfig); muiTheme.unstable_sx = function sx(props) { return styleFunctionSx$1({ sx: props, theme: this }); }; return muiTheme; } const defaultTheme$1 = createTheme(); const defaultTheme$2 = defaultTheme$1; function useTheme() { const theme = useTheme$1(defaultTheme$2); return theme; } function useThemeProps({ props, name }) { return useThemeProps$1({ props, name, defaultTheme: defaultTheme$2 }); } const rootShouldForwardProp = prop => shouldForwardProp(prop) && prop !== 'classes'; const slotShouldForwardProp = shouldForwardProp; const styled = createStyled({ defaultTheme: defaultTheme$2, rootShouldForwardProp }); const styled$1 = styled; // Inspired by https://github.com/material-components/material-components-ios/blob/bca36107405594d5b7b16265a5b0ed698f85a5ee/components/Elevation/src/UIColor%2BMaterialElevation.m#L61 const getOverlayAlpha = elevation => { let alphaValue; if (elevation < 1) { alphaValue = 5.11916 * elevation ** 2; } else { alphaValue = 4.5 * Math.log(elevation + 1) + 2; } return (alphaValue / 100).toFixed(2); }; const getOverlayAlpha$1 = getOverlayAlpha; /** * Determines if a given element is a DOM element name (i.e. not a React component). */ function isHostComponent(element) { return typeof element === 'string'; } /** * Type of the ownerState based on the type of an element it applies to. * This resolves to the provided OwnerState for React components and `undefined` for host components. * Falls back to `OwnerState | undefined` when the exact type can't be determined in development time. */ /** * Appends the ownerState object to the props, merging with the existing one if necessary. * * @param elementType Type of the element that owns the `existingProps`. If the element is a DOM node or undefined, `ownerState` is not applied. * @param otherProps Props of the element. * @param ownerState */ function appendOwnerState(elementType, otherProps, ownerState) { if (elementType === undefined || isHostComponent(elementType)) { return otherProps; } return _extends({}, otherProps, { ownerState: _extends({}, otherProps.ownerState, ownerState) }); } /** * Extracts event handlers from a given object. * A prop is considered an event handler if it is a function and its name starts with `on`. * * @param object An object to extract event handlers from. * @param excludeKeys An array of keys to exclude from the returned object. */ function extractEventHandlers(object, excludeKeys = []) { if (object === undefined) { return {}; } const result = {}; Object.keys(object).filter(prop => prop.match(/^on[A-Z]/) && typeof object[prop] === 'function' && !excludeKeys.includes(prop)).forEach(prop => { result[prop] = object[prop]; }); return result; } /** * If `componentProps` is a function, calls it with the provided `ownerState`. * Otherwise, just returns `componentProps`. */ function resolveComponentProps(componentProps, ownerState) { if (typeof componentProps === 'function') { return componentProps(ownerState); } return componentProps; } /** * Removes event handlers from the given object. * A field is considered an event handler if it is a function with a name beginning with `on`. * * @param object Object to remove event handlers from. * @returns Object with event handlers removed. */ function omitEventHandlers(object) { if (object === undefined) { return {}; } const result = {}; Object.keys(object).filter(prop => !(prop.match(/^on[A-Z]/) && typeof object[prop] === 'function')).forEach(prop => { result[prop] = object[prop]; }); return result; } /** * Merges the slot component internal props (usually coming from a hook) * with the externally provided ones. * * The merge order is (the latter overrides the former): * 1. The internal props (specified as a getter function to work with get*Props hook result) * 2. Additional props (specified internally on an unstyled component) * 3. External props specified on the owner component. These should only be used on a root slot. * 4. External props specified in the `slotProps.*` prop. * 5. The `className` prop - combined from all the above. * @param parameters * @returns */ function mergeSlotProps(parameters) { const { getSlotProps, additionalProps, externalSlotProps, externalForwardedProps, className } = parameters; if (!getSlotProps) { // The simpler case - getSlotProps is not defined, so no internal event handlers are defined, // so we can simply merge all the props without having to worry about extracting event handlers. const joinedClasses = clsx(externalForwardedProps == null ? void 0 : externalForwardedProps.className, externalSlotProps == null ? void 0 : externalSlotProps.className, className, additionalProps == null ? void 0 : additionalProps.className); const mergedStyle = _extends({}, additionalProps == null ? void 0 : additionalProps.style, externalForwardedProps == null ? void 0 : externalForwardedProps.style, externalSlotProps == null ? void 0 : externalSlotProps.style); const props = _extends({}, additionalProps, externalForwardedProps, externalSlotProps); if (joinedClasses.length > 0) { props.className = joinedClasses; } if (Object.keys(mergedStyle).length > 0) { props.style = mergedStyle; } return { props, internalRef: undefined }; } // In this case, getSlotProps is responsible for calling the external event handlers. // We don't need to include them in the merged props because of this. const eventHandlers = extractEventHandlers(_extends({}, externalForwardedProps, externalSlotProps)); const componentsPropsWithoutEventHandlers = omitEventHandlers(externalSlotProps); const otherPropsWithoutEventHandlers = omitEventHandlers(externalForwardedProps); const internalSlotProps = getSlotProps(eventHandlers); // The order of classes is important here. // Emotion (that we use in libraries consuming MUI Base) depends on this order // to properly override style. It requires the most important classes to be last // (see https://github.com/mui/material-ui/pull/33205) for the related discussion. const joinedClasses = clsx(internalSlotProps == null ? void 0 : internalSlotProps.className, additionalProps == null ? void 0 : additionalProps.className, className, externalForwardedProps == null ? void 0 : externalForwardedProps.className, externalSlotProps == null ? void 0 : externalSlotProps.className); const mergedStyle = _extends({}, internalSlotProps == null ? void 0 : internalSlotProps.style, additionalProps == null ? void 0 : additionalProps.style, externalForwardedProps == null ? void 0 : externalForwardedProps.style, externalSlotProps == null ? void 0 : externalSlotProps.style); const props = _extends({}, internalSlotProps, additionalProps, otherPropsWithoutEventHandlers, componentsPropsWithoutEventHandlers); if (joinedClasses.length > 0) { props.className = joinedClasses; } if (Object.keys(mergedStyle).length > 0) { props.style = mergedStyle; } return { props, internalRef: internalSlotProps.ref }; } const _excluded$I = ["elementType", "externalSlotProps", "ownerState"]; /** * Builds the props to be passed into the slot of an unstyled component. * It merges the internal props of the component with the ones supplied by the user, allowing to customize the behavior. * If the slot component is not a host component, it also merges in the `ownerState`. * * @param parameters.getSlotProps - A function that returns the props to be passed to the slot component. */ function useSlotProps(parameters) { var _parameters$additiona; const { elementType, externalSlotProps, ownerState } = parameters, rest = _objectWithoutPropertiesLoose$2(parameters, _excluded$I); const resolvedComponentsProps = resolveComponentProps(externalSlotProps, ownerState); const { props: mergedProps, internalRef } = mergeSlotProps(_extends({}, rest, { externalSlotProps: resolvedComponentsProps })); const ref = useForkRef(internalRef, resolvedComponentsProps == null ? void 0 : resolvedComponentsProps.ref, (_parameters$additiona = parameters.additionalProps) == null ? void 0 : _parameters$additiona.ref); const props = appendOwnerState(elementType, _extends({}, mergedProps, { ref }), ownerState); return props; } /* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */ // Inspired by https://github.com/focus-trap/tabbable const candidatesSelector = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])'].join(','); function getTabIndex(node) { const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10); if (!Number.isNaN(tabindexAttr)) { return tabindexAttr; } // Browsers do not return `tabIndex` correctly for contentEditable nodes; // https://bugs.chromium.org/p/chromium/issues/detail?id=661108&q=contenteditable%20tabindex&can=2 // so if they don't have a tabindex attribute specifically set, assume it's 0. // in Chrome,
,