/*!
 * wq.js for wq.app 2.0.0

 * Mobile data collection & survey framework
 * (c) 2012-2023, S. Andrew Sheppard
 * https://wq.io/license
 */
import './maplibre-gl.js';

function _mergeNamespaces(n, m) {
  m.forEach(function (e) {
    e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
      if (k !== 'default' && !(k in n)) {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  });
  return Object.freeze(n);
}

function _typeof$c(obj) {
  "@babel/helpers - typeof";

  return _typeof$c = "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$c(obj);
}

function _toPrimitive$1(input, hint) {
  if (_typeof$c(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (_typeof$c(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}

function _toPropertyKey$1(arg) {
  var key = _toPrimitive$1(arg, "string");
  return _typeof$c(key) === "symbol" ? key : String(key);
}

function _defineProperty$7(obj, key, value) {
  key = _toPropertyKey$1(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$b(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$b(Object(source), !0).forEach(function (key) {
      _defineProperty$7(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$b(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}

// 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$3(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;
}

// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
function miniKindOf(val) {
  if (val === void 0) return 'undefined';
  if (val === null) return 'null';
  var type = typeof val;
  switch (type) {
    case 'boolean':
    case 'string':
    case 'number':
    case 'symbol':
    case 'function':
      {
        return type;
      }
  }
  if (Array.isArray(val)) return 'array';
  if (isDate$1(val)) return 'date';
  if (isError(val)) return 'error';
  var constructorName = ctorName(val);
  switch (constructorName) {
    case 'Symbol':
    case 'Promise':
    case 'WeakMap':
    case 'WeakSet':
    case 'Map':
    case 'Set':
      return constructorName;
  } // other

  return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
}
function ctorName(val) {
  return typeof val.constructor === 'function' ? val.constructor.name : null;
}
function isError(val) {
  return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';
}
function isDate$1(val) {
  if (val instanceof Date) return true;
  return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';
}
function kindOf(val) {
  var typeOfVal = typeof val;
  {
    typeOfVal = miniKindOf(val);
  }
  return typeOfVal;
}

/**
 * @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('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');
  }
  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState;
    preloadedState = undefined;
  }
  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error("Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'");
    }
    return enhancer(createStore)(reducer, preloadedState);
  }
  if (typeof reducer !== 'function') {
    throw new Error("Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer) + "'");
  }
  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('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
    }
    return currentState;
  }
  /**
   * Adds a change listener. It will be called any time an action is dispatched,
   * and some part of the state tree may potentially have changed. You may then
   * call `getState()` to read the current state tree inside the callback.
   *
   * You may call `dispatch()` from a change listener, with the following
   * caveats:
   *
   * 1. The subscriptions are snapshotted just before every `dispatch()` call.
   * If you subscribe or unsubscribe while the listeners are being invoked, this
   * will not have any effect on the `dispatch()` that is currently in progress.
   * However, the next `dispatch()` call, whether nested or not, will use a more
   * recent snapshot of the subscription list.
   *
   * 2. The listener should not expect to see all state changes, as the state
   * might have been updated multiple times during a nested `dispatch()` before
   * the listener is called. It is, however, guaranteed that all subscribers
   * registered before the `dispatch()` started will be called with the latest
   * state by the time it exits.
   *
   * @param {Function} listener A callback to be invoked on every dispatch.
   * @returns {Function} A function to remove this change listener.
   */

  function subscribe(listener) {
    if (typeof listener !== 'function') {
      throw new Error("Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'");
    }
    if (isDispatching) {
      throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
    }
    var isSubscribed = true;
    ensureCanMutateNextListeners();
    nextListeners.push(listener);
    return function unsubscribe() {
      if (!isSubscribed) {
        return;
      }
      if (isDispatching) {
        throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
      }
      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$3(action)) {
      throw new Error("Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");
    }
    if (typeof action.type === 'undefined') {
      throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
    }
    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.');
    }
    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }
    var listeners = currentListeners = nextListeners;
    for (var i = 0; i < listeners.length; i++) {
      var listener = listeners[i];
      listener();
    }
    return action;
  }
  /**
   * Replaces the reducer currently used by the store to calculate the state.
   *
   * You might need this if your app implements code splitting and you want to
   * load some of the reducers dynamically. You might also need this if you
   * implement a hot reloading mechanism for Redux.
   *
   * @param {Function} nextReducer The reducer for the store to use instead.
   * @returns {void}
   */

  function replaceReducer(nextReducer) {
    if (typeof nextReducer !== 'function') {
      throw new Error("Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer));
    }
    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("Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'");
        }
        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;
}
/**
 * Creates a Redux store that holds the state tree.
 *
 * **We recommend using `configureStore` from the
 * `@reduxjs/toolkit` package**, which replaces `createStore`:
 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
 *
 * The only way to change the data in the store is to call `dispatch()` on it.
 *
 * There should only be a single store in your app. To specify how different
 * parts of the state tree respond to actions, you may combine several reducers
 * into a single reducer function by using `combineReducers`.
 *
 * @param {Function} reducer A function that returns the next state tree, given
 * the current state tree and the action to handle.
 *
 * @param {any} [preloadedState] The initial state. You may optionally specify it
 * to hydrate the state from the server in universal apps, or to restore a
 * previously serialized user session.
 * If you use `combineReducers` to produce the root reducer function, this must be
 * an object with the same shape as `combineReducers` keys.
 *
 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
 * to enhance the store with third-party capabilities such as middleware,
 * time travel, persistence, etc. The only store enhancer that ships with Redux
 * is `applyMiddleware()`.
 *
 * @returns {Store} A Redux store that lets you read the state, dispatch actions
 * and subscribe to changes.
 */

var legacy_createStore = createStore;

/**
 * Prints a warning in the console if it exists.
 *
 * @param {String} message The warning message.
 * @returns {void}
 */
function warning$3(message) {
  /* eslint-disable no-console */
  if (typeof console !== 'undefined' && typeof console.error === 'function') {
    console.error(message);
  }
  /* eslint-enable no-console */

  try {
    // This error was thrown as a convenience so that if you enable
    // "break on all exceptions" in your console,
    // it would pause the execution at this line.
    throw new Error(message);
  } catch (e) {} // eslint-disable-line no-empty
}

function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
  var reducerKeys = Object.keys(reducers);
  var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
  if (reducerKeys.length === 0) {
    return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
  }
  if (!isPlainObject$3(inputState)) {
    return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
  }
  var unexpectedKeys = Object.keys(inputState).filter(function (key) {
    return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
  });
  unexpectedKeys.forEach(function (key) {
    unexpectedKeyCache[key] = true;
  });
  if (action && action.type === ActionTypes.REPLACE) return;
  if (unexpectedKeys.length > 0) {
    return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
  }
}
function assertReducerShape(reducers) {
  Object.keys(reducers).forEach(function (key) {
    var reducer = reducers[key];
    var initialState = reducer(undefined, {
      type: ActionTypes.INIT
    });
    if (typeof initialState === 'undefined') {
      throw new Error("The slice reducer for key \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
    }
    if (typeof reducer(undefined, {
      type: ActionTypes.PROBE_UNKNOWN_ACTION()
    }) === 'undefined') {
      throw new Error("The slice reducer for key \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle '" + ActionTypes.INIT + "' or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
    }
  });
}
/**
 * Turns an object whose values are different reducer functions, into a single
 * reducer function. It will call every child reducer, and gather their results
 * into a single state object, whose keys correspond to the keys of the passed
 * reducer functions.
 *
 * @param {Object} reducers An object whose values correspond to different
 * reducer functions that need to be combined into one. One handy way to obtain
 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
 * undefined for any action. Instead, they should return their initial state
 * if the state passed to them was undefined, and the current state for any
 * unrecognized action.
 *
 * @returns {Function} A reducer function that invokes every reducer inside the
 * passed object, and builds a state object with the same shape.
 */

function combineReducers(reducers) {
  var reducerKeys = Object.keys(reducers);
  var finalReducers = {};
  for (var i = 0; i < reducerKeys.length; i++) {
    var key = reducerKeys[i];
    {
      if (typeof reducers[key] === 'undefined') {
        warning$3("No reducer provided for key \"" + key + "\"");
      }
    }
    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
  // keys multiple times.

  var unexpectedKeyCache;
  {
    unexpectedKeyCache = {};
  }
  var shapeAssertionError;
  try {
    assertReducerShape(finalReducers);
  } catch (e) {
    shapeAssertionError = e;
  }
  return function combination(state, action) {
    if (state === void 0) {
      state = {};
    }
    if (shapeAssertionError) {
      throw shapeAssertionError;
    }
    {
      var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
      if (warningMessage) {
        warning$3(warningMessage);
      }
    }
    var hasChanged = false;
    var nextState = {};
    for (var _i = 0; _i < finalReducerKeys.length; _i++) {
      var _key = finalReducerKeys[_i];
      var reducer = finalReducers[_key];
      var previousStateForKey = state[_key];
      var nextStateForKey = reducer(previousStateForKey, action);
      if (typeof nextStateForKey === 'undefined') {
        var actionType = action && action.type;
        throw new Error("When called with an action of type " + (actionType ? "\"" + String(actionType) + "\"" : '(unknown type)') + ", the slice reducer for key \"" + _key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.");
      }
      nextState[_key] = nextStateForKey;
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
    }
    hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
    return hasChanged ? nextState : state;
  };
}
function bindActionCreator(actionCreator, dispatch) {
  return function () {
    return dispatch(actionCreator.apply(this, arguments));
  };
}
/**
 * Turns an object whose values are action creators, into an object with the
 * same keys, but with every function wrapped into a `dispatch` call so they
 * may be invoked directly. This is just a convenience method, as you can call
 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
 *
 * For convenience, you can also pass an action creator as the first argument,
 * and get a dispatch wrapped function in return.
 *
 * @param {Function|Object} actionCreators An object whose values are action
 * creator functions. One handy way to obtain it is to use ES6 `import * as`
 * syntax. You may also pass a single function.
 *
 * @param {Function} dispatch The `dispatch` function available on your Redux
 * store.
 *
 * @returns {Function|Object} The object mimicking the original object, but with
 * every action creator wrapped into the `dispatch` call. If you passed a
 * function as `actionCreators`, the return value will also be a single
 * function.
 */

function bindActionCreators$1(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch);
  }
  if (typeof actionCreators !== 'object' || actionCreators === null) {
    throw new Error("bindActionCreators expected an object or a function, but instead received: '" + kindOf(actionCreators) + "'. " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
  }
  var boundActionCreators = {};
  for (var key in actionCreators) {
    var actionCreator = actionCreators[key];
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
    }
  }
  return boundActionCreators;
}

/**
 * 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('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
      };
      var middlewareAPI = {
        getState: store.getState,
        dispatch: function dispatch() {
          return _dispatch.apply(void 0, arguments);
        }
      };
      var chain = middlewares.map(function (middleware) {
        return middleware(middlewareAPI);
      });
      _dispatch = compose$1.apply(void 0, chain)(store.dispatch);
      return _objectSpread2(_objectSpread2({}, store), {}, {
        dispatch: _dispatch
      });
    };
  };
}

var redux = /*#__PURE__*/Object.freeze({
  __proto__: null,
  __DO_NOT_USE__ActionTypes: ActionTypes,
  applyMiddleware: applyMiddleware,
  bindActionCreators: bindActionCreators$1,
  combineReducers: combineReducers,
  compose: compose$1,
  createStore: createStore,
  legacy_createStore: legacy_createStore
});

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 reduxLogger = {exports: {}};

(function (module, exports) {
	!function (e, t) {
	  t(exports) ;
	}(commonjsGlobal, function (e) {

	  function t(e, t) {
	    e.super_ = t, e.prototype = Object.create(t.prototype, {
	      constructor: {
	        value: e,
	        enumerable: !1,
	        writable: !0,
	        configurable: !0
	      }
	    });
	  }
	  function r(e, t) {
	    Object.defineProperty(this, "kind", {
	      value: e,
	      enumerable: !0
	    }), t && t.length && Object.defineProperty(this, "path", {
	      value: t,
	      enumerable: !0
	    });
	  }
	  function n(e, t, r) {
	    n.super_.call(this, "E", e), Object.defineProperty(this, "lhs", {
	      value: t,
	      enumerable: !0
	    }), Object.defineProperty(this, "rhs", {
	      value: r,
	      enumerable: !0
	    });
	  }
	  function o(e, t) {
	    o.super_.call(this, "N", e), Object.defineProperty(this, "rhs", {
	      value: t,
	      enumerable: !0
	    });
	  }
	  function i(e, t) {
	    i.super_.call(this, "D", e), Object.defineProperty(this, "lhs", {
	      value: t,
	      enumerable: !0
	    });
	  }
	  function a(e, t, r) {
	    a.super_.call(this, "A", e), Object.defineProperty(this, "index", {
	      value: t,
	      enumerable: !0
	    }), Object.defineProperty(this, "item", {
	      value: r,
	      enumerable: !0
	    });
	  }
	  function f(e, t, r) {
	    var n = e.slice((r || t) + 1 || e.length);
	    return e.length = t < 0 ? e.length + t : t, e.push.apply(e, n), e;
	  }
	  function u(e) {
	    var t = "undefined" == typeof e ? "undefined" : N(e);
	    return "object" !== t ? t : e === Math ? "math" : null === e ? "null" : Array.isArray(e) ? "array" : "[object Date]" === Object.prototype.toString.call(e) ? "date" : "function" == typeof e.toString && /^\/.*\//.test(e.toString()) ? "regexp" : "object";
	  }
	  function l(e, t, r, c, s, d, p) {
	    s = s || [], p = p || [];
	    var g = s.slice(0);
	    if ("undefined" != typeof d) {
	      if (c) {
	        if ("function" == typeof c && c(g, d)) return;
	        if ("object" === ("undefined" == typeof c ? "undefined" : N(c))) {
	          if (c.prefilter && c.prefilter(g, d)) return;
	          if (c.normalize) {
	            var h = c.normalize(g, d, e, t);
	            h && (e = h[0], t = h[1]);
	          }
	        }
	      }
	      g.push(d);
	    }
	    "regexp" === u(e) && "regexp" === u(t) && (e = e.toString(), t = t.toString());
	    var y = "undefined" == typeof e ? "undefined" : N(e),
	      v = "undefined" == typeof t ? "undefined" : N(t),
	      b = "undefined" !== y || p && p[p.length - 1].lhs && p[p.length - 1].lhs.hasOwnProperty(d),
	      m = "undefined" !== v || p && p[p.length - 1].rhs && p[p.length - 1].rhs.hasOwnProperty(d);
	    if (!b && m) r(new o(g, t));else if (!m && b) r(new i(g, e));else if (u(e) !== u(t)) r(new n(g, e, t));else if ("date" === u(e) && e - t !== 0) r(new n(g, e, t));else if ("object" === y && null !== e && null !== t) {
	      if (p.filter(function (t) {
	        return t.lhs === e;
	      }).length) e !== t && r(new n(g, e, t));else {
	        if (p.push({
	          lhs: e,
	          rhs: t
	        }), Array.isArray(e)) {
	          var w;
	          e.length;
	          for (w = 0; w < e.length; w++) w >= t.length ? r(new a(g, w, new i(void 0, e[w]))) : l(e[w], t[w], r, c, g, w, p);
	          for (; w < t.length;) r(new a(g, w, new o(void 0, t[w++])));
	        } else {
	          var x = Object.keys(e),
	            S = Object.keys(t);
	          x.forEach(function (n, o) {
	            var i = S.indexOf(n);
	            i >= 0 ? (l(e[n], t[n], r, c, g, n, p), S = f(S, i)) : l(e[n], void 0, r, c, g, n, p);
	          }), S.forEach(function (e) {
	            l(void 0, t[e], r, c, g, e, p);
	          });
	        }
	        p.length = p.length - 1;
	      }
	    } else e !== t && ("number" === y && isNaN(e) && isNaN(t) || r(new n(g, e, t)));
	  }
	  function c(e, t, r, n) {
	    return n = n || [], l(e, t, function (e) {
	      e && n.push(e);
	    }, r), n.length ? n : void 0;
	  }
	  function s(e, t, r) {
	    if (r.path && r.path.length) {
	      var n,
	        o = e[t],
	        i = r.path.length - 1;
	      for (n = 0; n < i; n++) o = o[r.path[n]];
	      switch (r.kind) {
	        case "A":
	          s(o[r.path[n]], r.index, r.item);
	          break;
	        case "D":
	          delete o[r.path[n]];
	          break;
	        case "E":
	        case "N":
	          o[r.path[n]] = r.rhs;
	      }
	    } else switch (r.kind) {
	      case "A":
	        s(e[t], r.index, r.item);
	        break;
	      case "D":
	        e = f(e, t);
	        break;
	      case "E":
	      case "N":
	        e[t] = r.rhs;
	    }
	    return e;
	  }
	  function d(e, t, r) {
	    if (e && t && r && r.kind) {
	      for (var n = e, o = -1, i = r.path ? r.path.length - 1 : 0; ++o < i;) "undefined" == typeof n[r.path[o]] && (n[r.path[o]] = "number" == typeof r.path[o] ? [] : {}), n = n[r.path[o]];
	      switch (r.kind) {
	        case "A":
	          s(r.path ? n[r.path[o]] : n, r.index, r.item);
	          break;
	        case "D":
	          delete n[r.path[o]];
	          break;
	        case "E":
	        case "N":
	          n[r.path[o]] = r.rhs;
	      }
	    }
	  }
	  function p(e, t, r) {
	    if (r.path && r.path.length) {
	      var n,
	        o = e[t],
	        i = r.path.length - 1;
	      for (n = 0; n < i; n++) o = o[r.path[n]];
	      switch (r.kind) {
	        case "A":
	          p(o[r.path[n]], r.index, r.item);
	          break;
	        case "D":
	          o[r.path[n]] = r.lhs;
	          break;
	        case "E":
	          o[r.path[n]] = r.lhs;
	          break;
	        case "N":
	          delete o[r.path[n]];
	      }
	    } else switch (r.kind) {
	      case "A":
	        p(e[t], r.index, r.item);
	        break;
	      case "D":
	        e[t] = r.lhs;
	        break;
	      case "E":
	        e[t] = r.lhs;
	        break;
	      case "N":
	        e = f(e, t);
	    }
	    return e;
	  }
	  function g(e, t, r) {
	    if (e && t && r && r.kind) {
	      var n,
	        o,
	        i = e;
	      for (o = r.path.length - 1, n = 0; n < o; n++) "undefined" == typeof i[r.path[n]] && (i[r.path[n]] = {}), i = i[r.path[n]];
	      switch (r.kind) {
	        case "A":
	          p(i[r.path[n]], r.index, r.item);
	          break;
	        case "D":
	          i[r.path[n]] = r.lhs;
	          break;
	        case "E":
	          i[r.path[n]] = r.lhs;
	          break;
	        case "N":
	          delete i[r.path[n]];
	      }
	    }
	  }
	  function h(e, t, r) {
	    if (e && t) {
	      var n = function (n) {
	        r && !r(e, t, n) || d(e, t, n);
	      };
	      l(e, t, n);
	    }
	  }
	  function y(e) {
	    return "color: " + F[e].color + "; font-weight: bold";
	  }
	  function v(e) {
	    var t = e.kind,
	      r = e.path,
	      n = e.lhs,
	      o = e.rhs,
	      i = e.index,
	      a = e.item;
	    switch (t) {
	      case "E":
	        return [r.join("."), n, "→", o];
	      case "N":
	        return [r.join("."), o];
	      case "D":
	        return [r.join(".")];
	      case "A":
	        return [r.join(".") + "[" + i + "]", a];
	      default:
	        return [];
	    }
	  }
	  function b(e, t, r, n) {
	    var o = c(e, t);
	    try {
	      n ? r.groupCollapsed("diff") : r.group("diff");
	    } catch (e) {
	      r.log("diff");
	    }
	    o ? o.forEach(function (e) {
	      var t = e.kind,
	        n = v(e);
	      r.log.apply(r, ["%c " + F[t].text, y(t)].concat(P(n)));
	    }) : r.log("—— no diff ——");
	    try {
	      r.groupEnd();
	    } catch (e) {
	      r.log("—— diff end —— ");
	    }
	  }
	  function m(e, t, r, n) {
	    switch ("undefined" == typeof e ? "undefined" : N(e)) {
	      case "object":
	        return "function" == typeof e[n] ? e[n].apply(e, P(r)) : e[n];
	      case "function":
	        return e(t);
	      default:
	        return e;
	    }
	  }
	  function w(e) {
	    var t = e.timestamp,
	      r = e.duration;
	    return function (e, n, o) {
	      var i = ["action"];
	      return i.push("%c" + String(e.type)), t && i.push("%c@ " + n), r && i.push("%c(in " + o.toFixed(2) + " ms)"), i.join(" ");
	    };
	  }
	  function x(e, t) {
	    var r = t.logger,
	      n = t.actionTransformer,
	      o = t.titleFormatter,
	      i = void 0 === o ? w(t) : o,
	      a = t.collapsed,
	      f = t.colors,
	      u = t.level,
	      l = t.diff,
	      c = "undefined" == typeof t.titleFormatter;
	    e.forEach(function (o, s) {
	      var d = o.started,
	        p = o.startedTime,
	        g = o.action,
	        h = o.prevState,
	        y = o.error,
	        v = o.took,
	        w = o.nextState,
	        x = e[s + 1];
	      x && (w = x.prevState, v = x.started - d);
	      var S = n(g),
	        k = "function" == typeof a ? a(function () {
	          return w;
	        }, g, o) : a,
	        j = D(p),
	        E = f.title ? "color: " + f.title(S) + ";" : "",
	        A = ["color: gray; font-weight: lighter;"];
	      A.push(E), t.timestamp && A.push("color: gray; font-weight: lighter;"), t.duration && A.push("color: gray; font-weight: lighter;");
	      var O = i(S, j, v);
	      try {
	        k ? f.title && c ? r.groupCollapsed.apply(r, ["%c " + O].concat(A)) : r.groupCollapsed(O) : f.title && c ? r.group.apply(r, ["%c " + O].concat(A)) : r.group(O);
	      } catch (e) {
	        r.log(O);
	      }
	      var N = m(u, S, [h], "prevState"),
	        P = m(u, S, [S], "action"),
	        C = m(u, S, [y, h], "error"),
	        F = m(u, S, [w], "nextState");
	      if (N) if (f.prevState) {
	        var L = "color: " + f.prevState(h) + "; font-weight: bold";
	        r[N]("%c prev state", L, h);
	      } else r[N]("prev state", h);
	      if (P) if (f.action) {
	        var T = "color: " + f.action(S) + "; font-weight: bold";
	        r[P]("%c action    ", T, S);
	      } else r[P]("action    ", S);
	      if (y && C) if (f.error) {
	        var M = "color: " + f.error(y, h) + "; font-weight: bold;";
	        r[C]("%c error     ", M, y);
	      } else r[C]("error     ", y);
	      if (F) if (f.nextState) {
	        var _ = "color: " + f.nextState(w) + "; font-weight: bold";
	        r[F]("%c next state", _, w);
	      } else r[F]("next state", w);
	      l && b(h, w, r, k);
	      try {
	        r.groupEnd();
	      } catch (e) {
	        r.log("—— log end ——");
	      }
	    });
	  }
	  function S() {
	    var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
	      t = Object.assign({}, L, e),
	      r = t.logger,
	      n = t.stateTransformer,
	      o = t.errorTransformer,
	      i = t.predicate,
	      a = t.logErrors,
	      f = t.diffPredicate;
	    if ("undefined" == typeof r) return function () {
	      return function (e) {
	        return function (t) {
	          return e(t);
	        };
	      };
	    };
	    if (e.getState && e.dispatch) return console.error("[redux-logger] redux-logger not installed. Make sure to pass logger instance as middleware:\n// Logger with default options\nimport { logger } from 'redux-logger'\nconst store = createStore(\n  reducer,\n  applyMiddleware(logger)\n)\n// Or you can create your own logger with custom options http://bit.ly/redux-logger-options\nimport createLogger from 'redux-logger'\nconst logger = createLogger({\n  // ...options\n});\nconst store = createStore(\n  reducer,\n  applyMiddleware(logger)\n)\n"), function () {
	      return function (e) {
	        return function (t) {
	          return e(t);
	        };
	      };
	    };
	    var u = [];
	    return function (e) {
	      var r = e.getState;
	      return function (e) {
	        return function (l) {
	          if ("function" == typeof i && !i(r, l)) return e(l);
	          var c = {};
	          u.push(c), c.started = O.now(), c.startedTime = new Date(), c.prevState = n(r()), c.action = l;
	          var s = void 0;
	          if (a) try {
	            s = e(l);
	          } catch (e) {
	            c.error = o(e);
	          } else s = e(l);
	          c.took = O.now() - c.started, c.nextState = n(r());
	          var d = t.diff && "function" == typeof f ? f(r, l) : t.diff;
	          if (x(u, Object.assign({}, t, {
	            diff: d
	          })), u.length = 0, c.error) throw c.error;
	          return s;
	        };
	      };
	    };
	  }
	  var k,
	    j,
	    E = function (e, t) {
	      return new Array(t + 1).join(e);
	    },
	    A = function (e, t) {
	      return E("0", t - e.toString().length) + e;
	    },
	    D = function (e) {
	      return A(e.getHours(), 2) + ":" + A(e.getMinutes(), 2) + ":" + A(e.getSeconds(), 2) + "." + A(e.getMilliseconds(), 3);
	    },
	    O = "undefined" != typeof performance && null !== performance && "function" == typeof performance.now ? performance : Date,
	    N = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) {
	      return typeof e;
	    } : function (e) {
	      return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
	    },
	    P = function (e) {
	      if (Array.isArray(e)) {
	        for (var t = 0, r = Array(e.length); t < e.length; t++) r[t] = e[t];
	        return r;
	      }
	      return Array.from(e);
	    },
	    C = [];
	  k = "object" === ("undefined" == typeof commonjsGlobal ? "undefined" : N(commonjsGlobal)) && commonjsGlobal ? commonjsGlobal : "undefined" != typeof window ? window : {}, j = k.DeepDiff, j && C.push(function () {
	    "undefined" != typeof j && k.DeepDiff === c && (k.DeepDiff = j, j = void 0);
	  }), t(n, r), t(o, r), t(i, r), t(a, r), Object.defineProperties(c, {
	    diff: {
	      value: c,
	      enumerable: !0
	    },
	    observableDiff: {
	      value: l,
	      enumerable: !0
	    },
	    applyDiff: {
	      value: h,
	      enumerable: !0
	    },
	    applyChange: {
	      value: d,
	      enumerable: !0
	    },
	    revertChange: {
	      value: g,
	      enumerable: !0
	    },
	    isConflict: {
	      value: function () {
	        return "undefined" != typeof j;
	      },
	      enumerable: !0
	    },
	    noConflict: {
	      value: function () {
	        return C && (C.forEach(function (e) {
	          e();
	        }), C = null), c;
	      },
	      enumerable: !0
	    }
	  });
	  var F = {
	      E: {
	        color: "#2196F3",
	        text: "CHANGED:"
	      },
	      N: {
	        color: "#4CAF50",
	        text: "ADDED:"
	      },
	      D: {
	        color: "#F44336",
	        text: "DELETED:"
	      },
	      A: {
	        color: "#2196F3",
	        text: "ARRAY:"
	      }
	    },
	    L = {
	      level: "log",
	      logger: console,
	      logErrors: !0,
	      collapsed: void 0,
	      predicate: void 0,
	      duration: !1,
	      timestamp: !0,
	      stateTransformer: function (e) {
	        return e;
	      },
	      actionTransformer: function (e) {
	        return e;
	      },
	      errorTransformer: function (e) {
	        return e;
	      },
	      colors: {
	        title: function () {
	          return "inherit";
	        },
	        prevState: function () {
	          return "#9E9E9E";
	        },
	        action: function () {
	          return "#03A9F4";
	        },
	        nextState: function () {
	          return "#4CAF50";
	        },
	        error: function () {
	          return "#F20404";
	        }
	      },
	      diff: !1,
	      diffPredicate: void 0,
	      transformer: void 0
	    },
	    T = function () {
	      var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
	        t = e.dispatch,
	        r = e.getState;
	      return "function" == typeof t || "function" == typeof r ? S()({
	        dispatch: t,
	        getState: r
	      }) : void console.error("\n[redux-logger v3] BREAKING CHANGE\n[redux-logger v3] Since 3.0.0 redux-logger exports by default logger with default settings.\n[redux-logger v3] Change\n[redux-logger v3] import createLogger from 'redux-logger'\n[redux-logger v3] to\n[redux-logger v3] import { createLogger } from 'redux-logger'\n");
	    };
	  e.defaults = L, e.createLogger = S, e.logger = T, e.default = T, Object.defineProperty(e, "__esModule", {
	    value: !0
	  });
	}); 
} (reduxLogger, reduxLogger.exports));

var reduxLoggerExports = reduxLogger.exports;
var logger = /*@__PURE__*/getDefaultExportFromCjs(reduxLoggerExports);

var KEY_PREFIX$1 = 'persist:';
var FLUSH = 'persist/FLUSH';
var REHYDRATE$1 = 'persist/REHYDRATE';
var PAUSE = 'persist/PAUSE';
var PERSIST = 'persist/PERSIST';
var PURGE = 'persist/PURGE';
var REGISTER = 'persist/REGISTER';
var DEFAULT_VERSION = -1;

function _typeof$b(obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof$b = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof$b = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }
  return _typeof$b(obj);
}
function ownKeys$a(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$a(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$a(source, true).forEach(function (key) {
        _defineProperty$6(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$a(source).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
function _defineProperty$6(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) {
  var debug = _ref.debug;
  var newState = _objectSpread$a({}, reducedState); // only rehydrate if inboundState exists and is an object

  if (inboundState && _typeof$b(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]) {
        if (debug) console.log('redux-persist/stateReconciler: sub state for key `%s` modified, skipping.', key);
        return;
      } // otherwise hard set the new value

      newState[key] = inboundState[key];
    });
  }
  if (debug && inboundState && _typeof$b(inboundState) === 'object') console.log("redux-persist/stateReconciler: rehydrated keys '".concat(Object.keys(inboundState).join(', '), "'"));
  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$1).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 && "development" !== '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$1(config) {
  var transforms = config.transforms || [];
  var storageKey = "".concat(config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX$1).concat(config.key);
  var storage = config.storage;
  var debug = 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) {
        if (debug) console.log("redux-persist/getStoredState: Error restoring data ".concat(serialized), err);
        throw err;
      }
    }
  });
}
function defaultDeserialize(serial) {
  return JSON.parse(serial);
}

function purgeStoredState$1(config) {
  var storage = config.storage;
  var storageKey = "".concat(config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX$1).concat(config.key);
  return storage.removeItem(storageKey, warnIfRemoveError$1);
}
function warnIfRemoveError$1(err) {
  if (err && "development" !== 'production') {
    console.error('redux-persist/purgeStoredState: Error purging data stored state', err);
  }
}

function ownKeys$9(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$9(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$9(source, true).forEach(function (key) {
        _defineProperty$5(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$9(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;
}
function _objectWithoutProperties$2(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose$3(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$3(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) {
  {
    if (!config) throw new Error('config is required for persistReducer');
    if (!config.key) throw new Error('key is required in persistor config');
    if (!config.storage) throw new Error("redux-persist: config.storage is required. Try using one of the provided storage engines `import storage from 'redux-persist/lib/storage'`");
  }
  var version = config.version !== undefined ? config.version : DEFAULT_VERSION;
  config.debug || false;
  var stateReconciler = config.stateReconciler === undefined ? autoMergeLevel1 : config.stateReconciler;
  var getStoredState = config.getStoredState || getStoredState$1;
  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$2(_ref, ["_persist"]); // $FlowIgnore need to update State type

    var restState = rest;
    if (action.type === PERSIST) {
      var _sealed = false;
      var _rehydrate = function _rehydrate(payload, err) {
        // dev warning if we are already sealed
        if (_sealed) console.error("redux-persist: rehydrate for \"".concat(config.key, "\" called after timeout."), payload, err); // only rehydrate if we are not already sealed

        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$9({}, 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(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) {
          if (migrateErr) console.error('redux-persist: migration error', migrateErr);
          _rehydrate(undefined, migrateErr);
        });
      }, function (err) {
        _rehydrate(undefined, err);
      });
      return _objectSpread$9({}, baseReducer(restState, action), {
        _persist: {
          version: version,
          rehydrated: false
        }
      });
    } else if (action.type === PURGE) {
      _purge = true;
      action.result(purgeStoredState$1(config));
      return _objectSpread$9({}, baseReducer(restState, action), {
        _persist: _persist
      });
    } else if (action.type === FLUSH) {
      action.result(_persistoid && _persistoid.flush());
      return _objectSpread$9({}, baseReducer(restState, action), {
        _persist: _persist
      });
    } else if (action.type === PAUSE) {
      _paused = true;
    } else if (action.type === REHYDRATE$1) {
      // noop on restState if purging
      if (_purge) return _objectSpread$9({}, restState, {
        _persist: _objectSpread$9({}, _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$9({}, reconciledRest, {
          _persist: _objectSpread$9({}, _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$9({}, 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$8(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$8(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$8(source, true).forEach(function (key) {
        _defineProperty$4(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$8(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;
}
var initialState$1 = {
  registry: [],
  bootstrapped: false
};
var persistorReducer = function persistorReducer() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$1;
  var action = arguments.length > 1 ? arguments[1] : undefined;
  switch (action.type) {
    case REGISTER:
      return _objectSpread$8({}, state, {
        registry: [].concat(_toConsumableArray$2(state.registry), [action.key])
      });
    case REHYDRATE$1:
      var firstIndex = state.registry.indexOf(action.key);
      var registry = _toConsumableArray$2(state.registry);
      registry.splice(firstIndex, 1);
      return _objectSpread$8({}, state, {
        registry: registry,
        bootstrapped: registry.length === 0
      });
    default:
      return state;
  }
};
function persistStore$1(store, options, cb) {
  // help catch incorrect usage of passing PersistConfig in as PersistorOptions
  {
    var optionsToTest = options || {};
    var bannedKeys = ['blacklist', 'whitelist', 'transforms', 'storage', 'keyPrefix', 'migrate'];
    bannedKeys.forEach(function (k) {
      if (!!optionsToTest[k]) console.error("redux-persist: invalid option passed to persistStore: \"".concat(k, "\". You may be incorrectly passing persistConfig into persistStore, whereas it should be passed into persistReducer."));
    });
  }
  var boostrappedCb = cb || false;
  var _pStore = createStore(persistorReducer, initialState$1, 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$1,
      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$8({}, _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;
}

function createTransform$1(
// @NOTE inbound: transform state coming from redux on its way to being serialized and stored
inbound,
// @NOTE outbound: transform state coming from storage, on its way to be rehydrated into redux
outbound) {
  var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var whitelist = config.whitelist || null;
  var blacklist = config.blacklist || null;
  function whitelistBlacklistCheck(key) {
    if (whitelist && whitelist.indexOf(key) === -1) return true;
    if (blacklist && blacklist.indexOf(key) !== -1) return true;
    return false;
  }
  return {
    in: function _in(state, key, fullState) {
      return !whitelistBlacklistCheck(key) && inbound ? inbound(state, key, fullState) : state;
    },
    out: function out(state, key, fullState) {
      return !whitelistBlacklistCheck(key) && outbound ? outbound(state, key, fullState) : state;
    }
  };
}

var _default$d = autoMergeLevel2;
function _typeof$a(obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof$a = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof$a = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }
  return _typeof$a(obj);
}
function ownKeys$7(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$7(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$7(source, true).forEach(function (key) {
        _defineProperty$3(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$7(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;
}

/*
  autoMergeLevel2: 
    - merges 2 level of substate
    - skips substate if already modified
    - this is essentially redux-perist v4 behavior
*/
function autoMergeLevel2(inboundState, originalState, reducedState, _ref) {
  var debug = _ref.debug;
  var newState = _objectSpread$7({}, reducedState); // only rehydrate if inboundState exists and is an object

  if (inboundState && _typeof$a(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]) {
        if (debug) console.log('redux-persist/stateReconciler: sub state for key `%s` modified, skipping.', key);
        return;
      }
      if (isPlainEnoughObject(reducedState[key])) {
        // if object is plain enough shallow merge the new values (hence "Level2")
        newState[key] = _objectSpread$7({}, newState[key], {}, inboundState[key]);
        return;
      } // otherwise hard set

      newState[key] = inboundState[key];
    });
  }
  if (debug && inboundState && _typeof$a(inboundState) === 'object') console.log("redux-persist/stateReconciler: rehydrated keys '".concat(Object.keys(inboundState).join(', '), "'"));
  return newState;
}
function isPlainEnoughObject(o) {
  return o !== null && !Array.isArray(o) && _typeof$a(o) === 'object';
}

const REMOVE = "@@KVP_REMOVE";
const SET = "@@KVP_SET";
const CLEAR = "@@KVP_CLEAR";

// Internal variables and functions
var _verbosity = {
  Network: 1,
  Lookup: 2,
  Values: 3
};
class Store {
  constructor(name) {
    if (_stores[name]) {
      throw name + " store already exists!";
    }
    this.name = name;
    _stores[name] = this;
    this.debug = false;

    // Base URL of web service
    this.service = undefined;

    // Default parameters (e.g f=json)
    this.defaults = {};
    this.ready = {
      then: function () {
        throw new Error("Call init first!");
      }
    };

    // Registered redux functions
    this._reducers = {};
    this._enhanceReducers = [];
    this._persistKeys = [];
    this._transforms = [];
    this._middleware = [];
    this._enhancers = [];
    this._subscribers = [];
    this._deferActions = [];
    this._thunkHandler = null;
    this._promises = {}; // Save promises to prevent redundant fetches

    this.addReducer("kvp", (state, action) => this.kvpReducer(state, action), true);
  }
  setEngine({
    createStorage,
    serialize,
    deserialize
  }) {
    this.engine = {
      createStorage,
      serialize,
      deserialize
    };
  }
  init(opts = {}) {
    var self = this;
    var optlist = ["debug", "storageFail", "service", "defaults", "fetchFail", "ajax", "formatKeyword"];
    optlist.forEach(function (opt) {
      if (opts.hasOwnProperty(opt)) {
        self[opt] = opts[opt];
      }
    });
    if (self.debug) {
      for (var level in _verbosity) {
        if (self.debug >= _verbosity[level]) {
          self["debug" + level] = true;
        }
      }
      self.addMiddleware(logger.default || logger);
    }
    var storeReady;
    self.ready = new Promise(resolve => storeReady = resolve);
    var reducer = combineReducers(this._reducers);
    this._enhanceReducers.forEach(enhanceReducer => {
      reducer = enhanceReducer(reducer);
    });
    const enhancers = compose$1(...this._enhancers, applyMiddleware(...this._middleware));
    const {
      createStorage,
      serialize,
      deserialize
    } = this.engine || ds.engine;
    this.lf = createStorage(this.name);
    const persistConfig = {
      key: "root",
      storage: this.lf,
      stateReconciler: _default$d.default || _default$d,
      serialize,
      deserialize,
      transforms: this._transforms,
      whitelist: this._persistKeys,
      writeFailHandler: error => this.storageFail(error)
    };
    const persistedReducer = persistReducer(persistConfig, reducer);
    this._store = createStore(persistedReducer, {}, enhancers);
    this._persistor = persistStore$1(this._store);
    this._persistor.subscribe(() => {
      const {
        bootstrapped
      } = this._persistor.getState();
      if (bootstrapped) {
        storeReady();
      }
    });
    this._unsubscribers = this._subscribers.map(fn => this._store.subscribe(fn));
    this._deferActions.forEach(this._store.dispatch);
  }
  dispatch(action) {
    if (this._store) {
      return this._store.dispatch(action);
    } else {
      this._deferActions.push(action);
    }
  }
  subscribe(fn) {
    this._subscribers.push(fn);
    if (this._store) {
      return this._store.subscribe(fn);
    } else {
      const index = this._subscribers.length - 1;
      return () => {
        if (!this._unsubscribers) {
          throw new Error("Store was never fully initialized!");
        }
        this._unsubscribers[index]();
      };
    }
  }
  getState() {
    return this._store.getState();
  }
  addReducer(name, reducer, persist, restore) {
    this._reducers[name] = reducer;
    if (persist) {
      this.persistKey(name, persist, restore);
    }
  }
  addEnhanceReducer(name, enhanceReducer, persist, restore) {
    this._enhanceReducers.push(enhanceReducer);
    if (persist) {
      this.persistKey(name, persist, restore);
    }
  }
  persistKey(name, persist, restore) {
    this._persistKeys.push(name);
    if (persist && restore) {
      this._transforms.push(createTransform$1(persist, restore, {
        whitelist: [name]
      }));
    }
  }
  addMiddleware(middleware) {
    this._middleware.push(middleware);
  }
  addEnhancer(enhancer) {
    this._enhancers.push(enhancer);
  }
  bindActionCreators(actions) {
    return bindActionCreators$1(actions, this.dispatch.bind(this));
  }
  addThunk(name, thunk) {
    if (!this._thunkHandler) {
      throw new Error("@wq/router is required to handle thunks");
    }
    this._thunkHandler(name, thunk);
  }
  setThunkHandler(handler) {
    this._thunkHandler = handler;
  }
  kvpReducer(state = {}, action) {
    if (action.type === REMOVE) {
      state = {
        ...state
      };
      delete state[action.payload.key];
    } else if (action.type === SET) {
      state = {
        ...state,
        [action.payload.key]: action.payload.value
      };
    } else if (action.type === CLEAR) {
      state = {};
    }
    return state;
  }

  // Get value from datastore
  async get(query) {
    await this.ready;
    var self = this;
    if (Array.isArray(query)) {
      var promises = query.map(row => self.get(row));
      return Promise.all(promises);
    }
    query = self.normalizeQuery(query);
    var key = self.toKey(query);
    if (self.debugLookup) {
      console.log("looking up " + key);
    }

    // Check storage first
    const kvp = this.getState().kvp;
    if (kvp[key]) {
      if (self.debugLookup) {
        console.log("in storage");
      }
      return kvp[key];
    } else {
      // Search ends here if query is a simple string
      if (typeof query == "string") {
        if (self.debugLookup) {
          console.log("not found");
        }
        return null;
      }

      // More complex queries are assumed to be server requests
      return self.fetch(query, true);
    }
  }

  // Set value
  async set(query, value) {
    var self = this;
    var key = self.toKey(query);
    if (value === null) {
      if (self.debugLookup) {
        console.log("deleting " + key);
      }
      self.dispatch({
        type: REMOVE,
        payload: {
          key
        }
      });
      return;
    } else {
      if (self.debugLookup) {
        console.log("saving new value for " + key);
        if (self.debugValues) {
          console.log(value);
        }
      }
      self.dispatch({
        type: SET,
        payload: {
          key,
          value
        }
      });
      return;
    }
  }

  // Callback for localStorage failure - override to inform the user
  storageFail(error) {
    console.warn("Error persisting store:");
    console.warn(error);
  }

  // Convert "/url" to {'url': "url"} (simplify common use case)
  normalizeQuery(query) {
    if (typeof query === "string" && query.charAt(0) == "/") {
      query = {
        url: query.replace(/^\//, "")
      };
    }
    return query;
  }

  // Helper to allow simple objects to be used as keys
  toKey(query) {
    var self = this;
    query = self.normalizeQuery(query);
    if (!query) {
      throw "Invalid query!";
    }
    if (typeof query == "string") {
      return query;
    } else {
      return new URLSearchParams(query).toString();
    }
  }

  // Helper to check existence of a key without loading the object
  exists(query) {
    var self = this;
    var key = self.toKey(query);
    return self.keys().then(function (keys) {
      var found = false;
      keys.forEach(function (k) {
        if (k === key) {
          found = true;
        }
      });
      return found;
    });
  }

  // Fetch data from server
  fetch(query, cache) {
    var self = this;
    query = self.normalizeQuery(query);
    var key = self.toKey(query);
    var data = {
      ...self.defaults,
      ...query
    };
    var url = self.service;
    if (data.hasOwnProperty("url")) {
      url = url + "/" + data.url;
      delete data.url;
    }
    if (data.format && !self.formatKeyword) {
      url += "." + data.format;
      delete data.format;
    }
    if (this._promises[key]) {
      return this._promises[key];
    }
    if (self.debugNetwork) {
      console.log("fetching " + key);
    }
    var promise = self.ajax(url, data, "GET");
    this._promises[key] = promise.then(async data => {
      delete this._promises[key];
      if (!data) {
        self.fetchFail(query, "Error parsing data!");
        return;
      }
      if (self.debugNetwork) {
        console.log("received result for " + key);
        if (self.debugValues) {
          console.log(data);
        }
      }
      if (cache) {
        await self.set(query, data);
      }
      return data;
    }, error => {
      delete this._promises[key];
      console.error(error);
      self.fetchFail(query, "Error parsing data!");
    });
    return this._promises[key];
  }

  // Hook to allow full AJAX customization
  ajax(url, data, method, headers) {
    var urlObj = new URL(url, window.location);
    if (!method) {
      method = "GET";
    } else {
      method = method.toUpperCase();
    }
    if (method == "GET") {
      Object.entries(data || {}).forEach(([key, value]) => urlObj.searchParams.append(key, value));
      data = null;
    }
    return fetch(urlObj, {
      method: method,
      body: data,
      headers: headers
    }).then(response => {
      if (response.ok) {
        if (response.status === 204) {
          return null;
        } else {
          return response.json();
        }
      } else {
        return response.text().then(result => {
          var error = new Error();
          try {
            error.json = JSON.parse(result);
          } catch (e) {
            error.text = result;
          }
          error.status = response.status;
          throw error;
        });
      }
    });
  }

  // Callback for fetch() failures - override to inform the user
  fetchFail(query, error) {
    var self = this;
    var key = self.toKey(query);
    console.warn("Error loading " + key + ": " + error);
  }

  // Helper function for prefetching data
  prefetch(query) {
    var self = this;
    return self.fetch(query, true);
  }

  // Clear local caches
  async reset() {
    this.dispatch({
      type: CLEAR
    });
    await this._persistor.purge();
  }

  // List storage keys matching this store's key prefix
  async keys() {
    return Object.keys(this.getState().kvp);
  }
}
var _stores = {};

// Hybrid module object provides/is a singleton instance...
var ds = new Store("main");

// ... and a way to retrieve/autoinit other stores
ds.getStore = getStore;
function getStore(name) {
  if (_stores[name]) {
    return _stores[name];
  } else {
    return new Store(name);
  }
}

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 localforage = {exports: {}};

/*!
    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 < r.length; o++) s(r[o]);
	    return s;
	  }({
	    1: [function (_dereq_, module, exports) {
	      (function (global) {

	        var Mutation = global.MutationObserver || global.WebKitMutationObserver;
	        var scheduleDrain;
	        {
	          if (Mutation) {
	            var called = 0;
	            var observer = new Mutation(nextTick);
	            var element = global.document.createTextNode('');
	            observer.observe(element, {
	              characterData: true
	            });
	            scheduleDrain = function () {
	              element.data = called = ++called % 2;
	            };
	          } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
	            var channel = new global.MessageChannel();
	            channel.port1.onmessage = nextTick;
	            scheduleDrain = function () {
	              channel.port2.postMessage(0);
	            };
	          } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
	            scheduleDrain = function () {
	              // Create a <script> 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));

var localforageExports = localforage.exports;
var localForage = /*@__PURE__*/getDefaultExportFromCjs(localforageExports);

function createStorage(name) {
  return localForage.createInstance({
    name
  });
}
const serialize$1 = false;
const deserialize = false;

var storage = /*#__PURE__*/Object.freeze({
  __proto__: null,
  createStorage: createStorage,
  deserialize: deserialize,
  serialize: serialize$1
});

ds.setEngine(storage);

var typeDetect$1 = {exports: {}};

(function (module, exports) {
	(function (global, factory) {
	  module.exports = factory() ;
	})(commonjsGlobal, function () {

	  /* !
	   * type-detect
	   * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
	   * MIT Licensed
	   */
	  var promiseExists = typeof Promise === 'function';

	  /* eslint-disable no-undef */
	  var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist

	  var symbolExists = typeof Symbol !== 'undefined';
	  var mapExists = typeof Map !== 'undefined';
	  var setExists = typeof Set !== 'undefined';
	  var weakMapExists = typeof WeakMap !== 'undefined';
	  var weakSetExists = typeof WeakSet !== 'undefined';
	  var dataViewExists = typeof DataView !== 'undefined';
	  var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
	  var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
	  var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
	  var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
	  var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
	  var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
	  var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
	  var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
	  var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
	  var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
	  var toStringLeftSliceLength = 8;
	  var toStringRightSliceLength = -1;
	  /**
	   * ### typeOf (obj)
	   *
	   * Uses `Object.prototype.toString` to determine the type of an object,
	   * normalising behaviour across engine versions & well optimised.
	   *
	   * @param {Mixed} object
	   * @return {String} object type
	   * @api public
	   */
	  function typeDetect(obj) {
	    /* ! Speed optimisation
	     * Pre:
	     *   string literal     x 3,039,035 ops/sec ±1.62% (78 runs sampled)
	     *   boolean literal    x 1,424,138 ops/sec ±4.54% (75 runs sampled)
	     *   number literal     x 1,653,153 ops/sec ±1.91% (82 runs sampled)
	     *   undefined          x 9,978,660 ops/sec ±1.92% (75 runs sampled)
	     *   function           x 2,556,769 ops/sec ±1.73% (77 runs sampled)
	     * Post:
	     *   string literal     x 38,564,796 ops/sec ±1.15% (79 runs sampled)
	     *   boolean literal    x 31,148,940 ops/sec ±1.10% (79 runs sampled)
	     *   number literal     x 32,679,330 ops/sec ±1.90% (78 runs sampled)
	     *   undefined          x 32,363,368 ops/sec ±1.07% (82 runs sampled)
	     *   function           x 31,296,870 ops/sec ±0.96% (83 runs sampled)
	     */
	    var typeofObj = typeof obj;
	    if (typeofObj !== 'object') {
	      return typeofObj;
	    }

	    /* ! Speed optimisation
	     * Pre:
	     *   null               x 28,645,765 ops/sec ±1.17% (82 runs sampled)
	     * Post:
	     *   null               x 36,428,962 ops/sec ±1.37% (84 runs sampled)
	     */
	    if (obj === null) {
	      return 'null';
	    }

	    /* ! Spec Conformance
	     * Test: `Object.prototype.toString.call(window)``
	     *  - Node === "[object global]"
	     *  - Chrome === "[object global]"
	     *  - Firefox === "[object Window]"
	     *  - PhantomJS === "[object Window]"
	     *  - Safari === "[object Window]"
	     *  - IE 11 === "[object Window]"
	     *  - IE Edge === "[object Window]"
	     * Test: `Object.prototype.toString.call(this)``
	     *  - Chrome Worker === "[object global]"
	     *  - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
	     *  - Safari Worker === "[object DedicatedWorkerGlobalScope]"
	     *  - IE 11 Worker === "[object WorkerGlobalScope]"
	     *  - IE Edge Worker === "[object WorkerGlobalScope]"
	     */
	    if (obj === globalObject) {
	      return 'global';
	    }

	    /* ! Speed optimisation
	     * Pre:
	     *   array literal      x 2,888,352 ops/sec ±0.67% (82 runs sampled)
	     * Post:
	     *   array literal      x 22,479,650 ops/sec ±0.96% (81 runs sampled)
	     */
	    if (Array.isArray(obj) && (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))) {
	      return 'Array';
	    }

	    // Not caching existence of `window` and related properties due to potential
	    // for `window` to be unset before tests in quasi-browser environments.
	    if (typeof window === 'object' && window !== null) {
	      /* ! Spec Conformance
	       * (https://html.spec.whatwg.org/multipage/browsers.html#location)
	       * WhatWG HTML$7.7.3 - The `Location` interface
	       * Test: `Object.prototype.toString.call(window.location)``
	       *  - IE <=11 === "[object Object]"
	       *  - IE Edge <=13 === "[object Object]"
	       */
	      if (typeof window.location === 'object' && obj === window.location) {
	        return 'Location';
	      }

	      /* ! Spec Conformance
	       * (https://html.spec.whatwg.org/#document)
	       * WhatWG HTML$3.1.1 - The `Document` object
	       * Note: Most browsers currently adher to the W3C DOM Level 2 spec
	       *       (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
	       *       which suggests that browsers should use HTMLTableCellElement for
	       *       both TD and TH elements. WhatWG separates these.
	       *       WhatWG HTML states:
	       *         > For historical reasons, Window objects must also have a
	       *         > writable, configurable, non-enumerable property named
	       *         > HTMLDocument whose value is the Document interface object.
	       * Test: `Object.prototype.toString.call(document)``
	       *  - Chrome === "[object HTMLDocument]"
	       *  - Firefox === "[object HTMLDocument]"
	       *  - Safari === "[object HTMLDocument]"
	       *  - IE <=10 === "[object Document]"
	       *  - IE 11 === "[object HTMLDocument]"
	       *  - IE Edge <=13 === "[object HTMLDocument]"
	       */
	      if (typeof window.document === 'object' && obj === window.document) {
	        return 'Document';
	      }
	      if (typeof window.navigator === 'object') {
	        /* ! Spec Conformance
	         * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
	         * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
	         * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
	         *  - IE <=10 === "[object MSMimeTypesCollection]"
	         */
	        if (typeof window.navigator.mimeTypes === 'object' && obj === window.navigator.mimeTypes) {
	          return 'MimeTypeArray';
	        }

	        /* ! Spec Conformance
	         * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
	         * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
	         * Test: `Object.prototype.toString.call(navigator.plugins)``
	         *  - IE <=10 === "[object MSPluginsCollection]"
	         */
	        if (typeof window.navigator.plugins === 'object' && obj === window.navigator.plugins) {
	          return 'PluginArray';
	        }
	      }
	      if ((typeof window.HTMLElement === 'function' || typeof window.HTMLElement === 'object') && obj instanceof window.HTMLElement) {
	        /* ! Spec Conformance
	        * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
	        * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
	        * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
	        *  - IE <=10 === "[object HTMLBlockElement]"
	        */
	        if (obj.tagName === 'BLOCKQUOTE') {
	          return 'HTMLQuoteElement';
	        }

	        /* ! Spec Conformance
	         * (https://html.spec.whatwg.org/#htmltabledatacellelement)
	         * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
	         * Note: Most browsers currently adher to the W3C DOM Level 2 spec
	         *       (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
	         *       which suggests that browsers should use HTMLTableCellElement for
	         *       both TD and TH elements. WhatWG separates these.
	         * Test: Object.prototype.toString.call(document.createElement('td'))
	         *  - Chrome === "[object HTMLTableCellElement]"
	         *  - Firefox === "[object HTMLTableCellElement]"
	         *  - Safari === "[object HTMLTableCellElement]"
	         */
	        if (obj.tagName === 'TD') {
	          return 'HTMLTableDataCellElement';
	        }

	        /* ! Spec Conformance
	         * (https://html.spec.whatwg.org/#htmltableheadercellelement)
	         * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
	         * Note: Most browsers currently adher to the W3C DOM Level 2 spec
	         *       (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
	         *       which suggests that browsers should use HTMLTableCellElement for
	         *       both TD and TH elements. WhatWG separates these.
	         * Test: Object.prototype.toString.call(document.createElement('th'))
	         *  - Chrome === "[object HTMLTableCellElement]"
	         *  - Firefox === "[object HTMLTableCellElement]"
	         *  - Safari === "[object HTMLTableCellElement]"
	         */
	        if (obj.tagName === 'TH') {
	          return 'HTMLTableHeaderCellElement';
	        }
	      }
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   Float64Array       x 625,644 ops/sec ±1.58% (80 runs sampled)
	    *   Float32Array       x 1,279,852 ops/sec ±2.91% (77 runs sampled)
	    *   Uint32Array        x 1,178,185 ops/sec ±1.95% (83 runs sampled)
	    *   Uint16Array        x 1,008,380 ops/sec ±2.25% (80 runs sampled)
	    *   Uint8Array         x 1,128,040 ops/sec ±2.11% (81 runs sampled)
	    *   Int32Array         x 1,170,119 ops/sec ±2.88% (80 runs sampled)
	    *   Int16Array         x 1,176,348 ops/sec ±5.79% (86 runs sampled)
	    *   Int8Array          x 1,058,707 ops/sec ±4.94% (77 runs sampled)
	    *   Uint8ClampedArray  x 1,110,633 ops/sec ±4.20% (80 runs sampled)
	    * Post:
	    *   Float64Array       x 7,105,671 ops/sec ±13.47% (64 runs sampled)
	    *   Float32Array       x 5,887,912 ops/sec ±1.46% (82 runs sampled)
	    *   Uint32Array        x 6,491,661 ops/sec ±1.76% (79 runs sampled)
	    *   Uint16Array        x 6,559,795 ops/sec ±1.67% (82 runs sampled)
	    *   Uint8Array         x 6,463,966 ops/sec ±1.43% (85 runs sampled)
	    *   Int32Array         x 5,641,841 ops/sec ±3.49% (81 runs sampled)
	    *   Int16Array         x 6,583,511 ops/sec ±1.98% (80 runs sampled)
	    *   Int8Array          x 6,606,078 ops/sec ±1.74% (81 runs sampled)
	    *   Uint8ClampedArray  x 6,602,224 ops/sec ±1.77% (83 runs sampled)
	    */
	    var stringTag = symbolToStringTagExists && obj[Symbol.toStringTag];
	    if (typeof stringTag === 'string') {
	      return stringTag;
	    }
	    var objPrototype = Object.getPrototypeOf(obj);
	    /* ! Speed optimisation
	    * Pre:
	    *   regex literal      x 1,772,385 ops/sec ±1.85% (77 runs sampled)
	    *   regex constructor  x 2,143,634 ops/sec ±2.46% (78 runs sampled)
	    * Post:
	    *   regex literal      x 3,928,009 ops/sec ±0.65% (78 runs sampled)
	    *   regex constructor  x 3,931,108 ops/sec ±0.58% (84 runs sampled)
	    */
	    if (objPrototype === RegExp.prototype) {
	      return 'RegExp';
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   date               x 2,130,074 ops/sec ±4.42% (68 runs sampled)
	    * Post:
	    *   date               x 3,953,779 ops/sec ±1.35% (77 runs sampled)
	    */
	    if (objPrototype === Date.prototype) {
	      return 'Date';
	    }

	    /* ! Spec Conformance
	     * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
	     * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
	     * Test: `Object.prototype.toString.call(Promise.resolve())``
	     *  - Chrome <=47 === "[object Object]"
	     *  - Edge <=20 === "[object Object]"
	     *  - Firefox 29-Latest === "[object Promise]"
	     *  - Safari 7.1-Latest === "[object Promise]"
	     */
	    if (promiseExists && objPrototype === Promise.prototype) {
	      return 'Promise';
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   set                x 2,222,186 ops/sec ±1.31% (82 runs sampled)
	    * Post:
	    *   set                x 4,545,879 ops/sec ±1.13% (83 runs sampled)
	    */
	    if (setExists && objPrototype === Set.prototype) {
	      return 'Set';
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   map                x 2,396,842 ops/sec ±1.59% (81 runs sampled)
	    * Post:
	    *   map                x 4,183,945 ops/sec ±6.59% (82 runs sampled)
	    */
	    if (mapExists && objPrototype === Map.prototype) {
	      return 'Map';
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   weakset            x 1,323,220 ops/sec ±2.17% (76 runs sampled)
	    * Post:
	    *   weakset            x 4,237,510 ops/sec ±2.01% (77 runs sampled)
	    */
	    if (weakSetExists && objPrototype === WeakSet.prototype) {
	      return 'WeakSet';
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   weakmap            x 1,500,260 ops/sec ±2.02% (78 runs sampled)
	    * Post:
	    *   weakmap            x 3,881,384 ops/sec ±1.45% (82 runs sampled)
	    */
	    if (weakMapExists && objPrototype === WeakMap.prototype) {
	      return 'WeakMap';
	    }

	    /* ! Spec Conformance
	     * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
	     * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
	     * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
	     *  - Edge <=13 === "[object Object]"
	     */
	    if (dataViewExists && objPrototype === DataView.prototype) {
	      return 'DataView';
	    }

	    /* ! Spec Conformance
	     * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
	     * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
	     * Test: `Object.prototype.toString.call(new Map().entries())``
	     *  - Edge <=13 === "[object Object]"
	     */
	    if (mapExists && objPrototype === mapIteratorPrototype) {
	      return 'Map Iterator';
	    }

	    /* ! Spec Conformance
	     * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
	     * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
	     * Test: `Object.prototype.toString.call(new Set().entries())``
	     *  - Edge <=13 === "[object Object]"
	     */
	    if (setExists && objPrototype === setIteratorPrototype) {
	      return 'Set Iterator';
	    }

	    /* ! Spec Conformance
	     * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
	     * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
	     * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
	     *  - Edge <=13 === "[object Object]"
	     */
	    if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
	      return 'Array Iterator';
	    }

	    /* ! Spec Conformance
	     * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
	     * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
	     * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
	     *  - Edge <=13 === "[object Object]"
	     */
	    if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
	      return 'String Iterator';
	    }

	    /* ! Speed optimisation
	    * Pre:
	    *   object from null   x 2,424,320 ops/sec ±1.67% (76 runs sampled)
	    * Post:
	    *   object from null   x 5,838,000 ops/sec ±0.99% (84 runs sampled)
	    */
	    if (objPrototype === null) {
	      return 'Object';
	    }
	    return Object.prototype.toString.call(obj).slice(toStringLeftSliceLength, toStringRightSliceLength);
	  }
	  return typeDetect;
	}); 
} (typeDetect$1));

var typeDetectExports = typeDetect$1.exports;
var typeDetect = /*@__PURE__*/getDefaultExportFromCjs(typeDetectExports);

const isBufferExists = typeof Buffer !== 'undefined';
const isBufferFromExists = isBufferExists && typeof Buffer.from !== 'undefined';

const isBuffer$5 = isBufferExists
  ? /**
     * is value is Buffer?
     *
     * @param {*} value
     * @return {boolean}
     */
    function isBuffer(value) {
      return Buffer.isBuffer(value);
    }
  : /**
     * return false
     *
     * NOTE: for Buffer unsupported
     *
     * @return {boolean}
     */
    function isBuffer() {
      return false;
    };

const copy$2 = isBufferFromExists
  ? /**
     * copy Buffer
     *
     * @param {Buffer} value
     * @return {Buffer}
     */
    function copy(value) {
      return Buffer.from(value);
    }
  : isBufferExists
  ? /**
     * copy Buffer
     *
     * NOTE: for old node.js
     *
     * @param {Buffer} value
     * @return {Buffer}
     */
    function copy(value) {
      return new Buffer(value);
    }
  : /**
     * shallow copy
     *
     * NOTE: for Buffer unsupported
     *
     * @param {*}
     * @return {*}
     */
    function copy(value) {
      return value;
    };

/**
 * detect type of value
 *
 * @param {*} value
 * @return {string}
 */
function detectType(value) {
  // NOTE: isBuffer must execute before type-detect,
  // because type-detect returns 'Uint8Array'.
  if (isBuffer$5(value)) {
    return 'Buffer';
  }

  return typeDetect(value);
}

/**
 * collection types
 */
const collectionTypeSet = new Set([
  'Arguments',
  'Array',
  'Map',
  'Object',
  'Set'
]);

/**
 * get value from collection
 *
 * @param {Array|Object|Map|Set} collection
 * @param {string|number|symbol} key
 * @param {string} [type=null]
 * @return {*}
 */
function get$2(collection, key, type = null) {
  const valueType = type || detectType(collection);

  switch (valueType) {
    case 'Arguments':
    case 'Array':
    case 'Object':
      return collection[key];
    case 'Map':
      return collection.get(key);
    case 'Set':
      // NOTE: Set.prototype.keys is alias of Set.prototype.values
      // it means key is equals value
      return key;
  }
}

/**
 * check to type string is collection
 *
 * @param {string} type
 */
function isCollection(type) {
  return collectionTypeSet.has(type);
}

/**
 * set value to collection
 *
 * @param {Array|Object|Map|Set} collection
 * @param {string|number|symbol} key
 * @param {*} value
 * @param {string} [type=null]
 * @return {Array|Object|Map|Set}
 */
function set(collection, key, value, type = null) {
  const valueType = type || detectType(collection);

  switch (valueType) {
    case 'Arguments':
    case 'Array':
    case 'Object':
      collection[key] = value;
      break;
    case 'Map':
      collection.set(key, value);
      break;
    case 'Set':
      collection.add(value);
      break;
  }

  return collection;
}

const freeGlobalThis =
  typeof globalThis !== 'undefined' &&
  globalThis !== null &&
  globalThis.Object === Object &&
  globalThis;

const freeGlobal$4 =
  typeof global !== 'undefined' &&
  global !== null &&
  global.Object === Object &&
  global;

const freeSelf$2 =
  typeof self !== 'undefined' &&
  self !== null &&
  self.Object === Object &&
  self;

const globalObject =
  freeGlobalThis || freeGlobal$4 || freeSelf$2 || Function('return this')();

/**
 * copy ArrayBuffer
 *
 * @param {ArrayBuffer} value
 * @return {ArrayBuffer}
 */
function copyArrayBuffer(value) {
  return value.slice(0);
}

/**
 * copy Boolean
 *
 * @param {Boolean} value
 * @return {Boolean}
 */
function copyBoolean(value) {
  return new Boolean(value.valueOf());
}

/**
 * copy DataView
 *
 * @param {DataView} value
 * @return {DataView}
 */
function copyDataView(value) {
  // TODO: copy ArrayBuffer?
  return new DataView(value.buffer);
}

/**
 * copy Buffer
 *
 * @param {Buffer} value
 * @return {Buffer}
 */
function copyBuffer(value) {
  return copy$2(value);
}

/**
 * copy Date
 *
 * @param {Date} value
 * @return {Date}
 */
function copyDate(value) {
  return new Date(value.getTime());
}

/**
 * copy Number
 *
 * @param {Number} value
 * @return {Number}
 */
function copyNumber(value) {
  return new Number(value);
}

/**
 * copy RegExp
 *
 * @param {RegExp} value
 * @return {RegExp}
 */
function copyRegExp(value) {
  return new RegExp(value.source, value.flags);
}

/**
 * copy String
 *
 * @param {String} value
 * @return {String}
 */
function copyString(value) {
  return new String(value);
}

/**
 * copy TypedArray
 *
 * @param {*} value
 * @return {*}
 */
function copyTypedArray(value, type) {
  const typedArray = globalObject[type];

  if (typedArray.from) {
    return globalObject[type].from(value);
  }

  return new globalObject[type](value);
}

/**
 * shallow copy
 *
 * @param {*} value
 * @return {*}
 */
function shallowCopy(value) {
  return value;
}

/**
 * get empty Array
 *
 * @return {Array}
 */
function getEmptyArray() {
  return [];
}

/**
 * get empty Map
 *
 * @return {Map}
 */
function getEmptyMap() {
  return new Map();
}

/**
 * get empty Object
 *
 * @return {Object}
 */
function getEmptyObject() {
  return {};
}

/**
 * get empty Set
 *
 * @return {Set}
 */
function getEmptySet() {
  return new Set();
}

var copyMap = new Map([
  // deep copy
  ['ArrayBuffer', copyArrayBuffer],
  ['Boolean', copyBoolean],
  ['Buffer', copyBuffer],
  ['DataView', copyDataView],
  ['Date', copyDate],
  ['Number', copyNumber],
  ['RegExp', copyRegExp],
  ['String', copyString],

  // typed arrays
  // TODO: pass bound function
  ['Float32Array', copyTypedArray],
  ['Float64Array', copyTypedArray],
  ['Int16Array', copyTypedArray],
  ['Int32Array', copyTypedArray],
  ['Int8Array', copyTypedArray],
  ['Uint16Array', copyTypedArray],
  ['Uint32Array', copyTypedArray],
  ['Uint8Array', copyTypedArray],
  ['Uint8ClampedArray', copyTypedArray],

  // shallow copy
  ['Array Iterator', shallowCopy],
  ['Map Iterator', shallowCopy],
  ['Promise', shallowCopy],
  ['Set Iterator', shallowCopy],
  ['String Iterator', shallowCopy],
  ['function', shallowCopy],
  ['global', shallowCopy],
  // NOTE: WeakMap and WeakSet cannot get entries
  ['WeakMap', shallowCopy],
  ['WeakSet', shallowCopy],

  // primitives
  ['boolean', shallowCopy],
  ['null', shallowCopy],
  ['number', shallowCopy],
  ['string', shallowCopy],
  ['symbol', shallowCopy],
  ['undefined', shallowCopy],

  // collections
  // NOTE: return empty value, because recursively copy later.
  ['Arguments', getEmptyArray],
  ['Array', getEmptyArray],
  ['Map', getEmptyMap],
  ['Object', getEmptyObject],
  ['Set', getEmptySet]

  // NOTE: type-detect returns following types
  // 'Location'
  // 'Document'
  // 'MimeTypeArray'
  // 'PluginArray'
  // 'HTMLQuoteElement'
  // 'HTMLTableDataCellElement'
  // 'HTMLTableHeaderCellElement'

  // TODO: is type-detect never return 'object'?
  // 'object'
]);

/**
 * no operation
 */
function noop$1() {}

/**
 * copy value
 *
 * @param {*} value
 * @param {string} [type=null]
 * @param {Function} [customizer=noop]
 * @return {*}
 */
function copy$1(value, type = null, customizer = noop$1) {
  if (arguments.length === 2 && typeof type === 'function') {
    customizer = type;
    type = null;
  }

  const valueType = type || detectType(value);
  const copyFunction = copyMap.get(valueType);

  if (valueType === 'Object') {
    const result = customizer(value, valueType);

    if (result !== undefined) {
      return result;
    }
  }

  // NOTE: TypedArray needs pass type to argument
  return copyFunction ? copyFunction(value, valueType) : value;
}

/**
 * deepcopy function
 *
 * @param {*} value
 * @param {Object|Function} [options]
 * @return {*}
 */
function deepcopy(value, options = {}) {
  if (typeof options === 'function') {
    options = {
      customizer: options
    };
  }

  const {
    // TODO: before/after customizer
    customizer
    // TODO: max depth
    // depth = Infinity,
  } = options;

  const valueType = detectType(value);

  if (!isCollection(valueType)) {
    return recursiveCopy(value, null, null, null);
  }

  const copiedValue = copy$1(value, valueType, customizer);

  const references = new WeakMap([[value, copiedValue]]);
  const visited = new WeakSet([value]);

  return recursiveCopy(value, copiedValue, references, visited);
}

/**
 * recursively copy
 *
 * @param {*} value target value
 * @param {*} clone clone of value
 * @param {WeakMap} references visited references of clone
 * @param {WeakSet} visited visited references of value
 * @param {Function} customizer user customize function
 * @return {*}
 */
function recursiveCopy(value, clone, references, visited, customizer) {
  const type = detectType(value);
  const copiedValue = copy$1(value, type);

  // return if not a collection value
  if (!isCollection(type)) {
    return copiedValue;
  }

  let keys;

  switch (type) {
    case 'Arguments':
    case 'Array':
      keys = Object.keys(value);
      break;
    case 'Object':
      keys = Object.keys(value);
      keys.push(...Object.getOwnPropertySymbols(value));
      break;
    case 'Map':
    case 'Set':
      keys = value.keys();
      break;
  }

  // walk within collection with iterator
  for (let collectionKey of keys) {
    const collectionValue = get$2(value, collectionKey, type);

    if (visited.has(collectionValue)) {
      // for [Circular]
      set(clone, collectionKey, references.get(collectionValue), type);
    } else {
      const collectionValueType = detectType(collectionValue);
      const copiedCollectionValue = copy$1(collectionValue, collectionValueType);

      // save reference if value is collection
      if (isCollection(collectionValueType)) {
        references.set(collectionValue, copiedCollectionValue);
        visited.add(collectionValue);
      }

      set(
        clone,
        collectionKey,
        recursiveCopy(
          collectionValue,
          copiedCollectionValue,
          references,
          visited),
        type
      );
    }
  }

  // TODO: isSealed/isFrozen/isExtensible

  return clone;
}

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, _toPropertyKey$1(descriptor.key), descriptor);
  }
}
function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", {
    writable: false
  });
  return Constructor;
}

function _arrayWithHoles$1(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArrayLimit$1(arr, i) {
  var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (_x = (_i = _i.call(arr)).next, 0 === i) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
    } catch (err) {
      _d = !0, _e = err;
    } finally {
      try {
        if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}

function _arrayLikeToArray$1(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}

function _unsupportedIterableToArray$1(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
}

function _nonIterableRest$1() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function _slicedToArray$1(arr, i) {
  return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$1();
}

function _arrayWithoutHoles$1(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
}

function _iterableToArray$1(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}

function _nonIterableSpread$1() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function _toConsumableArray$1(arr) {
  return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1();
}

/**
 * A special placeholder value used to specify "gaps" within curried functions,
 * allowing partial application of any combination of arguments, regardless of
 * their positions.
 *
 * If `g` is a curried ternary function and `_` is `R.__`, the following are
 * equivalent:
 *
 *   - `g(1, 2, 3)`
 *   - `g(_, 2, 3)(1)`
 *   - `g(_, _, 3)(1)(2)`
 *   - `g(_, _, 3)(1, 2)`
 *   - `g(_, 2, _)(1, 3)`
 *   - `g(_, 2)(1)(3)`
 *   - `g(_, 2)(1, 3)`
 *   - `g(_, 2)(_, 3)(1)`
 *
 * @name __
 * @constant
 * @memberOf R
 * @since v0.6.0
 * @category Function
 * @example
 *
 *      const greet = R.replace('{name}', R.__, 'Hello, {name}!');
 *      greet('Alice'); //=> 'Hello, Alice!'
 */
var placeholder = {
  '@@functional/placeholder': true
};

function _isPlaceholder(a) {
  return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true;
}

/**
 * Optimized internal one-arity curry function.
 *
 * @private
 * @category Function
 * @param {Function} fn The function to curry.
 * @return {Function} The curried function.
 */
function _curry1(fn) {
  return function f1(a) {
    if (arguments.length === 0 || _isPlaceholder(a)) {
      return f1;
    } else {
      return fn.apply(this, arguments);
    }
  };
}

/**
 * Optimized internal two-arity curry function.
 *
 * @private
 * @category Function
 * @param {Function} fn The function to curry.
 * @return {Function} The curried function.
 */
function _curry2(fn) {
  return function f2(a, b) {
    switch (arguments.length) {
      case 0:
        return f2;
      case 1:
        return _isPlaceholder(a) ? f2 : _curry1(function (_b) {
          return fn(a, _b);
        });
      default:
        return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {
          return fn(_a, b);
        }) : _isPlaceholder(b) ? _curry1(function (_b) {
          return fn(a, _b);
        }) : fn(a, b);
    }
  };
}

function _arity(n, fn) {
  /* eslint-disable no-unused-vars */
  switch (n) {
    case 0:
      return function () {
        return fn.apply(this, arguments);
      };
    case 1:
      return function (a0) {
        return fn.apply(this, arguments);
      };
    case 2:
      return function (a0, a1) {
        return fn.apply(this, arguments);
      };
    case 3:
      return function (a0, a1, a2) {
        return fn.apply(this, arguments);
      };
    case 4:
      return function (a0, a1, a2, a3) {
        return fn.apply(this, arguments);
      };
    case 5:
      return function (a0, a1, a2, a3, a4) {
        return fn.apply(this, arguments);
      };
    case 6:
      return function (a0, a1, a2, a3, a4, a5) {
        return fn.apply(this, arguments);
      };
    case 7:
      return function (a0, a1, a2, a3, a4, a5, a6) {
        return fn.apply(this, arguments);
      };
    case 8:
      return function (a0, a1, a2, a3, a4, a5, a6, a7) {
        return fn.apply(this, arguments);
      };
    case 9:
      return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
        return fn.apply(this, arguments);
      };
    case 10:
      return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
        return fn.apply(this, arguments);
      };
    default:
      throw new Error('First argument to _arity must be a non-negative integer no greater than ten');
  }
}

/**
 * Internal curryN function.
 *
 * @private
 * @category Function
 * @param {Number} length The arity of the curried function.
 * @param {Array} received An array of arguments received thus far.
 * @param {Function} fn The function to curry.
 * @return {Function} The curried function.
 */
function _curryN(length, received, fn) {
  return function () {
    var combined = [];
    var argsIdx = 0;
    var left = length;
    var combinedIdx = 0;
    while (combinedIdx < received.length || argsIdx < arguments.length) {
      var result;
      if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) {
        result = received[combinedIdx];
      } else {
        result = arguments[argsIdx];
        argsIdx += 1;
      }
      combined[combinedIdx] = result;
      if (!_isPlaceholder(result)) {
        left -= 1;
      }
      combinedIdx += 1;
    }
    return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn));
  };
}

/**
 * Returns a curried equivalent of the provided function, with the specified
 * arity. The curried function has two unusual capabilities. First, its
 * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the
 * following are equivalent:
 *
 *   - `g(1)(2)(3)`
 *   - `g(1)(2, 3)`
 *   - `g(1, 2)(3)`
 *   - `g(1, 2, 3)`
 *
 * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
 * "gaps", allowing partial application of any combination of arguments,
 * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
 * the following are equivalent:
 *
 *   - `g(1, 2, 3)`
 *   - `g(_, 2, 3)(1)`
 *   - `g(_, _, 3)(1)(2)`
 *   - `g(_, _, 3)(1, 2)`
 *   - `g(_, 2)(1)(3)`
 *   - `g(_, 2)(1, 3)`
 *   - `g(_, 2)(_, 3)(1)`
 *
 * @func
 * @memberOf R
 * @since v0.5.0
 * @category Function
 * @sig Number -> (* -> a) -> (* -> a)
 * @param {Number} length The arity for the returned function.
 * @param {Function} fn The function to curry.
 * @return {Function} A new, curried function.
 * @see R.curry
 * @example
 *
 *      const sumArgs = (...args) => R.sum(args);
 *
 *      const curriedAddFourNumbers = R.curryN(4, sumArgs);
 *      const f = curriedAddFourNumbers(1, 2);
 *      const g = f(3);
 *      g(4); //=> 10
 */
var curryN = /*#__PURE__*/_curry2(function curryN(length, fn) {
  if (length === 1) {
    return _curry1(fn);
  }
  return _arity(length, _curryN(length, [], fn));
});
var curryN$1 = curryN;

/**
 * Returns a curried equivalent of the provided function. The curried function
 * has two unusual capabilities. First, its arguments needn't be provided one
 * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the
 * following are equivalent:
 *
 *   - `g(1)(2)(3)`
 *   - `g(1)(2, 3)`
 *   - `g(1, 2)(3)`
 *   - `g(1, 2, 3)`
 *
 * Secondly, the special placeholder value [`R.__`](#__) may be used to specify
 * "gaps", allowing partial application of any combination of arguments,
 * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
 * the following are equivalent:
 *
 *   - `g(1, 2, 3)`
 *   - `g(_, 2, 3)(1)`
 *   - `g(_, _, 3)(1)(2)`
 *   - `g(_, _, 3)(1, 2)`
 *   - `g(_, 2)(1)(3)`
 *   - `g(_, 2)(1, 3)`
 *   - `g(_, 2)(_, 3)(1)`
 *
 * @func
 * @memberOf R
 * @since v0.1.0
 * @category Function
 * @sig (* -> a) -> (* -> a)
 * @param {Function} fn The function to curry.
 * @return {Function} A new, curried function.
 * @see R.curryN, R.partial
 * @example
 *
 *      const addFourNumbers = (a, b, c, d) => a + b + c + d;
 *
 *      const curriedAddFourNumbers = R.curry(addFourNumbers);
 *      const f = curriedAddFourNumbers(1, 2);
 *      const g = f(3);
 *      g(4); //=> 10
 */
var curry = /*#__PURE__*/_curry1(function curry(fn) {
  return curryN$1(fn.length, fn);
});
var curry$1 = curry;

function forOwn(obj, fn) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      fn(obj[key], key);
    }
  }
}
function isArrayLike$6(value) {
  return value && _typeof$c(value) === 'object' && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0;
}
var OWNER_ID_TAG = '@@_______immutableOpsOwnerID';
function fastArrayCopy(arr) {
  var copied = new Array(arr.length);
  for (var i = 0; i < arr.length; i++) {
    copied[i] = arr[i];
  }
  return copied;
}
function canMutate(obj, ownerID) {
  if (!ownerID) return false;
  return obj[OWNER_ID_TAG] === ownerID;
}
var newOwnerID = typeof Symbol === 'function' ? function () {
  return Symbol('ownerID');
} : function () {
  return {};
};
var getBatchToken = newOwnerID;
function addOwnerID(obj, ownerID) {
  Object.defineProperty(obj, OWNER_ID_TAG, {
    value: ownerID,
    configurable: true,
    enumerable: false
  });
  return obj;
}
function prepareNewObject(instance, ownerID) {
  if (ownerID) {
    addOwnerID(instance, ownerID);
  }
  return instance;
}
function forceArray(arg) {
  if (!(arg instanceof Array)) {
    return [arg];
  }
  return arg;
}
var PATH_SEPARATOR = '.';
function normalizePath(pathArg) {
  if (typeof pathArg === 'string') {
    if (pathArg.indexOf(PATH_SEPARATOR) === -1) {
      return [pathArg];
    }
    return pathArg.split(PATH_SEPARATOR);
  }
  return pathArg;
}
function mutableSet(key, value, obj) {
  obj[key] = value;
  return obj;
}
function mutableSetIn(_pathArg, value, obj) {
  var originalPathArg = normalizePath(_pathArg);
  var pathLen = originalPathArg.length;
  var done = false;
  var idx = 0;
  var acc = obj;
  var curr = originalPathArg[idx];
  while (!done) {
    if (idx === pathLen - 1) {
      acc[curr] = value;
      done = true;
    } else {
      var currType = _typeof$c(acc[curr]);
      if (currType === 'undefined') {
        var newObj = {};
        prepareNewObject(newObj, null);
        acc[curr] = newObj;
      } else if (currType !== 'object') {
        var pathRepr = "".concat(originalPathArg[idx - 1], ".").concat(curr);
        throw new Error("A non-object value was encountered when traversing setIn path at ".concat(pathRepr, "."));
      }
      acc = acc[curr];
      idx++;
      curr = originalPathArg[idx];
    }
  }
  return obj;
}
function valueInPath(_pathArg, obj) {
  var pathArg = normalizePath(_pathArg);
  var acc = obj;
  for (var i = 0; i < pathArg.length; i++) {
    var curr = pathArg[i];
    var currRef = acc[curr];
    if (i === pathArg.length - 1) {
      return currRef;
    }
    if (_typeof$c(currRef) === 'object') {
      acc = currRef;
    } else {
      return undefined;
    }
  }
  return undefined;
}
function immutableSetIn(ownerID, _pathArg, value, obj) {
  var pathArg = normalizePath(_pathArg);
  var currentValue = valueInPath(pathArg, obj);
  if (value === currentValue) return obj;
  var pathLen = pathArg.length;
  var acc;
  if (canMutate(obj, ownerID)) {
    acc = obj;
  } else {
    acc = Object.assign(prepareNewObject({}, ownerID), obj);
  }
  var rootObj = acc;
  pathArg.forEach(function (curr, idx) {
    if (idx === pathLen - 1) {
      acc[curr] = value;
      return;
    }
    var currRef = acc[curr];
    var currType = _typeof$c(currRef);
    if (currType === 'object') {
      if (canMutate(currRef, ownerID)) {
        acc = currRef;
      } else {
        var newObj = prepareNewObject({}, ownerID);
        acc[curr] = Object.assign(newObj, currRef);
        acc = newObj;
      }
      return;
    }
    if (currType === 'undefined') {
      var _newObj = prepareNewObject({}, ownerID);
      acc[curr] = _newObj;
      acc = _newObj;
      return;
    }
    var pathRepr = "".concat(pathArg[idx - 1], ".").concat(curr);
    throw new Error("A non-object value was encountered when traversing setIn path at ".concat(pathRepr, "."));
  });
  return rootObj;
}
function mutableMerge(isDeep, _mergeObjs, baseObj) {
  var mergeObjs = forceArray(_mergeObjs);
  if (isDeep) {
    mergeObjs.forEach(function (mergeObj) {
      forOwn(mergeObj, function (value, key) {
        if (isDeep && baseObj.hasOwnProperty(key)) {
          var assignValue;
          if (_typeof$c(value) === 'object') {
            assignValue = mutableMerge(isDeep, [value], baseObj[key]);
          } else {
            assignValue = value;
          }
          baseObj[key] = assignValue;
        } else {
          baseObj[key] = value;
        }
      });
    });
  } else {
    Object.assign.apply(Object, [baseObj].concat(_toConsumableArray$1(mergeObjs)));
  }
  return baseObj;
}
var mutableShallowMerge = mutableMerge.bind(null, false);
var mutableDeepMerge = mutableMerge.bind(null, true);
function mutableOmit(_keys, obj) {
  var keys = forceArray(_keys);
  keys.forEach(function (key) {
    delete obj[key];
  });
  return obj;
}
function shouldMergeKey(obj, other, key) {
  return obj[key] !== other[key];
}
function immutableMerge(isDeep, ownerID, _mergeObjs, obj) {
  if (canMutate(obj, ownerID)) return mutableMerge(isDeep, _mergeObjs, obj);
  var mergeObjs = forceArray(_mergeObjs);
  var hasChanges = false;
  var nextObject = obj;
  var willChange = function willChange() {
    if (!hasChanges) {
      hasChanges = true;
      nextObject = Object.assign({}, obj);
      prepareNewObject(nextObject, ownerID);
    }
  };
  mergeObjs.forEach(function (mergeObj) {
    forOwn(mergeObj, function (mergeValue, key) {
      if (isDeep && obj.hasOwnProperty(key)) {
        var currentValue = nextObject[key];
        if (_typeof$c(mergeValue) === 'object' && !(mergeValue instanceof Array)) {
          if (shouldMergeKey(nextObject, mergeObj, key)) {
            var recursiveMergeResult = immutableMerge(isDeep, ownerID, mergeValue, currentValue);
            if (recursiveMergeResult !== currentValue) {
              willChange();
              nextObject[key] = recursiveMergeResult;
            }
          }
          return true; // continue forOwn
        }
      }

      if (shouldMergeKey(nextObject, mergeObj, key)) {
        willChange();
        nextObject[key] = mergeValue;
      }
      return undefined;
    });
  });
  return nextObject;
}
var immutableDeepMerge = immutableMerge.bind(null, true);
var immutableShallowMerge = immutableMerge.bind(null, false);
function immutableArrSet(ownerID, index, value, arr) {
  if (canMutate(arr, ownerID)) return mutableSet(index, value, arr);
  if (arr[index] === value) return arr;
  var newArr = fastArrayCopy(arr);
  newArr[index] = value;
  prepareNewObject(newArr, ownerID);
  return newArr;
}
function immutableSet(ownerID, key, value, obj) {
  if (isArrayLike$6(obj)) return immutableArrSet(ownerID, key, value, obj);
  if (canMutate(obj, ownerID)) return mutableSet(key, value, obj);
  if (obj[key] === value) return obj;
  var newObj = Object.assign({}, obj);
  prepareNewObject(newObj, ownerID);
  newObj[key] = value;
  return newObj;
}
function immutableOmit(ownerID, _keys, obj) {
  if (canMutate(obj, ownerID)) return mutableOmit(_keys, obj);
  var keys = forceArray(_keys);
  var keysInObj = keys.filter(function (key) {
    return obj.hasOwnProperty(key);
  }); // None of the keys were in the object, so we can return `obj`.

  if (keysInObj.length === 0) return obj;
  var newObj = Object.assign({}, obj);
  keysInObj.forEach(function (key) {
    delete newObj[key];
  });
  prepareNewObject(newObj, ownerID);
  return newObj;
}
function mutableArrPush(_vals, arr) {
  var vals = forceArray(_vals);
  arr.push.apply(arr, _toConsumableArray$1(vals));
  return arr;
}
function mutableArrFilter(func, arr) {
  var currIndex = 0;
  var originalIndex = 0;
  while (currIndex < arr.length) {
    var item = arr[currIndex];
    if (!func(item, originalIndex)) {
      arr.splice(currIndex, 1);
    } else {
      currIndex++;
    }
    originalIndex++;
  }
  return arr;
}
function mutableArrSplice(index, deleteCount, _vals, arr) {
  var vals = forceArray(_vals);
  arr.splice.apply(arr, [index, deleteCount].concat(_toConsumableArray$1(vals)));
  return arr;
}
function mutableArrInsert(index, _vals, arr) {
  return mutableArrSplice(index, 0, _vals, arr);
}
function immutableArrSplice(ownerID, index, deleteCount, _vals, arr) {
  if (canMutate(arr, ownerID)) return mutableArrSplice(index, deleteCount, _vals, arr);
  var vals = forceArray(_vals);
  var newArr = arr.slice();
  prepareNewObject(newArr, ownerID);
  newArr.splice.apply(newArr, [index, deleteCount].concat(_toConsumableArray$1(vals)));
  return newArr;
}
function immutableArrInsert(ownerID, index, _vals, arr) {
  if (canMutate(arr, ownerID)) return mutableArrInsert(index, _vals, arr);
  return immutableArrSplice(ownerID, index, 0, _vals, arr);
}
function immutableArrPush(ownerID, vals, arr) {
  return immutableArrInsert(ownerID, arr.length, vals, arr);
}
function immutableArrFilter(ownerID, func, arr) {
  if (canMutate(arr, ownerID)) return mutableArrFilter(func, arr);
  var newArr = arr.filter(func);
  if (newArr.length === arr.length) return arr;
  prepareNewObject(newArr, ownerID);
  return newArr;
}
var immutableOperations = {
  // object operations
  merge: immutableShallowMerge,
  deepMerge: immutableDeepMerge,
  omit: immutableOmit,
  setIn: immutableSetIn,
  // array operations
  insert: immutableArrInsert,
  push: immutableArrPush,
  filter: immutableArrFilter,
  splice: immutableArrSplice,
  // both
  set: immutableSet
};
var mutableOperations = {
  // object operations
  merge: mutableShallowMerge,
  deepMerge: mutableDeepMerge,
  omit: mutableOmit,
  setIn: mutableSetIn,
  // array operations
  insert: mutableArrInsert,
  push: mutableArrPush,
  filter: mutableArrFilter,
  splice: mutableArrSplice,
  // both
  set: mutableSet
};
function getImmutableOps() {
  var immutableOps = Object.assign({}, immutableOperations);
  forOwn(immutableOps, function (value, key) {
    immutableOps[key] = curry$1(value.bind(null, null));
  });
  var mutableOps = Object.assign({}, mutableOperations);
  forOwn(mutableOps, function (value, key) {
    mutableOps[key] = curry$1(value);
  });
  var batchOps = Object.assign({}, immutableOperations);
  forOwn(batchOps, function (value, key) {
    batchOps[key] = curry$1(value);
  });
  function batched(_token, _fn) {
    var token;
    var fn;
    if (typeof _token === 'function') {
      fn = _token;
      token = getBatchToken();
    } else {
      token = _token;
      fn = _fn;
    }
    var immutableOpsBoundToToken = Object.assign({}, immutableOperations);
    forOwn(immutableOpsBoundToToken, function (value, key) {
      immutableOpsBoundToToken[key] = curry$1(value.bind(null, token));
    });
    return fn(immutableOpsBoundToToken);
  }
  return Object.assign(immutableOps, {
    mutable: mutableOps,
    batch: batchOps,
    batched: batched,
    __: placeholder,
    getBatchToken: getBatchToken
  });
}
var ops = getImmutableOps();

var UPDATE$2 = "REDUX_ORM_UPDATE";
var DELETE$2 = "REDUX_ORM_DELETE";
var CREATE$1 = "REDUX_ORM_CREATE";
var FILTER = "REDUX_ORM_FILTER";
var EXCLUDE = "REDUX_ORM_EXCLUDE";
var ORDER_BY = "REDUX_ORM_ORDER_BY";
var SUCCESS$2 = "SUCCESS";

var STATE_FLAG = "@@_______REDUX_ORM_STATE_FLAG"; // for detecting keyed selectors and storing the corresponding model

var KEYED_SELECTOR_MARKER = "@@_______REDUX_ORM_KEYED_SELECTOR"; // for caching selectors based on their ID argument

var ALL_INSTANCES = Symbol("REDUX_ORM_ALL_INSTANCES");
var ID_ARG_KEY_SELECTOR = function ID_ARG_KEY_SELECTOR(_state, idArg) {
  return typeof idArg === "undefined" ? ALL_INSTANCES : idArg;
};
var EMPTY_ARRAY = Object.freeze([]);

/**
 * @module utils
 * @private
 */

/** @private */

function warnDeprecated(msg) {
  var logger = typeof console.warn === "function" ? console.warn.bind(console) : console.log.bind(console);
  return logger(msg);
}
/** @private */

function capitalize$1(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
 * Returns the branch name for a many-to-many relation.
 * The name is the combination of the model name and the field name the relation
 * was declared. The field name's first letter is capitalized.
 *
 * Example: model `Author` has a many-to-many relation to the model `Book`, defined
 * in the `Author` field `books`. The many-to-many branch name will be `AuthorBooks`.
 *
 * @param  {string} declarationModelName - the name of the model the many-to-many relation was declared on
 * @param  {string} fieldName            - the field name where the many-to-many relation was declared on
 * @return {string} The branch name for the many-to-many relation.
 */

function m2mName(declarationModelName, fieldName) {
  return declarationModelName + capitalize$1(fieldName);
}
/**
 * Returns the fieldname that saves a foreign key to the
 * model id where the many-to-many relation was declared.
 *
 * Example: `Author` => `fromAuthorId`
 *
 * @param  {string} declarationModelName - the name of the model where the relation was declared
 * @return {string} the field name in the through model for `declarationModelName`'s foreign key.
 */

function m2mFromFieldName(declarationModelName) {
  return "from".concat(declarationModelName, "Id");
}
/**
 * Returns the fieldname that saves a foreign key in a many-to-many through model to the
 * model where the many-to-many relation was declared.
 *
 * Example: `Book` => `toBookId`
 *
 * @param  {string} otherModelName - the name of the model that was the target of the many-to-many
 *                                   declaration.
 * @return {string} the field name in the through model for `otherModelName`'s foreign key..
 */

function m2mToFieldName(otherModelName) {
  return "to".concat(otherModelName, "Id");
}
/** */

function reverseFieldName(modelName) {
  return modelName.toLowerCase() + "Set"; // eslint-disable-line prefer-template
}
/** @private */

function querySetDelegatorFactory(methodName) {
  return function querySetDelegator() {
    var _this$getQuerySet;
    return (_this$getQuerySet = this.getQuerySet())[methodName].apply(_this$getQuerySet, arguments);
  };
}
/** @private */

function querySetGetterDelegatorFactory(getterName) {
  return function querySetGetterDelegator() {
    var qs = this.getQuerySet();
    return qs[getterName];
  };
}
/** @private */

function forEachSuperClass(subClass, func) {
  var currClass = subClass;
  while (currClass !== Function.prototype) {
    func(currClass);
    currClass = Object.getPrototypeOf(currClass);
  }
}
/** */

function attachQuerySetMethods(modelClass, querySetClass) {
  var leftToDefine = querySetClass.sharedMethods.slice(); // There is no way to get a property descriptor for the whole prototype chain;
  // only from an objects own properties. Therefore we traverse the whole prototype
  // chain for querySet.

  forEachSuperClass(querySetClass, function (cls) {
    for (var i = 0; i < leftToDefine.length; i++) {
      var defined = false;
      var methodName = leftToDefine[i];
      var descriptor = Object.getOwnPropertyDescriptor(cls.prototype, methodName);
      if (typeof descriptor !== "undefined") {
        if (typeof descriptor.get !== "undefined") {
          descriptor.get = querySetGetterDelegatorFactory(methodName);
          Object.defineProperty(modelClass, methodName, descriptor);
        } else {
          modelClass[methodName] = querySetDelegatorFactory(methodName);
        }
        defined = true;
      }
      if (defined) {
        leftToDefine.splice(i--, 1);
      }
    }
  });
}
/**
 * Normalizes `entity` to an id, where `entity` can be an id
 * or a Model instance.
 *
 * @param  {*} entity - either a Model instance or an id value
 * @return {*} the id value of `entity`
 */

function normalizeEntity(entity) {
  if (entity !== null && typeof entity !== "undefined" && typeof entity.getId === "function") {
    return entity.getId();
  }
  return entity;
}
/** */

function reverseFieldErrorMessage(modelName, fieldName, toModelName, backwardsFieldName) {
  return ["Reverse field ".concat(backwardsFieldName, " already defined"), " on model ".concat(toModelName, ". To fix, set a custom related"), " name on ".concat(modelName, ".").concat(fieldName, ".")].join("");
}
/**
 * Fastest way to check if two objects are equal.
 * Object and array values have to be referentially equal.
 */

function objectShallowEquals(a, b) {
  var entriesInA = Object.entries(Object(a));
  if (entriesInA.length !== Object.keys(b).length) {
    return false;
  }
  return entriesInA.every(function (_ref) {
    var _ref2 = _slicedToArray$1(_ref, 2),
      key = _ref2[0],
      value = _ref2[1];
    return b.hasOwnProperty(key) && b[key] === value;
  });
}
/** */

function arrayDiffActions(sourceArr, targetArr) {
  var itemsInBoth = sourceArr.filter(function (item) {
    return targetArr.includes(item);
  });
  var deleteItems = sourceArr.filter(function (item) {
    return !itemsInBoth.includes(item);
  });
  var addItems = targetArr.filter(function (item) {
    return !itemsInBoth.includes(item);
  });
  if (deleteItems.length || addItems.length) {
    return {
      "delete": deleteItems,
      add: addItems
    };
  }
  return null;
}
ops.getBatchToken;
/**
 * @return boolean
 */

function clauseFiltersByAttribute(_ref3, attribute) {
  var type = _ref3.type,
    payload = _ref3.payload;
  if (type !== FILTER) return false;
  if (_typeof$c(payload) !== "object") {
    /**
     * payload could also be a function in which case
     * we would have no way of knowing what it does,
     * so we default to false for non-objects
     */
    return false;
  }
  if (!payload.hasOwnProperty(attribute)) return false;
  var attributeValue = payload[attribute];
  if (attributeValue === null) return false;
  if (attributeValue === undefined) return false;
  return true;
}
/**
 * @return boolean
 */

function clauseReducesResultSetSize(_ref4) {
  var type = _ref4.type;
  return [FILTER, EXCLUDE].includes(type);
}
/**
 * @param {Object} object
 * @return Object
 */

function mapValues(object, func) {
  return Object.entries(object).reduce(function (newObject, _ref5) {
    var _ref6 = _slicedToArray$1(_ref5, 2),
      key = _ref6[0],
      value = _ref6[1];
    newObject[key] = func(value);
    return newObject;
  }, {});
}
/** */

function normalizeModelReference(modelNameOrClass) {
  if (!modelNameOrClass || typeof modelNameOrClass === "string") {
    return modelNameOrClass;
  }
  return modelNameOrClass.modelName;
}

function ownKeys$6(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$6(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$6(Object(source), true).forEach(function (key) {
        _defineProperty$7(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$6(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
/**
 * This class is used to build and make queries to the database
 * and operating the resulting set (such as updating attributes
 * or deleting the records).
 *
 * The queries are built lazily. For example:
 *
 * ```javascript
 * const qs = Book.all()
 *     .filter(book => book.releaseYear > 1999)
 *     .orderBy('name');
 * ```
 *
 * Doesn't execute a query. The query is executed only when
 * you need information from the query result, such as {@link QuerySet#count},
 * {@link QuerySet#toRefArray}. After the query is executed, the resulting
 * set is cached in the QuerySet instance.
 *
 * QuerySet instances also return copies, so chaining filters doesn't
 * mutate the previous instances.
 */

var QuerySet = /*#__PURE__*/function () {
  /**
   * Creates a QuerySet. The constructor is mainly for internal use;
   * You should access QuerySet instances from {@link Model}.
   *
   * @param  {Model} modelClass - the model class of objects in this QuerySet.
   * @param  {any[]} clauses - query clauses needed to evaluate the set.
   * @param {Object} [opts] - additional options
   */
  function QuerySet(modelClass, clauses, opts) {
    Object.assign(this, {
      modelClass: modelClass,
      clauses: clauses || []
    });
    this._opts = opts;
  }
  QuerySet.addSharedMethod = function addSharedMethod(methodName) {
    this.sharedMethods = this.sharedMethods.concat(methodName);
  };
  var _proto = QuerySet.prototype;
  _proto._new = function _new(clauses, userOpts) {
    var opts = _objectSpread$6(_objectSpread$6({}, this._opts), userOpts);
    return new this.constructor(this.modelClass, clauses, opts);
  };
  _proto.toString = function toString() {
    var _this = this;
    this._evaluate();
    var contents = this.rows.map(function (_ref) {
      var id = _ref.id;
      return _this.modelClass.withId(id).toString();
    }).join("\n    - ");
    return "QuerySet contents:\n    - ".concat(contents);
  }
  /**
   * Returns an array of the plain objects represented by the QuerySet.
   * The plain objects are direct references to the store.
   *
   * @return {Object[]} references to the plain JS objects represented by
   *                    the QuerySet
   */;

  _proto.toRefArray = function toRefArray() {
    var arr = this._evaluate();
    if (arr.length === 0) {
      return EMPTY_ARRAY;
    }
    return arr;
  }
  /**
   * Returns an array of {@link Model} instances represented by the QuerySet.
   * @return {Model[]} model instances represented by the QuerySet
   */;

  _proto.toModelArray = function toModelArray() {
    var ModelClass = this.modelClass;
    var arr = this._evaluate();
    if (arr.length === 0) {
      return EMPTY_ARRAY;
    }
    return arr.map(function (props) {
      return new ModelClass(props);
    });
  }
  /**
   * Returns the number of {@link Model} instances represented by the QuerySet.
   *
   * @return {number} length of the QuerySet
   */;

  _proto.count = function count() {
    this._evaluate();
    return this.rows.length;
  }
  /**
   * Checks if the {@link QuerySet} instance has any records matching the query
   * in the database.
   *
   * @return {Boolean} `true` if the {@link QuerySet} instance contains entities, else `false`.
   */;

  _proto.exists = function exists() {
    return Boolean(this.count());
  }
  /**
   * Returns the {@link Model} instance at index `index` in the {@link QuerySet} instance if
   * `withRefs` flag is set to `false`, or a reference to the plain JavaScript
   * object in the model state if `true`.
   *
   * @param  {number} index - index of the model instance to get
   * @return {Model|undefined} a {@link Model} instance at index
   *                           `index` in the {@link QuerySet} instance,
   *                           or undefined if the index is out of bounds.
   */;

  _proto.at = function at(index) {
    var ModelClass = this.modelClass;
    var rows = this._evaluate();
    if (index >= 0 && index < rows.length) {
      return new ModelClass(rows[index]);
    }
    return undefined;
  }
  /**
   * Returns the {@link Model} instance at index 0 in the {@link QuerySet} instance.
   * @return {Model}
   */;

  _proto.first = function first() {
    return this.at(0);
  }
  /**
   * Returns the {@link Model} instance at index `QuerySet.count() - 1`
   * @return {Model}
   */;

  _proto.last = function last() {
    var rows = this._evaluate();
    return this.at(rows.length - 1);
  }
  /**
   * Returns a new {@link QuerySet} instance with the same entities.
   * @return {QuerySet} a new QuerySet with the same entities.
   */;

  _proto.all = function all() {
    return this._new(this.clauses);
  }
  /**
   * Returns a new {@link QuerySet} instance with entities that match properties in `lookupObj`.
   *
   * @param  {Object} lookupObj - the properties to match objects with. Can also be a function.
   *                              It works the same as [Lodash filter](https://lodash.com/docs/#filter).
   * @return {QuerySet} a new {@link QuerySet} instance with objects that passed the filter.
   */;

  _proto.filter = function filter(lookupObj) {
    /**
     * allow foreign keys to be specified as model instances,
     * transform model instances to their primary keys
     */
    var normalizedLookupObj = _typeof$c(lookupObj) === "object" ? mapValues(lookupObj, normalizeEntity) : lookupObj;
    var filterDescriptor = {
      type: FILTER,
      payload: normalizedLookupObj
    };
    /**
     * create a new QuerySet
     * including only rows matching the lookupObj
     */

    return this._new(this.clauses.concat(filterDescriptor));
  }
  /**
   * Returns a new {@link QuerySet} instance with entities that do not match
   * properties in `lookupObj`.
   *
   * @param  {Object} lookupObj - the properties to unmatch objects with. Can also be a function.
   *                              It works the same as [Lodash reject](https://lodash.com/docs/#reject).
   * @return {QuerySet} a new {@link QuerySet} instance with objects that did not pass the filter.
   */;

  _proto.exclude = function exclude(lookupObj) {
    /**
     * allow foreign keys to be specified as model instances,
     * transform model instances to their primary keys
     */
    var normalizedLookupObj = _typeof$c(lookupObj) === "object" ? mapValues(lookupObj, normalizeEntity) : lookupObj;
    var excludeDescriptor = {
      type: EXCLUDE,
      payload: normalizedLookupObj
    };
    /**
     * create a new QuerySet
     * excluding all rows matching the lookupObj
     */

    return this._new(this.clauses.concat(excludeDescriptor));
  }
  /**
   * Performs the actual database query.
   * @private
   * @return {Array} rows corresponding to the QuerySet's clauses
   */;

  _proto._evaluate = function _evaluate() {
    if (typeof this.modelClass.session === "undefined") {
      throw new Error(["Tried to query the ".concat(this.modelClass.modelName, " model's table without a session. "), "Create a session using `session = orm.session()` and use ", "`session[\"".concat(this.modelClass.modelName, "\"]` for querying instead.")].join(""));
    }
    if (!this._evaluated) {
      var _this$modelClass = this.modelClass,
        session = _this$modelClass.session,
        table = _this$modelClass.modelName;
      var querySpec = {
        table: table,
        clauses: this.clauses
      };
      this.rows = session.query(querySpec).rows;
      this._evaluated = true;
    }
    return this.rows;
  }
  /**
   * Returns a new {@link QuerySet} instance with entities ordered by `iteratees` in ascending
   * order, unless otherwise specified. Delegates to [Lodash orderBy](https://lodash.com/docs/#orderBy).
   *
   * @param  {string[]|Function[]} iteratees - an array where each item can be a string or a
   *                                           function. If a string is supplied, it should
   *                                           correspond to property on the entity that will
   *                                           determine the order. If a function is supplied,
   *                                           it should return the value to order by.
   * @param {Array<Boolean|'asc'|'desc'>} [orders] - the sort orders of `iteratees`. If unspecified, all iteratees
   *                               will be sorted in ascending order. `true` and `'asc'`
   *                               correspond to ascending order, and `false` and `'desc'`
   *                               to descending order.
   * @return {QuerySet} a new {@link QuerySet} with objects ordered by `iteratees`.
   */;

  _proto.orderBy = function orderBy(iteratees, orders) {
    var orderByDescriptor = {
      type: ORDER_BY,
      payload: [iteratees, orders]
    };
    /**
     * create a new QuerySet
     * sorting all rows according to the passed arguments
     */

    return this._new(this.clauses.concat(orderByDescriptor));
  }
  /**
   * Records an update specified with `mergeObj` to all the objects
   * in the {@link QuerySet} instance.
   *
   * @param  {Object} mergeObj - an object to merge with all the objects in this
   *                             queryset.
   * @return {undefined}
   */;

  _proto.update = function update(mergeObj) {
    var _this$modelClass2 = this.modelClass,
      session = _this$modelClass2.session,
      table = _this$modelClass2.modelName;
    session.applyUpdate({
      action: UPDATE$2,
      query: {
        table: table,
        clauses: this.clauses
      },
      payload: mergeObj
    });
    this._evaluated = false;
  }
  /**
   * Records a deletion of all the objects in this {@link QuerySet} instance.
   * @return {undefined}
   */;

  _proto["delete"] = function _delete() {
    var _this$modelClass3 = this.modelClass,
      session = _this$modelClass3.session,
      table = _this$modelClass3.modelName;
    this.toModelArray().forEach(function (model) {
      return model._onDelete();
    } // eslint-disable-line no-underscore-dangle
    );

    session.applyUpdate({
      action: DELETE$2,
      query: {
        table: table,
        clauses: this.clauses
      }
    });
    this._evaluated = false;
  } // DEPRECATED AND REMOVED METHODS

  /**
   * @deprecated
   * Use {@link QuerySet#toModelArray} or predicate functions that
   * instantiate Models from refs, e.g. `new Model(ref)`.
   */;

  /**
   * @deprecated
   * Call {@link QuerySet#toModelArray} or {@link QuerySet#toRefArray} first to map.
   */
  _proto.map = function map() {
    throw new Error("`QuerySet.prototype.map` has been removed. " + "Call `.toModelArray()` or `.toRefArray()` first to map.");
  }
  /**
   * @deprecated
   * Call {@link QuerySet#toModelArray} or {@link QuerySet#toRefArray} first to iterate.
   */;

  _proto.forEach = function forEach() {
    throw new Error("`QuerySet.prototype.forEach` has been removed. " + "Call `.toModelArray()` or `.toRefArray()` first to iterate.");
  };
  _createClass(QuerySet, [{
    key: "withModels",
    get: function get() {
      throw new Error("`QuerySet.prototype.withModels` has been removed. " + "Use `.toModelArray()` or predicate functions that " + "instantiate Models from refs, e.g. `new Model(ref)`.");
    }
    /**
     * @deprecated Query building operates on refs only now.
     */
  }, {
    key: "withRefs",
    get: function get() {
      warnDeprecated("`QuerySet.prototype.withRefs` has been deprecated. " + "Query building operates on refs only now.");
      return undefined;
    }
  }]);
  return QuerySet;
}();
QuerySet.sharedMethods = ["count", "at", "all", "last", "first", "filter", "exclude", "orderBy", "update", "delete"];
var QuerySet$1 = QuerySet;

var Session = /*#__PURE__*/function () {
  /**
   * Creates a new Session.
   *
   * @param  {Database} db - a {@link Database} instance
   * @param  {Object} state - the database state
   * @param  {Boolean} [withMutations] - whether the session should mutate data
   * @param  {Object} [batchToken] - used by the backend to identify objects that can be
   *                                 mutated.
   */
  function Session(schema, db, state, withMutations, batchToken) {
    var _this = this;
    this.schema = schema;
    this.db = db;
    this.state = state || db.getEmptyState();
    this.initialState = this.state;
    this.withMutations = Boolean(withMutations);
    this.batchToken = batchToken || getBatchToken();
    this.modelData = {};
    this.models = schema.getModelClasses();
    this.sessionBoundModels = this.models.map(function (modelClass) {
      function SessionBoundModel() {
        return Reflect.construct(modelClass, arguments, SessionBoundModel); // eslint-disable-line prefer-rest-params
      }

      Reflect.setPrototypeOf(SessionBoundModel.prototype, modelClass.prototype);
      Reflect.setPrototypeOf(SessionBoundModel, modelClass);
      Object.defineProperty(_this, modelClass.modelName, {
        get: function get() {
          return SessionBoundModel;
        }
      });
      SessionBoundModel.connect(_this);
      return SessionBoundModel;
    });
  }
  var _proto = Session.prototype;
  _proto.getDataForModel = function getDataForModel(modelName) {
    if (!this.modelData[modelName]) {
      this.modelData[modelName] = {};
    }
    return this.modelData[modelName];
  };
  _proto.getModelData = function getModelData() {
    return this.modelData;
  };
  _proto.markAccessed = function markAccessed(modelName, modelIds) {
    var data = this.getDataForModel(modelName);
    if (!data.accessedInstances) {
      data.accessedInstances = {};
    }
    modelIds.forEach(function (id) {
      data.accessedInstances[id] = true;
    });
  };
  _proto.markFullTableScanned = function markFullTableScanned(modelName) {
    var data = this.getDataForModel(modelName);
    data.fullTableScanned = true;
  };
  _proto.markAccessedIndexes = function markAccessedIndexes(indexes) {
    var _this2 = this;
    indexes.forEach(function (_ref) {
      var _ref2 = _slicedToArray$1(_ref, 3),
        table = _ref2[0],
        attr = _ref2[1],
        value = _ref2[2];
      var data = _this2.getDataForModel(table);
      if (!data.accessedIndexes) {
        data.accessedIndexes = {};
      }
      data.accessedIndexes[attr] = [].concat(_toConsumableArray$1(data.accessedIndexes[attr] || []), [value]);
    });
  };

  /**
   * Applies update to a model state.
   *
   * @private
   * @param {Object} update - the update object. Must have keys
   *                          `type`, `payload`.
   */
  _proto.applyUpdate = function applyUpdate(updateSpec) {
    var tx = this._getTransaction(updateSpec);
    var result = this.db.update(updateSpec, tx, this.state);
    var status = result.status,
      state = result.state,
      payload = result.payload;
    if (status !== SUCCESS$2) {
      throw new Error("Applying update failed with status ".concat(status, ". Payload: ").concat(payload));
    }
    this.state = state;
    return payload;
  };
  _proto.query = function query(querySpec) {
    var result = this.db.query(querySpec, this.state);
    this._markAccessedByQuery(querySpec, result);
    return result;
  };
  _proto._getTransaction = function _getTransaction(updateSpec) {
    var withMutations = this.withMutations;
    var action = updateSpec.action;
    var batchToken = this.batchToken;
    if ([UPDATE$2, DELETE$2].includes(action)) {
      batchToken = getBatchToken();
    }
    return {
      batchToken: batchToken,
      withMutations: withMutations
    };
  };
  _proto._markAccessedByQuery = function _markAccessedByQuery(querySpec, result) {
    var table = querySpec.table,
      clauses = querySpec.clauses;
    var rows = result.rows;
    var idAttribute = this[table].idAttribute;
    var accessedIds = new Set(rows.map(function (row) {
      return row[idAttribute];
    }));
    var anyClauseFilteredByPk = clauses.some(function (clause) {
      if (!clauseFiltersByAttribute(clause, idAttribute)) {
        return false;
      }
      /**
       * We previously knew which row we wanted to access,
       * so there was no need to scan the entire table.
       */

      accessedIds.add(clause.payload[idAttribute]);
      return true;
    });
    var accessedIndexes = [];
    var indexes = this.state[table].indexes;
    clauses.forEach(function (clause) {
      Object.keys(indexes).forEach(function (attr) {
        if (!clauseFiltersByAttribute(clause, attr)) {
          return;
        }
        var value = clause.payload[attr];
        accessedIndexes.push([table, attr, value]);
      });
    });
    if (anyClauseFilteredByPk) {
      /**
       * The clauses have been ordered so that an indexed one was
       * the first to have been evaluated, and thus only the row
       * with the specified PK value has actually been accessed.
       */
      this.markAccessed(table, accessedIds);
    } else if (accessedIndexes.length) {
      /**
       * At least one clause was optimized using indexes.
       */
      this.markAccessed(table, accessedIds);
      this.markAccessedIndexes(accessedIndexes);
    } else {
      /**
       * At least one clause could not be efficiently optimized
       * or no clause was specified at all.
       */
      this.markFullTableScanned(table);
    }
  } // DEPRECATED AND REMOVED METHODS

  /**
   * @deprecated Access {@link Session#state} instead.
   */;

  _proto.getNextState = function getNextState() {
    warnDeprecated("`Session.prototype.getNextState` has been deprecated. Access " + "the `Session.prototype.state` property instead.");
    return this.state;
  }
  /**
   * @deprecated
   * The Redux integration API is now decoupled from ORM and Session.<br>
   * See the 0.9 migration guide in the GitHub repo.
   */;

  _proto.reduce = function reduce() {
    throw new Error("`Session.prototype.reduce` has been removed. The Redux integration API " + "is now decoupled from ORM and Session - see the 0.9 migration guide " + "in the GitHub repo.");
  };
  _createClass(Session, [{
    key: "accessedModelInstances",
    get: function get() {
      return Object.entries(this.getModelData()).reduce(function (result, _ref3) {
        var _ref4 = _slicedToArray$1(_ref3, 2),
          key = _ref4[0],
          value = _ref4[1];
        if (value.accessedInstances) {
          result[key] = value.accessedInstances;
        }
        return result;
      }, {});
    }
  }, {
    key: "fullTableScannedModels",
    get: function get() {
      return Object.entries(this.getModelData()).reduce(function (result, _ref5) {
        var _ref6 = _slicedToArray$1(_ref5, 2),
          key = _ref6[0],
          value = _ref6[1];
        if (value.fullTableScanned) {
          result.push(key);
        }
        return result;
      }, []);
    }
  }, {
    key: "accessedIndexes",
    get: function get() {
      return Object.entries(this.getModelData()).reduce(function (result, _ref7) {
        var _ref8 = _slicedToArray$1(_ref7, 2),
          key = _ref8[0],
          value = _ref8[1];
        if (value.accessedIndexes) {
          result[key] = value.accessedIndexes;
        }
        return result;
      }, {});
    }
  }]);
  return Session;
}();
var Session$1 = Session;

function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };
  return _setPrototypeOf(o, p);
}

function _isNativeReflectConstruct() {
  if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  if (Reflect.construct.sham) return false;
  if (typeof Proxy === "function") return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
    return true;
  } catch (e) {
    return false;
  }
}

function _construct(Parent, args, Class) {
  if (_isNativeReflectConstruct()) {
    _construct = Reflect.construct.bind();
  } else {
    _construct = function _construct(Parent, args, Class) {
      var a = [null];
      a.push.apply(a, args);
      var Constructor = Function.bind.apply(Parent, a);
      var instance = new Constructor();
      if (Class) _setPrototypeOf(instance, Class.prototype);
      return instance;
    };
  }
  return _construct.apply(null, arguments);
}

function _inheritsLoose$1(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  _setPrototypeOf(subClass, superClass);
}

/**
 * Defines algorithm for installing a field onto a model and related models.
 * Conforms to the template method behavioral design pattern.
 * @private
 * @memberof module:fields
 */
var FieldInstallerTemplate = /*#__PURE__*/function () {
  function FieldInstallerTemplate(opts) {
    this.field = opts.field;
    this.fieldName = opts.fieldName;
    this.model = opts.model;
    this.orm = opts.orm;
    /**
     * the field itself has no knowledge of the model
     * it is being installed upon; we need to inform it
     * that it is a self-referencing field for the field
     * to be able to make better informed decisions
     */

    if (this.field.references(this.model)) {
      this.field.toModelName = "this";
    }
  }
  var _proto = FieldInstallerTemplate.prototype;
  _proto.run = function run() {
    this.installForwardsDescriptor();
    if (this.field.installsForwardsVirtualField) {
      this.installForwardsVirtualField();
    }
    /**
     * Install a backwards field on a model as a consequence
     * of having installed the forwards field on another model.
     */

    if (this.field.installsBackwardsDescriptor) {
      this.installBackwardsDescriptor();
    }
    if (this.field.installsBackwardsVirtualField) {
      this.installBackwardsVirtualField();
    }
  };
  _createClass(FieldInstallerTemplate, [{
    key: "toModel",
    get: function get() {
      if (typeof this._toModel === "undefined") {
        var toModelName = this.field.toModelName;
        if (!toModelName) {
          this._toModel = null;
        } else if (toModelName === "this") {
          this._toModel = this.model;
        } else {
          this._toModel = this.orm.get(toModelName);
        }
      }
      return this._toModel;
    }
  }, {
    key: "throughModel",
    get: function get() {
      if (typeof this._throughModel === "undefined") {
        var throughModelName = this.field.getThroughModelName(this.fieldName, this.model);
        if (!throughModelName) {
          this._throughModel = null;
        } else {
          this._throughModel = this.orm.get(throughModelName);
        }
      }
      return this._throughModel;
    }
  }, {
    key: "backwardsFieldName",
    get: function get() {
      return this.field.getBackwardsFieldName(this.model);
    }
  }]);
  return FieldInstallerTemplate;
}();
var FieldInstallerTemplate$1 = FieldInstallerTemplate;

/**
 * Default implementation for the template method in FieldInstallerTemplate.
 * @private
 * @memberof module:fields
 */

var DefaultFieldInstaller = /*#__PURE__*/function (_FieldInstallerTempla) {
  _inheritsLoose$1(DefaultFieldInstaller, _FieldInstallerTempla);
  function DefaultFieldInstaller() {
    return _FieldInstallerTempla.apply(this, arguments) || this;
  }
  var _proto = DefaultFieldInstaller.prototype;
  _proto.installForwardsDescriptor = function installForwardsDescriptor() {
    Object.defineProperty(this.model.prototype, this.fieldName, this.field.createForwardsDescriptor(this.fieldName, this.model, this.toModel, this.throughModel));
  };
  _proto.installForwardsVirtualField = function installForwardsVirtualField() {
    this.model.virtualFields[this.fieldName] = this.field.createForwardsVirtualField(this.fieldName, this.model, this.toModel, this.throughModel);
  };
  _proto.installBackwardsDescriptor = function installBackwardsDescriptor() {
    var backwardsDescriptor = Object.getOwnPropertyDescriptor(this.toModel.prototype, this.backwardsFieldName);
    if (backwardsDescriptor) {
      throw new Error(reverseFieldErrorMessage(this.model.modelName, this.fieldName, this.toModel.modelName, this.backwardsFieldName));
    } // install backwards descriptor

    Object.defineProperty(this.toModel.prototype, this.backwardsFieldName, this.field.createBackwardsDescriptor(this.fieldName, this.model, this.toModel, this.throughModel));
  };
  _proto.installBackwardsVirtualField = function installBackwardsVirtualField() {
    this.toModel.virtualFields[this.backwardsFieldName] = this.field.createBackwardsVirtualField(this.fieldName, this.model, this.toModel, this.throughModel);
  };
  return DefaultFieldInstaller;
}(FieldInstallerTemplate$1);
var DefaultFieldInstaller$1 = DefaultFieldInstaller;

/**
 * @private
 * @memberof module:fields
 */

var Field$1 = /*#__PURE__*/function () {
  function Field() {}
  var _proto = Field.prototype;
  _proto.getClass = function getClass() {
    return this.constructor;
  };
  _proto.references = function references(model) {
    return false;
  };
  _proto.getThroughModelName = function getThroughModelName(fieldName, model) {
    return null;
  };
  _createClass(Field, [{
    key: "installerClass",
    get: function get() {
      return DefaultFieldInstaller$1;
    }
  }, {
    key: "installsForwardsVirtualField",
    get: function get() {
      return false;
    }
  }, {
    key: "installsBackwardsDescriptor",
    get: function get() {
      return false;
    }
  }, {
    key: "installsBackwardsVirtualField",
    get: function get() {
      return false;
    }
  }, {
    key: "index",
    get: function get() {
      return false;
    }
  }]);
  return Field;
}();
var Field$2 = Field$1;

/**
 * The functions in this file return custom JS property descriptors
 * that are supposed to be assigned to Model fields.
 *
 * Some include the logic to look up models using foreign keys and
 * to add or remove relationships between models.
 *
 * @module descriptors
 * @private
 */

/**
 * Defines a basic non-key attribute.
 * @param  {string} fieldName - the name of the field the descriptor will be assigned to.
 */

function attrDescriptor(fieldName) {
  return {
    get: function get() {
      return this._fields[fieldName];
    },
    set: function set(value) {
      return this.set(fieldName, value);
    },
    enumerable: true,
    configurable: true
  };
}
/**
 * Forwards direction of a Foreign Key: returns one object.
 * Also works as {@link .forwardsOneToOneDescriptor|forwardsOneToOneDescriptor}.
 *
 * For `book.author` referencing an `Author` model instance,
 * `fieldName` would be `'author'` and `declaredToModelName` would be `'Author'`.
 * @param  {string} fieldName - the name of the field the descriptor will be assigned to.
 * @param  {string} declaredToModelName - the name of the model that the field references.
 */

function forwardsManyToOneDescriptor(fieldName, declaredToModelName) {
  return {
    get: function get() {
      var _this$getClass = this.getClass(),
        DeclaredToModel = _this$getClass.session[declaredToModelName];
      var toId = this._fields[fieldName];
      return DeclaredToModel.withId(toId);
    },
    set: function set(value) {
      this.update(_defineProperty$7({}, fieldName, normalizeEntity(value)));
    }
  };
}
/**
 * Dereferencing foreign keys in {@link module:fields.oneToOne|oneToOne}
 * relationships works the same way as in many-to-one relationships:
 * just look up the related model.
 *
 * For example, a human face tends to have a single nose.
 * So if we want to resolve `face.nose`, we need to
 * look up the `Nose` that has the primary key that `face` references.
 *
 * @see {@link module:descriptors~forwardsManyToOneDescriptor|forwardsManyToOneDescriptor}
 */

function forwardsOneToOneDescriptor() {
  return forwardsManyToOneDescriptor.apply(void 0, arguments);
}
/**
 * Here we resolve 1-to-1 relationships starting at the model on which the
 * field was not installed. This means we need to find the instance of the
 * other model whose {@link module:fields.oneToOne|oneToOne} FK field contains the current model's primary key.
 *
 * @param  {string} declaredFieldName - the name of the field referencing the current model.
 * @param  {string} declaredFromModelName - the name of the other model.
 */

function backwardsOneToOneDescriptor(declaredFieldName, declaredFromModelName) {
  return {
    get: function get() {
      var _this$getClass2 = this.getClass(),
        DeclaredFromModel = _this$getClass2.session[declaredFromModelName];
      return DeclaredFromModel.get(_defineProperty$7({}, declaredFieldName, this.getId()));
    },
    set: function set() {
      throw new Error("Can't mutate a reverse one-to-one relation.");
    }
  };
}
/**
 * The backwards direction of a n-to-1 relationship (i.e. 1-to-n),
 * meaning this will return an a collection (`QuerySet`) of model instances.
 *
 * An example would be `author.books` referencing all instances of
 * the `Book` model that reference the author using `fk()`.
 */

function backwardsManyToOneDescriptor(declaredFieldName, declaredFromModelName) {
  return {
    get: function get() {
      var _this$getClass3 = this.getClass(),
        DeclaredFromModel = _this$getClass3.session[declaredFromModelName];
      return DeclaredFromModel.filter(_defineProperty$7({}, declaredFieldName, this.getId()));
    },
    set: function set() {
      throw new Error("Can't mutate a reverse many-to-one relation.");
    }
  };
}
/**
 * This descriptor is assigned to both sides of a many-to-many relationship.
 * To indicate the backwards direction pass `true` for `reverse`.
 */

function manyToManyDescriptor(declaredFromModelName, declaredToModelName, throughModelName, throughFields, reverse) {
  return {
    get: function get() {
      var _this$getClass4 = this.getClass(),
        _this$getClass4$sessi = _this$getClass4.session,
        DeclaredFromModel = _this$getClass4$sessi[declaredFromModelName],
        DeclaredToModel = _this$getClass4$sessi[declaredToModelName],
        ThroughModel = _this$getClass4$sessi[throughModelName];
      var ThisModel = reverse ? DeclaredToModel : DeclaredFromModel;
      var OtherModel = reverse ? DeclaredFromModel : DeclaredToModel;
      var thisReferencingField = reverse ? throughFields.to : throughFields.from;
      var otherReferencingField = reverse ? throughFields.from : throughFields.to;
      var thisId = this.getId();
      var throughQs = ThroughModel.filter(_defineProperty$7({}, thisReferencingField, thisId));
      /**
       * all IDs of instances of the other model that are
       * referenced by any instance of the current model
       */

      var referencedOtherIds = new Set(throughQs.toRefArray().map(function (obj) {
        return obj[otherReferencingField];
      }));
      /**
       * selects all instances of other model that are referenced
       * by any instance of the current model
       */

      var qs = OtherModel.filter(function (otherModelInstance) {
        return referencedOtherIds.has(otherModelInstance[OtherModel.idAttribute]);
      });
      /**
       * Allows adding OtherModel instances to be referenced by the current instance.
       *
       * E.g. Book.first().authors.add(1, 2) would add the authors with IDs 1 and 2
       * to the first book's list of referenced authors.
       *
       * @return undefined
       */

      qs.add = function add() {
        for (var _len = arguments.length, entities = new Array(_len), _key = 0; _key < _len; _key++) {
          entities[_key] = arguments[_key];
        }
        var idsToAdd = new Set(entities.map(normalizeEntity));
        var existingQs = throughQs.filter(function (through) {
          return idsToAdd.has(through[otherReferencingField]);
        });
        if (existingQs.exists()) {
          var existingIds = existingQs.toRefArray().map(function (through) {
            return through[otherReferencingField];
          });
          throw new Error("Tried to add already existing ".concat(OtherModel.modelName, " id(s) ").concat(existingIds, " to the ").concat(ThisModel.modelName, " instance with id ").concat(thisId));
        }
        idsToAdd.forEach(function (id) {
          var _ThroughModel$create;
          ThroughModel.create((_ThroughModel$create = {}, _defineProperty$7(_ThroughModel$create, otherReferencingField, id), _defineProperty$7(_ThroughModel$create, thisReferencingField, thisId), _ThroughModel$create));
        });
      };
      /**
       * Removes references to all OtherModel instances from the current model.
       *
       * E.g. Book.first().authors.clear() would cause the first book's list
       * of referenced authors to become empty.
       *
       * @return undefined
       */

      qs.clear = function clear() {
        throughQs["delete"]();
      };
      /**
       * Removes references to all passed OtherModel instances from the current model.
       *
       * E.g. Book.first().authors.remove(1, 2) would cause the authors with
       * IDs 1 and 2 to no longer be referenced by the first book.
       *
       * @return undefined
       */

      qs.remove = function remove() {
        for (var _len2 = arguments.length, entities = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          entities[_key2] = arguments[_key2];
        }
        var idsToRemove = new Set(entities.map(normalizeEntity));
        var entitiesToDelete = throughQs.filter(function (through) {
          return idsToRemove.has(through[otherReferencingField]);
        });
        if (entitiesToDelete.count() !== idsToRemove.size) {
          // Tried deleting non-existing entities.
          var entitiesToDeleteIds = entitiesToDelete.toRefArray().map(function (through) {
            return through[otherReferencingField];
          });
          var unexistingIds = _toConsumableArray$1(idsToRemove).filter(function (id) {
            return !entitiesToDeleteIds.includes(id);
          });
          throw new Error("Tried to delete non-existing ".concat(OtherModel.modelName, " id(s) ").concat(unexistingIds, " from the ").concat(ThisModel.modelName, " instance with id ").concat(thisId));
        }
        entitiesToDelete["delete"]();
      };
      return qs;
    },
    set: function set() {
      throw new Error("Tried setting a M2M field. Please use the related QuerySet methods add, remove and clear.");
    }
  };
}

/**
 * @memberof module:fields
 */

var Attribute = /*#__PURE__*/function (_Field) {
  _inheritsLoose$1(Attribute, _Field);
  function Attribute(opts) {
    var _this;
    _this = _Field.call(this) || this;
    _this.opts = opts || {};
    if (_this.opts.hasOwnProperty("getDefault")) {
      _this.getDefault = _this.opts.getDefault;
    }
    return _this;
  }
  var _proto = Attribute.prototype;
  _proto.createForwardsDescriptor = function createForwardsDescriptor(fieldName, model) {
    return attrDescriptor(fieldName);
  };
  return Attribute;
}(Field$2);
var Attribute$1 = Attribute;

/**
 * @private
 * @memberof module:fields
 */

var RelationalField = /*#__PURE__*/function (_Field) {
  _inheritsLoose$1(RelationalField, _Field);
  function RelationalField() {
    var _this;
    _this = _Field.call(this) || this;
    if (arguments.length === 1 && _typeof$c(arguments.length <= 0 ? undefined : arguments[0]) === "object") {
      var opts = arguments.length <= 0 ? undefined : arguments[0];
      _this.toModelName = normalizeModelReference(opts.to);
      _this.relatedName = opts.relatedName;
      _this.through = normalizeModelReference(opts.through);
      _this.throughFields = opts.throughFields;
      _this.as = opts.as;
    } else {
      var _ref = [normalizeModelReference(arguments.length <= 0 ? undefined : arguments[0]), arguments.length <= 1 ? undefined : arguments[1]];
      _this.toModelName = _ref[0];
      _this.relatedName = _ref[1];
    }
    return _this;
  }
  var _proto = RelationalField.prototype;
  _proto.getBackwardsFieldName = function getBackwardsFieldName(model) {
    return this.relatedName || reverseFieldName(model.modelName);
  };
  _proto.createBackwardsVirtualField = function createBackwardsVirtualField(fieldName, model, toModel, throughModel) {
    var ThisField = this.getClass();
    return new ThisField(model.modelName, fieldName);
  };
  _proto.references = function references(model) {
    return this.toModelName === model.modelName;
  };
  _createClass(RelationalField, [{
    key: "installsBackwardsVirtualField",
    get: function get() {
      return true;
    }
  }, {
    key: "installsBackwardsDescriptor",
    get: function get() {
      return true;
    }
  }, {
    key: "installerClass",
    get: function get() {
      return /*#__PURE__*/function (_DefaultFieldInstalle) {
        _inheritsLoose$1(AliasedForwardsDescriptorInstaller, _DefaultFieldInstalle);
        function AliasedForwardsDescriptorInstaller() {
          return _DefaultFieldInstalle.apply(this, arguments) || this;
        }
        var _proto2 = AliasedForwardsDescriptorInstaller.prototype;
        _proto2.installForwardsDescriptor = function installForwardsDescriptor() {
          Object.defineProperty(this.model.prototype, this.field.as || this.fieldName,
          // use supplied name if possible
          this.field.createForwardsDescriptor(this.fieldName, this.model, this.toModel, this.throughModel));
        };
        return AliasedForwardsDescriptorInstaller;
      }(DefaultFieldInstaller$1);
    }
  }]);
  return RelationalField;
}(Field$2);
var RelationalField$1 = RelationalField;

/**
 * @memberof module:fields
 */

var ForeignKey$3 = /*#__PURE__*/function (_RelationalField) {
  _inheritsLoose$1(ForeignKey, _RelationalField);
  function ForeignKey() {
    return _RelationalField.apply(this, arguments) || this;
  }
  var _proto = ForeignKey.prototype;
  _proto.createForwardsDescriptor = function createForwardsDescriptor(fieldName, model, toModel, throughModel) {
    return forwardsManyToOneDescriptor(fieldName, toModel.modelName);
  };
  _proto.createBackwardsDescriptor = function createBackwardsDescriptor(fieldName, model, toModel, throughModel) {
    return backwardsManyToOneDescriptor(fieldName, model.modelName);
  };
  _createClass(ForeignKey, [{
    key: "index",
    get: function get() {
      return true;
    }
  }]);
  return ForeignKey;
}(RelationalField$1);
var ForeignKey$4 = ForeignKey$3;

/**
 * @memberof module:fields
 */

var ManyToMany = /*#__PURE__*/function (_RelationalField) {
  _inheritsLoose$1(ManyToMany, _RelationalField);
  function ManyToMany() {
    return _RelationalField.apply(this, arguments) || this;
  }
  var _proto = ManyToMany.prototype;
  _proto.getDefault = function getDefault() {
    return [];
  };
  _proto.getThroughModelName = function getThroughModelName(fieldName, model) {
    return this.through || m2mName(model.modelName, fieldName);
  };
  _proto.createForwardsDescriptor = function createForwardsDescriptor(fieldName, model, toModel, throughModel) {
    return manyToManyDescriptor(model.modelName, toModel.modelName, throughModel.modelName, this.getThroughFields(fieldName, model, toModel, throughModel), false);
  };
  _proto.createBackwardsDescriptor = function createBackwardsDescriptor(fieldName, model, toModel, throughModel) {
    return manyToManyDescriptor(model.modelName, toModel.modelName, throughModel.modelName, this.getThroughFields(fieldName, model, toModel, throughModel), true);
  };
  _proto.createBackwardsVirtualField = function createBackwardsVirtualField(fieldName, model, toModel, throughModel) {
    var ThisField = this.getClass();
    return new ThisField({
      to: model.modelName,
      relatedName: fieldName,
      through: throughModel.modelName,
      throughFields: this.getThroughFields(fieldName, model, toModel, throughModel)
    });
  };
  _proto.createForwardsVirtualField = function createForwardsVirtualField(fieldName, model, toModel, throughModel) {
    var ThisField = this.getClass();
    return new ThisField({
      to: toModel.modelName,
      relatedName: fieldName,
      through: this.through,
      throughFields: this.getThroughFields(fieldName, model, toModel, throughModel),
      as: this.as
    });
  };
  _proto.getThroughFields = function getThroughFields(fieldName, model, toModel, throughModel) {
    if (this.throughFields) {
      var _this$throughFields = _slicedToArray$1(this.throughFields, 2),
        fieldAName = _this$throughFields[0],
        fieldBName = _this$throughFields[1];
      var fieldA = throughModel.fields[fieldAName];
      return {
        to: fieldA.references(toModel) ? fieldAName : fieldBName,
        from: fieldA.references(toModel) ? fieldBName : fieldAName
      };
    }
    if (model.modelName === toModel.modelName) {
      /**
       * we have no way of determining the relationship's
       * direction here, so we need to assume that the user
       * did not use a custom through model
       * see ORM#registerManyToManyModelsFor
       */
      return {
        to: m2mToFieldName(toModel.modelName),
        from: m2mFromFieldName(model.modelName)
      };
    }
    /**
     * determine which field references which model
     * and infer the directions from that
     */

    var throughModelFieldReferencing = function throughModelFieldReferencing(otherModel) {
      return Object.keys(throughModel.fields).find(function (someFieldName) {
        return throughModel.fields[someFieldName].references(otherModel);
      });
    };
    return {
      to: throughModelFieldReferencing(toModel),
      from: throughModelFieldReferencing(model)
    };
  };
  _createClass(ManyToMany, [{
    key: "installsForwardsVirtualField",
    get: function get() {
      return true;
    }
  }]);
  return ManyToMany;
}(RelationalField$1);
var ManyToMany$1 = ManyToMany;

/**
 * @memberof module:fields
 */

var OneToOne = /*#__PURE__*/function (_RelationalField) {
  _inheritsLoose$1(OneToOne, _RelationalField);
  function OneToOne() {
    return _RelationalField.apply(this, arguments) || this;
  }
  var _proto = OneToOne.prototype;
  _proto.getBackwardsFieldName = function getBackwardsFieldName(model) {
    return this.relatedName || model.modelName.toLowerCase();
  };
  _proto.createForwardsDescriptor = function createForwardsDescriptor(fieldName, model, toModel, throughModel) {
    return forwardsOneToOneDescriptor(fieldName, toModel.modelName);
  };
  _proto.createBackwardsDescriptor = function createBackwardsDescriptor(fieldName, model, toModel, throughModel) {
    return backwardsOneToOneDescriptor(fieldName, model.modelName);
  };
  return OneToOne;
}(RelationalField$1);
var OneToOne$1 = OneToOne;

/**
 * Contains the logic for how fields on {@link Model}s work
 * and which descriptors must be installed.
 *
 * If your goal is to define fields on a Model class,
 * please use the more convenient methods {@link attr},
 * {@link fk}, {@link many} and {@link oneToOne}.
 *
 * @module fields
 */

/**
 * Defines a value attribute on the model.
 * Though not required, it is recommended to define this for each non-foreign key you wish to use.
 * Getters and setters need to be defined on each Model
 * instantiation for undeclared data fields, which is slower.
 * You can use the optional `getDefault` parameter to fill in unpassed values
 * to {@link Model.create}, such as for generating ID's with UUID:
 *
 * ```javascript
 * import getUUID from 'your-uuid-package-of-choice';
 *
 * fields = {
 *   id: attr({ getDefault: () => getUUID() }),
 *   title: attr(),
 * }
 * ```
 *
 * @param  {Object} [opts]
 * @param {Function} [opts.getDefault] - If you give a function here, its return
 *                                       value from calling with zero arguments will
 *                                       be used as the value when creating a new Model
 *                                       instance with {@link Model#create} if the field
 *                                       value is not passed.
 * @return {Attribute}
 */

function attr$1(opts) {
  return new Attribute$1(opts);
}
/**
 * Defines a foreign key on a model, which points
 * to a single entity on another model.
 *
 * You can pass arguments as either a single object,
 * or two arguments.
 *
 * If you pass two arguments, the first one is the name
 * of the Model the foreign key is pointing to, and
 * the second one is an optional related name, which will
 * be used to access the Model the foreign key
 * is being defined from, from the target Model.
 *
 * If the related name is not passed, it will be set as
 * `${toModelName}Set`.
 *
 * If you pass an object to `fk`, it has to be in the form
 *
 * ```javascript
 * fields = {
 *   author: fk({ to: 'Author', relatedName: 'books' })
 * }
 * ```
 *
 * Which is equal to
 *
 * ```javascript
 * fields = {
 *   author: fk('Author', 'books'),
 * }
 * ```
 *
 * @param {string|Class<Model>|Object} options - The target Model class, its `modelName`
 *                                               attribute or an options object that
 *                                               contains either as the `to` key.
 * @param {string|Class<Model>} options.to - The target Model class or its `modelName` attribute.
 * @param {string} [options.as] - Name for the new accessor defined for this field. If you don't
 *                                supply this, the key that this field is defined under will be
 *                                overridden.
 * @param {string} [options.relatedName] - The property name that will be used to access
 *                                         a QuerySet for all source models that reference
 *                                         the respective target Model's instance.
 * @param {string} [relatedName] - If you didn't pass an object as the first argument,
 *                                 this is the property name that will be used to
 *                                 access a QuerySet for all source models that reference
 *                                 the respective target Model's instance.
 * @return {ForeignKey}
 */

function fk$1() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return _construct(ForeignKey$4, args);
}
/**
 * Defines a many-to-many relationship between
 * this (source) and another (target) model.
 *
 * The relationship is modeled with an extra model called the through model.
 * The through model has foreign keys to both the source and target models.
 *
 * You can define your own through model if you want to associate more information
 * to the relationship. A custom through model must have at least two foreign keys,
 * one pointing to the source Model, and one pointing to the target Model.
 *
 * Like `fk`, this function accepts one or two string arguments specifying the other
 * Model and the related name, or a single object argument that allows you to pass
 * a custom through model.
 *
 * If you have more than one foreign key pointing to a source or target Model in the
 * through Model, you must pass the option `throughFields`, which is an array of two
 * strings, where the strings are the field names that identify the foreign keys to
 * be used for the many-to-many relationship. Redux-ORM will figure out which field name
 * points to which model by checking the "through model" definition.
 *
 * ```javascript
 * class Authorship extends Model {}
 * Authorship.modelName = 'Authorship';
 * Authorship.fields = {
 *   author: fk('Author', 'authorships'),
 *   book: fk('Book', 'authorships'),
 * };
 *
 * class Author extends Model {}
 * Author.modelName = 'Author';
 * Author.fields = {
 *   books: many({
 *     to: 'Book',
 *     relatedName: 'authors',
 *     through: 'Authorship',
 *
 *     // here this is optional: Redux-ORM can figure
 *     // out the through fields itself since the two
 *     // foreign key fields point to different Models
 *     throughFields: ['author', 'book'],
 *   })
 * };
 *
 * class Book extends Model {}
 * Book.modelName = 'Book';
 * ```
 *
 * You should only define the many-to-many relationship on one side. In the
 * above case of Authors to Books through Authorships, the relationship is
 * defined only on the Author model.
 *
 * @param {string|Class<Model>|Object} options - The target Model class, its `modelName`
 *                                               attribute or an options object that
 *                                               contains either as the `to` key.
 * @param {string|Class<Model>} options.to - The target Model class or its `modelName` attribute.
 * @param {string} [options.as] - Name for the new accessor defined for this field. If you don't
 *                                supply this, the key that this field is defined under will be
 *                                overridden.
 * @param {string|Class<Model>} [options.through] - The through Model class or its `modelName`
 *                                                  attribute. It must declare at least one
 *                                                  foreign key to both source and target models.
 *                                                  If not supplied, Redux-ORM will generate one.
 * @param {string[]} [options.throughFields] - Must be supplied only when a custom through
 *                                             Model has more than one foreign key pointing to
 *                                             either the source or target mode. In this case
 *                                             Redux-ORM can't figure out the correct fields for
 *                                             you, you must provide them. The supplied array should
 *                                             have two elements that are the field names for the
 *                                             through fields you want to declare the many-to-many
 *                                             relationship with. The order doesn't matter;
 *                                             Redux-ORM will figure out which field points to
 *                                             the source Model and which to the target Model.
 * @param {string} [options.relatedName] - The attribute used to access a QuerySet for all
 *                                         source models that reference the respective target
 *                                         Model's instance.
 * @param {string} [relatedName] - If you didn't pass an object as the first argument,
 *                                 this is the property name that will be used to
 *                                 access a QuerySet for all source models that reference
 *                                 the respective target Model's instance.
 * @return {ManyToMany}
 */

function many() {
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    args[_key2] = arguments[_key2];
  }
  return _construct(ManyToMany$1, args);
}
/**
 * Defines a one-to-one relationship. In database terms, this is a foreign key with the
 * added restriction that only one entity can point to single target entity.
 *
 * The arguments are the same as with `fk`. If `relatedName` is not supplied,
 * the source model name in lowercase will be used. Note that with the one-to-one
 * relationship, the `relatedName` should be in singular, not plural.
 *
 *
 * @param {string|Class<Model>|Object} options - The target Model class, its `modelName`
 *                                               attribute or an options object that
 *                                               contains either as the `to` key.
 * @param {string|Class<Model>} options.to - The target Model class or its `modelName` attribute.
 * @param {string} [options.as] - Name for the new accessor defined for this field. If you don't
 *                                supply this, the key that this field is defined under will be
 *                                overridden.
 * @param {string} [options.relatedName] - The property name that will be used to access the source
 *                                         model instance referencing the target model instance.
 * @param {string} [relatedName] - The property name that will be used to access the source
 *                                 model instance referencing the target model instance
 * @return {OneToOne}
 */

function oneToOne() {
  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
    args[_key3] = arguments[_key3];
  }
  return _construct(OneToOne$1, args);
}

function ownKeys$5(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$5(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$5(Object(source), true).forEach(function (key) {
        _defineProperty$7(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$5(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
/**
 * Generates a query specification to get the instance's
 * corresponding table row using its primary key.
 *
 * @private
 * @returns {Object}
 */

function getByIdQuery(modelInstance) {
  var modelClass = modelInstance.getClass();
  var idAttribute = modelClass.idAttribute,
    modelName = modelClass.modelName;
  return {
    table: modelName,
    clauses: [{
      type: FILTER,
      payload: _defineProperty$7({}, idAttribute, modelInstance.getId())
    }]
  };
}
/**
 * The heart of an ORM, the data model.
 *
 * The fields you specify to the Model will be used to generate
 * a schema to the database, related property accessors, and
 * possibly through models.
 *
 * In each {@link Session} you instantiate from an {@link ORM} instance,
 * you will receive a session-specific subclass of this Model. The methods
 * you define here will be available to you in sessions.
 *
 * An instance of {@link Model} represents a record in the database, though
 * it is possible to generate multiple instances from the same record in the database.
 *
 * To create data models in your schema, subclass {@link Model}. To define
 * information about the data model, override static class methods. Define instance
 * logic by defining prototype methods (without `static` keyword).
 */

var Model$1 = /*#__PURE__*/function () {
  /**
   * Creates a Model instance from it's properties.
   * Don't use this to create a new record; Use the static method {@link Model#create}.
   * @param  {Object} props - the properties to instantiate with
   */
  function Model(props) {
    this._initFields(props);
  }
  var _proto = Model.prototype;
  _proto._initFields = function _initFields(props) {
    var _this = this;
    var propsObj = Object(props);
    this._fields = _objectSpread$5({}, propsObj);
    Object.keys(propsObj).forEach(function (fieldName) {
      // In this case, we got a prop that wasn't defined as a field.
      // Assuming it's an arbitrary data field, making an instance-specific
      // descriptor for it.
      // Using the in operator as the property could be defined anywhere
      // on the prototype chain.
      if (!(fieldName in _this)) {
        Object.defineProperty(_this, fieldName, {
          get: function get() {
            return _this._fields[fieldName];
          },
          set: function set(value) {
            return _this.set(fieldName, value);
          },
          configurable: true,
          enumerable: true
        });
      }
    });
  };
  Model.toString = function toString() {
    return "ModelClass: ".concat(this.modelName);
  }
  /**
   * Returns the options object passed to the database for the table that represents
   * this Model class.
   *
   * Returns an empty object by default, which means the database
   * will use default options. You can either override this function to return the options
   * you want to use, or assign the options object as a static property of the same name to the
   * Model class.
   *
   * @return {Object} the options object passed to the database for the table
   *                  representing this Model class.
   */;

  Model.options = function options() {
    return {};
  }
  /**
   * Manually mark individual instances as accessed.
   * This allows invalidating selector memoization within mutable sessions.
   *
   * @param {Array.<*>} ids - Array of primary key values
   * @return {undefined}
   */;

  Model.markAccessed = function markAccessed(ids) {
    if (typeof this._session === "undefined") {
      throw new Error(["Tried to mark rows of the ".concat(this.modelName, " model as accessed without a session. "), "Create a session using `session = orm.session()` and call ", "`session[\"".concat(this.modelName, "\"].markAccessed` instead.")].join(""));
    }
    this.session.markAccessed(this.modelName, ids);
  }
  /**
   * Manually mark this model's table as scanned.
   * This allows invalidating selector memoization within mutable sessions.
   *
   * @return {undefined}
   */;

  Model.markFullTableScanned = function markFullTableScanned() {
    if (typeof this._session === "undefined") {
      throw new Error(["Tried to mark the ".concat(this.modelName, " model as full table scanned without a session. "), "Create a session using `session = orm.session()` and call ", "`session[\"".concat(this.modelName, "\"].markFullTableScanned` instead.")].join(""));
    }
    this.session.markFullTableScanned(this.modelName);
  }
  /**
   * Manually mark indexes as accessed.
   * This allows invalidating selector memoization within mutable sessions.
   *
   * @param {Array.<Array.<*,*>>} indexes - Array of column-value pairs
   * @return {undefined}
   */;

  Model.markAccessedIndexes = function markAccessedIndexes(indexes) {
    var _this2 = this;
    if (typeof this._session === "undefined") {
      throw new Error(["Tried to mark indexes for the ".concat(this.modelName, " model as accessed without a session. "), "Create a session using `session = orm.session()` and call ", "`session[\"".concat(this.modelName, "\"].markAccessedIndexes` instead.")].join(""));
    }
    this.session.markAccessedIndexes(indexes.map(function (_ref) {
      var _ref2 = _slicedToArray$1(_ref, 2),
        attribute = _ref2[0],
        value = _ref2[1];
      return [_this2.modelName, attribute, value];
    }));
  }
  /**
   * Returns the id attribute of this {@link Model}.
   *
   * @return {string} The id attribute of this {@link Model}.
   */;

  /**
   * Connect the model class to a {@link Session}.
   *
   * @private
   * @param  {Session} session - The session to connect to.
   */
  Model.connect = function connect(session) {
    if (!(session instanceof Session$1)) {
      throw new Error("A model can only be connected to instances of Session.");
    }
    this._session = session;
  }
  /**
   * Get the current {@link Session} instance.
   *
   * @private
   * @return {Session} The current {@link Session} instance.
   */;

  /**
   * Returns an instance of the model's `querySetClass` field.
   * By default, this will be an empty {@link QuerySet}.
   *
   * @return {Object} An instance of the model's `querySetClass`.
   */
  Model.getQuerySet = function getQuerySet() {
    var QuerySetClass = this.querySetClass;
    return new QuerySetClass(this);
  }
  /**
   * @return {undefined}
   */;

  Model.invalidateClassCache = function invalidateClassCache() {
    this.isSetUp = undefined;
    this.virtualFields = {};
  }
  /**
   * @see {@link Model.getQuerySet}
   */;

  /**
   * Returns parameters to be passed to {@link Table} instance.
   *
   * @private
   */
  Model.tableOptions = function tableOptions() {
    if (typeof this.backend === "function") {
      warnDeprecated("`Model.backend` has been deprecated. Please rename to `.options`.");
      return this.backend();
    }
    if (this.backend) {
      warnDeprecated("`Model.backend` has been deprecated. Please rename to `.options`.");
      return this.backend;
    }
    if (typeof this.options === "function") {
      return this.options();
    }
    return this.options;
  }
  /**
   * Creates a new record in the database, instantiates a {@link Model} and returns it.
   *
   * If you pass values for many-to-many fields, instances are created on the through
   * model as well.
   *
   * @param  {Object} userProps - the new {@link Model}'s properties.
   * @return {Model} a new {@link Model} instance.
   */;

  Model.create = function create(userProps) {
    var _this3 = this;
    if (typeof this._session === "undefined") {
      throw new Error(["Tried to create a ".concat(this.modelName, " model instance without a session. "), "Create a session using `session = orm.session()` and call ", "`session[\"".concat(this.modelName, "\"].create` instead.")].join(""));
    }
    var props = _objectSpread$5({}, userProps);
    var m2mRelations = {};
    var declaredFieldNames = Object.keys(this.fields);
    var declaredVirtualFieldNames = Object.keys(this.virtualFields);
    declaredFieldNames.forEach(function (key) {
      var field = _this3.fields[key];
      var valuePassed = userProps.hasOwnProperty(key);
      if (!(field instanceof ManyToMany$1)) {
        if (valuePassed) {
          var value = userProps[key];
          props[key] = normalizeEntity(value);
        } else if (field.getDefault) {
          props[key] = field.getDefault();
        }
      } else if (valuePassed) {
        // Save for later processing
        m2mRelations[key] = userProps[key];
        if (!field.as) {
          /**
           * The relationship does not have an accessor
           * Discard the value from props as the field will be populated later with instances
           * from the target models when refreshing the M2M relations.
           * If the relationship does have an accessor (`as`) field then we do want to keep this
           * original value in the props to expose the raw list of IDs from the instance.
           */
          delete props[key];
        }
      }
    }); // add backward many-many if required

    declaredVirtualFieldNames.forEach(function (key) {
      if (!m2mRelations.hasOwnProperty(key)) {
        var field = _this3.virtualFields[key];
        if (userProps.hasOwnProperty(key) && field instanceof ManyToMany$1) {
          // If a value is supplied for a ManyToMany field,
          // discard them from props and save for later processing.
          m2mRelations[key] = userProps[key];
          delete props[key];
        }
      }
    });
    var newEntry = this.session.applyUpdate({
      action: CREATE$1,
      table: this.modelName,
      payload: props
    });
    var ThisModel = this;
    var instance = new ThisModel(newEntry);
    instance._refreshMany2Many(m2mRelations); // eslint-disable-line no-underscore-dangle

    return instance;
  }
  /**
   * Creates a new or update existing record in the database, instantiates a {@link Model} and returns it.
   *
   * If you pass values for many-to-many fields, instances are created on the through
   * model as well.
   *
   * @param  {Object} userProps - the required {@link Model}'s properties.
   * @return {Model} a {@link Model} instance.
   */;

  Model.upsert = function upsert(userProps) {
    if (typeof this.session === "undefined") {
      throw new Error(["Tried to upsert a ".concat(this.modelName, " model instance without a session. "), "Create a session using `session = orm.session()` and call ", "`session[\"".concat(this.modelName, "\"].upsert` instead.")].join(""));
    }
    var idAttribute = this.idAttribute;
    if (userProps.hasOwnProperty(idAttribute)) {
      var id = userProps[idAttribute];
      if (this.idExists(id)) {
        var model = this.withId(id);
        model.update(userProps);
        return model;
      }
    }
    return this.create(userProps);
  }
  /**
   * Returns a {@link Model} instance for the object with id `id`.
   * Returns `null` if the model has no instance with id `id`.
   *
   * You can use {@link Model#idExists} to check for existence instead.
   *
   * @param  {*} id - the `id` of the object to get
   * @throws If object with id `id` doesn't exist
   * @return {Model|null} {@link Model} instance with id `id`
   */;

  Model.withId = function withId(id) {
    return this.get(_defineProperty$7({}, this.idAttribute, id));
  }
  /**
   * Returns a boolean indicating if an entity
   * with the id `id` exists in the state.
   *
   * @param  {*}  id - a value corresponding to the id attribute of the {@link Model} class.
   * @return {Boolean} a boolean indicating if entity with `id` exists in the state
   *
   * @since 0.11.0
   */;

  Model.idExists = function idExists(id) {
    return this.exists(_defineProperty$7({}, this.idAttribute, id));
  }
  /**
   * Returns a boolean indicating if an entity
   * with the given props exists in the state.
   *
   * @param  {*}  props - a key-value that {@link Model} instances should have to be considered as existing.
   * @return {Boolean} a boolean indicating if entity with `props` exists in the state
   */;

  Model.exists = function exists(lookupObj) {
    if (typeof this.session === "undefined") {
      throw new Error(["Tried to check if a ".concat(this.modelName, " model instance exists without a session. "), "Create a session using `session = orm.session()` and call ", "`session[\"".concat(this.modelName, "\"].exists` instead.")].join(""));
    }
    return Boolean(this._findDatabaseRows(lookupObj).length);
  }
  /**
   * Gets the {@link Model} instance that matches properties in `lookupObj`.
   * Throws an error if {@link Model} if multiple records match
   * the properties.
   *
   * @param  {Object} lookupObj - the properties used to match a single entity.
   * @throws {Error} If more than one entity matches the properties in `lookupObj`.
   * @return {Model} a {@link Model} instance that matches the properties in `lookupObj`.
   */;

  Model.get = function get(lookupObj) {
    var ThisModel = this;
    var rows = this._findDatabaseRows(lookupObj);
    if (rows.length === 0) {
      return null;
    }
    if (rows.length > 1) {
      throw new Error("Expected to find a single row in `".concat(this.modelName, ".get`. Found ").concat(rows.length, "."));
    }
    return new ThisModel(rows[0]);
  }
  /**
   * Gets the {@link Model} class or subclass constructor (the class that
   * instantiated this instance).
   *
   * @return {Model} The {@link Model} class or subclass constructor used to instantiate
   *                 this instance.
   */;

  _proto.getClass = function getClass() {
    return this.constructor;
  }
  /**
   * Gets the id value of the current instance by looking up the id attribute.
   * @return {*} The id value of the current instance.
   */;

  _proto.getId = function getId() {
    return this._fields[this.getClass().idAttribute];
  }
  /**
   * Returns a reference to the plain JS object in the store.
   * It contains all the properties that you pass when creating the model,
   * except for primary keys of many-to-many relationships with a custom accessor.
   *
   * Make sure never to mutate this.
   *
   * @return {Object} a reference to the plain JS object in the store
   */;

  /**
   * Finds all rows in this model's table that match the given `lookupObj`.
   * If no `lookupObj` is passed, all rows in the model's table will be returned.
   *
   * @param  {*}  props - a key-value that {@link Model} instances should have to be considered as existing.
   * @return {Boolean} a boolean indicating if entity with `props` exists in the state
   * @private
   */
  Model._findDatabaseRows = function _findDatabaseRows(lookupObj) {
    var querySpec = {
      table: this.modelName
    };
    if (lookupObj) {
      querySpec.clauses = [{
        type: FILTER,
        payload: lookupObj
      }];
    }
    return this.session.query(querySpec).rows;
  }
  /**
   * Returns a string representation of the {@link Model} instance.
   *
   * @return {string} A string representation of this {@link Model} instance.
   */;

  _proto.toString = function toString() {
    var _this4 = this;
    var ThisModel = this.getClass();
    var className = ThisModel.modelName;
    var fieldNames = Object.keys(ThisModel.fields);
    var fields = fieldNames.map(function (fieldName) {
      var field = ThisModel.fields[fieldName];
      if (field instanceof ManyToMany$1) {
        var ids = _this4[fieldName].toModelArray().map(function (model) {
          return model.getId();
        });
        return "".concat(fieldName, ": [").concat(ids.join(", "), "]");
      }
      var val = _this4._fields[fieldName];
      return "".concat(fieldName, ": ").concat(val);
    }).join(", ");
    return "".concat(className, ": {").concat(fields, "}");
  }
  /**
   * Returns a boolean indicating if `otherModel` equals this {@link Model} instance.
   * Equality is determined by shallow comparing their attributes.
   *
   * This equality is used when you call {@link Model#update}.
   * You can prevent model updates by returning `true` here.
   * However, a model will always be updated if its relationships are changed.
   *
   * @param  {Model} otherModel - a {@link Model} instance to compare
   * @return {Boolean} a boolean indicating if the {@link Model} instance's are equal.
   */;

  _proto.equals = function equals(otherModel) {
    // eslint-disable-next-line no-underscore-dangle
    return objectShallowEquals(this._fields, otherModel._fields);
  }
  /**
   * Updates a property name to given value for this {@link Model} instance.
   * The values are immediately committed to the database.
   *
   * @param {string} propertyName - name of the property to set
   * @param {*} value - value assigned to the property
   * @return {undefined}
   */;

  _proto.set = function set(propertyName, value) {
    this.update(_defineProperty$7({}, propertyName, value));
  }
  /**
   * Assigns multiple fields and corresponding values to this {@link Model} instance.
   * The updates are immediately committed to the database.
   *
   * @param  {Object} userMergeObj - an object that will be merged with this instance.
   * @return {undefined}
   */;

  _proto.update = function update(userMergeObj) {
    var ThisModel = this.getClass();
    if (typeof ThisModel.session === "undefined") {
      throw new Error(["Tried to update a ".concat(ThisModel.modelName, " model instance without a session. "), "You cannot call `.update` on an instance that you did not receive from the database."].join(""));
    }
    var mergeObj = _objectSpread$5({}, userMergeObj);
    var fields = ThisModel.fields,
      virtualFields = ThisModel.virtualFields;
    var m2mRelations = {}; // If an array of entities or id's is supplied for a
    // many-to-many related field, clear the old relations
    // and add the new ones.
    // eslint-disable-next-line guard-for-in, no-restricted-syntax

    for (var mergeKey in mergeObj) {
      var isRealField = fields.hasOwnProperty(mergeKey);
      if (isRealField) {
        var field = fields[mergeKey];
        if (field instanceof ForeignKey$4 || field instanceof OneToOne$1) {
          // update one-one/fk relations
          mergeObj[mergeKey] = normalizeEntity(mergeObj[mergeKey]);
        } else if (field instanceof ManyToMany$1) {
          // field is forward relation
          m2mRelations[mergeKey] = mergeObj[mergeKey];
          if (!field.as) {
            /**
             * The relationship does not have an accessor
             * Discard the value from props as the field will be populated later with instances
             * from the target models when refreshing the M2M relations.
             * If the relationship does have an accessor (`as`) field then we do want to keep this
             * original value in the props to expose the raw list of IDs from the instance.
             */
            delete mergeObj[mergeKey];
          }
        }
      } else if (virtualFields.hasOwnProperty(mergeKey)) {
        var _field = virtualFields[mergeKey];
        if (_field instanceof ManyToMany$1) {
          // field is backward relation
          m2mRelations[mergeKey] = mergeObj[mergeKey];
          delete mergeObj[mergeKey];
        }
      }
    }
    var mergedFields = _objectSpread$5(_objectSpread$5({}, this._fields), mergeObj);
    var updatedModel = new ThisModel(mergedFields); // only update fields if they have changed (referentially)

    if (!this.equals(updatedModel)) {
      this._initFields(mergedFields);
      ThisModel.session.applyUpdate({
        action: UPDATE$2,
        query: getByIdQuery(this),
        payload: mergeObj
      });
    } // update virtual fields

    this._refreshMany2Many(m2mRelations);
  }
  /**
   * Updates {@link Model} instance attributes to reflect the
   * database state in the current session.
   * @return {undefined}
   */;

  _proto.refreshFromState = function refreshFromState() {
    this._initFields(this.ref);
  }
  /**
   * Deletes the record for this {@link Model} instance.
   * You'll still be able to access fields and values on the instance.
   *
   * @return {undefined}
   */;

  _proto["delete"] = function _delete() {
    var ThisModel = this.getClass();
    if (typeof ThisModel.session === "undefined") {
      throw new Error(["Tried to delete a ".concat(ThisModel.modelName, " model instance without a session. "), "You cannot call `.delete` on an instance that you did not receive from the database."].join(""));
    }
    this._onDelete();
    ThisModel.session.applyUpdate({
      action: DELETE$2,
      query: getByIdQuery(this)
    });
  }
  /**
   * Update many-many relations for model.
   * @param relations
   * @return undefined
   * @private
   */;

  _proto._refreshMany2Many = function _refreshMany2Many(relations) {
    var _this5 = this;
    var ThisModel = this.getClass();
    var fields = ThisModel.fields,
      virtualFields = ThisModel.virtualFields,
      modelName = ThisModel.modelName;
    Object.keys(relations).forEach(function (name) {
      var reverse = !fields.hasOwnProperty(name);
      var field = virtualFields[name];
      var values = relations[name];
      if (!Array.isArray(values)) {
        throw new TypeError("Failed to resolve many-to-many relationship: ".concat(modelName, "[").concat(name, "] must be an array (passed: ").concat(values, ")"));
      }
      var normalizedNewIds = values.map(normalizeEntity);
      var uniqueIds = _toConsumableArray$1(new Set(normalizedNewIds));
      if (normalizedNewIds.length !== uniqueIds.length) {
        throw new Error("Found duplicate id(s) when passing \"".concat(normalizedNewIds, "\" to ").concat(ThisModel.modelName, ".").concat(name, " value"));
      }
      var throughModelName = field.through || m2mName(ThisModel.modelName, name);
      var ThroughModel = ThisModel.session[throughModelName];
      var fromField;
      var toField;
      if (!reverse) {
        var _field$throughFields = field.throughFields;
        fromField = _field$throughFields.from;
        toField = _field$throughFields.to;
      } else {
        var _field$throughFields2 = field.throughFields;
        toField = _field$throughFields2.from;
        fromField = _field$throughFields2.to;
      }
      var currentIds = ThroughModel.filter(function (through) {
        return through[fromField] === _this5[ThisModel.idAttribute];
      }).toRefArray().map(function (ref) {
        return ref[toField];
      });
      var diffActions = arrayDiffActions(currentIds, normalizedNewIds);
      if (diffActions) {
        var idsToDelete = diffActions["delete"],
          idsToAdd = diffActions.add;
        if (idsToDelete.length > 0) {
          var _this6;
          (_this6 = _this5[field.as || name]).remove.apply(_this6, _toConsumableArray$1(idsToDelete));
        }
        if (idsToAdd.length > 0) {
          var _this7;
          (_this7 = _this5[field.as || name]).add.apply(_this7, _toConsumableArray$1(idsToAdd));
        }
      }
    });
  }
  /**
   * @return {undefined}
   * @private
   */;

  _proto._onDelete = function _onDelete() {
    var _this$getClass = this.getClass(),
      virtualFields = _this$getClass.virtualFields; // eslint-disable-next-line guard-for-in, no-restricted-syntax

    for (var key in virtualFields) {
      var field = virtualFields[key];
      if (field instanceof ManyToMany$1) {
        // Delete any many-to-many rows the entity is included in.
        var descriptorKey = field.as || key;
        this[descriptorKey].clear();
      } else if (field instanceof ForeignKey$4) {
        var relatedQs = this[key];
        if (relatedQs.exists()) {
          relatedQs.update(_defineProperty$7({}, field.relatedName, null));
        }
      } else if (field instanceof OneToOne$1) {
        // Set null to any foreign keys or one to ones pointed to
        // this instance.
        if (this[key] !== null) {
          this[key][field.relatedName] = null;
        }
      }
    }
  } // DEPRECATED AND REMOVED METHODS

  /**
   * Returns a boolean indicating if an entity
   * with the id `id` exists in the state.
   *
   * @param  {*}  id - a value corresponding to the id attribute of the {@link Model} class.
   * @return {Boolean} a boolean indicating if entity with `id` exists in the state
   * @deprecated Please use {@link Model.idExists} instead.
   */;

  Model.hasId = function hasId(id) {
    console.warn("`Model.hasId` has been deprecated. Please use `Model.idExists` instead.");
    return this.idExists(id);
  }
  /**
   * @deprecated See the 0.9 migration guide on the GitHub repo.
   * @throws {Error} Due to deprecation.
   */;

  _proto.getNextState = function getNextState() {
    throw new Error("`Model.prototype.getNextState` has been removed. See the 0.9 " + "migration guide on the GitHub repo.");
  };
  _createClass(Model, [{
    key: "ref",
    get: function get() {
      var ThisModel = this.getClass(); // eslint-disable-next-line no-underscore-dangle

      return ThisModel._findDatabaseRows(_defineProperty$7({}, ThisModel.idAttribute, this.getId()))[0];
    }
  }], [{
    key: "idAttribute",
    get: function get() {
      if (typeof this._session === "undefined") {
        throw new Error(["Tried to get the ".concat(this.modelName, " model's id attribute without a session. "), "Create a session using `session = orm.session()` and access ", "`session[\"".concat(this.modelName, "\"].idAttribute` instead.")].join(""));
      }
      return this.session.db.describe(this.modelName).idAttribute;
    }
  }, {
    key: "session",
    get: function get() {
      return this._session;
    }
  }, {
    key: "query",
    get: function get() {
      return this.getQuerySet();
    }
  }]);
  return Model;
}();
Model$1.fields = {
  id: attr$1()
};
Model$1.virtualFields = {};
Model$1.querySetClass = QuerySet$1;
var Model$2 = Model$1;

/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */

function arrayFilter$4(array, predicate) {
  var index = -1,
    length = array == null ? 0 : array.length,
    resIndex = 0,
    result = [];
  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}
var _arrayFilter = arrayFilter$4;

/**
 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */

function createBaseFor$1(fromRight) {
  return function (object, iteratee, keysFunc) {
    var index = -1,
      iterable = Object(object),
      props = keysFunc(object),
      length = props.length;
    while (length--) {
      var key = props[fromRight ? length : ++index];
      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }
    return object;
  };
}
var _createBaseFor = createBaseFor$1;

var createBaseFor = _createBaseFor;

/**
 * The base implementation of `baseForOwn` which iterates over `object`
 * properties returned by `keysFunc` and invokes `iteratee` for each property.
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */
var baseFor$1 = createBaseFor();
var _baseFor = baseFor$1;

/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */

function baseTimes$2(n, iteratee) {
  var index = -1,
    result = Array(n);
  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}
var _baseTimes = baseTimes$2;

/** Detect free variable `global` from Node.js. */

var freeGlobal$3 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal$3;

var freeGlobal$2 = _freeGlobal;

/** Detect free variable `self`. */
var freeSelf$1 = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root$a = freeGlobal$2 || freeSelf$1 || Function('return this')();
var _root = root$a;

var root$9 = _root;

/** Built-in value references. */
var Symbol$8 = root$9.Symbol;
var _Symbol = Symbol$8;

var Symbol$7 = _Symbol;

/** Used for built-in method references. */
var objectProto$p = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$l = objectProto$p.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString$3 = objectProto$p.toString;

/** Built-in value references. */
var symToStringTag$3 = Symbol$7 ? Symbol$7.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag$2(value) {
  var isOwn = hasOwnProperty$l.call(value, symToStringTag$3),
    tag = value[symToStringTag$3];
  try {
    value[symToStringTag$3] = undefined;
    var unmasked = true;
  } catch (e) {}
  var result = nativeObjectToString$3.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag$3] = tag;
    } else {
      delete value[symToStringTag$3];
    }
  }
  return result;
}
var _getRawTag = getRawTag$2;

/** Used for built-in method references. */

var objectProto$o = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString$2 = objectProto$o.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString$3(value) {
  return nativeObjectToString$2.call(value);
}
var _objectToString = objectToString$3;

var Symbol$6 = _Symbol,
  getRawTag$1 = _getRawTag,
  objectToString$2 = _objectToString;

/** `Object#toString` result references. */
var nullTag$1 = '[object Null]',
  undefinedTag$1 = '[object Undefined]';

/** Built-in value references. */
var symToStringTag$2 = Symbol$6 ? Symbol$6.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag$6(value) {
  if (value == null) {
    return value === undefined ? undefinedTag$1 : nullTag$1;
  }
  return symToStringTag$2 && symToStringTag$2 in Object(value) ? getRawTag$1(value) : objectToString$2(value);
}
var _baseGetTag = baseGetTag$6;

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */

function isObjectLike$6(value) {
  return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike$6;

var baseGetTag$5 = _baseGetTag,
  isObjectLike$5 = isObjectLike_1;

/** `Object#toString` result references. */
var argsTag$5 = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments$2(value) {
  return isObjectLike$5(value) && baseGetTag$5(value) == argsTag$5;
}
var _baseIsArguments = baseIsArguments$2;

var baseIsArguments$1 = _baseIsArguments,
  isObjectLike$4 = isObjectLike_1;

/** Used for built-in method references. */
var objectProto$n = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$k = objectProto$n.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable$3 = objectProto$n.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments$5 = baseIsArguments$1(function () {
  return arguments;
}()) ? baseIsArguments$1 : function (value) {
  return isObjectLike$4(value) && hasOwnProperty$k.call(value, 'callee') && !propertyIsEnumerable$3.call(value, 'callee');
};
var isArguments_1 = isArguments$5;

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */

var isArray$h = Array.isArray;
var isArray_1 = isArray$h;

var isBuffer$4 = {exports: {}};

/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */

function stubFalse$1() {
  return false;
}
var stubFalse_1 = stubFalse$1;

isBuffer$4.exports;

(function (module, exports) {
	var root = _root,
	  stubFalse = stubFalse_1;

	/** Detect free variable `exports`. */
	var freeExports = exports && !exports.nodeType && exports;

	/** Detect free variable `module`. */
	var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;

	/** Detect the popular CommonJS extension `module.exports`. */
	var moduleExports = freeModule && freeModule.exports === freeExports;

	/** Built-in value references. */
	var Buffer = moduleExports ? root.Buffer : undefined;

	/* Built-in method references for those with the same name as other `lodash` methods. */
	var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

	/**
	 * Checks if `value` is a buffer.
	 *
	 * @static
	 * @memberOf _
	 * @since 4.3.0
	 * @category Lang
	 * @param {*} value The value to check.
	 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
	 * @example
	 *
	 * _.isBuffer(new Buffer(2));
	 * // => true
	 *
	 * _.isBuffer(new Uint8Array(2));
	 * // => false
	 */
	var isBuffer = nativeIsBuffer || stubFalse;
	module.exports = isBuffer; 
} (isBuffer$4, isBuffer$4.exports));

var isBufferExports = isBuffer$4.exports;

/** Used as references for various `Number` constants. */

var MAX_SAFE_INTEGER$3 = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint$1 = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex$4(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER$3 : length;
  return !!length && (type == 'number' || type != 'symbol' && reIsUint$1.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var _isIndex = isIndex$4;

/** Used as references for various `Number` constants. */

var MAX_SAFE_INTEGER$2 = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength$4(value) {
  return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$2;
}
var isLength_1 = isLength$4;

var baseGetTag$4 = _baseGetTag,
  isLength$3 = isLength_1,
  isObjectLike$3 = isObjectLike_1;

/** `Object#toString` result references. */
var argsTag$4 = '[object Arguments]',
  arrayTag$3 = '[object Array]',
  boolTag$4 = '[object Boolean]',
  dateTag$4 = '[object Date]',
  errorTag$3 = '[object Error]',
  funcTag$4 = '[object Function]',
  mapTag$7 = '[object Map]',
  numberTag$4 = '[object Number]',
  objectTag$6 = '[object Object]',
  regexpTag$4 = '[object RegExp]',
  setTag$7 = '[object Set]',
  stringTag$4 = '[object String]',
  weakMapTag$4 = '[object WeakMap]';
var arrayBufferTag$4 = '[object ArrayBuffer]',
  dataViewTag$6 = '[object DataView]',
  float32Tag$3 = '[object Float32Array]',
  float64Tag$3 = '[object Float64Array]',
  int8Tag$3 = '[object Int8Array]',
  int16Tag$3 = '[object Int16Array]',
  int32Tag$3 = '[object Int32Array]',
  uint8Tag$3 = '[object Uint8Array]',
  uint8ClampedTag$3 = '[object Uint8ClampedArray]',
  uint16Tag$3 = '[object Uint16Array]',
  uint32Tag$3 = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags$1 = {};
typedArrayTags$1[float32Tag$3] = typedArrayTags$1[float64Tag$3] = typedArrayTags$1[int8Tag$3] = typedArrayTags$1[int16Tag$3] = typedArrayTags$1[int32Tag$3] = typedArrayTags$1[uint8Tag$3] = typedArrayTags$1[uint8ClampedTag$3] = typedArrayTags$1[uint16Tag$3] = typedArrayTags$1[uint32Tag$3] = true;
typedArrayTags$1[argsTag$4] = typedArrayTags$1[arrayTag$3] = typedArrayTags$1[arrayBufferTag$4] = typedArrayTags$1[boolTag$4] = typedArrayTags$1[dataViewTag$6] = typedArrayTags$1[dateTag$4] = typedArrayTags$1[errorTag$3] = typedArrayTags$1[funcTag$4] = typedArrayTags$1[mapTag$7] = typedArrayTags$1[numberTag$4] = typedArrayTags$1[objectTag$6] = typedArrayTags$1[regexpTag$4] = typedArrayTags$1[setTag$7] = typedArrayTags$1[stringTag$4] = typedArrayTags$1[weakMapTag$4] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray$2(value) {
  return isObjectLike$3(value) && isLength$3(value.length) && !!typedArrayTags$1[baseGetTag$4(value)];
}
var _baseIsTypedArray = baseIsTypedArray$2;

/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */

function baseUnary$3(func) {
  return function (value) {
    return func(value);
  };
}
var _baseUnary = baseUnary$3;

var _nodeUtil = {exports: {}};

_nodeUtil.exports;

(function (module, exports) {
	var freeGlobal = _freeGlobal;

	/** Detect free variable `exports`. */
	var freeExports = exports && !exports.nodeType && exports;

	/** Detect free variable `module`. */
	var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;

	/** Detect the popular CommonJS extension `module.exports`. */
	var moduleExports = freeModule && freeModule.exports === freeExports;

	/** Detect free variable `process` from Node.js. */
	var freeProcess = moduleExports && freeGlobal.process;

	/** Used to access faster Node.js helpers. */
	var nodeUtil = function () {
	  try {
	    // Use `util.types` for Node.js 10+.
	    var types = freeModule && freeModule.require && freeModule.require('util').types;
	    if (types) {
	      return types;
	    }

	    // Legacy `process.binding('util')` for Node.js < 10.
	    return freeProcess && freeProcess.binding && freeProcess.binding('util');
	  } catch (e) {}
	}();
	module.exports = nodeUtil; 
} (_nodeUtil, _nodeUtil.exports));

var _nodeUtilExports = _nodeUtil.exports;

var baseIsTypedArray$1 = _baseIsTypedArray,
  baseUnary$2 = _baseUnary,
  nodeUtil$2 = _nodeUtilExports;

/* Node.js helper references. */
var nodeIsTypedArray$1 = nodeUtil$2 && nodeUtil$2.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray$4 = nodeIsTypedArray$1 ? baseUnary$2(nodeIsTypedArray$1) : baseIsTypedArray$1;
var isTypedArray_1 = isTypedArray$4;

var baseTimes$1 = _baseTimes,
  isArguments$4 = isArguments_1,
  isArray$g = isArray_1,
  isBuffer$3 = isBufferExports,
  isIndex$3 = _isIndex,
  isTypedArray$3 = isTypedArray_1;

/** Used for built-in method references. */
var objectProto$m = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$j = objectProto$m.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys$2(value, inherited) {
  var isArr = isArray$g(value),
    isArg = !isArr && isArguments$4(value),
    isBuff = !isArr && !isArg && isBuffer$3(value),
    isType = !isArr && !isArg && !isBuff && isTypedArray$3(value),
    skipIndexes = isArr || isArg || isBuff || isType,
    result = skipIndexes ? baseTimes$1(value.length, String) : [],
    length = result.length;
  for (var key in value) {
    if ((inherited || hasOwnProperty$j.call(value, key)) && !(skipIndexes && (
    // Safari 9 has enumerable `arguments.length` in strict mode.
    key == 'length' ||
    // Node.js 0.10 has enumerable non-index properties on buffers.
    isBuff && (key == 'offset' || key == 'parent') ||
    // PhantomJS 2 has enumerable non-index properties on typed arrays.
    isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
    // Skip index properties.
    isIndex$3(key, length)))) {
      result.push(key);
    }
  }
  return result;
}
var _arrayLikeKeys = arrayLikeKeys$2;

/** Used for built-in method references. */

var objectProto$l = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype$2(value) {
  var Ctor = value && value.constructor,
    proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$l;
  return value === proto;
}
var _isPrototype = isPrototype$2;

/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */

function overArg$2(func, transform) {
  return function (arg) {
    return func(transform(arg));
  };
}
var _overArg = overArg$2;

var overArg$1 = _overArg;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys$3 = overArg$1(Object.keys, Object);
var _nativeKeys = nativeKeys$3;

var isPrototype$1 = _isPrototype,
  nativeKeys$2 = _nativeKeys;

/** Used for built-in method references. */
var objectProto$k = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$i = objectProto$k.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys$2(object) {
  if (!isPrototype$1(object)) {
    return nativeKeys$2(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty$i.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}
var _baseKeys = baseKeys$2;

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */

function isObject$6(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}
var isObject_1 = isObject$6;

var baseGetTag$3 = _baseGetTag,
  isObject$5 = isObject_1;

/** `Object#toString` result references. */
var asyncTag$1 = '[object AsyncFunction]',
  funcTag$3 = '[object Function]',
  genTag$2 = '[object GeneratorFunction]',
  proxyTag$1 = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction$5(value) {
  if (!isObject$5(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = baseGetTag$3(value);
  return tag == funcTag$3 || tag == genTag$2 || tag == asyncTag$1 || tag == proxyTag$1;
}
var isFunction_1 = isFunction$5;

var isFunction$4 = isFunction_1,
  isLength$2 = isLength_1;

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike$5(value) {
  return value != null && isLength$2(value.length) && !isFunction$4(value);
}
var isArrayLike_1 = isArrayLike$5;

var arrayLikeKeys$1 = _arrayLikeKeys,
  baseKeys$1 = _baseKeys,
  isArrayLike$4 = isArrayLike_1;

/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys$4(object) {
  return isArrayLike$4(object) ? arrayLikeKeys$1(object) : baseKeys$1(object);
}
var keys_1 = keys$4;

var baseFor = _baseFor,
  keys$3 = keys_1;

/**
 * The base implementation of `_.forOwn` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */
function baseForOwn$1(object, iteratee) {
  return object && baseFor(object, iteratee, keys$3);
}
var _baseForOwn = baseForOwn$1;

var isArrayLike$3 = isArrayLike_1;

/**
 * Creates a `baseEach` or `baseEachRight` function.
 *
 * @private
 * @param {Function} eachFunc The function to iterate over a collection.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseEach$1(eachFunc, fromRight) {
  return function (collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!isArrayLike$3(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length,
      index = fromRight ? length : -1,
      iterable = Object(collection);
    while (fromRight ? index-- : ++index < length) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}
var _createBaseEach = createBaseEach$1;

var baseForOwn = _baseForOwn,
  createBaseEach = _createBaseEach;

/**
 * The base implementation of `_.forEach` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */
var baseEach$2 = createBaseEach(baseForOwn);
var _baseEach = baseEach$2;

var baseEach$1 = _baseEach;

/**
 * The base implementation of `_.filter` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function baseFilter$2(collection, predicate) {
  var result = [];
  baseEach$1(collection, function (value, index, collection) {
    if (predicate(value, index, collection)) {
      result.push(value);
    }
  });
  return result;
}
var _baseFilter = baseFilter$2;

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */

function listCacheClear$2() {
  this.__data__ = [];
  this.size = 0;
}
var _listCacheClear = listCacheClear$2;

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */

function eq$4(value, other) {
  return value === other || value !== value && other !== other;
}
var eq_1 = eq$4;

var eq$3 = eq_1;

/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf$5(array, key) {
  var length = array.length;
  while (length--) {
    if (eq$3(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}
var _assocIndexOf = assocIndexOf$5;

var assocIndexOf$4 = _assocIndexOf;

/** Used for built-in method references. */
var arrayProto$1 = Array.prototype;

/** Built-in value references. */
var splice$1 = arrayProto$1.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete$2(key) {
  var data = this.__data__,
    index = assocIndexOf$4(data, key);
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice$1.call(data, index, 1);
  }
  --this.size;
  return true;
}
var _listCacheDelete = listCacheDelete$2;

var assocIndexOf$3 = _assocIndexOf;

/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet$2(key) {
  var data = this.__data__,
    index = assocIndexOf$3(data, key);
  return index < 0 ? undefined : data[index][1];
}
var _listCacheGet = listCacheGet$2;

var assocIndexOf$2 = _assocIndexOf;

/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas$2(key) {
  return assocIndexOf$2(this.__data__, key) > -1;
}
var _listCacheHas = listCacheHas$2;

var assocIndexOf$1 = _assocIndexOf;

/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet$2(key, value) {
  var data = this.__data__,
    index = assocIndexOf$1(data, key);
  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}
var _listCacheSet = listCacheSet$2;

var listCacheClear$1 = _listCacheClear,
  listCacheDelete$1 = _listCacheDelete,
  listCacheGet$1 = _listCacheGet,
  listCacheHas$1 = _listCacheHas,
  listCacheSet$1 = _listCacheSet;

/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache$5(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
ListCache$5.prototype.clear = listCacheClear$1;
ListCache$5.prototype['delete'] = listCacheDelete$1;
ListCache$5.prototype.get = listCacheGet$1;
ListCache$5.prototype.has = listCacheHas$1;
ListCache$5.prototype.set = listCacheSet$1;
var _ListCache = ListCache$5;

var ListCache$4 = _ListCache;

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear$2() {
  this.__data__ = new ListCache$4();
  this.size = 0;
}
var _stackClear = stackClear$2;

/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */

function stackDelete$2(key) {
  var data = this.__data__,
    result = data['delete'](key);
  this.size = data.size;
  return result;
}
var _stackDelete = stackDelete$2;

/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */

function stackGet$2(key) {
  return this.__data__.get(key);
}
var _stackGet = stackGet$2;

/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */

function stackHas$2(key) {
  return this.__data__.has(key);
}
var _stackHas = stackHas$2;

var root$8 = _root;

/** Used to detect overreaching core-js shims. */
var coreJsData$3 = root$8['__core-js_shared__'];
var _coreJsData = coreJsData$3;

var coreJsData$2 = _coreJsData;

/** Used to detect methods masquerading as native. */
var maskSrcKey$1 = function () {
  var uid = /[^.]+$/.exec(coreJsData$2 && coreJsData$2.keys && coreJsData$2.keys.IE_PROTO || '');
  return uid ? 'Symbol(src)_1.' + uid : '';
}();

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked$2(func) {
  return !!maskSrcKey$1 && maskSrcKey$1 in func;
}
var _isMasked = isMasked$2;

/** Used for built-in method references. */

var funcProto$4 = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString$4 = funcProto$4.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource$3(func) {
  if (func != null) {
    try {
      return funcToString$4.call(func);
    } catch (e) {}
    try {
      return func + '';
    } catch (e) {}
  }
  return '';
}
var _toSource = toSource$3;

var isFunction$3 = isFunction_1,
  isMasked$1 = _isMasked,
  isObject$4 = isObject_1,
  toSource$2 = _toSource;

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor$1 = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var funcProto$3 = Function.prototype,
  objectProto$j = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString$3 = funcProto$3.toString;

/** Used to check objects for own properties. */
var hasOwnProperty$h = objectProto$j.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative$1 = RegExp('^' + funcToString$3.call(hasOwnProperty$h).replace(reRegExpChar$1, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative$2(value) {
  if (!isObject$4(value) || isMasked$1(value)) {
    return false;
  }
  var pattern = isFunction$3(value) ? reIsNative$1 : reIsHostCtor$1;
  return pattern.test(toSource$2(value));
}
var _baseIsNative = baseIsNative$2;

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */

function getValue$3(object, key) {
  return object == null ? undefined : object[key];
}
var _getValue = getValue$3;

var baseIsNative$1 = _baseIsNative,
  getValue$2 = _getValue;

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative$8(object, key) {
  var value = getValue$2(object, key);
  return baseIsNative$1(value) ? value : undefined;
}
var _getNative = getNative$8;

var getNative$7 = _getNative,
  root$7 = _root;

/* Built-in method references that are verified to be native. */
var Map$b = getNative$7(root$7, 'Map');
var _Map = Map$b;

var getNative$6 = _getNative;

/* Built-in method references that are verified to be native. */
var nativeCreate$6 = getNative$6(Object, 'create');
var _nativeCreate = nativeCreate$6;

var nativeCreate$5 = _nativeCreate;

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear$2() {
  this.__data__ = nativeCreate$5 ? nativeCreate$5(null) : {};
  this.size = 0;
}
var _hashClear = hashClear$2;

/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */

function hashDelete$2(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}
var _hashDelete = hashDelete$2;

var nativeCreate$4 = _nativeCreate;

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$4 = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var objectProto$i = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$g = objectProto$i.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet$2(key) {
  var data = this.__data__;
  if (nativeCreate$4) {
    var result = data[key];
    return result === HASH_UNDEFINED$4 ? undefined : result;
  }
  return hasOwnProperty$g.call(data, key) ? data[key] : undefined;
}
var _hashGet = hashGet$2;

var nativeCreate$3 = _nativeCreate;

/** Used for built-in method references. */
var objectProto$h = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$f = objectProto$h.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas$2(key) {
  var data = this.__data__;
  return nativeCreate$3 ? data[key] !== undefined : hasOwnProperty$f.call(data, key);
}
var _hashHas = hashHas$2;

var nativeCreate$2 = _nativeCreate;

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$3 = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet$2(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = nativeCreate$2 && value === undefined ? HASH_UNDEFINED$3 : value;
  return this;
}
var _hashSet = hashSet$2;

var hashClear$1 = _hashClear,
  hashDelete$1 = _hashDelete,
  hashGet$1 = _hashGet,
  hashHas$1 = _hashHas,
  hashSet$1 = _hashSet;

/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash$2(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
Hash$2.prototype.clear = hashClear$1;
Hash$2.prototype['delete'] = hashDelete$1;
Hash$2.prototype.get = hashGet$1;
Hash$2.prototype.has = hashHas$1;
Hash$2.prototype.set = hashSet$1;
var _Hash = Hash$2;

var Hash$1 = _Hash,
  ListCache$3 = _ListCache,
  Map$a = _Map;

/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear$2() {
  this.size = 0;
  this.__data__ = {
    'hash': new Hash$1(),
    'map': new (Map$a || ListCache$3)(),
    'string': new Hash$1()
  };
}
var _mapCacheClear = mapCacheClear$2;

/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */

function isKeyable$2(value) {
  var type = typeof value;
  return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
}
var _isKeyable = isKeyable$2;

var isKeyable$1 = _isKeyable;

/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData$5(map, key) {
  var data = map.__data__;
  return isKeyable$1(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
}
var _getMapData = getMapData$5;

var getMapData$4 = _getMapData;

/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete$2(key) {
  var result = getMapData$4(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}
var _mapCacheDelete = mapCacheDelete$2;

var getMapData$3 = _getMapData;

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet$2(key) {
  return getMapData$3(this, key).get(key);
}
var _mapCacheGet = mapCacheGet$2;

var getMapData$2 = _getMapData;

/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas$2(key) {
  return getMapData$2(this, key).has(key);
}
var _mapCacheHas = mapCacheHas$2;

var getMapData$1 = _getMapData;

/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet$2(key, value) {
  var data = getMapData$1(this, key),
    size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}
var _mapCacheSet = mapCacheSet$2;

var mapCacheClear$1 = _mapCacheClear,
  mapCacheDelete$1 = _mapCacheDelete,
  mapCacheGet$1 = _mapCacheGet,
  mapCacheHas$1 = _mapCacheHas,
  mapCacheSet$1 = _mapCacheSet;

/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache$4(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
MapCache$4.prototype.clear = mapCacheClear$1;
MapCache$4.prototype['delete'] = mapCacheDelete$1;
MapCache$4.prototype.get = mapCacheGet$1;
MapCache$4.prototype.has = mapCacheHas$1;
MapCache$4.prototype.set = mapCacheSet$1;
var _MapCache = MapCache$4;

var ListCache$2 = _ListCache,
  Map$9 = _Map,
  MapCache$3 = _MapCache;

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE$1 = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet$2(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache$2) {
    var pairs = data.__data__;
    if (!Map$9 || pairs.length < LARGE_ARRAY_SIZE$1 - 1) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new MapCache$3(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}
var _stackSet = stackSet$2;

var ListCache$1 = _ListCache,
  stackClear$1 = _stackClear,
  stackDelete$1 = _stackDelete,
  stackGet$1 = _stackGet,
  stackHas$1 = _stackHas,
  stackSet$1 = _stackSet;

/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack$3(entries) {
  var data = this.__data__ = new ListCache$1(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
Stack$3.prototype.clear = stackClear$1;
Stack$3.prototype['delete'] = stackDelete$1;
Stack$3.prototype.get = stackGet$1;
Stack$3.prototype.has = stackHas$1;
Stack$3.prototype.set = stackSet$1;
var _Stack = Stack$3;

/** Used to stand-in for `undefined` hash values. */

var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd$1(value) {
  this.__data__.set(value, HASH_UNDEFINED$2);
  return this;
}
var _setCacheAdd = setCacheAdd$1;

/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */

function setCacheHas$1(value) {
  return this.__data__.has(value);
}
var _setCacheHas = setCacheHas$1;

var MapCache$2 = _MapCache,
  setCacheAdd = _setCacheAdd,
  setCacheHas = _setCacheHas;

/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache$1(values) {
  var index = -1,
    length = values == null ? 0 : values.length;
  this.__data__ = new MapCache$2();
  while (++index < length) {
    this.add(values[index]);
  }
}

// Add methods to `SetCache`.
SetCache$1.prototype.add = SetCache$1.prototype.push = setCacheAdd;
SetCache$1.prototype.has = setCacheHas;
var _SetCache = SetCache$1;

/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */

function arraySome$1(array, predicate) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}
var _arraySome = arraySome$1;

/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */

function cacheHas$1(cache, key) {
  return cache.has(key);
}
var _cacheHas = cacheHas$1;

var SetCache = _SetCache,
  arraySome = _arraySome,
  cacheHas = _cacheHas;

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$5 = 1,
  COMPARE_UNORDERED_FLAG$3 = 2;

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
    arrLength = array.length,
    othLength = other.length;
  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Check that cyclic values are equal.
  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);
  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }
  var index = -1,
    result = true,
    seen = bitmask & COMPARE_UNORDERED_FLAG$3 ? new SetCache() : undefined;
  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
      othValue = other[index];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!arraySome(other, function (othValue, othIndex) {
        if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          return seen.push(othIndex);
        }
      })) {
        result = false;
        break;
      }
    } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}
var _equalArrays = equalArrays$2;

var root$6 = _root;

/** Built-in value references. */
var Uint8Array$4 = root$6.Uint8Array;
var _Uint8Array = Uint8Array$4;

/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */

function mapToArray$1(map) {
  var index = -1,
    result = Array(map.size);
  map.forEach(function (value, key) {
    result[++index] = [key, value];
  });
  return result;
}
var _mapToArray = mapToArray$1;

/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */

function setToArray$1(set) {
  var index = -1,
    result = Array(set.size);
  set.forEach(function (value) {
    result[++index] = value;
  });
  return result;
}
var _setToArray = setToArray$1;

var Symbol$5 = _Symbol,
  Uint8Array$3 = _Uint8Array,
  eq$2 = eq_1,
  equalArrays$1 = _equalArrays,
  mapToArray = _mapToArray,
  setToArray = _setToArray;

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$4 = 1,
  COMPARE_UNORDERED_FLAG$2 = 2;

/** `Object#toString` result references. */
var boolTag$3 = '[object Boolean]',
  dateTag$3 = '[object Date]',
  errorTag$2 = '[object Error]',
  mapTag$6 = '[object Map]',
  numberTag$3 = '[object Number]',
  regexpTag$3 = '[object RegExp]',
  setTag$6 = '[object Set]',
  stringTag$3 = '[object String]',
  symbolTag$4 = '[object Symbol]';
var arrayBufferTag$3 = '[object ArrayBuffer]',
  dataViewTag$5 = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var symbolProto$3 = Symbol$5 ? Symbol$5.prototype : undefined,
  symbolValueOf$1 = symbolProto$3 ? symbolProto$3.valueOf : undefined;

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalByTag$1(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case dataViewTag$5:
      if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;
    case arrayBufferTag$3:
      if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array$3(object), new Uint8Array$3(other))) {
        return false;
      }
      return true;
    case boolTag$3:
    case dateTag$3:
    case numberTag$3:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return eq$2(+object, +other);
    case errorTag$2:
      return object.name == other.name && object.message == other.message;
    case regexpTag$3:
    case stringTag$3:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == other + '';
    case mapTag$6:
      var convert = mapToArray;
    case setTag$6:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
      convert || (convert = setToArray);
      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= COMPARE_UNORDERED_FLAG$2;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = equalArrays$1(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;
    case symbolTag$4:
      if (symbolValueOf$1) {
        return symbolValueOf$1.call(object) == symbolValueOf$1.call(other);
      }
  }
  return false;
}
var _equalByTag = equalByTag$1;

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */

function arrayPush$3(array, values) {
  var index = -1,
    length = values.length,
    offset = array.length;
  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}
var _arrayPush = arrayPush$3;

var arrayPush$2 = _arrayPush,
  isArray$f = isArray_1;

/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys$2(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray$f(object) ? result : arrayPush$2(result, symbolsFunc(object));
}
var _baseGetAllKeys = baseGetAllKeys$2;

/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */

function stubArray$2() {
  return [];
}
var stubArray_1 = stubArray$2;

var arrayFilter$3 = _arrayFilter,
  stubArray$1 = stubArray_1;

/** Used for built-in method references. */
var objectProto$g = Object.prototype;

/** Built-in value references. */
var propertyIsEnumerable$2 = objectProto$g.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$2 = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols$3 = !nativeGetSymbols$2 ? stubArray$1 : function (object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter$3(nativeGetSymbols$2(object), function (symbol) {
    return propertyIsEnumerable$2.call(object, symbol);
  });
};
var _getSymbols = getSymbols$3;

var baseGetAllKeys$1 = _baseGetAllKeys,
  getSymbols$2 = _getSymbols,
  keys$2 = keys_1;

/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys$2(object) {
  return baseGetAllKeys$1(object, keys$2, getSymbols$2);
}
var _getAllKeys = getAllKeys$2;

var getAllKeys$1 = _getAllKeys;

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$3 = 1;

/** Used for built-in method references. */
var objectProto$f = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$e = objectProto$f.hasOwnProperty;

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
    objProps = getAllKeys$1(object),
    objLength = objProps.length,
    othProps = getAllKeys$1(other),
    othLength = othProps.length;
  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : hasOwnProperty$e.call(other, key))) {
      return false;
    }
  }
  // Check that cyclic values are equal.
  var objStacked = stack.get(object);
  var othStacked = stack.get(other);
  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);
  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
      othValue = other[key];
    if (customizer) {
      var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
      othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}
var _equalObjects = equalObjects$1;

var getNative$5 = _getNative,
  root$5 = _root;

/* Built-in method references that are verified to be native. */
var DataView$4 = getNative$5(root$5, 'DataView');
var _DataView = DataView$4;

var getNative$4 = _getNative,
  root$4 = _root;

/* Built-in method references that are verified to be native. */
var Promise$4 = getNative$4(root$4, 'Promise');
var _Promise = Promise$4;

var getNative$3 = _getNative,
  root$3 = _root;

/* Built-in method references that are verified to be native. */
var Set$4 = getNative$3(root$3, 'Set');
var _Set = Set$4;

var getNative$2 = _getNative,
  root$2 = _root;

/* Built-in method references that are verified to be native. */
var WeakMap$4 = getNative$2(root$2, 'WeakMap');
var _WeakMap = WeakMap$4;

var DataView$3 = _DataView,
  Map$8 = _Map,
  Promise$3 = _Promise,
  Set$3 = _Set,
  WeakMap$3 = _WeakMap,
  baseGetTag$2 = _baseGetTag,
  toSource$1 = _toSource;

/** `Object#toString` result references. */
var mapTag$5 = '[object Map]',
  objectTag$5 = '[object Object]',
  promiseTag$1 = '[object Promise]',
  setTag$5 = '[object Set]',
  weakMapTag$3 = '[object WeakMap]';
var dataViewTag$4 = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString$1 = toSource$1(DataView$3),
  mapCtorString$1 = toSource$1(Map$8),
  promiseCtorString$1 = toSource$1(Promise$3),
  setCtorString$1 = toSource$1(Set$3),
  weakMapCtorString$1 = toSource$1(WeakMap$3);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag$3 = baseGetTag$2;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if (DataView$3 && getTag$3(new DataView$3(new ArrayBuffer(1))) != dataViewTag$4 || Map$8 && getTag$3(new Map$8()) != mapTag$5 || Promise$3 && getTag$3(Promise$3.resolve()) != promiseTag$1 || Set$3 && getTag$3(new Set$3()) != setTag$5 || WeakMap$3 && getTag$3(new WeakMap$3()) != weakMapTag$3) {
  getTag$3 = function (value) {
    var result = baseGetTag$2(value),
      Ctor = result == objectTag$5 ? value.constructor : undefined,
      ctorString = Ctor ? toSource$1(Ctor) : '';
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString$1:
          return dataViewTag$4;
        case mapCtorString$1:
          return mapTag$5;
        case promiseCtorString$1:
          return promiseTag$1;
        case setCtorString$1:
          return setTag$5;
        case weakMapCtorString$1:
          return weakMapTag$3;
      }
    }
    return result;
  };
}
var _getTag = getTag$3;

var Stack$2 = _Stack,
  equalArrays = _equalArrays,
  equalByTag = _equalByTag,
  equalObjects = _equalObjects,
  getTag$2 = _getTag,
  isArray$e = isArray_1,
  isBuffer$2 = isBufferExports,
  isTypedArray$2 = isTypedArray_1;

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$2 = 1;

/** `Object#toString` result references. */
var argsTag$3 = '[object Arguments]',
  arrayTag$2 = '[object Array]',
  objectTag$4 = '[object Object]';

/** Used for built-in method references. */
var objectProto$e = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$d = objectProto$e.hasOwnProperty;

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = isArray$e(object),
    othIsArr = isArray$e(other),
    objTag = objIsArr ? arrayTag$2 : getTag$2(object),
    othTag = othIsArr ? arrayTag$2 : getTag$2(other);
  objTag = objTag == argsTag$3 ? objectTag$4 : objTag;
  othTag = othTag == argsTag$3 ? objectTag$4 : othTag;
  var objIsObj = objTag == objectTag$4,
    othIsObj = othTag == objectTag$4,
    isSameTag = objTag == othTag;
  if (isSameTag && isBuffer$2(object)) {
    if (!isBuffer$2(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new Stack$2());
    return objIsArr || isTypedArray$2(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
    var objIsWrapped = objIsObj && hasOwnProperty$d.call(object, '__wrapped__'),
      othIsWrapped = othIsObj && hasOwnProperty$d.call(other, '__wrapped__');
    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
        othUnwrapped = othIsWrapped ? other.value() : other;
      stack || (stack = new Stack$2());
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new Stack$2());
  return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
var _baseIsEqualDeep = baseIsEqualDeep$1;

var baseIsEqualDeep = _baseIsEqualDeep,
  isObjectLike$2 = isObjectLike_1;

/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual$2(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || !isObjectLike$2(value) && !isObjectLike$2(other)) {
    return value !== value && other !== other;
  }
  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$2, stack);
}
var _baseIsEqual = baseIsEqual$2;

var Stack$1 = _Stack,
  baseIsEqual$1 = _baseIsEqual;

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$1 = 1,
  COMPARE_UNORDERED_FLAG$1 = 2;

/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */
function baseIsMatch$1(object, source, matchData, customizer) {
  var index = matchData.length,
    length = index,
    noCustomizer = !customizer;
  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index--) {
    var data = matchData[index];
    if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key = data[0],
      objValue = object[key],
      srcValue = data[1];
    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new Stack$1();
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }
      if (!(result === undefined ? baseIsEqual$1(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) : result)) {
        return false;
      }
    }
  }
  return true;
}
var _baseIsMatch = baseIsMatch$1;

var isObject$3 = isObject_1;

/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */
function isStrictComparable$2(value) {
  return value === value && !isObject$3(value);
}
var _isStrictComparable = isStrictComparable$2;

var isStrictComparable$1 = _isStrictComparable,
  keys$1 = keys_1;

/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */
function getMatchData$1(object) {
  var result = keys$1(object),
    length = result.length;
  while (length--) {
    var key = result[length],
      value = object[key];
    result[length] = [key, value, isStrictComparable$1(value)];
  }
  return result;
}
var _getMatchData = getMatchData$1;

/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */

function matchesStrictComparable$2(key, srcValue) {
  return function (object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  };
}
var _matchesStrictComparable = matchesStrictComparable$2;

var baseIsMatch = _baseIsMatch,
  getMatchData = _getMatchData,
  matchesStrictComparable$1 = _matchesStrictComparable;

/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatches$1(source) {
  var matchData = getMatchData(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return matchesStrictComparable$1(matchData[0][0], matchData[0][1]);
  }
  return function (object) {
    return object === source || baseIsMatch(object, source, matchData);
  };
}
var _baseMatches = baseMatches$1;

var baseGetTag$1 = _baseGetTag,
  isObjectLike$1 = isObjectLike_1;

/** `Object#toString` result references. */
var symbolTag$3 = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol$5(value) {
  return typeof value == 'symbol' || isObjectLike$1(value) && baseGetTag$1(value) == symbolTag$3;
}
var isSymbol_1 = isSymbol$5;

var isArray$d = isArray_1,
  isSymbol$4 = isSymbol_1;

/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  reIsPlainProp = /^\w*$/;

/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */
function isKey$3(value, object) {
  if (isArray$d(value)) {
    return false;
  }
  var type = typeof value;
  if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol$4(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
var _isKey = isKey$3;

var MapCache$1 = _MapCache;

/** Error message constants. */
var FUNC_ERROR_TEXT$2 = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function memoize$5(func, resolver) {
  if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT$2);
  }
  var memoized = function () {
    var args = arguments,
      key = resolver ? resolver.apply(this, args) : args[0],
      cache = memoized.cache;
    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize$5.Cache || MapCache$1)();
  return memoized;
}

// Expose `MapCache`.
memoize$5.Cache = MapCache$1;
var memoize_1 = memoize$5;

var memoize$4 = memoize_1;

/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE$1 = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped$2(func) {
  var result = memoize$4(func, function (key) {
    if (cache.size === MAX_MEMOIZE_SIZE$1) {
      cache.clear();
    }
    return key;
  });
  var cache = result.cache;
  return result;
}
var _memoizeCapped = memoizeCapped$2;

var memoizeCapped$1 = _memoizeCapped;

/** Used to match property names within property paths. */
var rePropName$1 = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar$1 = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var stringToPath$3 = memoizeCapped$1(function (string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(rePropName$1, function (match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar$1, '$1') : number || match);
  });
  return result;
});
var _stringToPath = stringToPath$3;

/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */

function arrayMap$3(array, iteratee) {
  var index = -1,
    length = array == null ? 0 : array.length,
    result = Array(length);
  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}
var _arrayMap = arrayMap$3;

var Symbol$4 = _Symbol,
  arrayMap$2 = _arrayMap,
  isArray$c = isArray_1,
  isSymbol$3 = isSymbol_1;

/** Used as references for various `Number` constants. */
var INFINITY$3 = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var symbolProto$2 = Symbol$4 ? Symbol$4.prototype : undefined,
  symbolToString$1 = symbolProto$2 ? symbolProto$2.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString$2(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (isArray$c(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return arrayMap$2(value, baseToString$2) + '';
  }
  if (isSymbol$3(value)) {
    return symbolToString$1 ? symbolToString$1.call(value) : '';
  }
  var result = value + '';
  return result == '0' && 1 / value == -INFINITY$3 ? '-0' : result;
}
var _baseToString = baseToString$2;

var baseToString$1 = _baseToString;

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString$2(value) {
  return value == null ? '' : baseToString$1(value);
}
var toString_1 = toString$2;

var isArray$b = isArray_1,
  isKey$2 = _isKey,
  stringToPath$2 = _stringToPath,
  toString$1 = toString_1;

/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */
function castPath$2(value, object) {
  if (isArray$b(value)) {
    return value;
  }
  return isKey$2(value, object) ? [value] : stringToPath$2(toString$1(value));
}
var _castPath = castPath$2;

var isSymbol$2 = isSymbol_1;

/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function toKey$5(value) {
  if (typeof value == 'string' || isSymbol$2(value)) {
    return value;
  }
  var result = value + '';
  return result == '0' && 1 / value == -INFINITY$2 ? '-0' : result;
}
var _toKey = toKey$5;

var castPath$1 = _castPath,
  toKey$4 = _toKey;

/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */
function baseGet$3(object, path) {
  path = castPath$1(path, object);
  var index = 0,
    length = path.length;
  while (object != null && index < length) {
    object = object[toKey$4(path[index++])];
  }
  return index && index == length ? object : undefined;
}
var _baseGet = baseGet$3;

var baseGet$2 = _baseGet;

/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function get$1(object, path, defaultValue) {
  var result = object == null ? undefined : baseGet$2(object, path);
  return result === undefined ? defaultValue : result;
}
var get_1 = get$1;

/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */

function baseHasIn$1(object, key) {
  return object != null && key in Object(object);
}
var _baseHasIn = baseHasIn$1;

var castPath = _castPath,
  isArguments$3 = isArguments_1,
  isArray$a = isArray_1,
  isIndex$2 = _isIndex,
  isLength$1 = isLength_1,
  toKey$3 = _toKey;

/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */
function hasPath$1(object, path, hasFunc) {
  path = castPath(path, object);
  var index = -1,
    length = path.length,
    result = false;
  while (++index < length) {
    var key = toKey$3(path[index]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && isLength$1(length) && isIndex$2(key, length) && (isArray$a(object) || isArguments$3(object));
}
var _hasPath = hasPath$1;

var baseHasIn = _baseHasIn,
  hasPath = _hasPath;

/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */
function hasIn$1(object, path) {
  return object != null && hasPath(object, path, baseHasIn);
}
var hasIn_1 = hasIn$1;

var baseIsEqual = _baseIsEqual,
  get = get_1,
  hasIn = hasIn_1,
  isKey$1 = _isKey,
  isStrictComparable = _isStrictComparable,
  matchesStrictComparable = _matchesStrictComparable,
  toKey$2 = _toKey;

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
  COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatchesProperty$1(path, srcValue) {
  if (isKey$1(path) && isStrictComparable(srcValue)) {
    return matchesStrictComparable(toKey$2(path), srcValue);
  }
  return function (object) {
    var objValue = get(object, path);
    return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  };
}
var _baseMatchesProperty = baseMatchesProperty$1;

/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */

function identity$4(value) {
  return value;
}
var identity_1 = identity$4;

/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */

function baseProperty$1(key) {
  return function (object) {
    return object == null ? undefined : object[key];
  };
}
var _baseProperty = baseProperty$1;

var baseGet$1 = _baseGet;

/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyDeep$1(path) {
  return function (object) {
    return baseGet$1(object, path);
  };
}
var _basePropertyDeep = basePropertyDeep$1;

var baseProperty = _baseProperty,
  basePropertyDeep = _basePropertyDeep,
  isKey = _isKey,
  toKey$1 = _toKey;

/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */
function property$1(path) {
  return isKey(path) ? baseProperty(toKey$1(path)) : basePropertyDeep(path);
}
var property_1 = property$1;

var baseMatches = _baseMatches,
  baseMatchesProperty = _baseMatchesProperty,
  identity$3 = identity_1,
  isArray$9 = isArray_1,
  property = property_1;

/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */
function baseIteratee$3(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }
  if (value == null) {
    return identity$3;
  }
  if (typeof value == 'object') {
    return isArray$9(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
  }
  return property(value);
}
var _baseIteratee = baseIteratee$3;

var arrayFilter$2 = _arrayFilter,
  baseFilter$1 = _baseFilter,
  baseIteratee$2 = _baseIteratee,
  isArray$8 = isArray_1;

/**
 * Iterates over elements of `collection`, returning an array of all elements
 * `predicate` returns truthy for. The predicate is invoked with three
 * arguments: (value, index|key, collection).
 *
 * **Note:** Unlike `_.remove`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 * @see _.reject
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': true },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * _.filter(users, function(o) { return !o.active; });
 * // => objects for ['fred']
 *
 * // The `_.matches` iteratee shorthand.
 * _.filter(users, { 'age': 36, 'active': true });
 * // => objects for ['barney']
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.filter(users, ['active', false]);
 * // => objects for ['fred']
 *
 * // The `_.property` iteratee shorthand.
 * _.filter(users, 'active');
 * // => objects for ['barney']
 *
 * // Combining several predicates using `_.overEvery` or `_.overSome`.
 * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
 * // => objects for ['fred', 'barney']
 */
function filter(collection, predicate) {
  var func = isArray$8(collection) ? arrayFilter$2 : baseFilter$1;
  return func(collection, baseIteratee$2(predicate));
}
var filter_1 = filter;

var filter$1 = /*@__PURE__*/getDefaultExportFromCjs(filter_1);

var baseEach = _baseEach,
  isArrayLike$2 = isArrayLike_1;

/**
 * The base implementation of `_.map` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function baseMap$1(collection, iteratee) {
  var index = -1,
    result = isArrayLike$2(collection) ? Array(collection.length) : [];
  baseEach(collection, function (value, key, collection) {
    result[++index] = iteratee(value, key, collection);
  });
  return result;
}
var _baseMap = baseMap$1;

/**
 * The base implementation of `_.sortBy` which uses `comparer` to define the
 * sort order of `array` and replaces criteria objects with their corresponding
 * values.
 *
 * @private
 * @param {Array} array The array to sort.
 * @param {Function} comparer The function to define sort order.
 * @returns {Array} Returns `array`.
 */

function baseSortBy$1(array, comparer) {
  var length = array.length;
  array.sort(comparer);
  while (length--) {
    array[length] = array[length].value;
  }
  return array;
}
var _baseSortBy = baseSortBy$1;

var isSymbol$1 = isSymbol_1;

/**
 * Compares values to sort them in ascending order.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {number} Returns the sort order indicator for `value`.
 */
function compareAscending$1(value, other) {
  if (value !== other) {
    var valIsDefined = value !== undefined,
      valIsNull = value === null,
      valIsReflexive = value === value,
      valIsSymbol = isSymbol$1(value);
    var othIsDefined = other !== undefined,
      othIsNull = other === null,
      othIsReflexive = other === other,
      othIsSymbol = isSymbol$1(other);
    if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
      return 1;
    }
    if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
      return -1;
    }
  }
  return 0;
}
var _compareAscending = compareAscending$1;

var compareAscending = _compareAscending;

/**
 * Used by `_.orderBy` to compare multiple properties of a value to another
 * and stable sort them.
 *
 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
 * specify an order of "desc" for descending or "asc" for ascending sort order
 * of corresponding values.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {boolean[]|string[]} orders The order to sort by for each property.
 * @returns {number} Returns the sort order indicator for `object`.
 */
function compareMultiple$1(object, other, orders) {
  var index = -1,
    objCriteria = object.criteria,
    othCriteria = other.criteria,
    length = objCriteria.length,
    ordersLength = orders.length;
  while (++index < length) {
    var result = compareAscending(objCriteria[index], othCriteria[index]);
    if (result) {
      if (index >= ordersLength) {
        return result;
      }
      var order = orders[index];
      return result * (order == 'desc' ? -1 : 1);
    }
  }
  // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  // that causes it, under certain circumstances, to provide the same value for
  // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  // for more details.
  //
  // This also ensures a stable sort in V8 and other engines.
  // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
  return object.index - other.index;
}
var _compareMultiple = compareMultiple$1;

var arrayMap$1 = _arrayMap,
  baseGet = _baseGet,
  baseIteratee$1 = _baseIteratee,
  baseMap = _baseMap,
  baseSortBy = _baseSortBy,
  baseUnary$1 = _baseUnary,
  compareMultiple = _compareMultiple,
  identity$2 = identity_1,
  isArray$7 = isArray_1;

/**
 * The base implementation of `_.orderBy` without param guards.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
 * @param {string[]} orders The sort orders of `iteratees`.
 * @returns {Array} Returns the new sorted array.
 */
function baseOrderBy$2(collection, iteratees, orders) {
  if (iteratees.length) {
    iteratees = arrayMap$1(iteratees, function (iteratee) {
      if (isArray$7(iteratee)) {
        return function (value) {
          return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
        };
      }
      return iteratee;
    });
  } else {
    iteratees = [identity$2];
  }
  var index = -1;
  iteratees = arrayMap$1(iteratees, baseUnary$1(baseIteratee$1));
  var result = baseMap(collection, function (value, key, collection) {
    var criteria = arrayMap$1(iteratees, function (iteratee) {
      return iteratee(value);
    });
    return {
      'criteria': criteria,
      'index': ++index,
      'value': value
    };
  });
  return baseSortBy(result, function (object, other) {
    return compareMultiple(object, other, orders);
  });
}
var _baseOrderBy = baseOrderBy$2;

var baseOrderBy$1 = _baseOrderBy,
  isArray$6 = isArray_1;

/**
 * This method is like `_.sortBy` except that it allows specifying the sort
 * orders of the iteratees to sort by. If `orders` is unspecified, all values
 * are sorted in ascending order. Otherwise, specify an order of "desc" for
 * descending or "asc" for ascending sort order of corresponding values.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
 *  The iteratees to sort by.
 * @param {string[]} [orders] The sort orders of `iteratees`.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
 * @returns {Array} Returns the new sorted array.
 * @example
 *
 * var users = [
 *   { 'user': 'fred',   'age': 48 },
 *   { 'user': 'barney', 'age': 34 },
 *   { 'user': 'fred',   'age': 40 },
 *   { 'user': 'barney', 'age': 36 }
 * ];
 *
 * // Sort by `user` in ascending order and by `age` in descending order.
 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
 */
function orderBy(collection, iteratees, orders, guard) {
  if (collection == null) {
    return [];
  }
  if (!isArray$6(iteratees)) {
    iteratees = iteratees == null ? [] : [iteratees];
  }
  orders = guard ? undefined : orders;
  if (!isArray$6(orders)) {
    orders = orders == null ? [] : [orders];
  }
  return baseOrderBy$1(collection, iteratees, orders);
}
var orderBy_1 = orderBy;

var orderBy$1 = /*@__PURE__*/getDefaultExportFromCjs(orderBy_1);

/** Error message constants. */

var FUNC_ERROR_TEXT$1 = 'Expected a function';

/**
 * Creates a function that negates the result of the predicate `func`. The
 * `func` predicate is invoked with the `this` binding and arguments of the
 * created function.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Function
 * @param {Function} predicate The predicate to negate.
 * @returns {Function} Returns the new negated function.
 * @example
 *
 * function isEven(n) {
 *   return n % 2 == 0;
 * }
 *
 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
 * // => [1, 3, 5]
 */
function negate$1(predicate) {
  if (typeof predicate != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT$1);
  }
  return function () {
    var args = arguments;
    switch (args.length) {
      case 0:
        return !predicate.call(this);
      case 1:
        return !predicate.call(this, args[0]);
      case 2:
        return !predicate.call(this, args[0], args[1]);
      case 3:
        return !predicate.call(this, args[0], args[1], args[2]);
    }
    return !predicate.apply(this, args);
  };
}
var negate_1 = negate$1;

var arrayFilter$1 = _arrayFilter,
  baseFilter = _baseFilter,
  baseIteratee = _baseIteratee,
  isArray$5 = isArray_1,
  negate = negate_1;

/**
 * The opposite of `_.filter`; this method returns the elements of `collection`
 * that `predicate` does **not** return truthy for.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 * @see _.filter
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': false },
 *   { 'user': 'fred',   'age': 40, 'active': true }
 * ];
 *
 * _.reject(users, function(o) { return !o.active; });
 * // => objects for ['fred']
 *
 * // The `_.matches` iteratee shorthand.
 * _.reject(users, { 'age': 40, 'active': true });
 * // => objects for ['barney']
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.reject(users, ['active', false]);
 * // => objects for ['fred']
 *
 * // The `_.property` iteratee shorthand.
 * _.reject(users, 'active');
 * // => objects for ['barney']
 */
function reject(collection, predicate) {
  var func = isArray$5(collection) ? arrayFilter$1 : baseFilter;
  return func(collection, negate(baseIteratee(predicate)));
}
var reject_1 = reject;

var reject$1 = /*@__PURE__*/getDefaultExportFromCjs(reject_1);

var Symbol$3 = _Symbol,
  isArguments$2 = isArguments_1,
  isArray$4 = isArray_1;

/** Built-in value references. */
var spreadableSymbol = Symbol$3 ? Symbol$3.isConcatSpreadable : undefined;

/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable$1(value) {
  return isArray$4(value) || isArguments$2(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
var _isFlattenable = isFlattenable$1;

var arrayPush$1 = _arrayPush,
  isFlattenable = _isFlattenable;

/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten$1(array, depth, predicate, isStrict, result) {
  var index = -1,
    length = array.length;
  predicate || (predicate = isFlattenable);
  result || (result = []);
  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten$1(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush$1(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}
var _baseFlatten = baseFlatten$1;

/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */

function apply$1(func, thisArg, args) {
  switch (args.length) {
    case 0:
      return func.call(thisArg);
    case 1:
      return func.call(thisArg, args[0]);
    case 2:
      return func.call(thisArg, args[0], args[1]);
    case 3:
      return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}
var _apply = apply$1;

var apply = _apply;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */
function overRest$1(func, start, transform) {
  start = nativeMax(start === undefined ? func.length - 1 : start, 0);
  return function () {
    var args = arguments,
      index = -1,
      length = nativeMax(args.length - start, 0),
      array = Array(length);
    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = transform(array);
    return apply(func, this, otherArgs);
  };
}
var _overRest = overRest$1;

/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */

function constant$1(value) {
  return function () {
    return value;
  };
}
var constant_1 = constant$1;

var getNative$1 = _getNative;
var defineProperty$5 = function () {
  try {
    var func = getNative$1(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}();
var _defineProperty$2 = defineProperty$5;

var constant = constant_1,
  defineProperty$4 = _defineProperty$2,
  identity$1 = identity_1;

/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var baseSetToString$1 = !defineProperty$4 ? identity$1 : function (func, string) {
  return defineProperty$4(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(string),
    'writable': true
  });
};
var _baseSetToString = baseSetToString$1;

/** Used to detect hot functions by number of calls within a span of milliseconds. */

var HOT_COUNT = 800,
  HOT_SPAN = 16;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;

/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */
function shortOut$1(func) {
  var count = 0,
    lastCalled = 0;
  return function () {
    var stamp = nativeNow(),
      remaining = HOT_SPAN - (stamp - lastCalled);
    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(undefined, arguments);
  };
}
var _shortOut = shortOut$1;

var baseSetToString = _baseSetToString,
  shortOut = _shortOut;

/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var setToString$1 = shortOut(baseSetToString);
var _setToString = setToString$1;

var identity = identity_1,
  overRest = _overRest,
  setToString = _setToString;

/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest$1(func, start) {
  return setToString(overRest(func, start, identity), func + '');
}
var _baseRest = baseRest$1;

var eq$1 = eq_1,
  isArrayLike$1 = isArrayLike_1,
  isIndex$1 = _isIndex,
  isObject$2 = isObject_1;

/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */
function isIterateeCall$1(value, index, object) {
  if (!isObject$2(object)) {
    return false;
  }
  var type = typeof index;
  if (type == 'number' ? isArrayLike$1(object) && isIndex$1(index, object.length) : type == 'string' && index in object) {
    return eq$1(object[index], value);
  }
  return false;
}
var _isIterateeCall = isIterateeCall$1;

var baseFlatten = _baseFlatten,
  baseOrderBy = _baseOrderBy,
  baseRest = _baseRest,
  isIterateeCall = _isIterateeCall;

/**
 * Creates an array of elements, sorted in ascending order by the results of
 * running each element in a collection thru each iteratee. This method
 * performs a stable sort, that is, it preserves the original sort order of
 * equal elements. The iteratees are invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {...(Function|Function[])} [iteratees=[_.identity]]
 *  The iteratees to sort by.
 * @returns {Array} Returns the new sorted array.
 * @example
 *
 * var users = [
 *   { 'user': 'fred',   'age': 48 },
 *   { 'user': 'barney', 'age': 36 },
 *   { 'user': 'fred',   'age': 30 },
 *   { 'user': 'barney', 'age': 34 }
 * ];
 *
 * _.sortBy(users, [function(o) { return o.user; }]);
 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
 *
 * _.sortBy(users, ['user', 'age']);
 * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
 */
var sortBy = baseRest(function (collection, iteratees) {
  if (collection == null) {
    return [];
  }
  var length = iteratees.length;
  if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }
  return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
var sortBy_1 = sortBy;

var sortBy$1 = /*@__PURE__*/getDefaultExportFromCjs(sortBy_1);

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(Object(source), true).forEach(function (key) {
        _defineProperty$7(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$4(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
var DEFAULT_TABLE_OPTIONS = {
  idAttribute: "id",
  arrName: "items",
  mapName: "itemsById",
  fields: {}
};
/**
 * @private
 * @param {*} _currMax - the current max id
 * @param {*} userPassedId - the new id passed to the create action
 *
 * Both may be undefined. The current max id in the case that this is the first Model
 * being created, and the new id if the id was not explicitly passed to the
 * database.
 *
 * @return {Array} the new max id and the id to use to create the new row
 *
 * If the id's are strings, the id must be passed explicitly every time.
 * In this case, the current max id will remain `NaN` due to `Math.max`, but that's fine.
 */

function idSequencer(_currMax, userPassedId) {
  var currMax = _currMax;
  var newMax;
  var newId;
  if (currMax === undefined) {
    currMax = -1;
  }
  if (userPassedId === undefined) {
    newMax = currMax + 1;
    newId = newMax;
  } else {
    newMax = Math.max(currMax + 1, userPassedId);
    newId = userPassedId;
  }
  return [newMax,
  // new max id
  newId // id to use for row creation
  ];
}
/**
 * Adapt order directions array to @{lodash.orderBy} API.
 *
 * @private
 *
 * @param {Array<Boolean|'asc'|'desc'>} orders? - an array of optional order query directions as provided to {@Link {QuerySet.orderBy}}
 * @return {Array<'asc'|'desc'>|undefined} A normalized ordering array or undefined if none was provided.
 */

function normalizeOrders(orders) {
  if (orders === undefined) {
    return undefined;
  }
  var convert = function convert(order) {
    if (["desc", false].includes(order)) {
      return "desc";
    }
    return "asc";
  };
  return Array.isArray(orders) ? orders.map(convert) : convert(orders);
}
/**
 * Handles the underlying data structure for a {@link Model} class.
 * @private
 */

var Table$3 = /*#__PURE__*/function () {
  /**
   * Creates a new {@link Table} instance.
   * @param  {Object} userOpts - options to use.
   * @param  {string} [userOpts.idAttribute=id] - the id attribute of the entity.
   * @param  {string} [userOpts.arrName=items] - the state attribute where an array of
   *                                             entity id's are stored
   * @param  {string} [userOpts.mapName=itemsById] - the state attribute where the entity objects
   *                                                 are stored in a id to entity object
   *                                                 map.
   * @param  {string} [userOpts.fields={}] - mapping of field key to {@link Field} object
   */
  function Table(userOpts) {
    Object.assign(this, DEFAULT_TABLE_OPTIONS, userOpts);
  }
  /**
   * Returns a reference to the object at index `id`
   * in state `branch`.
   *
   * @param  {Object} branch - the state
   * @param  {Number} id - the id of the object to get
   * @return {Object|undefined} A reference to the raw object in the state or
   *                            `undefined` if not found.
   */

  var _proto = Table.prototype;
  _proto.accessId = function accessId(branch, id) {
    return branch[this.mapName][id];
  };
  _proto.accessIds = function accessIds(branch, ids) {
    var map = branch[this.mapName];
    return ids.map(function (id) {
      return map[id];
    });
  };
  _proto.idExists = function idExists(branch, id) {
    return branch[this.mapName].hasOwnProperty(id);
  };
  _proto.accessIdList = function accessIdList(branch) {
    return branch[this.arrName];
  };
  _proto.accessList = function accessList(branch) {
    return this.accessIds(branch, this.accessIdList(branch));
  };
  _proto.getMaxId = function getMaxId(branch) {
    return this.getMeta(branch, "maxId");
  };
  _proto.setMaxId = function setMaxId(tx, branch, newMaxId) {
    return this.setMeta(tx, branch, "maxId", newMaxId);
  };
  _proto.nextId = function nextId(id) {
    return id + 1;
  }
  /**
   * Returns the default state for the data structure.
   * @return {Object} The default state for this {@link ORM} instance's data structure
   */;

  _proto.getEmptyState = function getEmptyState() {
    var _pkIndex,
      _this = this;
    var pkIndex = (_pkIndex = {}, _defineProperty$7(_pkIndex, this.arrName, []), _defineProperty$7(_pkIndex, this.mapName, {}), _pkIndex);
    var attrIndexes = Object.keys(this.fields).filter(function (attr) {
      return attr !== _this.idAttribute;
    }).filter(function (attr) {
      return _this.fields[attr].index;
    }).reduce(function (indexes, attr) {
      return _objectSpread$4(_objectSpread$4({}, indexes), {}, _defineProperty$7({}, attr, {}));
    }, {});
    return _objectSpread$4(_objectSpread$4({}, pkIndex), {}, {
      indexes: attrIndexes,
      meta: {}
    });
  };
  _proto.setMeta = function setMeta(tx, branch, key, value) {
    var batchToken = tx.batchToken,
      withMutations = tx.withMutations;
    if (withMutations) {
      var res = ops.mutable.setIn(["meta", key], value, branch);
      return res;
    }
    return ops.batch.setIn(batchToken, ["meta", key], value, branch);
  };
  _proto.getMeta = function getMeta(branch, key) {
    return branch.meta[key];
  };
  _proto.query = function query(branch, clauses) {
    var _this2 = this;
    if (clauses.length === 0) {
      return this.accessList(branch);
    }
    var idAttribute = this.idAttribute;
    var optimallyOrderedClauses = sortBy$1(clauses, function (clause) {
      if (clauseFiltersByAttribute(clause, idAttribute)) {
        return 1;
      }
      if (clauseReducesResultSetSize(clause)) {
        return 2;
      }
      return 3;
    });
    var reducer = function reducer(rows, clause) {
      var type = clause.type,
        payload = clause.payload;
      if (!rows) {
        /**
         * First time this reducer is called during query.
         * This is where we apply query optimizations.
         */
        if (clauseFiltersByAttribute(clause, idAttribute)) {
          /**
           * Payload specified a primary key. Use PK index
           * to look up the single row identified by the PK.
           */
          var id = payload[idAttribute];
          var remainingPayload = Object.keys(payload).reduce(function (withoutPkAttr, filterAttr) {
            if (filterAttr !== idAttribute) {
              withoutPkAttr[filterAttr] = payload[filterAttr];
            }
            return withoutPkAttr;
          }, {});
          var ids = _this2.idExists(branch, id) ? [id] : [];
          if (Object.keys(remainingPayload).length) {
            /**
             * Payload has additional, non-PK columns.
             * Filter accessed row by remaining payload (if one was found).
             */
            return reducer(_this2.accessIds(branch, ids), _objectSpread$4(_objectSpread$4({}, clause), {}, {
              payload: remainingPayload
            }));
          }
          /**
           * No need to filter these rows any further.
           * The primary key value satisfies this clause's conditions.
           */

          return _this2.accessIds(branch, ids);
        }
        if (type === FILTER && _typeof$c(payload) === "object") {
          var indexes = Object.entries(branch.indexes);
          var accessedIndexes = [];
          var indexAttrs = [];
          indexes.forEach(function (_ref) {
            var _ref2 = _slicedToArray$1(_ref, 2),
              attr = _ref2[0],
              index = _ref2[1];
            if (clauseFiltersByAttribute(clause, attr)) {
              /**
               * Payload specified an indexed attribute. Use index
               * to potentially decrease amount of accessed rows.
               */
              if (index.hasOwnProperty(payload[attr])) {
                accessedIndexes.push(index[payload[attr]]);
                indexAttrs.push(attr);
              }
            }
          });
          /**
           * Calculate set of unique PK values corresponding to each
           * foreign key's attribute value. Then retrieve all those rows.
           */

          if (accessedIndexes.length) {
            var lastIndex = accessedIndexes.pop();
            var indexedIds = accessedIndexes.reduce(function (result, index) {
              var indexSet = new Set(index);
              return result.filter(Set.prototype.has, indexSet);
            }, lastIndex);
            var _remainingPayload = Object.keys(payload).reduce(function (withoutIndexAttrs, filterAttr) {
              if (!indexAttrs.includes(filterAttr)) {
                withoutIndexAttrs[filterAttr] = payload[filterAttr];
              }
              return withoutIndexAttrs;
            }, {});
            if (Object.keys(_remainingPayload).length) {
              /**
               * Payload has additional, non-indexed columns.
               * Filter indexed rows by remaining payload (if any were found).
               */
              return reducer(_this2.accessIds(branch, indexedIds), _objectSpread$4(_objectSpread$4({}, clause), {}, {
                payload: _remainingPayload
              }));
            }
            /**
             * No need to filter these rows any further.
             * The used indexes satisfy this clause's conditions.
             */

            return _this2.accessIds(branch, indexedIds);
          }
        } // Give up optimization: Retrieve all rows (full table scan).

        return reducer(_this2.accessList(branch), clause);
      }
      switch (type) {
        case FILTER:
          {
            return filter$1(rows, payload);
          }
        case EXCLUDE:
          {
            return reject$1(rows, payload);
          }
        case ORDER_BY:
          {
            var _payload = _slicedToArray$1(payload, 2),
              iteratees = _payload[0],
              orders = _payload[1];
            return orderBy$1(rows, iteratees, normalizeOrders(orders));
          }
        default:
          return rows;
      }
    };
    return optimallyOrderedClauses.reduce(reducer, undefined);
  }
  /**
   * Returns the data structure including a new object `entry`
   * @param  {Object} tx - transaction info
   * @param  {Object} branch - the data structure state
   * @param  {Object} entry - the object to insert
   * @return {Object} an object with two keys: `state` and `created`.
   *                  `state` is the new table state and `created` is the
   *                  row that was created.
   */;

  _proto.insert = function insert(tx, branch, entry) {
    var _ops$batch$merge3;
    var batchToken = tx.batchToken,
      withMutations = tx.withMutations;
    var hasId = entry.hasOwnProperty(this.idAttribute);
    var workingState = branch; // This will not affect string id's.

    var _idSequencer = idSequencer(this.getMaxId(branch), entry[this.idAttribute]),
      _idSequencer2 = _slicedToArray$1(_idSequencer, 2),
      newMaxId = _idSequencer2[0],
      id = _idSequencer2[1];
    workingState = this.setMaxId(tx, branch, newMaxId);
    var finalEntry = hasId ? entry : ops.batch.set(batchToken, this.idAttribute, id, entry);
    var indexesToAppendTo = Object.keys(workingState.indexes).filter(function (fkAttr) {
      return entry.hasOwnProperty(fkAttr) && entry[fkAttr] !== null;
    }).map(function (fkAttr) {
      return [fkAttr, entry[fkAttr]];
    });
    if (withMutations) {
      ops.mutable.push(id, workingState[this.arrName]);
      ops.mutable.set(id, finalEntry, workingState[this.mapName]); // add id to indexes

      indexesToAppendTo.forEach(function (_ref3) {
        var _ref4 = _slicedToArray$1(_ref3, 2),
          attr = _ref4[0],
          value = _ref4[1];
        var attrIndex = workingState.indexes[attr];
        if (attrIndex.hasOwnProperty(value)) {
          ops.mutable.push(id, attrIndex[value]);
        } else {
          ops.mutable.set(value, [id], attrIndex);
        }
      });
      return {
        state: workingState,
        created: finalEntry
      };
    }
    var nextIndexes = ops.batch.merge(batchToken, indexesToAppendTo.reduce(function (indexMap, _ref5) {
      var _ref6 = _slicedToArray$1(_ref5, 2),
        attr = _ref6[0],
        value = _ref6[1];
      indexMap[attr] = ops.batch.merge(batchToken, _defineProperty$7({}, value, ops.batch.push(batchToken, id, indexMap[attr][value] || [])), indexMap[attr]);
      return indexMap;
    }, _objectSpread$4({}, workingState.indexes)), workingState.indexes);
    var nextState = ops.batch.merge(batchToken, (_ops$batch$merge3 = {}, _defineProperty$7(_ops$batch$merge3, this.arrName, ops.batch.push(batchToken, id, workingState[this.arrName])), _defineProperty$7(_ops$batch$merge3, this.mapName, ops.batch.merge(batchToken, _defineProperty$7({}, id, finalEntry), workingState[this.mapName])), _defineProperty$7(_ops$batch$merge3, "indexes", nextIndexes), _ops$batch$merge3), workingState);
    return {
      state: nextState,
      created: finalEntry
    };
  }
  /**
   * Returns the data structure with objects where `rows`
   * are merged with `mergeObj`.
   *
   * @param  {Object} tx - transaction info
   * @param  {Object} branch - the data structure state
   * @param  {Object[]} rows - rows to update
   * @param  {Object} mergeObj - The object to merge with each row.
   * @return {Object}
   */;

  _proto.update = function update(tx, branch, rows, mergeObj) {
    var _this3 = this,
      _ops$batch$merge6;
    var batchToken = tx.batchToken,
      withMutations = tx.withMutations;
    var mergeObjInto = function mergeObjInto(row) {
      var merge = withMutations ? ops.mutable.merge : ops.batch.merge(batchToken);
      return merge(mergeObj, row);
    };
    var set = withMutations ? ops.mutable.set : ops.batch.set(batchToken);
    var indexedAttrs = Object.keys(branch.indexes).filter(function (attr) {
      return mergeObj.hasOwnProperty(attr);
    });
    var indexIdsToAdd = [];
    var indexIdsToDelete = [];
    var nextMap = rows.reduce(function (map, row) {
      var prevAttrValues = indexedAttrs.reduce(function (valueMap, attr) {
        return _objectSpread$4(_objectSpread$4({}, valueMap), {}, _defineProperty$7({}, attr, row[attr]));
      }, {});
      var result = mergeObjInto(row);
      var nextAttrValues = indexedAttrs.reduce(function (valueMap, attr) {
        return _objectSpread$4(_objectSpread$4({}, valueMap), {}, _defineProperty$7({}, attr, result[attr]));
      }, {});
      var id = result[_this3.idAttribute];
      var nextRow = set(id, result, map);
      indexedAttrs.forEach(function (attr) {
        var prevValue = prevAttrValues[attr];
        var nextValue = nextAttrValues[attr];
        if (prevValue === nextValue) {
          // attribute has not changed, no need to update any index
          return;
        }
        if (prevValue !== null && typeof prevValue !== "undefined") {
          // remove id from attribute's index for its old value
          indexIdsToDelete.push([attr, prevValue, id]);
        }
        if (nextValue !== null) {
          // add id to attribute's index for its new value
          indexIdsToAdd.push([attr, nextValue, id]);
        }
      });
      return nextRow;
    }, branch[this.mapName]);
    var nextIndexes = branch.indexes;
    if (withMutations) {
      indexIdsToDelete.forEach(function (_ref7) {
        var _ref8 = _slicedToArray$1(_ref7, 3),
          attr = _ref8[0],
          value = _ref8[1],
          id = _ref8[2];
        var arr = nextIndexes[attr][value];
        var idx = arr.indexOf(id);
        ops.mutable.splice(idx, 1, [], arr);
      });
      indexIdsToAdd.forEach(function (_ref9) {
        var _ref10 = _slicedToArray$1(_ref9, 3),
          attr = _ref10[0],
          value = _ref10[1],
          id = _ref10[2];
        ops.mutable.push(id, nextIndexes[attr][value]);
      });
    } else {
      if (indexIdsToAdd.length) {
        nextIndexes = ops.batch.merge(batchToken, indexIdsToAdd.reduce(function (indexMap, _ref11) {
          var _ref12 = _slicedToArray$1(_ref11, 3),
            attr = _ref12[0],
            value = _ref12[1],
            id = _ref12[2];
          indexMap[attr] = ops.batch.merge(batchToken, _defineProperty$7({}, value, ops.batch.push(batchToken, id, indexMap[attr][value] || [])), indexMap[attr]);
          return indexMap;
        }, _objectSpread$4({}, nextIndexes)), nextIndexes);
      }
      if (indexIdsToDelete.length) {
        nextIndexes = ops.batch.merge(batchToken, indexIdsToDelete.reduce(function (indexMap, _ref13) {
          var _ref14 = _slicedToArray$1(_ref13, 3),
            attr = _ref14[0],
            value = _ref14[1],
            id = _ref14[2];
          indexMap[attr] = ops.batch.merge(batchToken, _defineProperty$7({}, value, ops.batch.filter(batchToken, function (rowId) {
            return rowId !== id;
          }, indexMap[attr][value])), indexMap[attr]);
          return indexMap;
        }, _objectSpread$4({}, nextIndexes)), nextIndexes);
      }
    }
    return ops.batch.merge(batchToken, (_ops$batch$merge6 = {}, _defineProperty$7(_ops$batch$merge6, this.mapName, nextMap), _defineProperty$7(_ops$batch$merge6, "indexes", nextIndexes), _ops$batch$merge6), branch);
  }
  /**
   * Returns the data structure without rows `rows`.
   * @param  {Object} tx - transaction info
   * @param  {Object} branch - the data structure state
   * @param  {Object[]} rows - rows to update
   * @return {Object} the data structure without ids in `idsToDelete`.
   */;

  _proto["delete"] = function _delete(tx, branch, rows) {
    var _this4 = this,
      _ops$batch$merge7;
    var batchToken = tx.batchToken,
      withMutations = tx.withMutations;
    var arrName = this.arrName,
      mapName = this.mapName;
    var arr = branch[arrName];
    var idsToDelete = rows.map(function (row) {
      return row[_this4.idAttribute];
    });
    if (withMutations) {
      idsToDelete.forEach(function (id) {
        var idx = arr.indexOf(id);
        ops.mutable.splice(idx, 1, [], arr);
        ops.mutable.omit(id, branch[mapName]);
      }); // delete ids from all indexes

      Object.values(branch.indexes).forEach(function (attrIndex) {
        return Object.values(attrIndex).forEach(function (valueIndex) {
          return idsToDelete.forEach(function (id) {
            var idx = valueIndex.indexOf(id);
            if (idx !== -1) {
              ops.mutable.splice(idx, 1, [], valueIndex);
            }
          });
        });
      });
      return branch;
    }
    var nextIndexes = ops.batch.merge(batchToken, Object.entries(branch.indexes).reduce(function (indexMap, _ref15) {
      var _ref16 = _slicedToArray$1(_ref15, 2),
        attr = _ref16[0],
        attrIndex = _ref16[1];
      indexMap[attr] = ops.batch.merge(batchToken, Object.entries(attrIndex).reduce(function (attrIndexMap, _ref17) {
        var _ref18 = _slicedToArray$1(_ref17, 2),
          value = _ref18[0],
          valueIndex = _ref18[1];
        attrIndexMap[value] = ops.batch.filter(batchToken, function (id) {
          return !idsToDelete.includes(id);
        }, valueIndex);
        return attrIndexMap;
      }, _objectSpread$4({}, indexMap[attr])), indexMap[attr]);
      return indexMap;
    }, _objectSpread$4({}, branch.indexes)), branch.indexes);
    return ops.batch.merge(batchToken, (_ops$batch$merge7 = {}, _defineProperty$7(_ops$batch$merge7, arrName, ops.batch.filter(batchToken, function (id) {
      return !idsToDelete.includes(id);
    }, branch[arrName])), _defineProperty$7(_ops$batch$merge7, mapName, ops.batch.omit(batchToken, idsToDelete, branch[mapName])), _defineProperty$7(_ops$batch$merge7, "indexes", ops.batch.merge(batchToken, nextIndexes, branch.indexes)), _ops$batch$merge7), branch);
  };
  return Table;
}();
var Table$4 = Table$3;

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(Object(source), true).forEach(function (key) {
        _defineProperty$7(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$3(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
var BASE_EMPTY_STATE = {};
Object.defineProperty(BASE_EMPTY_STATE, STATE_FLAG, {
  enumerable: true,
  value: true
});
/** @private */

function replaceTableState(tableName, newTableState, tx, state) {
  var batchToken = tx.batchToken,
    withMutations = tx.withMutations;
  if (withMutations) {
    state[tableName] = newTableState;
    return state;
  }
  return ops.batch.set(batchToken, tableName, newTableState, state);
}
/** @private */

function query(tables, querySpec, state) {
  var tableName = querySpec.table,
    clauses = querySpec.clauses;
  var table = tables[tableName];
  var rows = table.query(state[tableName], clauses);
  return {
    rows: rows
  };
}
/** @private */

function update(tables, updateSpec, tx, state) {
  var action = updateSpec.action,
    payload = updateSpec.payload;
  var tableName;
  var nextTableState;
  var resultPayload;
  if (action === CREATE$1) {
    tableName = updateSpec.table;
    var table = tables[tableName];
    var currTableState = state[tableName];
    var result = table.insert(tx, currTableState, payload);
    nextTableState = result.state;
    resultPayload = result.created;
  } else {
    var querySpec = updateSpec.query;
    tableName = querySpec.table;
    var _query = query(tables, querySpec, state),
      rows = _query.rows;
    var _table = tables[tableName];
    var _currTableState = state[tableName];
    if (action === UPDATE$2) {
      nextTableState = _table.update(tx, _currTableState, rows, payload); // return updated rows

      resultPayload = query(tables, querySpec, state).rows;
    } else if (action === DELETE$2) {
      nextTableState = _table["delete"](tx, _currTableState, rows); // return original rows that we just deleted

      resultPayload = rows;
    } else {
      throw new Error("Database received unknown update type: ".concat(action));
    }
  }
  var nextDBState = replaceTableState(tableName, nextTableState, tx, state);
  return {
    status: SUCCESS$2,
    state: nextDBState,
    payload: resultPayload
  };
}
/**
 * @memberof db
 * @param {Object} schemaSpec
 * @return Object database
 */

function createDatabase(schemaSpec) {
  var tableSpecs = schemaSpec.tables;
  var tables = Object.entries(tableSpecs).reduce(function (map, _ref) {
    var _ref2 = _slicedToArray$1(_ref, 2),
      tableName = _ref2[0],
      tableSpec = _ref2[1];
    return _objectSpread$3(_objectSpread$3({}, map), {}, _defineProperty$7({}, tableName, new Table$4(tableSpec)));
  }, {});
  var getEmptyState = function getEmptyState() {
    return Object.entries(tables).reduce(function (map, _ref3) {
      var _ref4 = _slicedToArray$1(_ref3, 2),
        tableName = _ref4[0],
        table = _ref4[1];
      return _objectSpread$3(_objectSpread$3({}, map), {}, _defineProperty$7({}, tableName, table.getEmptyState()));
    }, BASE_EMPTY_STATE);
  };
  return {
    getEmptyState: getEmptyState,
    query: query.bind(null, tables),
    update: update.bind(null, tables),
    // Used to inspect the schema.
    describe: function describe(tableName) {
      return tables[tableName];
    }
  };
}

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;
}

function _objectWithoutProperties$1(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose$2(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;
}

var SelectorSpec = /*#__PURE__*/function () {
  function SelectorSpec(_ref) {
    var parent = _ref.parent,
      orm = _ref.orm;
    this._parent = parent;
    this._orm = orm;
    this.keySelector = ID_ARG_KEY_SELECTOR;
  }
  _createClass(SelectorSpec, [{
    key: "cachePath",
    get: function get() {
      var basePath = this._parent ? this._parent.cachePath : [];
      return [].concat(_toConsumableArray$1(basePath), [this.key]);
    }
  }, {
    key: "orm",
    get: function get() {
      return this._orm;
    }
  }, {
    key: "parent",
    get: function get() {
      return this._parent;
    }
  }]);
  return SelectorSpec;
}();

function idArgSelector(state, idArg) {
  return idArg;
}

/**
 * @abstract
 */

var ModelBasedSelectorSpec = /*#__PURE__*/function (_SelectorSpec) {
  _inheritsLoose$1(ModelBasedSelectorSpec, _SelectorSpec);
  function ModelBasedSelectorSpec(_ref) {
    var _this;
    var model = _ref.model,
      other = _objectWithoutProperties$1(_ref, ["model"]);
    _this = _SelectorSpec.call(this, other) || this;
    _this._model = model;
    return _this;
  }
  var _proto = ModelBasedSelectorSpec.prototype;

  /** @abstract */
  _proto.valueForInstance = function valueForInstance(_instance, _session, _state) {
    throw new Error("Not implemented");
  };
  _proto.valueForRef = function valueForRef(ref, session, state) {
    var ModelClass = session[this._model.modelName];
    return this.valueForInstance(ModelClass.withId(ref[ModelClass.idAttribute]), session, state);
  };
  _proto.modelIs = function modelIs(modelName) {
    return modelName === this._model.modelName;
  };
  _createClass(ModelBasedSelectorSpec, [{
    key: "dependencies",
    get: function get() {
      return [function (state) {
        return state;
      }, this._orm, idArgSelector];
    }
  }, {
    key: "resultFunc",
    get: function get() {
      return function modelBasedSelectorResult(state, session, idArg) {
        var _this2 = this;
        var ModelClass = session[this._model.modelName];
        if (typeof idArg === "undefined") {
          return ModelClass.all().toModelArray().map(function (instance) {
            return _this2.valueForInstance(instance, session, state);
          });
        }
        if (Array.isArray(idArg)) {
          return idArg.map(function (id) {
            return _this2.valueForInstance(ModelClass.withId(id), session, state);
          });
        }
        return this.valueForInstance(ModelClass.withId(idArg), session, state);
      };
    }
  }, {
    key: "model",
    get: function get() {
      return this._model;
    }
  }]);
  return ModelBasedSelectorSpec;
}(SelectorSpec);

var MapSelectorSpec = /*#__PURE__*/function (_ModelBasedSelectorSp) {
  _inheritsLoose$1(MapSelectorSpec, _ModelBasedSelectorSp);
  function MapSelectorSpec(_ref) {
    var _this;
    var field = _ref.field,
      selector = _ref.selector,
      other = _objectWithoutProperties$1(_ref, ["field", "selector"]);
    _this = _ModelBasedSelectorSp.call(this, other) || this;
    _this._field = field;
    _this._selector = selector;
    return _this;
  }
  /** Result for createSelectorFromSpec, not createSelectorFromSpecFor! */

  var _proto = MapSelectorSpec.prototype;
  _proto.createResultFunc = function createResultFunc(parentSelector) {
    return function mapSelectorResult(state, _session, idArg) {
      var _this2 = this;

      /**
       * The parent selector should return a ref array
       * in case of a single ID being passed.
       * Otherwise it should return an array of ref arrays.
       */
      var parentResult = parentSelector(state, idArg);
      if (parentResult === null) {
        return null;
      }
      if (typeof idArg === "undefined" || Array.isArray(idArg)) {
        return parentResult.map(function (refArray) {
          return refArray === null ? null : refArray.map(function (ref) {
            return ref === null ? null : _this2.valueForRef(ref, null, state);
          });
        });
      }
      return parentResult.map(function (ref) {
        return _this2.valueForRef(ref, null, state);
      });
    };
  };
  _proto.valueForRef = function valueForRef(ref, _session, state) {
    var idAttribute = this._parent.toModel.idAttribute;
    return this._selector(state, ref[idAttribute]);
  };
  _createClass(MapSelectorSpec, [{
    key: "selector",
    get: function get() {
      return this._selector;
    },
    set: function set(selector) {
      this._selector = selector;
    }
  }, {
    key: "key",
    get: function get() {
      return this._selector;
    }
  }]);
  return MapSelectorSpec;
}(ModelBasedSelectorSpec);

var ModelSelectorSpec = /*#__PURE__*/function (_SelectorSpec) {
  _inheritsLoose$1(ModelSelectorSpec, _SelectorSpec);
  function ModelSelectorSpec(_ref) {
    var _this;
    var model = _ref.model,
      other = _objectWithoutProperties$1(_ref, ["model"]);
    _this = _SelectorSpec.call(this, other) || this;
    _this._model = model;
    return _this;
  }
  var _proto = ModelSelectorSpec.prototype;
  _proto.valueForRef = function valueForRef(ref, _session) {
    return ref;
  };
  _proto.modelIs = function modelIs(modelName) {
    return modelName === this._model.modelName;
  };
  _createClass(ModelSelectorSpec, [{
    key: "key",
    get: function get() {
      return this._model.modelName;
    }
  }, {
    key: "dependencies",
    get: function get() {
      return [function (state) {
        return state;
      }, this._orm, idArgSelector];
    }
  }, {
    key: "resultFunc",
    get: function get() {
      return function modelSelectorResult(_state, session, idArg) {
        var ModelClass = session[this._model.modelName];
        if (typeof idArg === "undefined") {
          return ModelClass.all().toRefArray();
        }
        if (Array.isArray(idArg)) {
          return idArg.map(function (id) {
            var instance = ModelClass.withId(id);
            return instance ? instance.ref : null;
          });
        }
        var instance = ModelClass.withId(idArg);
        return instance ? instance.ref : null;
      };
    }
  }, {
    key: "model",
    get: function get() {
      return this._model;
    }
  }]);
  return ModelSelectorSpec;
}(SelectorSpec);

var FieldSelectorSpec = /*#__PURE__*/function (_ModelBasedSelectorSp) {
  _inheritsLoose$1(FieldSelectorSpec, _ModelBasedSelectorSp);
  function FieldSelectorSpec(_ref) {
    var _this;
    var field = _ref.field,
      fieldModel = _ref.fieldModel,
      accessorName = _ref.accessorName,
      isVirtual = _ref.isVirtual,
      other = _objectWithoutProperties$1(_ref, ["field", "fieldModel", "accessorName", "isVirtual"]);
    _this = _ModelBasedSelectorSp.call(this, other) || this;
    _this._field = field;
    _this._fieldModel = fieldModel;
    _this._accessorName = accessorName;
    _this._isVirtual = isVirtual;
    return _this;
  }
  var _proto = FieldSelectorSpec.prototype;
  _proto.valueForInstance = function valueForInstance(instance, session, state) {
    if (!instance) {
      return null;
    }
    var value;
    if (this._parent instanceof ModelSelectorSpec) {
      /* orm.Model.field */
      value = instance[this._accessorName];
    } else {
      /* orm.Model.field1.field2..fieldN.field */
      var ParentToModel = session[this._parent.toModelName];
      var parentRef = this._parent.valueForInstance(instance, session, state);
      var parentInstance = parentRef ? new ParentToModel(parentRef) : null;
      value = parentInstance ? parentInstance[this._accessorName] : null;
    }
    if (value instanceof Model$2) {
      return value.ref;
    }
    if (value instanceof QuerySet$1) {
      return value.toRefArray();
    }
    return value;
  };
  _proto.map = function map(selector) {
    if (selector instanceof ModelSelectorSpec) {
      if (this.toModelName === selector.model.modelName) {
        throw new Error("Cannot select models in a `map()` call. If you just want the `".concat(this._accessorName, "` as a ref array then you can simply drop the `map()`. Otherwise make sure you're passing a field selector of the form `").concat(this.toModelName, ".<field>` or a custom selector instead."));
      } else {
        throw new Error("Cannot select `".concat(selector.model.modelName, "` models in this `map()` call. Make sure you're passing a field selector of the form `").concat(this.toModelName, ".<field>` or a custom selector instead."));
      }
    } else if (selector instanceof FieldSelectorSpec || selector instanceof MapSelectorSpec) {
      if (this.toModelName !== selector.model.modelName) {
        throw new Error("Cannot select fields of the `".concat(selector.model.modelName, "` model in this `map()` call. Make sure you're passing a field selector of the form `").concat(this.toModelName, ".<field>` or a custom selector instead."));
      }
    } else if (!selector || typeof selector !== "function" || !selector.recomputations) {
      throw new Error("`map()` requires a selector as an input. Received: ".concat(JSON.stringify(selector), " of type ").concat(_typeof$c(selector)));
    }
    if (!(this._field instanceof ForeignKey$4) && !(this._field instanceof ManyToMany$1)) {
      throw new Error("Cannot map selectors for non-collection fields");
    }
    return new MapSelectorSpec({
      parent: this,
      model: this._model,
      orm: this._orm,
      field: this._field,
      selector: selector
    });
  };
  _createClass(FieldSelectorSpec, [{
    key: "key",
    get: function get() {
      return this._accessorName;
    }
  }, {
    key: "toModelName",
    get: function get() {
      return this._field.toModelName === "this" ? this._fieldModel.modelName : this._field.toModelName;
    }
  }, {
    key: "toModel",
    get: function get() {
      var db = this._orm.getDatabase();
      return db.describe(this.toModelName);
    }
  }]);
  return FieldSelectorSpec;
}(ModelBasedSelectorSpec);

/**
 * @module selectors
 * @private
 */

function createFieldSelectorSpec(_ref) {
  var parent = _ref.parent,
    model = _ref.model,
    field = _ref.field,
    fieldModel = _ref.fieldModel,
    accessorName = _ref.accessorName,
    orm = _ref.orm,
    isVirtual = _ref.isVirtual;
  var fieldSelectorSpec = new FieldSelectorSpec({
    parent: parent,
    model: model,
    field: field,
    fieldModel: fieldModel,
    accessorName: accessorName,
    orm: orm,
    isVirtual: isVirtual
  });
  /* Do not even try to create field selectors below attributes. */

  if (!(field instanceof RelationalField$1)) {
    // "orm.Author.name.publisher" would be nonsense
    return fieldSelectorSpec;
  }
  /* Prevent field selectors below collections. */

  if (parent instanceof FieldSelectorSpec) {
    /* eslint-disable no-underscore-dangle */
    if (
    // "orm.Author.books.publisher" would be nonsense
    parent._field instanceof ForeignKey$4 && parent._isVirtual ||
    // "orm.Genre.books.publisher" would be nonsense
    parent._field instanceof ManyToMany$1) {
      throw new Error("Cannot create a selector for `".concat(parent._accessorName, ".").concat(accessorName, "` because `").concat(parent._accessorName, "` is a collection field."));
    }
  }
  var toModelName = field.toModelName;
  var toModel = orm.get(toModelName === "this" ? model.modelName : toModelName);
  Object.entries(toModel.fields).forEach(function (_ref2) {
    var _ref3 = _slicedToArray$1(_ref2, 2),
      relatedFieldName = _ref3[0],
      relatedField = _ref3[1];
    var fieldAccessorName = relatedField.as || relatedFieldName;
    Object.defineProperty(fieldSelectorSpec, fieldAccessorName, {
      get: function get() {
        return createFieldSelectorSpec({
          parent: fieldSelectorSpec,
          model: model,
          fieldModel: toModel,
          field: relatedField,
          accessorName: fieldAccessorName,
          orm: orm,
          isVirtual: false
        });
      }
    });
  });
  Object.entries(toModel.virtualFields).forEach(function (_ref4) {
    var _ref5 = _slicedToArray$1(_ref4, 2),
      relatedFieldName = _ref5[0],
      relatedField = _ref5[1];
    var fieldAccessorName = relatedField.as || relatedFieldName;
    if (fieldSelectorSpec.hasOwnProperty(fieldAccessorName)) {
      return;
    }
    Object.defineProperty(fieldSelectorSpec, fieldAccessorName, {
      get: function get() {
        return createFieldSelectorSpec({
          parent: fieldSelectorSpec,
          model: model,
          fieldModel: toModel,
          field: relatedField,
          accessorName: fieldAccessorName,
          orm: orm,
          isVirtual: true
        });
      }
    });
  });
  return fieldSelectorSpec;
}
function createModelSelectorSpec(_ref6) {
  var model = _ref6.model,
    orm = _ref6.orm;
  var modelSelectorSpec = new ModelSelectorSpec({
    parent: null,
    orm: orm,
    model: model
  });
  Object.entries(model.fields).forEach(function (_ref7) {
    var _ref8 = _slicedToArray$1(_ref7, 2),
      fieldName = _ref8[0],
      field = _ref8[1];
    var fieldAccessorName = field.as || fieldName;
    Object.defineProperty(modelSelectorSpec, fieldAccessorName, {
      get: function get() {
        return createFieldSelectorSpec({
          parent: modelSelectorSpec,
          model: model,
          fieldModel: model,
          field: field,
          accessorName: fieldAccessorName,
          orm: orm,
          isVirtual: false
        });
      }
    });
  });
  Object.entries(model.virtualFields).forEach(function (_ref9) {
    var _ref10 = _slicedToArray$1(_ref9, 2),
      fieldName = _ref10[0],
      field = _ref10[1];
    var fieldAccessorName = field.as || fieldName;
    if (modelSelectorSpec.hasOwnProperty(fieldAccessorName)) {
      return;
    }
    Object.defineProperty(modelSelectorSpec, fieldAccessorName, {
      get: function get() {
        return createFieldSelectorSpec({
          parent: modelSelectorSpec,
          model: model,
          fieldModel: model,
          field: field,
          accessorName: fieldAccessorName,
          orm: orm,
          isVirtual: true
        });
      }
    });
  });
  return modelSelectorSpec;
}

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(Object(source), true).forEach(function (key) {
        _defineProperty$7(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$2(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
var ORM_DEFAULTS = {
  createDatabase: createDatabase
};
var RESERVED_TABLE_OPTIONS = ["indexes", "meta"];
var isReservedTableOption = function isReservedTableOption(word) {
  return RESERVED_TABLE_OPTIONS.includes(word);
};
/**
 * ORM - the Object Relational Mapper.
 *
 * Use instances of this class to:
 *
 * - Register your {@link Model} classes using {@link ORM#register}
 * - Get the empty state for the underlying database with {@link ORM#getEmptyState}
 * - Start an immutable database session with {@link ORM#session}
 * - Start a mutating database session with {@link ORM#mutableSession}
 *
 * Internally, this class handles generating a schema specification from models
 * to the database.
 */

var ORM$1 = /*#__PURE__*/function () {
  /**
   * Creates a new ORM instance.
   *
   * @param {Object} [opts]
   * @param {Function} [opts.stateSelector] - function that given a Redux state tree
   *                                          will return the ORM state's subtree,
   *                                          e.g. `state => state.orm`
   *                                          (necessary if you want to use selectors)
   * @param {Function} [opts.createDatabase] - function that creates a database
   */
  function ORM(opts) {
    var _ORM_DEFAULTS = _objectSpread$2(_objectSpread$2({}, ORM_DEFAULTS), opts || {}),
      createDatabase = _ORM_DEFAULTS.createDatabase;
    this.createDatabase = createDatabase;
    this.registry = [];
    this.implicitThroughModels = [];
    this.installedFields = {};
    this.stateSelector = opts ? opts.stateSelector : null;
  }
  /**
   * Registers a {@link Model} class to the ORM.
   *
   * If the model has declared any ManyToMany fields, their
   * through models will be generated and registered with
   * this call, unless a custom through model has been specified.
   *
   * @param  {...Model} models - a {@link Model} class to register
   * @return {undefined}
   */

  var _proto = ORM.prototype;
  _proto.register = function register() {
    var _this = this;
    for (var _len = arguments.length, models = new Array(_len), _key = 0; _key < _len; _key++) {
      models[_key] = arguments[_key];
    }
    models.forEach(function (model) {
      if (model.modelName === undefined) {
        throw new Error("A model was passed that doesn't have a modelName set");
      }
      model.invalidateClassCache();
      _this.registerManyToManyModelsFor(model);
      _this.registry.push(model);
      Object.defineProperty(_this, model.modelName, {
        get: function get() {
          // make sure virtualFields are set up
          _this._setupModelPrototypes(_this.registry);
          return createModelSelectorSpec({
            model: model,
            orm: _this
          });
        }
      });
    });
  };
  _proto.registerManyToManyModelsFor = function registerManyToManyModelsFor(model) {
    var _this2 = this;
    var fields = model.fields;
    var thisModelName = model.modelName;
    Object.entries(fields).forEach(function (_ref) {
      var _ref2 = _slicedToArray$1(_ref, 2),
        fieldName = _ref2[0],
        fieldInstance = _ref2[1];
      if (!(fieldInstance instanceof ManyToMany$1)) {
        return;
      }
      var toModelName;
      if (fieldInstance.toModelName === "this") {
        toModelName = thisModelName;
      } else {
        toModelName = fieldInstance.toModelName; // eslint-disable-line prefer-destructuring
      }

      var selfReferencing = thisModelName === toModelName;
      var fromFieldName = m2mFromFieldName(thisModelName);
      var toFieldName = m2mToFieldName(toModelName);
      if (fieldInstance.through) {
        if (selfReferencing && !fieldInstance.throughFields) {
          throw new Error("Self-referencing many-to-many relationship at " + "\"".concat(thisModelName, ".").concat(fieldName, "\" using custom ") + "model \"".concat(fieldInstance.through, "\" has no ") + "throughFields key. Cannot determine which " + "fields reference the instances partaking " + "in the relationship.");
        }
      } else {
        var _Through$fields;
        var Through = /*#__PURE__*/function (_Model) {
          _inheritsLoose$1(ThroughModel, _Model);
          function ThroughModel() {
            return _Model.apply(this, arguments) || this;
          }
          return ThroughModel;
        }(Model$2);
        Through.modelName = m2mName(thisModelName, fieldName);
        var PlainForeignKey = /*#__PURE__*/function (_ForeignKey) {
          _inheritsLoose$1(PlainForeignKey, _ForeignKey);
          function PlainForeignKey() {
            return _ForeignKey.apply(this, arguments) || this;
          }
          _createClass(PlainForeignKey, [{
            key: "installsBackwardsVirtualField",
            get: function get() {
              return false;
            }
          }, {
            key: "installsBackwardsDescriptor",
            get: function get() {
              return false;
            }
          }]);
          return PlainForeignKey;
        }(ForeignKey$4);
        var ForeignKeyClass = selfReferencing ? PlainForeignKey : ForeignKey$4;
        Through.fields = (_Through$fields = {
          id: attr$1()
        }, _defineProperty$7(_Through$fields, fromFieldName, new ForeignKeyClass(thisModelName)), _defineProperty$7(_Through$fields, toFieldName, new ForeignKeyClass(toModelName)), _Through$fields);
        Through.invalidateClassCache();
        _this2.implicitThroughModels.push(Through);
      }
    });
  }
  /**
   * Gets a {@link Model} class by its name from the registry.
   * @param  {string} modelName - the name of the {@link Model} class to get
   * @throws If {@link Model} class is not found.
   * @return {Model} the {@link Model} class, if found
   */;

  _proto.get = function get(modelName) {
    var allModels = this.registry.concat(this.implicitThroughModels);
    var found = Object.values(allModels).find(function (model) {
      return model.modelName === modelName;
    });
    if (typeof found === "undefined") {
      throw new Error("Did not find model ".concat(modelName, " from registry."));
    }
    return found;
  };
  _proto.getModelClasses = function getModelClasses() {
    this._setupModelPrototypes(this.registry);
    this._setupModelPrototypes(this.implicitThroughModels);
    return this.registry.concat(this.implicitThroughModels);
  };
  _proto.generateSchemaSpec = function generateSchemaSpec() {
    var models = this.getModelClasses();
    var tables = models.reduce(function (spec, modelClass) {
      var tableName = modelClass.modelName;
      var tableSpec = modelClass.tableOptions();
      Object.keys(tableSpec).filter(isReservedTableOption).forEach(function (key) {
        throw new Error("Reserved keyword `".concat(key, "` used in ").concat(tableName, ".options."));
      });
      spec[tableName] = _objectSpread$2({
        fields: _objectSpread$2({}, modelClass.fields)
      }, tableSpec);
      return spec;
    }, {});
    return {
      tables: tables
    };
  };
  _proto.getDatabase = function getDatabase() {
    if (!this.db) {
      this.db = this.createDatabase(this.generateSchemaSpec());
    }
    return this.db;
  }
  /**
   * Returns the empty database state.
   * @return {Object} the empty state
   */;

  _proto.getEmptyState = function getEmptyState() {
    return this.getDatabase().getEmptyState();
  }
  /**
   * Begins an immutable database session.
   *
   * @param  {Object} state  - the state the database manages
   * @return {Session} a new {@link Session} instance
   */;

  _proto.session = function session(state) {
    return new Session$1(this, this.getDatabase(), state);
  }
  /**
   * Begins a mutable database session.
   *
   * @param  {Object} state  - the state the database manages
   * @return {Session} a new {@link Session} instance
   */;

  _proto.mutableSession = function mutableSession(state) {
    return new Session$1(this, this.getDatabase(), state, true);
  }
  /**
   * @private
   */;

  _proto._setupModelPrototypes = function _setupModelPrototypes(models) {
    var _this3 = this;
    models.filter(function (model) {
      return !model.isSetUp;
    }).forEach(function (model) {
      var fields = model.fields,
        modelName = model.modelName,
        querySetClass = model.querySetClass;
      Object.entries(fields).forEach(function (_ref3) {
        var _ref4 = _slicedToArray$1(_ref3, 2),
          fieldName = _ref4[0],
          field = _ref4[1];
        if (!(field instanceof Field$2)) {
          throw new Error("".concat(modelName, ".").concat(fieldName, " is of type \"").concat(_typeof$c(field), "\" ") + "but must be an instance of Field. Please use the " + "`attr`, `fk`, `oneToOne` and `many` " + "functions to define fields.");
        }
        if (!_this3._isFieldInstalled(modelName, fieldName)) {
          _this3._installField(field, fieldName, model);
          _this3._setFieldInstalled(modelName, fieldName);
        }
      });
      attachQuerySetMethods(model, querySetClass);
      model.isSetUp = true;
    });
  }
  /**
   * @private
   */;

  _proto._isFieldInstalled = function _isFieldInstalled(modelName, fieldName) {
    return this.installedFields.hasOwnProperty(modelName) ? !!this.installedFields[modelName][fieldName] : false;
  }
  /**
   * @private
   */;

  _proto._setFieldInstalled = function _setFieldInstalled(modelName, fieldName) {
    if (!this.installedFields.hasOwnProperty(modelName)) {
      this.installedFields[modelName] = {};
    }
    this.installedFields[modelName][fieldName] = true;
  }
  /**
   * Installs a field on a model and its related models if necessary.
   * @private
   */;

  _proto._installField = function _installField(field, fieldName, model) {
    var FieldInstaller = field.installerClass;
    new FieldInstaller({
      field: field,
      fieldName: fieldName,
      model: model,
      orm: this
    }).run();
  } // DEPRECATED AND REMOVED METHODS

  /**
   * @deprecated Use {@link ORM#mutableSession} instead.
   */;

  _proto.withMutations = function withMutations(state) {
    warnDeprecated("`ORM.prototype.withMutations` has been deprecated. " + "Use `ORM.prototype.mutableSession` instead.");
    return this.mutableSession(state);
  }
  /**
   * @deprecated Use {@link ORM#session} instead.
   */;

  _proto.from = function from(state) {
    warnDeprecated("`ORM.prototype.from` has been deprecated. " + "Use `ORM.prototype.session` instead.");
    return this.session(state);
  }
  /**
   * @deprecated Use {@link ORM#getEmptyState} instead.
   */;

  _proto.getDefaultState = function getDefaultState() {
    warnDeprecated("`ORM.prototype.getDefaultState` has been deprecated. Use " + "`ORM.prototype.getEmptyState` instead.");
    return this.getEmptyState();
  }
  /**
   * @deprecated Define a Model class instead.
   */;

  _proto.define = function define() {
    throw new Error("`ORM.prototype.define` has been removed. Please define a Model class.");
  };
  return ORM;
}();
function DeprecatedSchema() {
  throw new Error("Schema has been renamed to ORM. Please import ORM instead of Schema " + "from Redux-ORM.");
}

var createSelectorCreator_1 = createSelectorCreator;
function defaultEqualityCheck$1(a, b) {
  return a === b;
}
function areArgumentsShallowlyEqual(equalityCheck, prev, next) {
  if (prev === null || next === null || prev.length !== next.length) {
    return false;
  }

  // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.
  var length = prev.length;
  for (var i = 0; i < length; i++) {
    if (!equalityCheck(prev[i], next[i])) {
      return false;
    }
  }
  return true;
}
function defaultMemoize(func) {
  var equalityCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultEqualityCheck$1;
  var lastArgs = null;
  var lastResult = null;
  // we reference arguments instead of spreading them for performance reasons
  return function () {
    if (!areArgumentsShallowlyEqual(equalityCheck, lastArgs, arguments)) {
      // apply arguments instead of spreading for performance.
      lastResult = func.apply(null, arguments);
    }
    lastArgs = arguments;
    return lastResult;
  };
}
function getDependencies(funcs) {
  var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs;
  if (!dependencies.every(function (dep) {
    return typeof dep === 'function';
  })) {
    var dependencyTypes = dependencies.map(function (dep) {
      return typeof dep;
    }).join(', ');
    throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']'));
  }
  return dependencies;
}
function createSelectorCreator(memoize) {
  for (var _len = arguments.length, memoizeOptions = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    memoizeOptions[_key - 1] = arguments[_key];
  }
  return function () {
    for (var _len2 = arguments.length, funcs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      funcs[_key2] = arguments[_key2];
    }
    var recomputations = 0;
    var resultFunc = funcs.pop();
    var dependencies = getDependencies(funcs);
    var memoizedResultFunc = memoize.apply(undefined, [function () {
      recomputations++;
      // apply arguments instead of spreading for performance.
      return resultFunc.apply(null, arguments);
    }].concat(memoizeOptions));

    // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.
    var selector = defaultMemoize(function () {
      var params = [];
      var length = dependencies.length;
      for (var i = 0; i < length; i++) {
        // apply arguments instead of spreading and mutate a local list of params for performance.
        params.push(dependencies[i].apply(null, arguments));
      }

      // apply arguments instead of spreading for performance.
      return memoizedResultFunc.apply(null, params);
    });
    selector.resultFunc = resultFunc;
    selector.recomputations = function () {
      return recomputations;
    };
    selector.resetRecomputations = function () {
      return recomputations = 0;
    };
    return selector;
  };
}
createSelectorCreator(defaultMemoize);

function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}

function _isNativeFunction(fn) {
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
}

function _wrapNativeSuper(Class) {
  var _cache = typeof Map === "function" ? new Map() : undefined;
  _wrapNativeSuper = function _wrapNativeSuper(Class) {
    if (Class === null || !_isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }
    function Wrapper() {
      return _construct(Class, arguments, _getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    return _setPrototypeOf(Wrapper, Class);
  };
  return _wrapNativeSuper(Class);
}

function _createForOfIteratorHelper(o, allowArrayLike) {
  var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  if (!it) {
    if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
      if (it) o = it;
      var i = 0;
      var F = function F() {};
      return {
        s: F,
        n: function n() {
          if (i >= o.length) return {
            done: true
          };
          return {
            done: false,
            value: o[i++]
          };
        },
        e: function e(_e) {
          throw _e;
        },
        f: F
      };
    }
    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  var normalCompletion = true,
    didErr = false,
    err;
  return {
    s: function s() {
      it = it.call(o);
    },
    n: function n() {
      var step = it.next();
      normalCompletion = step.done;
      return step;
    },
    e: function e(_e2) {
      didErr = true;
      err = _e2;
    },
    f: function f() {
      try {
        if (!normalCompletion && it["return"] != null) it["return"]();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }
  return arr2;
}
function ownKeys$1(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$1(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$1(Object(source), true).forEach(function (key) {
        _defineProperty$7(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$1(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
var defaultEqualityCheck = function defaultEqualityCheck(a, b) {
  return a === b;
};
var isOrmState = function isOrmState(arg) {
  return arg && _typeof$c(arg) === "object" && arg.hasOwnProperty(STATE_FLAG);
};
var argsAreEqual = function argsAreEqual(lastArgs, nextArgs, equalityCheck) {
  return nextArgs.every(function (arg, index) {
    return isOrmState(arg) && isOrmState(lastArgs[index]) || equalityCheck(arg, lastArgs[index]);
  });
};
var rowsAreEqual = function rowsAreEqual(ids, rowsA, rowsB) {
  return ids.every(function (id) {
    return rowsA[id] === rowsB[id];
  });
};
var accessedModelInstancesAreEqual = function accessedModelInstancesAreEqual(previous, ormState, orm) {
  var accessedInstances = previous.accessedInstances;
  return Object.entries(accessedInstances).every(function (_ref) {
    var _ref2 = _slicedToArray$1(_ref, 2),
      modelName = _ref2[0],
      instances = _ref2[1];

    // if the entire table has not been changed, we have nothing to do
    if (previous.ormState[modelName] === ormState[modelName]) {
      return true;
    }
    var _orm$getDatabase$desc = orm.getDatabase().describe(modelName),
      mapName = _orm$getDatabase$desc.mapName;
    var previousRows = previous.ormState[modelName][mapName];
    var rows = ormState[modelName][mapName];
    var accessedIds = Object.keys(instances);
    return rowsAreEqual(accessedIds, previousRows, rows);
  });
};
var accessedIndexesAreEqual = function accessedIndexesAreEqual(previous, ormState) {
  var accessedIndexes = previous.accessedIndexes;
  return Object.entries(accessedIndexes).every(function (_ref3) {
    var _ref4 = _slicedToArray$1(_ref3, 2),
      modelName = _ref4[0],
      indexes = _ref4[1];
    return Object.entries(indexes).every(function (_ref5) {
      var _ref6 = _slicedToArray$1(_ref5, 2),
        column = _ref6[0],
        values = _ref6[1];
      return values.every(function (value) {
        return previous.ormState[modelName].indexes[column][value] === ormState[modelName].indexes[column][value];
      });
    });
  });
};
var fullTableScannedModelsAreEqual = function fullTableScannedModelsAreEqual(previous, ormState) {
  return previous.fullTableScannedModels.every(function (modelName) {
    return previous.ormState[modelName] === ormState[modelName];
  });
};
var MEMOIZATION_STATE_KEY = "@@_______REDUX_ORM_MEMOIZATION_STATE";
var MEMOIZATION_STATE = {
  /* Result of the previous function call */
  result: null,
  /**
   * Snapshot of the previous database.
   *
   * Lets us know how the tables looked like
   * during the previous function call.
   */
  ormState: null,
  /**
   * Names of models whose tables have been scanned completely
   * during previous function call (contains only model names)
   * Format example: ['Book']
   */
  fullTableScannedModels: [],
  /**
   * Map of which model instances have been accessed
   * during previous function call.
   * Contains only PKs of accessed instances.
   * Format example: { Book: { 1: true, 3: true } }
   */
  accessedInstances: {},
  /**
   * Map of which attribute indexes have been accessed
   * during previous function call.
   * Contains only attributes that were actually filtered on.
   * Author.withId(3).books would add 3 to the authorId index below.
   * Format example: { Book: { authorId: [1, 2], publisherId: [5] } }
   */
  accessedIndexes: {},
  /* Whether the selector has been called */
  calledBefore: false
};
/**
 * A memoizer to use with redux-orm
 * selectors. When the memoized function is first run,
 * the memoizer will remember the models that are accessed
 * during that function run.
 *
 * On subsequent runs, the memoizer will check if those
 * models' states have changed compared to the previous run.
 *
 * Memoization algorithm operates like this:
 *
 * 1. Has the selector been run before? If not, go to 6.
 *
 * 2. If the selector has other input selectors in addition to the
 *    ORM state selector, check their results for equality with the previous results.
 *    If they aren't equal, go to 6.
 *
 * 3. Some filter queries may have required scanning entire tables during the last run.
 *    If any of those tables have changed, go to 6.
 *
 * 4. Check which foreign key indexes the database has used to speed up queries
 *    during the last run. If any have changed, go to 6.
 *
 * 5. Check which Model's instances the selector has accessed during the last run.
 *    Check for equality with each of those states versus their states in the
 *    previous ORM state. If all of them are equal, return the previous result.
 *
 * 6. Run the selector. Check the Session object used by the selector for
 *    which Model's states were accessed, and merge them with the previously
 *    saved information about accessed models (if-else branching can change
 *    which models are accessed on different inputs). Save the ORM state and
 *    other arguments the selector was called with, overriding previously
 *    saved values. Save the selector result. Return the selector result.
 *
 * @private
 * @param  {Function} func - function to memoize
 * @param  {ORM} orm - a redux-orm ORM instance
 * @return {Function} `func` memoized.
 */

function memoize$3(func, orm) {
  var previous = _objectSpread$1(_objectSpread$1({}, MEMOIZATION_STATE), {}, {
    args: null
  });
  return function () {
    for (var _len = arguments.length, stateAndArgs = new Array(_len), _key = 0; _key < _len; _key++) {
      stateAndArgs[_key] = arguments[_key];
    }

    /**
     * The first argument to this function needs to be
     * the ORM's reducer state in the user's Redux store.
     */
    var ormState = stateAndArgs[0],
      args = stateAndArgs.slice(1);
    if (previous.calledBefore && argsAreEqual(previous.args, args, defaultEqualityCheck) && fullTableScannedModelsAreEqual(previous, ormState) && accessedIndexesAreEqual(previous, ormState) && accessedModelInstancesAreEqual(previous, ormState, orm)) {
      /**
       * None of this selector's dependencies have changed
       * since the last time that we called it.
       */
      return previous.result;
    }
    /**
     * Start a session so that the selector can access the database.
     * Make this session immutable. This way we can find out if
     * the operations that the selector performs are cacheable.
     */

    var session = orm.session(ormState);
    /* Replace all ORM state arguments by the session above */

    var argsWithSession = args.map(function (arg) {
      return isOrmState(arg) ? session : arg;
    });
    /* This is where we call the actual function */

    var result = func.apply(null, argsWithSession); // eslint-disable-line prefer-spread

    /**
     * The metadata for the previous call are no longer valid.
     * Update cached values.
     */

    previous.result = result;
    previous.args = args;
    /* Redux state slice for session.state */

    previous.ormState = ormState;
    /* Rows retrieved by resolved primary key */

    previous.accessedInstances = session.accessedModelInstances;
    /* Foreign key indexes that were used to speed up queries */

    previous.accessedIndexes = session.accessedIndexes;
    /* Tables that had to be scanned completely */

    previous.fullTableScannedModels = session.fullTableScannedModels;
    /* Whether the selector has been called */

    previous.calledBefore = true;
    return result;
  };
}
var PreviousCalls = /*#__PURE__*/function (_Map) {
  _inheritsLoose$1(PreviousCalls, _Map);
  function PreviousCalls() {
    return _Map.apply(this, arguments) || this;
  }
  var _proto = PreviousCalls.prototype;
  _proto.getFromCacheKeys = function getFromCacheKeys(cacheKeys) {
    var level = this;
    var _iterator = _createForOfIteratorHelper(cacheKeys),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var key = _step.value;
        if (level.has(key)) {
          level = level.get(key);
          continue;
        }
        var newLevel = new Map([[MEMOIZATION_STATE_KEY, _objectSpread$1({}, MEMOIZATION_STATE)]]);
        level.set(key, newLevel);
        level = newLevel;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return level;
  };
  _proto.getState = function getState(cacheKeys) {
    var call = this.getFromCacheKeys(cacheKeys);
    return call ? call.get(MEMOIZATION_STATE_KEY) : null;
  };
  return PreviousCalls;
}( /*#__PURE__*/_wrapNativeSuper(Map));
function memoizeByKey(func, orm, ignoreDependenciesCount) {
  var previousCalls = new PreviousCalls([[MEMOIZATION_STATE_KEY, _objectSpread$1({}, MEMOIZATION_STATE)]]);
  return function () {
    for (var _len2 = arguments.length, stateAndKeysAndArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      stateAndKeysAndArgs[_key2] = arguments[_key2];
    }

    /**
     * The first argument to this function needs to be
     * the ORM's reducer state in the user's Redux store.
     */
    var ormState = stateAndKeysAndArgs[0],
      cacheKeys = stateAndKeysAndArgs[1],
      args = stateAndKeysAndArgs.slice(2);
    /** Ignore the first `ignoreDependenciesCount` dependencies. */

    var argsToCompare = args.slice(Math.max(0, ignoreDependenciesCount));
    var previous = previousCalls.getState([cacheKeys]);
    if (previous.calledBefore && argsAreEqual(previous.argsToCompare, argsToCompare, defaultEqualityCheck) && fullTableScannedModelsAreEqual(previous, ormState) && accessedIndexesAreEqual(previous, ormState) && accessedModelInstancesAreEqual(previous, ormState, orm)) {
      /**
       * None of this selector's dependencies have changed
       * since the last time that we called it.
       */
      return previous.result;
    }
    /**
     * Start a session so that the selector can access the database.
     * Make this session immutable. This way we can find out if
     * the operations that the selector performs are cacheable.
     */

    var session = orm.session(ormState);
    /* Replace all ORM state arguments by the session above */

    var argsWithSession = args.map(function (arg) {
      return isOrmState(arg) ? session : arg;
    });
    /* This is where we call the actual function */

    var result = func.apply(null, argsWithSession); // eslint-disable-line prefer-spread

    /**
     * The metadata for the previous call are no longer valid.
     * Update cached values.
     */

    previous.result = result;
    /* Redux state slice for session.state */

    previous.ormState = ormState;
    /* Rows retrieved by resolved primary key */

    previous.accessedInstances = session.accessedModelInstances;
    /* Foreign key indexes that were used to speed up queries */

    previous.accessedIndexes = session.accessedIndexes;
    /* Tables that had to be scanned completely */

    previous.fullTableScannedModels = session.fullTableScannedModels;
    /* Whether the selector has been called */

    previous.calledBefore = true;
    previous.argsToCompare = argsToCompare;
    return result;
  };
}

/**
 * @module redux
 * @desc Provides functions for integration with Redux.
 */

/**
 * Calls all models' reducers if they exist.
 *
 * @return {undefined}
 * @global
 */

function defaultUpdater(session, action) {
  session.sessionBoundModels.forEach(function (modelClass) {
    if (typeof modelClass.reducer === "function") {
      // This calls this.applyUpdate to update this.state
      modelClass.reducer(action, modelClass, session);
    }
  });
}
/**
 * Call the returned function to pass actions to Redux-ORM.
 *
 * @global
 *
 * @param {ORM} orm - the ORM instance.
 * @param {Function} [updater] - the function updating the ORM state based on the given action.
 * @return {Function} reducer that will update the ORM state.
 */

function createReducer(orm) {
  var updater = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultUpdater;
  return function (state, action) {
    var session = orm.session(state || orm.getEmptyState());
    updater(session, action);
    return session.state;
  };
}
/**
 * Turns a selector specification into its corresponding selector function.
 *
 * @private
 * @param {SelectorSpec} spec
 */

function createSelectorFromSpec(spec) {
  if (spec instanceof MapSelectorSpec) {
    var parentSelector = createSelectorFromSpec(spec.parent);
    var resultFunc = spec.createResultFunc(parentSelector);
    return function (state, idArg) {
      return resultFunc.call(spec, state, null, idArg);
    };
  }
  if (spec instanceof ModelSelectorSpec || spec instanceof ModelBasedSelectorSpec) {
    var modelSpec = spec.orm[spec.model.modelName];
    return createSelectorCreator_1(memoizeByKey, spec.orm, spec.dependencies.length)([spec.orm.stateSelector, idArgSelector].concat(_toConsumableArray$1(spec.dependencies.map(toSelectorFor(modelSpec)))), function () {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return spec.resultFunc.apply(spec, args);
    });
  }
  throw new Error("Unknown selector spec");
}
/**
 * Turns a selector specification into its corresponding selector function.
 *
 * @param {ModelSelectorSpec|ModelBasedSelectorSpec}
 * @private
 * @param {SelectorSpec} spec
 */

function createSelectorFromSpecFor(modelOrModelBasedSpec) {
  if (!(modelOrModelBasedSpec instanceof ModelSelectorSpec) && !(modelOrModelBasedSpec instanceof ModelBasedSelectorSpec)) {
    throw new Error("createSelectorFromSpecFor requires a ModelSelectorSpec or a ModelBasedSelectorSpec as its sole argument.");
  }
  var orm = modelOrModelBasedSpec.orm,
    modelName = modelOrModelBasedSpec.model.modelName;
  var modelSpec = orm[modelName];
  return function (spec) {
    if (!spec || !(spec instanceof ModelSelectorSpec || spec instanceof ModelBasedSelectorSpec)) {
      throw new Error("createSelectorFromSpecFor(X)(Y) requires Y to be a ModelSelectorSpec or a ModelBasedSelectorSpec.");
    }
    if (!spec.modelIs(modelName)) {
      /**
       * This causes user arguments not to affect the dependency.
       * So arguments meant for the model-based selector `spec` don't also get
       * passed to other model-based selector dependencies.
       *
       * Example:
       * const similarAuthors = createSelectorFor(orm.Book)(
       *      orm.Book.genre,
       *      orm.Author,
       *      (genre, allAuthors) =>
       *          allAuthors.books.filter({ genre }).count() > 0
       * );
       *
       * This causes `similarAuthors(state, 1)` to only resolve
       * the genre of the book with ID 1, but not the author with ID 1.
       * Instead, the `orm.Author` resultFunc will receive no arguments.
       */
      var selector = toSelector(arg);
      return function (state) {
        return selector(state);
      };
    }
    if (spec instanceof MapSelectorSpec) {
      var parentToModelName = spec.parent.toModelName;
      var parentToModelSpec = orm[parentToModelName];
      spec.selector = toSelectorFor(parentToModelSpec)(spec.selector);
      return createSelectorCreator_1(memoizeByKey, spec.orm, 3)([orm.stateSelector, idArgSelector, function (state) {
        return state;
      }, orm.stateSelector, idArgSelector], function (state, session, idArg) {
        var parentResult = spec.parent.resultFunc(state, session, idArg);
        if (parentResult === null) {
          return null;
        }
        if (typeof idArg === "undefined" || Array.isArray(idArg)) {
          return parentResult.map(function (refArray) {
            return refArray === null ? null : refArray.map(function (parentRef) {
              return parentRef === null ? null : spec.valueForRef(parentRef, session, state);
            });
          });
        }
        return parentResult.map(function (ref) {
          return ref === null ? null : spec.valueForRef(ref, session, state);
        });
      });
    } // Map arg.resultFunc by model using arg.modelSelectorSpec

    return createSelectorCreator_1(memoizeByKey, orm, 3)([orm.stateSelector, idArgSelector, function (state) {
      return state;
    }, orm.stateSelector, idArgSelector], function (state, session, idArg) {
      var refOrRefs = modelSpec.resultFunc(state, session, idArg);
      if (refOrRefs === null) {
        return null;
      }
      if (Array.isArray(refOrRefs)) {
        return refOrRefs.map(function (ref) {
          return ref === null ? null : spec.valueForRef(ref, session, state);
        });
      }
      return spec.valueForRef(refOrRefs, session, state);
    });
  };
}
/**
 * Tries to find ORM instance using the argument.
 * @private
 * @param {*} arg
 */

function toORM(arg) {
  /* eslint-disable no-underscore-dangle */
  if (arg instanceof ORM$1) {
    return arg;
  }
  if (arg instanceof SelectorSpec) {
    return arg._orm;
  }
  return false;
}
var selectorCache = new Map();
var SELECTOR_KEY = Symbol["for"]("REDUX_ORM_SELECTOR");
/**
 * Turns any argument into a selector function if possible.
 *
 * ORM instances become functions returning the ORM's state.
 *
 * Selector specs become actual selector functions. If possible
 * their cached version is retrieved instead of creating new ones.
 * Ordinary functions are kept the same.
 *
 * @private
 * @param {function|ORM|SelectorSpec} arg
 * @return {function}
 * @throws {Error} if argument is invalid
 */

function toSelector(arg) {
  if (typeof arg === "function") {
    return arg;
  }
  if (arg instanceof ORM$1) {
    return arg.stateSelector;
  }
  if (arg instanceof MapSelectorSpec) {
    // the argument to map() needs to be callable
    arg.selector = toSelector(arg.selector);
  }
  if (arg instanceof SelectorSpec) {
    var orm = arg.orm,
      cachePath = arg.cachePath;
    var level; // the selector cache for the spec's ORM

    if (!selectorCache.has(orm)) {
      selectorCache.set(orm, new Map());
    }
    var ormSelectors = selectorCache.get(orm);
    /**
     * Drill down into selector map by cachePath.
     *
     * The selector itself is stored under a special SELECTOR_KEY
     * so that we can store selectors below it as well.
     */

    level = ormSelectors;
    for (var i = 0; i < cachePath.length; ++i) {
      var storageKey = cachePath[i];
      if (!level.has(storageKey)) {
        level.set(storageKey, new Map());
      }
      level = level.get(storageKey);
    }
    if (level && level.has(SELECTOR_KEY)) {
      // Cache hit: the selector has been created before
      return level.get(SELECTOR_KEY);
    } // Cache miss: the selector needs to be created

    var selector = createSelectorFromSpec(arg); // Save the selector at the cachePath position

    level.set(SELECTOR_KEY, selector);
    return selector;
  }
  throw new Error("Failed to interpret selector argument: ".concat(JSON.stringify(arg), " of type ").concat(_typeof$c(arg)));
}
function toSelectorFor(spec) {
  if (!(spec instanceof ModelSelectorSpec)) {
    throw new Error("`toSelectorFor(orm.Model)` takes a model selector spec as its single argument.");
  }
  return function (arg) {
    if (typeof arg === "function") {
      return arg;
    }
    if (arg instanceof ORM$1) {
      return arg.stateSelector;
    }
    if (arg instanceof ModelSelectorSpec || arg instanceof ModelBasedSelectorSpec) {
      return createSelectorFromSpecFor(spec)(arg);
    }
    /**
     * All other args are treated as regular selectors.
     */

    return toSelector(arg);
  };
}
/**
 * Returns a memoized selector based on passed arguments.
 * This is similar to `reselect`'s `createSelector`,
 * except you can also pass a single function to be memoized.
 *
 * If you pass multiple functions, the format will be the
 * same as in `reselect`. The last argument is the selector
 * function and the previous are input selectors.
 *
 * When you use this method to create a selector, the returned selector
 * expects the whole `redux-orm` state branch as input. In the selector
 * function that you pass as the last argument, any of the arguments
 * you pass first will be considered selectors and mapped
 * to their outputs, like in `reselect`.
 *
 * Here are some example selectors:
 *
 * ```javascript
 * // orm is an instance of ORM
 * // reduxState is the state of a Redux store
 * const books = createSelector(orm.Book);
 * books(reduxState) // array of book refs
 *
 * const bookAuthors = createSelector(orm.Book.authors);
 * bookAuthors(reduxState) // two-dimensional array of author refs for each book
 * ```
 * Selectors can easily be applied to related models:
 * ```javascript
 * const bookAuthorNames = createSelector(
 *     orm.Book.authors.map(orm.Author.name),
 * );
 * bookAuthorNames(reduxState, 8) // names of all authors of book with ID 8
 * bookAuthorNames(reduxState, [8, 9]) // 2D array of names of all authors of books with IDs 8 and 9
 * ```
 * Also note that `orm.Author.name` did not need to be wrapped in another `createSelector` call,
 * although that would be possible.
 *
 * For more complex calculations you can access
 * entire session objects by passing an ORM instance.
 * ```javascript
 * const freshBananasCost = createSelector(
 *     orm,
 *     session => {
 *        const banana = session.Product.get({
 *            name: "Banana",
 *        });
 *        // amount of fresh bananas in shopping cart
 *        const amount = session.ShoppingCart.filter({
 *            product_id: banana.id,
 *            is_fresh: true,
 *        }).count();
 *        return `USD ${amount * banana.price}`;
 *     }
 * );
 * ```
 *
 * redux-orm uses a special memoization function to avoid recomputations.
 *
 * Everytime a selector runs, this function records which instances
 * of your `Model`s were accessed.<br>
 * On subsequent runs, the selector first checks if the previously
 * accessed instances or `args` have changed in any way:
 * <ul>
 *     <li>If yes, the selector calls the function you passed to it.</li>
 *     <li>If not, it just returns the previous result
 *         (unless you call it for the first time).</li>
 * </ul>
 *
 * This way you can use pure rendering in your React components
 * for performance gains.
 *
 * @global
 *
 * @param  {...Function} args - zero or more input selectors
 *                              and the selector function.
 * @return {Function} memoized selector
 */

function createSelector$1() {
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    args[_key2] = arguments[_key2];
  }
  if (!args.length) {
    throw new Error("Cannot create a selector without arguments.");
  }
  var resultArg = args.pop();
  var dependencies = Array.isArray(args[0]) ? args[0] : args;
  var orm = dependencies.map(toORM).find(Boolean);
  var inputFuncs = dependencies.map(toSelector);
  if (typeof resultArg === "function") {
    if (!orm) {
      throw new Error("Failed to resolve the current ORM database state. Please pass an ORM instance or an ORM selector as an argument to `createSelector()`.");
    } else if (!orm.stateSelector) {
      throw new Error("Failed to resolve the current ORM database state. Please pass an object to the ORM constructor that specifies a `stateSelector` function.");
    } else if (typeof orm.stateSelector !== "function") {
      throw new Error("Failed to resolve the current ORM database state. Please pass a function when specifying the ORM's `stateSelector`. Received: ".concat(JSON.stringify(orm.stateSelector), " of type ").concat(_typeof$c(orm.stateSelector)));
    }
    return createSelectorCreator_1(memoize$3, orm)([orm.stateSelector].concat(_toConsumableArray$1(inputFuncs)), resultArg);
  }
  if (resultArg instanceof ORM$1) {
    throw new Error("ORM instances cannot be the result function of selectors. You can access your models in the last function that you pass to `createSelector()`.");
  }
  if (inputFuncs.length) {
    console.warn("Your input selectors will be ignored: the passed result function does not require any input.");
  }
  return toSelector(resultArg);
}
/**
 * Creates a selector whose results will be cached by the second argument
 * passed to it.
 */

function createSelectorFor(spec) {
  if (!spec) {
    throw new Error("`createSelectorFor()` takes one argument of the form `orm.Model`, e.g. `orm.Book`.");
  }
  if (!(spec instanceof ModelSelectorSpec)) {
    throw new Error("The argument you passed to `createSelectorFor(orm.Model)` must be a model selector specification, e.g. `orm.Book`.");
  }
  return function () {
    for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
      args[_key3] = arguments[_key3];
    }
    if (!args.length) {
      throw new Error("Cannot create a selector without arguments.");
    }
    var resultArg = args.pop();
    var dependencies = Array.isArray(args[0]) ? args[0] : args;
    var orm = spec.orm;
    var inputFuncs = dependencies.map(toSelectorFor(spec));
    if (typeof resultArg === "function") {
      if (!orm.stateSelector) {
        throw new Error("Failed to resolve the current ORM database state. Please pass an object to the ORM constructor that specifies a `stateSelector` function.");
      } else if (typeof orm.stateSelector !== "function") {
        throw new Error("Failed to resolve the current ORM database state. Please pass a function when specifying the ORM's `stateSelector`. Received: ".concat(JSON.stringify(orm.stateSelector), " of type ").concat(_typeof$c(orm.stateSelector)));
      }
      var dependencyIsForModelRef = dependencies.map(function (dep) {
        return typeof dep === "function" && dep.hasOwnProperty(KEYED_SELECTOR_MARKER) && dep[KEYED_SELECTOR_MARKER] === spec.model.modelName || (dep instanceof ModelSelectorSpec || dep instanceof ModelBasedSelectorSpec) && dep.modelIs(spec.model.modelName);
      });
      var selector = createSelectorCreator_1(memoizeByKey, orm,
      // the additional argument refOrRefs to be ignored
      2)([
      // for wrapping the selector in a session
      orm.stateSelector,
      // idArg for cache key
      idArgSelector,
      // returns refOrRefs below
      idArgSelector, toSelector(spec)].concat(_toConsumableArray$1(inputFuncs)), function (idArg, refOrRefs) {
        for (var _len4 = arguments.length, args = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
          args[_key4 - 2] = arguments[_key4];
        }
        if (refOrRefs === null) {
          return null;
        }
        if (typeof idArg === "undefined" || Array.isArray(idArg)) {
          return refOrRefs.map(function (ref, refIdx) {
            if (ref === null) {
              return null;
            }
            return resultArg.apply(null, args.map(function (arg, i) {
              return dependencyIsForModelRef[i] ? arg[refIdx] : arg;
            }));
          });
        }
        return resultArg.apply(null, args);
      });
      selector[KEYED_SELECTOR_MARKER] = spec.model.modelName;
      return selector;
    }
    if (resultArg instanceof ORM$1) {
      throw new Error("ORM instances cannot be the result function of selectors. You can access your models in the last function that you pass to `createSelectorFor()`.");
    }
    if (inputFuncs.length) {
      console.warn("Your input selectors will be ignored: the passed result function does not require any input.");
    }
    return toSelector(resultArg);
  };
}

var Schema = DeprecatedSchema;
var Backend = function RemovedBackend() {
  throw new Error("Having a custom Backend instance is now unsupported. " + "Documentation for database customization is upcoming, for now " + "please look at the db folder in the source.");
};

var ReduxORM = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Attribute: Attribute$1,
  Backend: Backend,
  ForeignKey: ForeignKey$4,
  ManyToMany: ManyToMany$1,
  Model: Model$2,
  ORM: ORM$1,
  OneToOne: OneToOne$1,
  QuerySet: QuerySet$1,
  Schema: Schema,
  Session: Session$1,
  attr: attr$1,
  createReducer: createReducer,
  createSelector: createSelector$1,
  createSelectorFor: createSelectorFor,
  default: Model$2,
  fk: fk$1,
  many: many,
  oneToOne: oneToOne
});

const {
  Model: ORMModel,
  ORM,
  attr,
  fk,
  ForeignKey: ForeignKey$2
} = ReduxORM;
function model(config) {
  return new Model(config);
}
const _orms = {};
const CREATE = "CREATE",
  UPDATE$1 = "UPDATE",
  SUCCESS$1 = "SUCCESS",
  DELETE$1 = "DELETE",
  OVERWRITE = "OVERWRITE",
  ALWAYS = true,
  NEVER = false,
  IF_NOT_EXIST = "IF_NOT_EXIST";
class ORMWithReducer extends ORM {
  constructor(store) {
    super({
      stateSelector: state => state.orm
    });
    this.store = store;
  }
  getReverseRels(modelName) {
    if (!this._rrel) {
      this._rrel = {};
      const models = {};
      this.getModelClasses().forEach(cls => {
        models[cls.modelName] = cls;
      });
      Object.values(models).forEach(cls => {
        Object.entries(cls.fields).forEach(([name, field]) => {
          if (!(field instanceof ForeignKey$2)) {
            return;
          }
          const to = field.toModelName,
            toModel = models[to];
          if (!toModel || !toModel.wqConfig) {
            return;
          }
          const isNested = (toModel.wqConfig.form || []).filter(f => f.type === "repeat" && f.name === field.relatedName).length > 0;
          if (!this._rrel[to]) {
            this._rrel[to] = [];
          }
          this._rrel[to].push({
            model: cls.modelName,
            fkName: name,
            relatedName: field.relatedName,
            nested: isNested
          });
        });
      });
    }
    return this._rrel[modelName] || [];
  }
  getNestedModels(modelName) {
    return this.getReverseRels(modelName).filter(rel => rel.nested);
  }
  get prefix() {
    if (this.store.name === "main") {
      return "ORM";
    } else {
      return `${this.store.name.toUpperCase()}ORM`;
    }
  }
  reducer(lastState, action) {
    const state = action.type === `${this.prefix}_RESET` || !lastState ? this.getEmptyState() : lastState,
      session = this.session(state),
      match = action.type.match(/^([^_]+)_(.+)_([^_]+)$/);
    if (!match || match[1] !== this.prefix) {
      return session.state;
    }
    const modelName = match[2].toLowerCase(),
      actName = match[3],
      cls = session[modelName];
    if (!cls) {
      return session.state;
    }
    const currentCount = cls.count();
    let updateCount;
    switch (actName) {
      case CREATE:
        {
          this._nestedCreate(cls, action.payload);
          updateCount = true;
          break;
        }
      case UPDATE$1:
      case SUCCESS$1:
        {
          const items = Array.isArray(action.payload) ? action.payload : [action.payload];
          if (action.meta && action.meta.currentId && action.meta.currentId != items[0].id) {
            this._updateID(cls, action.meta.currentId, items[0].id);
          }
          items.forEach(item => this._nestedUpdate(cls, item));
          updateCount = true;
          break;
        }
      case DELETE$1:
        {
          this._nestedDelete(cls.withId(action.payload));
          updateCount = true;
          break;
        }
      case OVERWRITE:
        {
          const {
            list,
            ...info
          } = action.payload;
          this._removeObsolete(cls.all(), list, true);
          list.forEach(item => this._nestedUpdate(cls, item));
          session._modelmeta.upsert({
            id: cls.modelName,
            ...info
          });
          break;
        }
    }
    if (updateCount) {
      const meta = session._modelmeta.withId(cls.modelName);
      if (meta) {
        // Use delta in case server count != local count.
        const countChange = cls.count() - currentCount,
          update = {
            count: meta.count + countChange
          };
        if (meta.pages === 1 && meta.per_page === meta.count) {
          update.per_page = update.count;
        }
        meta.update(update);
      } else {
        session._modelmeta.create({
          id: cls.modelName,
          pages: 1,
          count: cls.count(),
          per_page: cls.count()
        });
      }
      // FIXME: Update count for nested models
    }

    return session.state;
  }
  _setNested(cls, data) {
    const item = {
        ...data
      },
      session = cls.session,
      nested = this.getNestedModels(cls.modelName);
    const exist = data.id ? cls.withId(data.id) : null;

    // Normalize nested records into their own models
    nested.forEach(({
      model,
      fkName,
      relatedName
    }) => {
      if (!Array.isArray(item[relatedName])) {
        return;
      }
      if (exist && exist[relatedName] && exist[relatedName].toRefArray) {
        this._removeObsolete(exist[relatedName], item[relatedName]);
      }
      item[relatedName].forEach(row => {
        session[model].upsert({
          ...row,
          [fkName]: item.id
        });
      });
      delete item[relatedName];
    });
    return item;
  }
  _removeObsolete(qs, newItems, nested) {
    const idsToKeep = newItems.map(row => row.id).filter(id => !!id),
      obsolete = qs.filter(item => !idsToKeep.includes(item.id));
    if (nested) {
      obsolete.toModelArray().forEach(item => this._nestedDelete(item));
    } else {
      obsolete.delete();
    }
  }
  _nestedCreate(cls, data) {
    const item = this._setNested(cls, data);
    cls.create(item);
  }
  _nestedUpdate(cls, data) {
    const item = this._setNested(cls, data);
    cls.upsert(item);
  }
  _nestedDelete(instance) {
    const nested = this.getNestedModels(instance.getClass().modelName);
    nested.forEach(({
      relatedName
    }) => {
      instance[relatedName].delete();
    });
    instance.delete();
  }
  _updateID(cls, oldId, newId) {
    // New ID was assigned (i.e. by the server)
    const exist = cls.withId(oldId),
      rrel = this.getReverseRels(cls.modelName);
    if (!exist) {
      return;
    }
    // Update any existing FKs to point to the new ID
    // (including both nested and non-nested relationships)
    rrel.forEach(({
      fkName,
      relatedName
    }) => {
      exist[relatedName].update({
        [fkName]: newId
      });
    });

    // Remove and replace (see redux-orm #176)
    cls.upsert({
      ...exist.ref,
      id: newId
    });
    exist.delete();
  }
}
class ModelMeta extends ORMModel {}
ModelMeta.modelName = "_modelmeta";
function orm$1(store) {
  if (!_orms[store.name]) {
    const orm = _orms[store.name] = new ORMWithReducer(store);
    orm.register(ModelMeta);
  }
  return _orms[store.name];
}
model.cacheOpts = {
  // First page (e.g. 50 records) is stored locally; subsequent pages can be
  // loaded from server.
  first_page: {
    server: ALWAYS,
    client: true,
    page: 1,
    reversed: true
  },
  // All data is prefetched and stored locally, no subsequent requests are
  // necessary.
  all: {
    server: NEVER,
    client: true,
    page: 0,
    reversed: false
  },
  // "Important" data is cached; other data can be accessed via pagination.
  filter: {
    server: ALWAYS,
    client: true,
    page: 0,
    reversed: true
  },
  // Start with filtered/empty list; store responses to subsequent requests
  autoupdate: {
    server: IF_NOT_EXIST,
    client: true,
    page: 0,
    reversed: true
  },
  // No data is cached locally; all data require a network request.
  none: {
    server: ALWAYS,
    client: false,
    page: 0,
    reversed: false
  }
};

// Retrieve a stored list as an object with helper functions
//  - especially useful for server-paginated lists
//  - methods must be called asynchronously
class Model {
  constructor(config) {
    if (!config) {
      throw "No configuration provided!";
    }
    if (typeof config == "string") {
      config = {
        query: config,
        name: config
      };
    }
    if (!config.name) {
      throw new Error("Model name is now required.");
    }
    if (!config.cache) {
      config.cache = "first_page";
    }
    this.config = config;
    this.name = config.name;
    this.idCol = config.idCol || "id";
    this.opts = model.cacheOpts[config.cache];
    if (!this.opts) {
      throw "Unknown cache option " + config.cache;
    }
    ["max_local_pages", "partial", "reversed"].forEach(function (name) {
      if (name in config) {
        throw '"' + name + '" is deprecated in favor of "cache"';
      }
    });

    // Default to main store, but allow overriding
    if (config.store) {
      if (config.store instanceof ds.constructor) {
        this.store = config.store;
      } else {
        this.store = ds.getStore(config.store);
      }
    } else {
      this.store = ds;
    }
    this.orm = orm$1(this.store);
    try {
      this._model = this.orm.get(this.name);
    } catch (e) {
      const idCol = this.idCol;
      class M extends ORMModel {
        static get idAttribute() {
          return idCol;
        }
        static get fields() {
          const fields = {},
            form = (config.form || []).slice(),
            root = form.find(field => field.name === "" && field.type === "group");
          if (root) {
            form.push(...root.children);
          }
          form.forEach(field => {
            if (field["wq:ForeignKey"]) {
              fields[field.name + "_id"] = fk({
                to: field["wq:ForeignKey"],
                as: field.name,
                relatedName: field["wq:related_name"] || config.url || config.name + "s"
              });
            } else if (field.type !== "repeat") {
              fields[field.name] = attr();
            }
          });
          return fields;
        }
        static get wqConfig() {
          return config;
        }
      }
      M.modelName = this.name;
      this.orm.register(M);
      this._model = M;
    }
    if (config.query) {
      this.query = this.store.normalizeQuery(config.query);
    } else if (config.url !== undefined) {
      this.query = {
        url: config.url
      };
    }

    // Configurable functions to e.g. filter data by
    this.functions = config.functions || {};
  }
  expandActionType(type) {
    return `${this.orm.prefix}_${this.name.toUpperCase()}_${type}`;
  }
  dispatch(type, payload, meta) {
    const action = {
      type: this.expandActionType(type),
      payload: payload
    };
    if (meta) {
      action.meta = meta;
    }
    return this.store.dispatch(action);
  }
  getSession() {
    return this.orm.session(this.store.getState().orm);
  }
  getSessionModel(session) {
    const model = (session || this.getSession())[this.name];
    if (!model) {
      throw new Error("Could not find model in session");
    }
    return model;
  }
  get model() {
    return this.getSessionModel();
  }
  getQuerySet(session) {
    const model = this.getSessionModel(session),
      ordering = this.config.ordering || [this.opts.reversed ? `-${this.idCol}` : this.idCol],
      columns = [],
      orders = [];
    ordering.map(name => {
      let order = "asc";
      if (name.startsWith("-")) {
        order = "desc";
        name = name.slice(1);
      }
      columns.push(name);
      orders.push(order);
    });
    return model.all().orderBy(columns, orders);
  }
  get objects() {
    return this.getQuerySet();
  }
  async getPage(page_num, limit) {
    var query = {
      ...this.query
    };
    if (page_num !== null) {
      query.page = page_num;
    }
    if (limit) {
      query.limit = limit;
    }
    const result = await this.store.fetch(query);
    var data = this._processData(result);
    if (!data.page) {
      data.page = page_num;
    }
    return data;
  }
  _processData(data) {
    if (!data) {
      data = [];
    }
    if (Array.isArray(data)) {
      data = {
        list: data
      };
    }
    if (!data.pages) {
      data.pages = 1;
    }
    if (!data.count) {
      data.count = data.list.length;
    }
    if (!data.per_page) {
      data.per_page = data.list.length;
    }
    return data;
  }
  _withNested(instance) {
    const data = deepcopy(instance.ref);
    const nested = this.orm.getNestedModels(instance.getClass().modelName);
    nested.forEach(({
      relatedName
    }) => {
      data[relatedName] = deepcopy(instance[relatedName].toRefArray());
    });
    return data;
  }
  async load() {
    const info = await this.info();
    return {
      ...info,
      list: this.getQuerySet().toModelArray().map(instance => this._withNested(instance))
    };
  }
  async info(retry = true) {
    const info = this.getSession()._modelmeta.withId(this.name);
    if (info) {
      const {
        pages,
        count,
        per_page
      } = info.ref;
      return {
        pages,
        count,
        per_page
      };
    } else {
      if (this.query && retry) {
        await this.prefetch();
        return this.info(false);
      } else {
        return {
          pages: 1,
          count: 0,
          per_page: 0
        };
      }
    }
  }
  async ensureLoaded() {
    await this.info();
  }

  // Load data for the given page number
  async page(page_num, limit) {
    if (!this.config.url) {
      if (page_num > this.opts.page) {
        throw new Error("No URL, cannot retrieve page " + page_num);
      }
    }
    if (page_num <= this.opts.page && !limit) {
      // Store data locally
      return this.load();
    } else {
      // Fetch on demand but don't store
      return this.getPage(page_num, limit);
    }
  }

  // Iterate across stored data
  async forEach(cb, thisarg) {
    const data = await this.load();
    data.list.forEach(cb, thisarg);
  }

  // Find an object by id
  async find(value, localOnly) {
    if (localOnly && typeof localOnly !== "boolean") {
      throw new Error("Usage: find(value[, localOnly).  To customize id attr use config.idCol");
    }
    await this.ensureLoaded();
    const model = this.getSessionModel(),
      instance = model.withId(value);
    if (instance) {
      return this._withNested(instance);
    } else if (value !== undefined && !localOnly && this.opts.server !== NEVER && this.config.url) {
      const result = await this.store.fetch("/" + this.config.url + "/" + value);
      if (result && result.id && this.opts.server === IF_NOT_EXIST) {
        await this.update([result]);
      }
      return result;
    } else {
      return null;
    }
  }
  filterFields() {
    let fields = [this.idCol];
    fields = fields.concat((this.config.form || []).map(field => field["wq:ForeignKey"] ? `${field.name}_id` : field.name));
    fields = fields.concat(Object.keys(this.functions));
    fields = fields.concat(this.config.filter_fields || []);
    if (this.config.filter_ignore) {
      fields = fields.filter(field => !this.config.filter_ignore.includes(field));
    }
    return fields;
  }

  // Filter an array of objects by one or more attributes
  async filterPage(filter, any, localOnly) {
    // Ignore fields that are not explicitly registered
    // (e.g. for use with list views that have custom URL params)
    const filterFields = this.filterFields(),
      pagination = {};
    Object.keys(filter).forEach(field => {
      if (!filterFields.includes(field)) {
        if (field === "page" || field === "limit") {
          pagination[field] = filter[field];
        } else if (!(this.config.filter_ignore || []).includes(field)) {
          console.warn(`Ignoring unrecognized field "${field}"` + ` while filtering ${this.name} list.` + " Add to form or filter_fields to enable filtering," + " or to filter_ignore to remove this warning.");
        }
        filter = {
          ...filter
        };
        delete filter[field];
      }
    });

    // If partial list, we can never be 100% sure all filter matches are
    // stored locally. In that case, run query on server.
    if (!localOnly && this.opts.server === ALWAYS && this.config.url) {
      // FIXME: won't work as expected if any == true
      const result = await this.store.fetch({
        url: this.config.url,
        ...filter,
        ...pagination
      });
      return this._processData(result);
    }
    if (!filter || !Object.keys(filter).length) {
      // No filter: return unmodified list directly
      return this.load();
    }
    await this.ensureLoaded();
    var qs = this.getQuerySet();
    if (any) {
      // any=true: Match on any of the provided filter attributes
      qs = qs.filter(item => {
        return Object.keys(filter).filter(attr => {
          return this.matches(item, attr, filter[attr]);
        }).length > 0;
      });
    } else {
      // Default: require match on all filter attributes

      // Use object filter to take advantage of redux-orm indexes -
      // except for boolean/array/computed filters.
      var defaultFilter = {},
        customFilter = {},
        hasDefaultFilter = false,
        hasCustomFilter = false;
      Object.keys(filter).forEach(attr => {
        const comp = filter[attr];
        if (this.isCustomFilter(attr, comp)) {
          customFilter[attr] = comp;
          hasCustomFilter = true;
        } else {
          defaultFilter[attr] = comp;
          hasDefaultFilter = true;
        }
      });
      if (hasDefaultFilter) {
        qs = qs.filter(defaultFilter);
      }
      if (hasCustomFilter) {
        qs = qs.filter(item => {
          var match = true;
          Object.keys(customFilter).forEach(attr => {
            if (!this.matches(item, attr, customFilter[attr])) {
              match = false;
            }
          });
          return match;
        });
      }
    }
    if (!qs.count() && !localOnly && this.opts.server === IF_NOT_EXIST && this.config.url) {
      await this.fetchUpdate(filter);
      return this.filterPage(filter, any, true);
    }
    return this._processData(qs.toModelArray().map(instance => this._withNested(instance)));
  }

  // Filter an array of objects by one or more attributes
  async filter(filter, any, localOnly) {
    const data = await this.filterPage(filter, any, localOnly);
    return data.list;
  }

  // Create new item
  async create(object, meta) {
    this.dispatch(CREATE, object, meta);
  }

  // Merge new/updated items into list
  async update(update, meta) {
    if (meta && typeof meta === "string") {
      throw new Error("Usage: update(items[, meta]).  To customize id attr use config.idCol");
    }
    return this.dispatch(UPDATE$1, update, meta);
  }
  async remove(id, meta) {
    if (meta && typeof meta === "string") {
      throw new Error("Usage: remove(id).  To customize id attr use config.idCol");
    }
    return this.dispatch(DELETE$1, id, meta);
  }

  // Overwrite entire list
  async overwrite(data, meta) {
    if (data.pages == 1 && data.list) {
      data.count = data.per_page = data.list.length;
    } else {
      data = this._processData(data);
    }
    return this.dispatch(OVERWRITE, data, meta);
  }

  // Prefetch list
  async prefetch() {
    const data = this.opts.client ? await this.getPage(null) : [];
    return this.overwrite(data);
  }

  // Helper for partial list updates (useful for large lists)
  // Note: params should contain correct arguments to fetch only "recent"
  // items from server; idcol should be a unique identifier for the list
  async fetchUpdate(params, idCol) {
    if (idCol) {
      throw new Error("Usage: fetchUpdate(params).  To customize id attr use config.idCol");
    }
    // Update local list with recent items from server
    var q = {
      ...this.query,
      ...params
    };
    const data = await this.store.fetch(q);
    return this.update(this._processData(data).list);
  }

  // Unsaved form items related to this list
  unsyncedItems(withData) {
    // Note: wq/outbox needs to have already been loaded for this to work
    var outbox = this.store.outbox;
    if (!outbox) {
      return Promise.resolve([]);
    }
    return outbox.unsyncedItems(this.query, withData);
  }

  // Apply a predefined function to a retreived item
  compute(fn, item) {
    if (this.functions[fn]) {
      return this.functions[fn](item);
    } else {
      return null;
    }
  }
  isCustomFilter(attr, comp) {
    return this.functions[attr] || isPotentialBoolean(comp) || isPotentialNumber(comp) || Array.isArray(comp);
  }
  matches(item, attr, comp) {
    var value;
    if (this.functions[attr]) {
      value = this.compute(attr, item);
    } else {
      value = item[attr];
    }
    if (Array.isArray(comp)) {
      return comp.filter(c => checkValue(value, c)).length > 0;
    } else {
      return checkValue(value, comp);
    }
    function checkValue(value, comp) {
      if (isRawBoolean(value)) {
        return value === toBoolean(comp);
      } else if (typeof value === "number") {
        return value === +comp;
      } else if (Array.isArray(value)) {
        return value.filter(v => checkValue(v, comp)).length > 0;
      } else {
        return value === comp;
      }
    }
  }
}
function isRawBoolean(value) {
  return [null, true, false].indexOf(value) > -1;
}
function toBoolean(value) {
  if ([true, "true", 1, "1", "t", "y"].indexOf(value) > -1) {
    return true;
  } else if ([false, "false", 0, "0", "f", "n"].indexOf(value) > -1) {
    return false;
  } else if ([null, "null"].indexOf(value) > -1) {
    return null;
  } else {
    return value;
  }
}
function isPotentialBoolean(value) {
  return isRawBoolean(toBoolean(value));
}
function isPotentialNumber(value) {
  return typeof value !== "number" && !Number.isNaN(+value);
}

const orm = {
  // Plugin attributes
  name: "orm",
  type: "orm",
  init() {
    for (const conf of Object.values(this.app.config.pages)) {
      if (!conf.list) {
        continue;
      }
      const model$1 = model(conf);
      this.models[conf.name] = model$1;
      if (!this._orm) {
        this._orm = model$1.orm;
      }
    }
    this.app.models = this.models;
    this.app.prefetchAll = message => this.prefetchAll(message);
    this.app.resetAll = () => this.reset();
  },
  actions: {
    reset() {
      return {
        type: "ORM_RESET"
      };
    }
  },
  reducer(state, action) {
    if (!this._orm) {
      return state || {};
    }
    return this._orm.reducer(state, action);
  },
  persist: true,
  // Custom attributes
  models: {},
  async prefetchAll(message) {
    if (message) {
      this.app.spin.start(message);
    }
    const result = await Promise.all(Object.values(this.models).map(model => model.prefetch()));
    if (message) {
      this.app.spin.stop(message);
    }
    return result;
  }
};

function isNumeric(value) {
  return /^\d+$/.test(value);
}
function parsePath(path) {
  var originalPath = path;
  var steps = [];
  var error = false;
  var firstKey = path.substr(0, path.indexOf('['));
  if (!firstKey.length) {
    error = true;
  } else {
    path = path.substr(path.indexOf('['), path.length);
    steps.push({
      key: firstKey,
      last: !path.length,
      type: 'object'
    });
  }
  var key;
  key = path.substr(1, path.indexOf(']') - 1);
  while (path.length && !error) {
    if (path[0] === '[' && path[1] === ']') {
      steps.push({
        append: true,
        type: 'array'
      });
      path = path.substr(2, path.length);
      error = path.length !== 0;
    } else if (isNumeric(key = path.substr(1, path.indexOf(']') - 1))) {
      key = parseInt(key, 10);
      path = path.substr(path.indexOf(']') + 1, path.length);
      steps.push({
        key: key,
        type: 'array'
      });
    } else if ((key = path.substr(1, path.indexOf(']') - 1)) && key.indexOf('[') === -1) {
      path = path.substr(path.indexOf(']') + 1, path.length);
      steps.push({
        key: key,
        type: 'object'
      });
    } else {
      error = true;
    }
  }
  if (error) {
    steps = [{
      key: originalPath,
      last: true,
      type: 'object'
    }];
  } else {
    for (var i = 0; i < steps.length; i++) {
      var step = steps[i];
      var nextStep = steps[i + 1];
      if (nextStep) {
        step.nextType = nextStep.type;
      } else {
        step.last = true;
      }
    }
  }
  return steps;
}
function setValue(context, step, currentValue, entryValue, isFile) {
  /*
  if (isFile) {
    entryValue = {
      name: 'filename',
      type: 'filetype',
      body: 'filebody'
    }
  }
  */
  if (step.last) {
    if (typeof currentValue === 'undefined') {
      if (step.append) {
        context.push(entryValue);
      } else {
        context[step.key] = entryValue;
      }
    } else if (currentValue.constructor == Array) {
      context[step.key].push(entryValue);
    } else if (currentValue.constructor == Object && !isFile) {
      return setValue(currentValue, {
        key: '',
        last: true,
        type: 'object'
      }, currentValue[''], entryValue, isFile);
    } else {
      context[step.key] = [currentValue, entryValue];
    }
    return context;
  }
  if (typeof currentValue === 'undefined') {
    if (step.nextType === 'array') {
      context[step.key] = [];
    } else {
      context[step.key] = {};
    }
    return context[step.key];
  } else if (currentValue.constructor === Object) {
    return context[step.key];
  } else if (currentValue.constructor === Array) {
    if (step.nextType === 'array') {
      return currentValue;
    } else {
      var object = {};
      currentValue.forEach(function (item, i) {
        if (typeof item !== 'undefined') {
          object[i] = item;
        } else {
          context[step.key] = object;
        }
      });
      return object;
    }
  } else {
    var object = {
      '': currentValue
    };
    context[step.key] = object;
    return object;
  }
}
function convert(entries) {
  var resultingObject = {};
  entries.forEach(function (entry) {
    var isFile = entry.value && entry.value.body !== undefined;
    var steps = parsePath(entry.name);
    var context = resultingObject;
    for (var i = 0; i < steps.length; i++) {
      var step = steps[i];
      var currentValue = context[step.key];
      context = setValue(context, step, currentValue, entry.value, isFile);
    }
  });
  return resultingObject;
}

var lib = {};

var interopRequireDefault = {exports: {}};

(function (module) {
	function _interopRequireDefault(obj) {
	  return obj && obj.__esModule ? obj : {
	    "default": obj
	  };
	}
	module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; 
} (interopRequireDefault));

var interopRequireDefaultExports = interopRequireDefault.exports;

var _typeof$9 = {exports: {}};

var hasRequired_typeof;

function require_typeof () {
	if (hasRequired_typeof) return _typeof$9.exports;
	hasRequired_typeof = 1;
	(function (module) {
		function _typeof(obj) {
		  "@babel/helpers - typeof";

		  return (module.exports = _typeof = "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;
		  }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
		}
		module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (_typeof$9));
	return _typeof$9.exports;
}

var require$$2 = /*@__PURE__*/getAugmentedNamespace(redux);

var middleware$1 = {};

var constants = {};

Object.defineProperty(constants, "__esModule", {
  value: true
});
constants.DEFAULT_ROLLBACK = constants.DEFAULT_COMMIT = constants.JS_ERROR = constants.PERSIST_REHYDRATE = RESET_STATE_1 = constants.RESET_STATE = constants.OFFLINE_BUSY = constants.OFFLINE_SEND = constants.OFFLINE_COMPLETE_RETRY = constants.OFFLINE_SCHEDULE_RETRY = constants.OFFLINE_STATUS_CHANGED = void 0;
// Literal ACTION typing allows to ensure a stricter type than string
var OFFLINE_STATUS_CHANGED = 'Offline/STATUS_CHANGED';
constants.OFFLINE_STATUS_CHANGED = OFFLINE_STATUS_CHANGED;
var OFFLINE_SCHEDULE_RETRY = 'Offline/SCHEDULE_RETRY';
constants.OFFLINE_SCHEDULE_RETRY = OFFLINE_SCHEDULE_RETRY;
var OFFLINE_COMPLETE_RETRY = 'Offline/COMPLETE_RETRY';
constants.OFFLINE_COMPLETE_RETRY = OFFLINE_COMPLETE_RETRY;
var OFFLINE_SEND = 'Offline/SEND';
constants.OFFLINE_SEND = OFFLINE_SEND;
var OFFLINE_BUSY = 'Offline/BUSY';
constants.OFFLINE_BUSY = OFFLINE_BUSY;
var RESET_STATE = 'Offline/RESET_STATE';
var RESET_STATE_1 = constants.RESET_STATE = RESET_STATE;
var PERSIST_REHYDRATE = 'persist/REHYDRATE';
constants.PERSIST_REHYDRATE = PERSIST_REHYDRATE;
var JS_ERROR = 'Offline/JS_ERROR';
constants.JS_ERROR = JS_ERROR;
var DEFAULT_COMMIT = 'Offline/DEFAULT_COMMIT';
constants.DEFAULT_COMMIT = DEFAULT_COMMIT;
var DEFAULT_ROLLBACK = 'Offline/DEFAULT_ROLLBACK';
constants.DEFAULT_ROLLBACK = DEFAULT_ROLLBACK;

var actions = {};

var _interopRequireDefault$f = interopRequireDefaultExports;
Object.defineProperty(actions, "__esModule", {
  value: true
});
var busy_1 = actions.busy = actions.completeRetry = actions.scheduleRetry = actions.networkStatusChanged = void 0;
var _typeof2$1 = _interopRequireDefault$f(require_typeof());
var _constants = constants;
var networkStatusChanged = function networkStatusChanged(params) {
  var payload;
  if ((0, _typeof2$1.default)(params) === 'object') {
    payload = params;
  } else {
    payload = {
      online: params
    };
  }
  return {
    type: _constants.OFFLINE_STATUS_CHANGED,
    payload: payload
  };
};
actions.networkStatusChanged = networkStatusChanged;
var scheduleRetry = function scheduleRetry() {
  var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  return {
    type: _constants.OFFLINE_SCHEDULE_RETRY,
    payload: {
      delay: delay
    }
  };
};
actions.scheduleRetry = scheduleRetry;
var completeRetry = function completeRetry(action) {
  return {
    type: _constants.OFFLINE_COMPLETE_RETRY,
    payload: action
  };
};
actions.completeRetry = completeRetry;
var busy = function busy(isBusy) {
  return {
    type: _constants.OFFLINE_BUSY,
    payload: {
      busy: isBusy
    }
  };
};
busy_1 = actions.busy = busy;

var send = {};

var regeneratorRuntime$1 = {exports: {}};

var hasRequiredRegeneratorRuntime;

function requireRegeneratorRuntime () {
	if (hasRequiredRegeneratorRuntime) return regeneratorRuntime$1.exports;
	hasRequiredRegeneratorRuntime = 1;
	(function (module) {
		var _typeof = require_typeof()["default"];
		function _regeneratorRuntime() {

		  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
		  module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
		    return exports;
		  }, module.exports.__esModule = true, module.exports["default"] = module.exports;
		  var exports = {},
		    Op = Object.prototype,
		    hasOwn = Op.hasOwnProperty,
		    defineProperty = Object.defineProperty || function (obj, key, desc) {
		      obj[key] = desc.value;
		    },
		    $Symbol = "function" == typeof Symbol ? Symbol : {},
		    iteratorSymbol = $Symbol.iterator || "@@iterator",
		    asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
		    toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
		  function define(obj, key, value) {
		    return Object.defineProperty(obj, key, {
		      value: value,
		      enumerable: !0,
		      configurable: !0,
		      writable: !0
		    }), obj[key];
		  }
		  try {
		    define({}, "");
		  } catch (err) {
		    define = function define(obj, key, value) {
		      return obj[key] = value;
		    };
		  }
		  function wrap(innerFn, outerFn, self, tryLocsList) {
		    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
		      generator = Object.create(protoGenerator.prototype),
		      context = new Context(tryLocsList || []);
		    return defineProperty(generator, "_invoke", {
		      value: makeInvokeMethod(innerFn, self, context)
		    }), generator;
		  }
		  function tryCatch(fn, obj, arg) {
		    try {
		      return {
		        type: "normal",
		        arg: fn.call(obj, arg)
		      };
		    } catch (err) {
		      return {
		        type: "throw",
		        arg: err
		      };
		    }
		  }
		  exports.wrap = wrap;
		  var ContinueSentinel = {};
		  function Generator() {}
		  function GeneratorFunction() {}
		  function GeneratorFunctionPrototype() {}
		  var IteratorPrototype = {};
		  define(IteratorPrototype, iteratorSymbol, function () {
		    return this;
		  });
		  var getProto = Object.getPrototypeOf,
		    NativeIteratorPrototype = getProto && getProto(getProto(values([])));
		  NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
		  var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
		  function defineIteratorMethods(prototype) {
		    ["next", "throw", "return"].forEach(function (method) {
		      define(prototype, method, function (arg) {
		        return this._invoke(method, arg);
		      });
		    });
		  }
		  function AsyncIterator(generator, PromiseImpl) {
		    function invoke(method, arg, resolve, reject) {
		      var record = tryCatch(generator[method], generator, arg);
		      if ("throw" !== record.type) {
		        var result = record.arg,
		          value = result.value;
		        return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
		          invoke("next", value, resolve, reject);
		        }, function (err) {
		          invoke("throw", err, resolve, reject);
		        }) : PromiseImpl.resolve(value).then(function (unwrapped) {
		          result.value = unwrapped, resolve(result);
		        }, function (error) {
		          return invoke("throw", error, resolve, reject);
		        });
		      }
		      reject(record.arg);
		    }
		    var previousPromise;
		    defineProperty(this, "_invoke", {
		      value: function value(method, arg) {
		        function callInvokeWithMethodAndArg() {
		          return new PromiseImpl(function (resolve, reject) {
		            invoke(method, arg, resolve, reject);
		          });
		        }
		        return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
		      }
		    });
		  }
		  function makeInvokeMethod(innerFn, self, context) {
		    var state = "suspendedStart";
		    return function (method, arg) {
		      if ("executing" === state) throw new Error("Generator is already running");
		      if ("completed" === state) {
		        if ("throw" === method) throw arg;
		        return doneResult();
		      }
		      for (context.method = method, context.arg = arg;;) {
		        var delegate = context.delegate;
		        if (delegate) {
		          var delegateResult = maybeInvokeDelegate(delegate, context);
		          if (delegateResult) {
		            if (delegateResult === ContinueSentinel) continue;
		            return delegateResult;
		          }
		        }
		        if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
		          if ("suspendedStart" === state) throw state = "completed", context.arg;
		          context.dispatchException(context.arg);
		        } else "return" === context.method && context.abrupt("return", context.arg);
		        state = "executing";
		        var record = tryCatch(innerFn, self, context);
		        if ("normal" === record.type) {
		          if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
		          return {
		            value: record.arg,
		            done: context.done
		          };
		        }
		        "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
		      }
		    };
		  }
		  function maybeInvokeDelegate(delegate, context) {
		    var methodName = context.method,
		      method = delegate.iterator[methodName];
		    if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
		    var record = tryCatch(method, delegate.iterator, context.arg);
		    if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
		    var info = record.arg;
		    return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
		  }
		  function pushTryEntry(locs) {
		    var entry = {
		      tryLoc: locs[0]
		    };
		    1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
		  }
		  function resetTryEntry(entry) {
		    var record = entry.completion || {};
		    record.type = "normal", delete record.arg, entry.completion = record;
		  }
		  function Context(tryLocsList) {
		    this.tryEntries = [{
		      tryLoc: "root"
		    }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
		  }
		  function values(iterable) {
		    if (iterable) {
		      var iteratorMethod = iterable[iteratorSymbol];
		      if (iteratorMethod) return iteratorMethod.call(iterable);
		      if ("function" == typeof iterable.next) return iterable;
		      if (!isNaN(iterable.length)) {
		        var i = -1,
		          next = function next() {
		            for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
		            return next.value = undefined, next.done = !0, next;
		          };
		        return next.next = next;
		      }
		    }
		    return {
		      next: doneResult
		    };
		  }
		  function doneResult() {
		    return {
		      value: undefined,
		      done: !0
		    };
		  }
		  return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
		    value: GeneratorFunctionPrototype,
		    configurable: !0
		  }), defineProperty(GeneratorFunctionPrototype, "constructor", {
		    value: GeneratorFunction,
		    configurable: !0
		  }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
		    var ctor = "function" == typeof genFun && genFun.constructor;
		    return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
		  }, exports.mark = function (genFun) {
		    return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
		  }, exports.awrap = function (arg) {
		    return {
		      __await: arg
		    };
		  }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
		    return this;
		  }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
		    void 0 === PromiseImpl && (PromiseImpl = Promise);
		    var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
		    return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
		      return result.done ? result.value : iter.next();
		    });
		  }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
		    return this;
		  }), define(Gp, "toString", function () {
		    return "[object Generator]";
		  }), exports.keys = function (val) {
		    var object = Object(val),
		      keys = [];
		    for (var key in object) keys.push(key);
		    return keys.reverse(), function next() {
		      for (; keys.length;) {
		        var key = keys.pop();
		        if (key in object) return next.value = key, next.done = !1, next;
		      }
		      return next.done = !0, next;
		    };
		  }, exports.values = values, Context.prototype = {
		    constructor: Context,
		    reset: function reset(skipTempReset) {
		      if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
		    },
		    stop: function stop() {
		      this.done = !0;
		      var rootRecord = this.tryEntries[0].completion;
		      if ("throw" === rootRecord.type) throw rootRecord.arg;
		      return this.rval;
		    },
		    dispatchException: function dispatchException(exception) {
		      if (this.done) throw exception;
		      var context = this;
		      function handle(loc, caught) {
		        return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
		      }
		      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
		        var entry = this.tryEntries[i],
		          record = entry.completion;
		        if ("root" === entry.tryLoc) return handle("end");
		        if (entry.tryLoc <= this.prev) {
		          var hasCatch = hasOwn.call(entry, "catchLoc"),
		            hasFinally = hasOwn.call(entry, "finallyLoc");
		          if (hasCatch && hasFinally) {
		            if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
		            if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
		          } else if (hasCatch) {
		            if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
		          } else {
		            if (!hasFinally) throw new Error("try statement without catch or finally");
		            if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
		          }
		        }
		      }
		    },
		    abrupt: function abrupt(type, arg) {
		      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
		        var entry = this.tryEntries[i];
		        if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
		          var finallyEntry = entry;
		          break;
		        }
		      }
		      finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
		      var record = finallyEntry ? finallyEntry.completion : {};
		      return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
		    },
		    complete: function complete(record, afterLoc) {
		      if ("throw" === record.type) throw record.arg;
		      return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
		    },
		    finish: function finish(finallyLoc) {
		      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
		        var entry = this.tryEntries[i];
		        if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
		      }
		    },
		    "catch": function _catch(tryLoc) {
		      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
		        var entry = this.tryEntries[i];
		        if (entry.tryLoc === tryLoc) {
		          var record = entry.completion;
		          if ("throw" === record.type) {
		            var thrown = record.arg;
		            resetTryEntry(entry);
		          }
		          return thrown;
		        }
		      }
		      throw new Error("illegal catch attempt");
		    },
		    delegateYield: function delegateYield(iterable, resultName, nextLoc) {
		      return this.delegate = {
		        iterator: values(iterable),
		        resultName: resultName,
		        nextLoc: nextLoc
		      }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
		    }
		  }, exports;
		}
		module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (regeneratorRuntime$1));
	return regeneratorRuntime$1.exports;
}

var regenerator;
var hasRequiredRegenerator;

function requireRegenerator () {
	if (hasRequiredRegenerator) return regenerator;
	hasRequiredRegenerator = 1;
	// TODO(Babel 8): Remove this file.

	var runtime = requireRegeneratorRuntime()();
	regenerator = runtime;

	// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
	try {
	  regeneratorRuntime = runtime;
	} catch (accidentalStrictMode) {
	  if (typeof globalThis === "object") {
	    globalThis.regeneratorRuntime = runtime;
	  } else {
	    Function("r", "regeneratorRuntime = r")(runtime);
	  }
	}
	return regenerator;
}

var asyncToGenerator = {exports: {}};

var hasRequiredAsyncToGenerator;

function requireAsyncToGenerator () {
	if (hasRequiredAsyncToGenerator) return asyncToGenerator.exports;
	hasRequiredAsyncToGenerator = 1;
	(function (module) {
		function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
		  try {
		    var info = gen[key](arg);
		    var value = info.value;
		  } catch (error) {
		    reject(error);
		    return;
		  }
		  if (info.done) {
		    resolve(value);
		  } else {
		    Promise.resolve(value).then(_next, _throw);
		  }
		}
		function _asyncToGenerator(fn) {
		  return function () {
		    var self = this,
		      args = arguments;
		    return new Promise(function (resolve, reject) {
		      var gen = fn.apply(self, args);
		      function _next(value) {
		        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
		      }
		      function _throw(err) {
		        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
		      }
		      _next(undefined);
		    });
		  };
		}
		module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (asyncToGenerator));
	return asyncToGenerator.exports;
}

var defineProperty$3 = {exports: {}};

var toPropertyKey = {exports: {}};

var toPrimitive = {exports: {}};

var hasRequiredToPrimitive;

function requireToPrimitive () {
	if (hasRequiredToPrimitive) return toPrimitive.exports;
	hasRequiredToPrimitive = 1;
	(function (module) {
		var _typeof = require_typeof()["default"];
		function _toPrimitive(input, hint) {
		  if (_typeof(input) !== "object" || input === null) return input;
		  var prim = input[Symbol.toPrimitive];
		  if (prim !== undefined) {
		    var res = prim.call(input, hint || "default");
		    if (_typeof(res) !== "object") return res;
		    throw new TypeError("@@toPrimitive must return a primitive value.");
		  }
		  return (hint === "string" ? String : Number)(input);
		}
		module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (toPrimitive));
	return toPrimitive.exports;
}

var hasRequiredToPropertyKey;

function requireToPropertyKey () {
	if (hasRequiredToPropertyKey) return toPropertyKey.exports;
	hasRequiredToPropertyKey = 1;
	(function (module) {
		var _typeof = require_typeof()["default"];
		var toPrimitive = requireToPrimitive();
		function _toPropertyKey(arg) {
		  var key = toPrimitive(arg, "string");
		  return _typeof(key) === "symbol" ? key : String(key);
		}
		module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (toPropertyKey));
	return toPropertyKey.exports;
}

var hasRequiredDefineProperty;

function requireDefineProperty () {
	if (hasRequiredDefineProperty) return defineProperty$3.exports;
	hasRequiredDefineProperty = 1;
	(function (module) {
		var toPropertyKey = requireToPropertyKey();
		function _defineProperty(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;
		}
		module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (defineProperty$3));
	return defineProperty$3.exports;
}

var hasRequiredSend;

function requireSend () {
	if (hasRequiredSend) return send;
	hasRequiredSend = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(send, "__esModule", {
	  value: true
	});
	send.default = void 0;
	var _regenerator = _interopRequireDefault(requireRegenerator());
	var _asyncToGenerator2 = _interopRequireDefault(requireAsyncToGenerator());
	var _defineProperty2 = _interopRequireDefault(requireDefineProperty());
	var _actions = actions;
	var _constants = constants;
	function ownKeys(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(target) {
	  for (var i = 1; i < arguments.length; i++) {
	    var source = arguments[i] != null ? arguments[i] : {};
	    if (i % 2) {
	      ownKeys(Object(source), true).forEach(function (key) {
	        (0, _defineProperty2.default)(target, key, source[key]);
	      });
	    } else if (Object.getOwnPropertyDescriptors) {
	      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
	    } else {
	      ownKeys(Object(source)).forEach(function (key) {
	        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
	      });
	    }
	  }
	  return target;
	}
	var complete = function complete(action, result, offlineAction, config) {
	  var _config$offlineAction = config.offlineActionTracker,
	    resolveAction = _config$offlineAction.resolveAction,
	    rejectAction = _config$offlineAction.rejectAction;
	  if (result.success) {
	    resolveAction(offlineAction.meta.transaction, result.payload);
	  } else if (result.payload) {
	    rejectAction(offlineAction.meta.transaction, result.payload);
	  }
	  return _objectSpread(_objectSpread({}, action), {}, {
	    payload: result.payload,
	    meta: _objectSpread(_objectSpread({}, action.meta), {}, {
	      success: result.success,
	      completed: true
	    })
	  });
	};
	var handleJsError = function handleJsError(error) {
	  return {
	    type: _constants.JS_ERROR,
	    meta: {
	      error: error,
	      success: false,
	      completed: true
	    }
	  };
	};
	var send$1 = function send(action, dispatch, config) {
	  var retries = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
	  var metadata = action.meta.offline;
	  dispatch((0, _actions.busy)(true));
	  return config.effect(metadata.effect, action).then(function (result) {
	    var commitAction = metadata.commit || _objectSpread(_objectSpread({}, config.defaultCommit), {}, {
	      meta: _objectSpread(_objectSpread({}, config.defaultCommit.meta), {}, {
	        offlineAction: action
	      })
	    });
	    try {
	      return dispatch(complete(commitAction, {
	        success: true,
	        payload: result
	      }, action, config));
	    } catch (error) {
	      return dispatch(handleJsError(error));
	    }
	  }).catch( /*#__PURE__*/function () {
	    var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(error) {
	      var rollbackAction, mustDiscard, delay;
	      return _regenerator.default.wrap(function _callee$(_context) {
	        while (1) {
	          switch (_context.prev = _context.next) {
	            case 0:
	              rollbackAction = metadata.rollback || _objectSpread(_objectSpread({}, config.defaultRollback), {}, {
	                meta: _objectSpread(_objectSpread({}, config.defaultRollback.meta), {}, {
	                  offlineAction: action
	                })
	              }); // discard

	              mustDiscard = true;
	              _context.prev = 2;
	              _context.next = 5;
	              return config.discard(error, action, retries);
	            case 5:
	              mustDiscard = _context.sent;
	              _context.next = 11;
	              break;
	            case 8:
	              _context.prev = 8;
	              _context.t0 = _context["catch"](2);
	              console.warn(_context.t0);
	            case 11:
	              if (mustDiscard) {
	                _context.next = 15;
	                break;
	              }
	              delay = config.retry(action, retries);
	              if (!(delay != null)) {
	                _context.next = 15;
	                break;
	              }
	              return _context.abrupt("return", dispatch((0, _actions.scheduleRetry)(delay)));
	            case 15:
	              return _context.abrupt("return", dispatch(complete(rollbackAction, {
	                success: false,
	                payload: error
	              }, action, config)));
	            case 16:
	            case "end":
	              return _context.stop();
	          }
	        }
	      }, _callee, null, [[2, 8]]);
	    }));
	    return function (_x) {
	      return _ref.apply(this, arguments);
	    };
	  }()).finally(function () {
	    return dispatch((0, _actions.busy)(false));
	  });
	};
	var _default = send$1;
	send.default = _default;
	return send;
}

var hasRequiredMiddleware;

function requireMiddleware () {
	if (hasRequiredMiddleware) return middleware$1;
	hasRequiredMiddleware = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(middleware$1, "__esModule", {
	  value: true
	});
	middleware$1.createOfflineMiddleware = void 0;
	var _constants = constants;
	var _actions = actions;
	var _send = _interopRequireDefault(requireSend());
	var after = function after() {
	  var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
	  return new Promise(function (resolve) {
	    return setTimeout(resolve, timeout);
	  });
	};
	var createOfflineMiddleware = function createOfflineMiddleware(config) {
	  return function (store) {
	    return function (next) {
	      return function (action) {
	        // allow other middleware to do their things
	        var result = next(action);
	        var promise; // find any actions to send, if any

	        var state = store.getState();
	        var offline = config.offlineStateLens(state).get;
	        var context = {
	          offline: offline
	        };
	        var offlineAction = config.queue.peek(offline.outbox, action, context); // create promise to return on enqueue offline action

	        if (action.meta && action.meta.offline) {
	          var registerAction = config.offlineActionTracker.registerAction;
	          promise = registerAction(offline.lastTransaction);
	        } // if there are any actions in the queue that we are not
	        // yet processing, send those actions

	        if (offlineAction && !offline.busy && !offline.retryScheduled && offline.online) {
	          (0, _send.default)(offlineAction, store.dispatch, config, offline.retryCount);
	        }
	        if (action.type === _constants.OFFLINE_SCHEDULE_RETRY) {
	          after(action.payload.delay).then(function () {
	            store.dispatch((0, _actions.completeRetry)(offlineAction));
	          });
	        }
	        if (action.type === _constants.OFFLINE_SEND && offlineAction && !offline.busy) {
	          (0, _send.default)(offlineAction, store.dispatch, config, offline.retryCount);
	        }
	        return promise || result;
	      };
	    };
	  };
	};
	middleware$1.createOfflineMiddleware = createOfflineMiddleware;
	return middleware$1;
}

var updater = {};

var hasRequiredUpdater;

function requireUpdater () {
	if (hasRequiredUpdater) return updater;
	hasRequiredUpdater = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(updater, "__esModule", {
	  value: true
	});
	updater.enhanceReducer = updater.buildOfflineUpdater = updater.initialState = void 0;
	var _defineProperty2 = _interopRequireDefault(requireDefineProperty());
	var _constants = constants;
	function ownKeys(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(target) {
	  for (var i = 1; i < arguments.length; i++) {
	    var source = arguments[i] != null ? arguments[i] : {};
	    if (i % 2) {
	      ownKeys(Object(source), true).forEach(function (key) {
	        (0, _defineProperty2.default)(target, key, source[key]);
	      });
	    } else if (Object.getOwnPropertyDescriptors) {
	      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
	    } else {
	      ownKeys(Object(source)).forEach(function (key) {
	        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
	      });
	    }
	  }
	  return target;
	}
	var initialState = {
	  busy: false,
	  lastTransaction: 0,
	  online: false,
	  outbox: [],
	  retryCount: 0,
	  retryScheduled: false,
	  netInfo: {
	    isConnectionExpensive: null,
	    reach: 'NONE'
	  }
	};
	updater.initialState = initialState;
	var buildOfflineUpdater = function buildOfflineUpdater(dequeue, enqueue) {
	  return function offlineUpdater() {
	    var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
	    var action = arguments.length > 1 ? arguments[1] : undefined;

	    // Update online/offline status
	    if (action.type === _constants.OFFLINE_STATUS_CHANGED && !action.meta) {
	      return _objectSpread(_objectSpread({}, state), {}, {
	        online: action.payload.online,
	        netInfo: action.payload.netInfo
	      });
	    }
	    if (action.type === _constants.PERSIST_REHYDRATE && action.payload) {
	      return _objectSpread(_objectSpread(_objectSpread({}, state), action.payload.offline || {}), {}, {
	        online: state.online,
	        netInfo: state.netInfo,
	        retryScheduled: initialState.retryScheduled,
	        retryCount: initialState.retryCount,
	        busy: initialState.busy
	      });
	    }
	    if (action.type === _constants.OFFLINE_SCHEDULE_RETRY) {
	      return _objectSpread(_objectSpread({}, state), {}, {
	        retryScheduled: true,
	        retryCount: state.retryCount + 1
	      });
	    }
	    if (action.type === _constants.OFFLINE_COMPLETE_RETRY) {
	      return _objectSpread(_objectSpread({}, state), {}, {
	        retryScheduled: false
	      });
	    }
	    if (action.type === _constants.OFFLINE_BUSY && !action.meta && action.payload && typeof action.payload.busy === 'boolean') {
	      return _objectSpread(_objectSpread({}, state), {}, {
	        busy: action.payload.busy
	      });
	    } // Add offline actions to queue

	    if (action.meta && action.meta.offline) {
	      var transaction = state.lastTransaction + 1;
	      var stamped = _objectSpread(_objectSpread({}, action), {}, {
	        meta: _objectSpread(_objectSpread({}, action.meta), {}, {
	          transaction: transaction
	        })
	      });
	      var offline = state;
	      return _objectSpread(_objectSpread({}, state), {}, {
	        lastTransaction: transaction,
	        outbox: enqueue(offline.outbox, stamped, {
	          offline: offline
	        })
	      });
	    } // Remove completed actions from queue (success or fail)

	    if (action.meta && action.meta.completed === true) {
	      var _offline = state;
	      return _objectSpread(_objectSpread({}, state), {}, {
	        outbox: dequeue(_offline.outbox, action, {
	          offline: _offline
	        }),
	        retryCount: 0
	      });
	    }
	    if (action.type === _constants.RESET_STATE) {
	      return _objectSpread(_objectSpread({}, initialState), {}, {
	        online: state.online,
	        netInfo: state.netInfo
	      });
	    }
	    return state;
	  };
	};
	updater.buildOfflineUpdater = buildOfflineUpdater;
	var enhanceReducer = function enhanceReducer(reducer, config) {
	  var _config$queue = config.queue,
	    dequeue = _config$queue.dequeue,
	    enqueue = _config$queue.enqueue;
	  var offlineUpdater = buildOfflineUpdater(dequeue, enqueue);
	  return function (state, action) {
	    var offlineState;
	    var restState;
	    if (typeof state !== 'undefined') {
	      offlineState = config.offlineStateLens(state).get;
	      restState = config.offlineStateLens(state).set();
	    }
	    return config.offlineStateLens(reducer(restState, action)).set(offlineUpdater(offlineState, action));
	  };
	};
	updater.enhanceReducer = enhanceReducer;
	return updater;
}

var config$1 = {};

var defaults$1 = {};

var persist = {};

var KEY_PREFIX = 'reduxPersist:';
var REHYDRATE = 'persist/REHYDRATE';

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
var freeGlobal$1 = freeGlobal;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal$1 || freeSelf || Function('return this')();
var root$1 = root;

/** Built-in value references. */
var Symbol$1 = root$1.Symbol;
var Symbol$2 = Symbol$1;

/** Used for built-in method references. */
var objectProto$d = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$c = objectProto$d.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString$1 = objectProto$d.toString;

/** Built-in value references. */
var symToStringTag$1 = Symbol$2 ? Symbol$2.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag(value) {
  var isOwn = hasOwnProperty$c.call(value, symToStringTag$1),
    tag = value[symToStringTag$1];
  try {
    value[symToStringTag$1] = undefined;
    var unmasked = true;
  } catch (e) {}
  var result = nativeObjectToString$1.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag$1] = tag;
    } else {
      delete value[symToStringTag$1];
    }
  }
  return result;
}

/** Used for built-in method references. */
var objectProto$c = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto$c.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString$1(value) {
  return nativeObjectToString.call(value);
}

/** `Object#toString` result references. */
var nullTag = '[object Null]',
  undefinedTag = '[object Undefined]';

/** Built-in value references. */
var symToStringTag = Symbol$2 ? Symbol$2.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }
  return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString$1(value);
}

/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function (arg) {
    return func(transform(arg));
  };
}

/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
var getPrototype$1 = getPrototype;

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

/** `Object#toString` result references. */
var objectTag$3 = '[object Object]';

/** Used for built-in method references. */
var funcProto$2 = Function.prototype,
  objectProto$b = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString$2 = funcProto$2.toString;

/** Used to check objects for own properties. */
var hasOwnProperty$b = objectProto$b.hasOwnProperty;

/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString$2.call(Object);

/**
 * Checks if `value` is a plain object, that is, an object created by the
 * `Object` constructor or one with a `[[Prototype]]` of `null`.
 *
 * @static
 * @memberOf _
 * @since 0.8.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * _.isPlainObject(new Foo);
 * // => false
 *
 * _.isPlainObject([1, 2, 3]);
 * // => false
 *
 * _.isPlainObject({ 'x': 0, 'y': 0 });
 * // => true
 *
 * _.isPlainObject(Object.create(null));
 * // => true
 */
function isPlainObject$2(value) {
  if (!isObjectLike(value) || baseGetTag(value) != objectTag$3) {
    return false;
  }
  var proto = getPrototype$1(value);
  if (proto === null) {
    return true;
  }
  var Ctor = hasOwnProperty$b.call(proto, 'constructor') && proto.constructor;
  return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString;
}

var _typeof$8 = 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 isStatePlainEnough(a) {
  // isPlainObject + duck type not immutable
  if (!a) return false;
  if ((typeof a === 'undefined' ? 'undefined' : _typeof$8(a)) !== 'object') return false;
  if (typeof a.asMutable === 'function') return false;
  if (!isPlainObject$2(a)) return false;
  return true;
}

var _typeof$7 = 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;
};
var _extends$c = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
function autoRehydrate() {
  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var stateReconciler = config.stateReconciler || defaultStateReconciler;
  return function (next) {
    return function (reducer, initialState, enhancer) {
      var store = next(liftReducer(reducer), initialState, enhancer);
      return _extends$c({}, store, {
        replaceReducer: function replaceReducer(reducer) {
          return store.replaceReducer(liftReducer(reducer));
        }
      });
    };
  };
  function liftReducer(reducer) {
    var rehydrated = false;
    var preRehydrateActions = [];
    return function (state, action) {
      if (action.type !== REHYDRATE) {
        if (config.log && !rehydrated) preRehydrateActions.push(action); // store pre-rehydrate actions for debugging
        return reducer(state, action);
      } else {
        if (config.log && !rehydrated) logPreRehydrate(preRehydrateActions);
        rehydrated = true;
        var inboundState = action.payload;
        var reducedState = reducer(state, action);
        return stateReconciler(state, inboundState, reducedState, config.log);
      }
    };
  }
}
function logPreRehydrate(preRehydrateActions) {
  var concernedActions = preRehydrateActions.slice(1);
  if (concernedActions.length > 0) {
    console.log('\n      redux-persist/autoRehydrate: %d actions were fired before rehydration completed. This can be a symptom of a race\n      condition where the rehydrate action may overwrite the previously affected state. Consider running these actions\n      after rehydration:\n    ', concernedActions.length, concernedActions);
  }
}
function defaultStateReconciler(state, inboundState, reducedState, log) {
  var newState = _extends$c({}, reducedState);
  Object.keys(inboundState).forEach(function (key) {
    // if initialState does not have key, skip auto rehydration
    if (!state.hasOwnProperty(key)) return;

    // if initial state is an object but inbound state is null/undefined, skip
    if (_typeof$7(state[key]) === 'object' && !inboundState[key]) {
      if (log) console.log('redux-persist/autoRehydrate: sub state for key `%s` is falsy but initial state is an object, skipping autoRehydrate.', key);
      return;
    }

    // if reducer modifies substate, skip auto rehydration
    if (state[key] !== reducedState[key]) {
      if (log) console.log('redux-persist/autoRehydrate: sub state for key `%s` modified, skipping autoRehydrate.', key);
      newState[key] = reducedState[key];
      return;
    }

    // otherwise take the inboundState
    if (isStatePlainEnough(inboundState[key]) && isStatePlainEnough(state[key])) newState[key] = _extends$c({}, state[key], inboundState[key]); // shallow merge
    else newState[key] = inboundState[key]; // hard set

    if (log) console.log('redux-persist/autoRehydrate: key `%s`, rehydrated to ', key, newState[key]);
  });
  return newState;
}

var hasNativeSupport = typeof global !== 'undefined' && typeof global.setImmediate !== 'undefined';
var setImmediate$1 = hasNativeSupport ? function (fn, ms) {
  return global.setImmediate(fn, ms);
} : function (fn, ms) {
  return setTimeout(fn, ms);
};

var _typeof$6 = 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;
};
var noStorage = function noStorage() {
  /* noop */return null;
};
{
  noStorage = function noStorage() {
    console.error('redux-persist asyncLocalStorage requires a global localStorage object. Either use a different storage backend or if this is a universal redux application you probably should conditionally persist like so: https://gist.github.com/rt2zz/ac9eb396793f95ff3c3b');
    return null;
  };
}
function _hasStorage(storageType) {
  if ((typeof window === 'undefined' ? 'undefined' : _typeof$6(window)) !== 'object' || !(storageType in window)) {
    return false;
  }
  try {
    var storage = window[storageType];
    var testKey = 'redux-persist ' + storageType + ' test';
    storage.setItem(testKey, 'test');
    storage.getItem(testKey);
    storage.removeItem(testKey);
  } catch (e) {
    console.warn('redux-persist ' + storageType + ' test failed, persistence will be disabled.');
    return false;
  }
  return true;
}
function hasLocalStorage() {
  return _hasStorage('localStorage');
}
function hasSessionStorage() {
  return _hasStorage('sessionStorage');
}
function getStorage(type) {
  if (type === 'local') {
    return hasLocalStorage() ? window.localStorage : {
      getItem: noStorage,
      setItem: noStorage,
      removeItem: noStorage,
      getAllKeys: noStorage
    };
  }
  if (type === 'session') {
    return hasSessionStorage() ? window.sessionStorage : {
      getItem: noStorage,
      setItem: noStorage,
      removeItem: noStorage,
      getAllKeys: noStorage
    };
  }
}
function createAsyncLocalStorage (type, config) {
  var storage = getStorage(type);
  return {
    getAllKeys: function getAllKeys(cb) {
      return new Promise(function (resolve, reject) {
        try {
          var keys = [];
          for (var i = 0; i < storage.length; i++) {
            keys.push(storage.key(i));
          }
          setImmediate$1(function () {
            cb && cb(null, keys);
            resolve(keys);
          });
        } catch (e) {
          cb && cb(e);
          reject(e);
        }
      });
    },
    getItem: function getItem(key, cb) {
      return new Promise(function (resolve, reject) {
        try {
          var s = storage.getItem(key);
          setImmediate$1(function () {
            cb && cb(null, s);
            resolve(s);
          });
        } catch (e) {
          cb && cb(e);
          reject(e);
        }
      });
    },
    setItem: function setItem(key, string, cb) {
      return new Promise(function (resolve, reject) {
        try {
          storage.setItem(key, string);
          setImmediate$1(function () {
            cb && cb(null);
            resolve();
          });
        } catch (e) {
          cb && cb(e);
          reject(e);
        }
      });
    },
    removeItem: function removeItem(key, cb) {
      return new Promise(function (resolve, reject) {
        try {
          storage.removeItem(key);
          setImmediate$1(function () {
            cb && cb(null);
            resolve();
          });
        } catch (e) {
          cb && cb(e);
          reject(e);
        }
      });
    }
  };
}

function purgeStoredState(config, keys) {
  var storage = config.storage;
  var keyPrefix = config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX;

  // basic validation
  if (Array.isArray(config)) throw new Error('redux-persist: purgeStoredState requires config as a first argument (found array). An array of keys is the optional second argument.');
  if (!storage) throw new Error('redux-persist: config.storage required in purgeStoredState');
  if (typeof keys === 'undefined') {
    // if keys is not defined, purge all keys
    return new Promise(function (resolve, reject) {
      storage.getAllKeys(function (err, allKeys) {
        if (err) {
          console.warn('redux-persist: error during purgeStoredState in storage.getAllKeys');
          reject(err);
        } else {
          resolve(purgeStoredState(config, allKeys.filter(function (key) {
            return key.indexOf(keyPrefix) === 0;
          }).map(function (key) {
            return key.slice(keyPrefix.length);
          })));
        }
      });
    });
  } else {
    // otherwise purge specified keys
    return Promise.all(keys.map(function (key) {
      return storage.removeItem('' + keyPrefix + key, warnIfRemoveError(key));
    }));
  }
}
function warnIfRemoveError(key) {
  return function removeError(err) {
    if (err && "development" !== 'production') {
      console.warn('Error storing data for key:', key, err);
    }
  };
}

var stringify$3 = {exports: {}};

(function (module, exports) {
	exports = module.exports = stringify;
	exports.getSerialize = serializer;
	function stringify(obj, replacer, spaces, cycleReplacer) {
	  return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
	}
	function serializer(replacer, cycleReplacer) {
	  var stack = [],
	    keys = [];
	  if (cycleReplacer == null) cycleReplacer = function (key, value) {
	    if (stack[0] === value) return "[Circular ~]";
	    return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
	  };
	  return function (key, value) {
	    if (stack.length > 0) {
	      var thisPos = stack.indexOf(this);
	      ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
	      ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
	      if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value);
	    } else stack.push(value);
	    return replacer == null ? value : replacer.call(this, key, value);
	  };
	} 
} (stringify$3, stringify$3.exports));

var stringifyExports = stringify$3.exports;
var stringify$2 = /*@__PURE__*/getDefaultExportFromCjs(stringifyExports);

function createPersistor(store, config) {
  // defaults
  var serializer = config.serialize === false ? function (data) {
    return data;
  } : defaultSerializer;
  var deserializer = config.serialize === false ? function (data) {
    return data;
  } : defaultDeserializer$1;
  var blacklist = config.blacklist || [];
  var whitelist = config.whitelist || false;
  var transforms = config.transforms || [];
  var debounce = config.debounce || false;
  var keyPrefix = config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX;

  // pluggable state shape (e.g. immutablejs)
  var stateInit = config._stateInit || {};
  var stateIterator = config._stateIterator || defaultStateIterator;
  var stateGetter = config._stateGetter || defaultStateGetter;
  var stateSetter = config._stateSetter || defaultStateSetter;

  // storage with keys -> getAllKeys for localForage support
  var storage = config.storage || createAsyncLocalStorage('local');
  if (storage.keys && !storage.getAllKeys) {
    storage.getAllKeys = storage.keys;
  }

  // initialize stateful values
  var lastState = stateInit;
  var paused = false;
  var storesToProcess = [];
  var timeIterator = null;
  store.subscribe(function () {
    if (paused) return;
    var state = store.getState();
    stateIterator(state, function (subState, key) {
      if (!passWhitelistBlacklist(key)) return;
      if (stateGetter(lastState, key) === stateGetter(state, key)) return;
      if (storesToProcess.indexOf(key) !== -1) return;
      storesToProcess.push(key);
    });
    var len = storesToProcess.length;

    // time iterator (read: debounce)
    if (timeIterator === null) {
      timeIterator = setInterval(function () {
        if (paused && len === storesToProcess.length || storesToProcess.length === 0) {
          clearInterval(timeIterator);
          timeIterator = null;
          return;
        }
        var key = storesToProcess.shift();
        var storageKey = createStorageKey(key);
        var endState = transforms.reduce(function (subState, transformer) {
          return transformer.in(subState, key);
        }, stateGetter(store.getState(), key));
        if (typeof endState !== 'undefined') storage.setItem(storageKey, serializer(endState), warnIfSetError(key));
      }, debounce);
    }
    lastState = state;
  });
  function passWhitelistBlacklist(key) {
    if (whitelist && whitelist.indexOf(key) === -1) return false;
    if (blacklist.indexOf(key) !== -1) return false;
    return true;
  }
  function adhocRehydrate(incoming) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var state = {};
    if (options.serial) {
      stateIterator(incoming, function (subState, key) {
        try {
          var data = deserializer(subState);
          var value = transforms.reduceRight(function (interState, transformer) {
            return transformer.out(interState, key);
          }, data);
          state = stateSetter(state, key, value);
        } catch (err) {
          console.warn('Error rehydrating data for key "' + key + '"', subState, err);
        }
      });
    } else state = incoming;
    store.dispatch(rehydrateAction$1(state));
    return state;
  }
  function createStorageKey(key) {
    return '' + keyPrefix + key;
  }

  // return `persistor`
  return {
    rehydrate: adhocRehydrate,
    pause: function pause() {
      paused = true;
    },
    resume: function resume() {
      paused = false;
    },
    purge: function purge(keys) {
      return purgeStoredState({
        storage: storage,
        keyPrefix: keyPrefix
      }, keys);
    }
  };
}
function warnIfSetError(key) {
  return function setError(err) {
    if (err && "development" !== 'production') {
      console.warn('Error storing data for key:', key, err);
    }
  };
}
function defaultSerializer(data) {
  return stringify$2(data, null, null, function (k, v) {
    return null;
  });
}
function defaultDeserializer$1(serial) {
  return JSON.parse(serial);
}
function rehydrateAction$1(data) {
  return {
    type: REHYDRATE,
    payload: data
  };
}
function defaultStateIterator(collection, callback) {
  return Object.keys(collection).forEach(function (key) {
    return callback(collection[key], key);
  });
}
function defaultStateGetter(state, key) {
  return state[key];
}
function defaultStateSetter(state, key, value) {
  state[key] = value;
  return state;
}

function createTransform(inbound, outbound) {
  var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var whitelist = config.whitelist || null;
  var blacklist = config.blacklist || null;
  function whitelistBlacklistCheck(key) {
    if (whitelist && whitelist.indexOf(key) === -1) return true;
    if (blacklist && blacklist.indexOf(key) !== -1) return true;
    return false;
  }
  return {
    in: function _in(state, key) {
      return !whitelistBlacklistCheck(key) && inbound ? inbound(state, key) : state;
    },
    out: function out(state, key) {
      return !whitelistBlacklistCheck(key) && outbound ? outbound(state, key) : state;
    }
  };
}

var _extends$b = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
function getStoredState(config, onComplete) {
  var storage = config.storage || createAsyncLocalStorage('local');
  var deserializer = config.serialize === false ? function (data) {
    return data;
  } : defaultDeserializer;
  var blacklist = config.blacklist || [];
  var whitelist = config.whitelist || false;
  var transforms = config.transforms || [];
  var keyPrefix = config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX;

  // fallback getAllKeys to `keys` if present (LocalForage compatability)
  if (storage.keys && !storage.getAllKeys) storage = _extends$b({}, storage, {
    getAllKeys: storage.keys
  });
  var restoredState = {};
  var completionCount = 0;
  storage.getAllKeys(function (err, allKeys) {
    if (err) {
      console.warn('redux-persist/getStoredState: Error in storage.getAllKeys');
      complete(err);
    }
    var persistKeys = allKeys.filter(function (key) {
      return key.indexOf(keyPrefix) === 0;
    }).map(function (key) {
      return key.slice(keyPrefix.length);
    });
    var keysToRestore = persistKeys.filter(passWhitelistBlacklist);
    var restoreCount = keysToRestore.length;
    if (restoreCount === 0) complete(null, restoredState);
    keysToRestore.forEach(function (key) {
      storage.getItem(createStorageKey(key), function (err, serialized) {
        if (err && "development" !== 'production') console.warn('redux-persist/getStoredState: Error restoring data for key:', key, err);else restoredState[key] = rehydrate(key, serialized);
        completionCount += 1;
        if (completionCount === restoreCount) complete(null, restoredState);
      });
    });
  });
  function rehydrate(key, serialized) {
    var state = null;
    try {
      var data = deserializer(serialized);
      state = transforms.reduceRight(function (subState, transformer) {
        return transformer.out(subState, key);
      }, data);
    } catch (err) {
      console.warn('redux-persist/getStoredState: Error restoring data for key:', key, err);
    }
    return state;
  }
  function complete(err, restoredState) {
    onComplete(err, restoredState);
  }
  function passWhitelistBlacklist(key) {
    if (whitelist && whitelist.indexOf(key) === -1) return false;
    if (blacklist.indexOf(key) !== -1) return false;
    return true;
  }
  function createStorageKey(key) {
    return '' + keyPrefix + key;
  }
  if (typeof onComplete !== 'function' && !!Promise) {
    return new Promise(function (resolve, reject) {
      onComplete = function onComplete(err, restoredState) {
        if (err) reject(err);else resolve(restoredState);
      };
    });
  }
}
function defaultDeserializer(serial) {
  return JSON.parse(serial);
}

var _extends$a = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
function persistStore(store) {
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var onComplete = arguments[2];

  // defaults
  // @TODO remove shouldRestore
  var shouldRestore = !config.skipRestore;
  if (config.skipRestore) console.warn('redux-persist: config.skipRestore has been deprecated. If you want to skip restoration use `createPersistor` instead');
  var purgeKeys = null;

  // create and pause persistor
  var persistor = createPersistor(store, config);
  persistor.pause();

  // restore
  if (shouldRestore) {
    setImmediate$1(function () {
      getStoredState(config, function (err, restoredState) {
        if (err) {
          complete(err);
          return;
        }
        // do not persist state for purgeKeys
        if (purgeKeys) {
          if (purgeKeys === '*') restoredState = {};else purgeKeys.forEach(function (key) {
            return delete restoredState[key];
          });
        }
        try {
          store.dispatch(rehydrateAction(restoredState, err));
        } finally {
          complete(err, restoredState);
        }
      });
    });
  } else setImmediate$1(complete);
  function complete(err, restoredState) {
    persistor.resume();
    onComplete && onComplete(err, restoredState);
  }
  return _extends$a({}, persistor, {
    purge: function purge(keys) {
      purgeKeys = keys || '*';
      return persistor.purge(keys);
    }
  });
}
function rehydrateAction(payload) {
  var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  return {
    type: REHYDRATE,
    payload: payload,
    error: error
  };
}

// @TODO remove in v5
var deprecated = function deprecated(cb, cb2, cb3) {
  console.error('redux-persist: this method of importing storages has been removed. instead use `import { asyncLocalStorage } from "redux-persist/storages"`');
  if (typeof cb === 'function') cb();
  if (typeof cb2 === 'function') cb2();
  if (typeof cb3 === 'function') cb3();
};
var deprecatedStorage = {
  getAllKeys: deprecated,
  getItem: deprecated,
  setItem: deprecated,
  removeItem: deprecated
};
var storages = {
  asyncLocalStorage: deprecatedStorage,
  asyncSessionStorage: deprecatedStorage
};

var es = /*#__PURE__*/Object.freeze({
  __proto__: null,
  autoRehydrate: autoRehydrate,
  createPersistor: createPersistor,
  createTransform: createTransform,
  getStoredState: getStoredState,
  persistStore: persistStore,
  purgeStoredState: purgeStoredState,
  storages: storages
});

var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(es);

var hasRequiredPersist;

function requirePersist () {
	if (hasRequiredPersist) return persist;
	hasRequiredPersist = 1;

	Object.defineProperty(persist, "__esModule", {
	  value: true
	});
	persist.default = void 0;
	var _reduxPersist = require$$0$2;

	// flow
	var _default = _reduxPersist.persistStore;
	persist.default = _default;
	return persist;
}

var detectNetwork = {};

var hasRequiredDetectNetwork;

function requireDetectNetwork () {
	if (hasRequiredDetectNetwork) return detectNetwork;
	hasRequiredDetectNetwork = 1;

	Object.defineProperty(detectNetwork, "__esModule", {
	  value: true
	});
	detectNetwork.default = void 0;
	var handle = function handle(callback, online) {
	  // NetInfo is not supported in browsers, hence we only pass online status
	  if (window.requestAnimationFrame) {
	    window.requestAnimationFrame(function () {
	      return callback({
	        online: online
	      });
	    });
	  } else {
	    setTimeout(function () {
	      return callback({
	        online: online
	      });
	    }, 0);
	  }
	};
	var _default = function _default(callback) {
	  if (typeof window !== 'undefined' && window.addEventListener) {
	    window.addEventListener('online', function () {
	      return handle(callback, true);
	    });
	    window.addEventListener('offline', function () {
	      return handle(callback, false);
	    });
	    handle(callback, window.navigator.onLine);
	  }
	};
	detectNetwork.default = _default;
	return detectNetwork;
}

var effect$3 = {};

var objectWithoutProperties = {exports: {}};

var objectWithoutPropertiesLoose = {exports: {}};

var hasRequiredObjectWithoutPropertiesLoose;

function requireObjectWithoutPropertiesLoose () {
	if (hasRequiredObjectWithoutPropertiesLoose) return objectWithoutPropertiesLoose.exports;
	hasRequiredObjectWithoutPropertiesLoose = 1;
	(function (module) {
		function _objectWithoutPropertiesLoose(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;
		}
		module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (objectWithoutPropertiesLoose));
	return objectWithoutPropertiesLoose.exports;
}

var hasRequiredObjectWithoutProperties;

function requireObjectWithoutProperties () {
	if (hasRequiredObjectWithoutProperties) return objectWithoutProperties.exports;
	hasRequiredObjectWithoutProperties = 1;
	(function (module) {
		var objectWithoutPropertiesLoose = requireObjectWithoutPropertiesLoose();
		function _objectWithoutProperties(source, excluded) {
		  if (source == null) return {};
		  var target = objectWithoutPropertiesLoose(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;
		}
		module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (objectWithoutProperties));
	return objectWithoutProperties.exports;
}

var hasRequiredEffect;

function requireEffect () {
	if (hasRequiredEffect) return effect$3;
	hasRequiredEffect = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(effect$3, "__esModule", {
	  value: true
	});
	effect$3.NetworkError = NetworkError;
	effect$3.default = effect$3.getFormData = effect$3.getHeaders = void 0;
	var _defineProperty2 = _interopRequireDefault(requireDefineProperty());
	var _objectWithoutProperties2 = _interopRequireDefault(requireObjectWithoutProperties());
	function ownKeys(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(target) {
	  for (var i = 1; i < arguments.length; i++) {
	    var source = arguments[i] != null ? arguments[i] : {};
	    if (i % 2) {
	      ownKeys(Object(source), true).forEach(function (key) {
	        (0, _defineProperty2.default)(target, key, source[key]);
	      });
	    } else if (Object.getOwnPropertyDescriptors) {
	      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
	    } else {
	      ownKeys(Object(source)).forEach(function (key) {
	        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
	      });
	    }
	  }
	  return target;
	}
	function NetworkError(response, status) {
	  this.name = 'NetworkError';
	  this.status = status;
	  this.response = response;
	} // $FlowFixMe

	NetworkError.prototype = Error.prototype;
	var tryParseJSON = function tryParseJSON(json) {
	  if (!json) {
	    return null;
	  }
	  try {
	    return JSON.parse(json);
	  } catch (e) {
	    throw new Error("Failed to parse unexpected JSON response: ".concat(json));
	  }
	};
	var getResponseBody = function getResponseBody(res) {
	  var contentType = res.headers.get('content-type') || false;
	  if (contentType && contentType.indexOf('json') >= 0) {
	    return res.text().then(tryParseJSON);
	  }
	  return res.text();
	};
	var getHeaders = function getHeaders(headers) {
	  var _ref = headers || {},
	    contentTypeCapitalized = _ref['Content-Type'],
	    contentTypeLowerCase = _ref['content-type'],
	    restOfHeaders = (0, _objectWithoutProperties2.default)(_ref, ["Content-Type", "content-type"]);
	  var contentType = contentTypeCapitalized || contentTypeLowerCase || 'application/json';
	  return _objectSpread(_objectSpread({}, restOfHeaders), {}, {
	    'content-type': contentType
	  });
	};
	effect$3.getHeaders = getHeaders;
	var getFormData = function getFormData(object) {
	  var formData = new FormData();
	  Object.keys(object).forEach(function (key) {
	    Object.keys(object[key]).forEach(function (innerObj) {
	      var newObj = object[key][innerObj];
	      formData.append(newObj[0], newObj[1]);
	    });
	  });
	  return formData;
	}; // eslint-disable-next-line no-unused-vars

	effect$3.getFormData = getFormData;
	var _default = function _default(effect, _action) {
	  var url = effect.url,
	    json = effect.json,
	    options = (0, _objectWithoutProperties2.default)(effect, ["url", "json"]);
	  var headers = getHeaders(options.headers);
	  if (!(options.body instanceof FormData) && Object.prototype.hasOwnProperty.call(headers, 'content-type') && headers['content-type'].toLowerCase().includes('multipart/form-data')) {
	    options.body = getFormData(options.body);
	  }
	  if (json !== null && json !== undefined) {
	    try {
	      options.body = JSON.stringify(json);
	    } catch (e) {
	      return Promise.reject(e);
	    }
	  }
	  return fetch(url, _objectSpread(_objectSpread({}, options), {}, {
	    headers: headers
	  })).then(function (res) {
	    if (res.ok) {
	      return getResponseBody(res);
	    }
	    return getResponseBody(res).then(function (body) {
	      throw new NetworkError(body || '', res.status);
	    });
	  });
	};
	effect$3.default = _default;
	return effect$3;
}

var retry = {};

var hasRequiredRetry;

function requireRetry () {
	if (hasRequiredRetry) return retry;
	hasRequiredRetry = 1;

	Object.defineProperty(retry, "__esModule", {
	  value: true
	});
	retry.default = void 0;
	var decaySchedule = [1000,
	// After 1 seconds
	1000 * 5,
	// After 5 seconds
	1000 * 15,
	// After 15 seconds
	1000 * 30,
	// After 30 seconds
	1000 * 60,
	// After 1 minute
	1000 * 60 * 3,
	// After 3 minutes
	1000 * 60 * 5,
	// After 5 minutes
	1000 * 60 * 10,
	// After 10 minutes
	1000 * 60 * 30,
	// After 30 minutes
	1000 * 60 * 60 // After 1 hour
	];

	var _default = function _default(action, retries) {
	  return decaySchedule[retries] || null;
	};
	retry.default = _default;
	return retry;
}

var discard = {};

var hasRequiredDiscard;

function requireDiscard () {
	if (hasRequiredDiscard) return discard;
	hasRequiredDiscard = 1;

	Object.defineProperty(discard, "__esModule", {
	  value: true
	});
	discard.default = void 0;
	requireEffect();
	var _default = function _default(error, action) {

	  // not a network error -> discard
	  if (!('status' in error)) {
	    return true;
	  } // discard http 4xx errors
	  // $FlowFixMe

	  return error.status >= 400 && error.status < 500;
	};
	discard.default = _default;
	return discard;
}

var defaultCommit = {};

var hasRequiredDefaultCommit;

function requireDefaultCommit () {
	if (hasRequiredDefaultCommit) return defaultCommit;
	hasRequiredDefaultCommit = 1;

	Object.defineProperty(defaultCommit, "__esModule", {
	  value: true
	});
	defaultCommit.default = void 0;
	var _constants = constants;
	var defaultCommit$1 = {
	  type: _constants.DEFAULT_COMMIT
	};
	var _default = defaultCommit$1;
	defaultCommit.default = _default;
	return defaultCommit;
}

var defaultRollback = {};

var hasRequiredDefaultRollback;

function requireDefaultRollback () {
	if (hasRequiredDefaultRollback) return defaultRollback;
	hasRequiredDefaultRollback = 1;

	Object.defineProperty(defaultRollback, "__esModule", {
	  value: true
	});
	defaultRollback.default = void 0;
	var _constants = constants;
	var defaultRollback$1 = {
	  type: _constants.DEFAULT_ROLLBACK
	};
	var _default = defaultRollback$1;
	defaultRollback.default = _default;
	return defaultRollback;
}

var persistAutoRehydrate = {};

var hasRequiredPersistAutoRehydrate;

function requirePersistAutoRehydrate () {
	if (hasRequiredPersistAutoRehydrate) return persistAutoRehydrate;
	hasRequiredPersistAutoRehydrate = 1;

	Object.defineProperty(persistAutoRehydrate, "__esModule", {
	  value: true
	});
	persistAutoRehydrate.default = void 0;
	var _reduxPersist = require$$0$2;
	var _default = _reduxPersist.autoRehydrate;
	persistAutoRehydrate.default = _default;
	return persistAutoRehydrate;
}

var offlineStateLens = {};

var hasRequiredOfflineStateLens;

function requireOfflineStateLens () {
	if (hasRequiredOfflineStateLens) return offlineStateLens;
	hasRequiredOfflineStateLens = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(offlineStateLens, "__esModule", {
	  value: true
	});
	offlineStateLens.default = void 0;
	var _defineProperty2 = _interopRequireDefault(requireDefineProperty());
	var _objectWithoutProperties2 = _interopRequireDefault(requireObjectWithoutProperties());
	function ownKeys(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(target) {
	  for (var i = 1; i < arguments.length; i++) {
	    var source = arguments[i] != null ? arguments[i] : {};
	    if (i % 2) {
	      ownKeys(Object(source), true).forEach(function (key) {
	        (0, _defineProperty2.default)(target, key, source[key]);
	      });
	    } else if (Object.getOwnPropertyDescriptors) {
	      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
	    } else {
	      ownKeys(Object(source)).forEach(function (key) {
	        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
	      });
	    }
	  }
	  return target;
	}
	var _default = function _default(state) {
	  var offline = state.offline,
	    rest = (0, _objectWithoutProperties2.default)(state, ["offline"]);
	  return {
	    get: offline,
	    set: function set(offlineState) {
	      return typeof offlineState === 'undefined' ? rest : _objectSpread({
	        offline: offlineState
	      }, rest);
	    }
	  };
	};
	offlineStateLens.default = _default;
	return offlineStateLens;
}

var queue = {};

var toArray = {exports: {}};

var arrayWithHoles = {exports: {}};

var hasRequiredArrayWithHoles;

function requireArrayWithHoles () {
	if (hasRequiredArrayWithHoles) return arrayWithHoles.exports;
	hasRequiredArrayWithHoles = 1;
	(function (module) {
		function _arrayWithHoles(arr) {
		  if (Array.isArray(arr)) return arr;
		}
		module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (arrayWithHoles));
	return arrayWithHoles.exports;
}

var iterableToArray = {exports: {}};

var hasRequiredIterableToArray;

function requireIterableToArray () {
	if (hasRequiredIterableToArray) return iterableToArray.exports;
	hasRequiredIterableToArray = 1;
	(function (module) {
		function _iterableToArray(iter) {
		  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
		}
		module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (iterableToArray));
	return iterableToArray.exports;
}

var unsupportedIterableToArray = {exports: {}};

var arrayLikeToArray = {exports: {}};

var hasRequiredArrayLikeToArray;

function requireArrayLikeToArray () {
	if (hasRequiredArrayLikeToArray) return arrayLikeToArray.exports;
	hasRequiredArrayLikeToArray = 1;
	(function (module) {
		function _arrayLikeToArray(arr, len) {
		  if (len == null || len > arr.length) len = arr.length;
		  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
		  return arr2;
		}
		module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (arrayLikeToArray));
	return arrayLikeToArray.exports;
}

var hasRequiredUnsupportedIterableToArray;

function requireUnsupportedIterableToArray () {
	if (hasRequiredUnsupportedIterableToArray) return unsupportedIterableToArray.exports;
	hasRequiredUnsupportedIterableToArray = 1;
	(function (module) {
		var arrayLikeToArray = requireArrayLikeToArray();
		function _unsupportedIterableToArray(o, minLen) {
		  if (!o) return;
		  if (typeof o === "string") return arrayLikeToArray(o, minLen);
		  var n = Object.prototype.toString.call(o).slice(8, -1);
		  if (n === "Object" && o.constructor) n = o.constructor.name;
		  if (n === "Map" || n === "Set") return Array.from(o);
		  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
		}
		module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (unsupportedIterableToArray));
	return unsupportedIterableToArray.exports;
}

var nonIterableRest = {exports: {}};

var hasRequiredNonIterableRest;

function requireNonIterableRest () {
	if (hasRequiredNonIterableRest) return nonIterableRest.exports;
	hasRequiredNonIterableRest = 1;
	(function (module) {
		function _nonIterableRest() {
		  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
		}
		module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (nonIterableRest));
	return nonIterableRest.exports;
}

var hasRequiredToArray;

function requireToArray () {
	if (hasRequiredToArray) return toArray.exports;
	hasRequiredToArray = 1;
	(function (module) {
		var arrayWithHoles = requireArrayWithHoles();
		var iterableToArray = requireIterableToArray();
		var unsupportedIterableToArray = requireUnsupportedIterableToArray();
		var nonIterableRest = requireNonIterableRest();
		function _toArray(arr) {
		  return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
		}
		module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (toArray));
	return toArray.exports;
}

var toConsumableArray = {exports: {}};

var arrayWithoutHoles = {exports: {}};

var hasRequiredArrayWithoutHoles;

function requireArrayWithoutHoles () {
	if (hasRequiredArrayWithoutHoles) return arrayWithoutHoles.exports;
	hasRequiredArrayWithoutHoles = 1;
	(function (module) {
		var arrayLikeToArray = requireArrayLikeToArray();
		function _arrayWithoutHoles(arr) {
		  if (Array.isArray(arr)) return arrayLikeToArray(arr);
		}
		module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (arrayWithoutHoles));
	return arrayWithoutHoles.exports;
}

var nonIterableSpread = {exports: {}};

var hasRequiredNonIterableSpread;

function requireNonIterableSpread () {
	if (hasRequiredNonIterableSpread) return nonIterableSpread.exports;
	hasRequiredNonIterableSpread = 1;
	(function (module) {
		function _nonIterableSpread() {
		  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
		}
		module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (nonIterableSpread));
	return nonIterableSpread.exports;
}

var hasRequiredToConsumableArray;

function requireToConsumableArray () {
	if (hasRequiredToConsumableArray) return toConsumableArray.exports;
	hasRequiredToConsumableArray = 1;
	(function (module) {
		var arrayWithoutHoles = requireArrayWithoutHoles();
		var iterableToArray = requireIterableToArray();
		var unsupportedIterableToArray = requireUnsupportedIterableToArray();
		var nonIterableSpread = requireNonIterableSpread();
		function _toConsumableArray(arr) {
		  return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
		}
		module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (toConsumableArray));
	return toConsumableArray.exports;
}

var hasRequiredQueue;

function requireQueue () {
	if (hasRequiredQueue) return queue;
	hasRequiredQueue = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(queue, "__esModule", {
	  value: true
	});
	queue.default = void 0;
	var _toArray2 = _interopRequireDefault(requireToArray());
	var _toConsumableArray2 = _interopRequireDefault(requireToConsumableArray());

	/* eslint-disable no-unused-vars */
	function enqueue(array, item, context) {
	  return [].concat((0, _toConsumableArray2.default)(array), [item]);
	}
	function dequeue(array, item, context) {
	  var _array = (0, _toArray2.default)(array),
	    rest = _array.slice(1);
	  return rest;
	}
	function peek(array, item, context) {
	  return array[0];
	}
	var _default = {
	  enqueue: enqueue,
	  dequeue: dequeue,
	  peek: peek
	};
	queue.default = _default;
	return queue;
}

var _interopRequireDefault$e = interopRequireDefaultExports;
Object.defineProperty(defaults$1, "__esModule", {
  value: true
});
var default_1$8 = defaults$1.default = void 0;
var _persist = _interopRequireDefault$e(requirePersist());
var _detectNetwork = _interopRequireDefault$e(requireDetectNetwork());
var _effect = _interopRequireDefault$e(requireEffect());
var _retry = _interopRequireDefault$e(requireRetry());
var _discard = _interopRequireDefault$e(requireDiscard());
var _defaultCommit = _interopRequireDefault$e(requireDefaultCommit());
var _defaultRollback = _interopRequireDefault$e(requireDefaultRollback());
var _persistAutoRehydrate = _interopRequireDefault$e(requirePersistAutoRehydrate());
var _offlineStateLens = _interopRequireDefault$e(requireOfflineStateLens());
var _queue = _interopRequireDefault$e(requireQueue());
var _default$c = {
  rehydrate: true,
  // backward compatibility, TODO remove in the next breaking change version
  persist: _persist.default,
  detectNetwork: _detectNetwork.default,
  effect: _effect.default,
  retry: _retry.default,
  discard: _discard.default,
  defaultCommit: _defaultCommit.default,
  defaultRollback: _defaultRollback.default,
  persistAutoRehydrate: _persistAutoRehydrate.default,
  offlineStateLens: _offlineStateLens.default,
  queue: _queue.default,
  returnPromises: false
};
default_1$8 = defaults$1.default = _default$c;

var hasRequiredConfig;

function requireConfig () {
	if (hasRequiredConfig) return config$1;
	hasRequiredConfig = 1;

	var _interopRequireDefault = interopRequireDefaultExports;
	Object.defineProperty(config$1, "__esModule", {
	  value: true
	});
	config$1.applyDefaults = void 0;
	var _defineProperty2 = _interopRequireDefault(requireDefineProperty());
	var _defaults = _interopRequireDefault(defaults$1);
	function ownKeys(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(target) {
	  for (var i = 1; i < arguments.length; i++) {
	    var source = arguments[i] != null ? arguments[i] : {};
	    if (i % 2) {
	      ownKeys(Object(source), true).forEach(function (key) {
	        (0, _defineProperty2.default)(target, key, source[key]);
	      });
	    } else if (Object.getOwnPropertyDescriptors) {
	      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
	    } else {
	      ownKeys(Object(source)).forEach(function (key) {
	        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
	      });
	    }
	  }
	  return target;
	}
	var applyDefaults = function applyDefaults() {
	  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
	  return _objectSpread(_objectSpread({}, _defaults.default), config);
	};
	config$1.applyDefaults = applyDefaults;
	return config$1;
}

var offlineActionTracker = {};

var hasRequiredOfflineActionTracker;

function requireOfflineActionTracker () {
	if (hasRequiredOfflineActionTracker) return offlineActionTracker;
	hasRequiredOfflineActionTracker = 1;

	Object.defineProperty(offlineActionTracker, "__esModule", {
	  value: true
	});
	offlineActionTracker.default = void 0;
	var subscriptions = {};
	function registerAction(transaction) {
	  return new Promise(function (resolve, reject) {
	    subscriptions[transaction] = {
	      resolve: resolve,
	      reject: reject
	    };
	  });
	}
	function resolveAction(transaction, value) {
	  var subscription = subscriptions[transaction];
	  if (subscription) {
	    subscription.resolve(value);
	    delete subscriptions[transaction];
	  }
	}
	function rejectAction(transaction, error) {
	  var subscription = subscriptions[transaction];
	  if (subscription) {
	    subscription.reject(error);
	    delete subscriptions[transaction];
	  }
	}
	var withPromises = {
	  registerAction: registerAction,
	  resolveAction: resolveAction,
	  rejectAction: rejectAction
	};
	var withoutPromises = {
	  registerAction: function registerAction() {},
	  resolveAction: function resolveAction() {},
	  rejectAction: function rejectAction() {}
	};
	var _default = {
	  withPromises: withPromises,
	  withoutPromises: withoutPromises
	};
	offlineActionTracker.default = _default;
	return offlineActionTracker;
}

var _interopRequireDefault$d = interopRequireDefaultExports;
Object.defineProperty(lib, "__esModule", {
  value: true
});
var createOffline_1 = lib.createOffline = lib.offline = void 0;
var _typeof2 = _interopRequireDefault$d(require_typeof());
var _redux = require$$2;
var _middleware = requireMiddleware();
var _updater = requireUpdater();
var _config = requireConfig();
var _actions = actions;
var _offlineActionTracker = _interopRequireDefault$d(requireOfflineActionTracker());

/* global $Shape */
// @TODO: Take createStore as config?
var warnIfNotReduxAction = function warnIfNotReduxAction(config, key) {
  var maybeAction = config[key];
  var isNotReduxAction = maybeAction === null || (0, _typeof2.default)(maybeAction) !== 'object' || typeof maybeAction.type !== 'string' || maybeAction.type === '';
  if (isNotReduxAction && console.warn) {
    var msg = "".concat(key, " must be a proper redux action, ") + "i.e. it must be an object and have a non-empty string type. " + "Instead you provided: ".concat(JSON.stringify(maybeAction, null, 2));
    console.warn(msg);
  }
};
var offline = function offline() {
  var userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (createStore) {
    return function (reducer, preloadedState) {
      var enhancer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (x) {
        return x;
      };
      var config = (0, _config.applyDefaults)(userConfig);
      warnIfNotReduxAction(config, 'defaultCommit');
      warnIfNotReduxAction(config, 'defaultRollback'); // toggle experimental returned promises

      config.offlineActionTracker = config.returnPromises ? _offlineActionTracker.default.withPromises : _offlineActionTracker.default.withoutPromises;
      delete config.returnPromises; // wraps userland reducer with a top-level
      // reducer that handles offline state updating

      var offlineReducer = (0, _updater.enhanceReducer)(reducer, config); // $FlowFixMe

      var offlineMiddleware = (0, _redux.applyMiddleware)((0, _middleware.createOfflineMiddleware)(config)); // create autoRehydrate enhancer if required

      var offlineEnhancer = config.persist && config.rehydrate && config.persistAutoRehydrate ? (0, _redux.compose)(offlineMiddleware, config.persistAutoRehydrate()) : offlineMiddleware; // create store

      var store = offlineEnhancer(createStore)(offlineReducer, preloadedState, enhancer);
      var baseReplaceReducer = store.replaceReducer.bind(store); // $FlowFixMe

      store.replaceReducer = function replaceReducer(nextReducer) {
        return baseReplaceReducer((0, _updater.enhanceReducer)(nextReducer, config));
      }; // launch store persistor

      if (config.persist) {
        config.persist(store, config.persistOptions, config.persistCallback);
      } // launch network detector

      if (config.detectNetwork) {
        config.detectNetwork(function (online) {
          store.dispatch((0, _actions.networkStatusChanged)(online));
        });
      }
      return store;
    };
  };
};
lib.offline = offline;
var createOffline = function createOffline() {
  var userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var config = (0, _config.applyDefaults)(userConfig); // toggle experimental returned promises

  config.offlineActionTracker = config.returnPromises ? _offlineActionTracker.default.withPromises : _offlineActionTracker.default.withoutPromises;
  delete config.returnPromises;
  warnIfNotReduxAction(config, 'defaultCommit');
  warnIfNotReduxAction(config, 'defaultRollback');
  var enhanceStore = function enhanceStore(next) {
    return function (reducer, preloadedState, enhancer) {
      // create autoRehydrate enhancer if required
      var createStore = config.persist && config.rehydrate && config.persistAutoRehydrate ? config.persistAutoRehydrate()(next) : next; // create store

      var store = createStore(reducer, preloadedState, enhancer);
      var baseReplaceReducer = store.replaceReducer.bind(store);
      store.replaceReducer = function replaceReducer(nextReducer) {
        return baseReplaceReducer((0, _updater.enhanceReducer)(nextReducer, config));
      }; // launch store persistor

      if (config.persist) {
        config.persist(store, config.persistOptions, config.persistCallback);
      } // launch network detector

      if (config.detectNetwork) {
        config.detectNetwork(function (online) {
          store.dispatch((0, _actions.networkStatusChanged)(online));
        });
      }
      return store;
    };
  };
  return {
    middleware: (0, _middleware.createOfflineMiddleware)(config),
    enhanceReducer: function enhanceReducer(reducer) {
      return (0, _updater.enhanceReducer)(reducer, config);
    },
    enhanceStore: enhanceStore
  };
};
createOffline_1 = lib.createOffline = createOffline;

const offlineConfig = default_1$8.default || default_1$8;

const {
  discard: defaultDiscard,
  retry: defaultRetry
} = offlineConfig;
const REMOVE_ITEMS = "@@REMOVE_OUTBOX_ITEMS",
  RETRY_ITEMS = "@@RETRY_OUTBOX_ITEMS",
  POST = "POST",
  DELETE = "DELETE",
  SUBMIT = "SUBMIT",
  SUCCESS = "SUCCESS",
  UPDATE = "UPDATE",
  ERROR = "ERROR",
  FORM_SUBMIT = "FORM_SUBMIT",
  FORM_SUCCESS = "FORM_SUCCESS",
  FORM_ERROR = "FORM_ERROR",
  BATCH_SUBMIT = "@@BATCH_SUBMIT",
  BATCH_SUCCESS = "@@BATCH_SUCCESS",
  BATCH_ERROR = "@@BATCH_ERROR",
  ON_SUCCESS = "ON_SUCCESS",
  IMMEDIATE = "IMMEDIATE",
  LOCAL_ONLY = "LOCAL_ONLY";
var _outboxes = {};
class Outbox {
  constructor(store) {
    _outboxes[store.name] = this;
    this.store = store;
    store.outbox = this;
    const {
      middleware,
      enhanceReducer,
      enhanceStore
    } = createOffline_1({
      ...offlineConfig,
      effect: (effect, action) => this._effect(effect, action),
      discard: (error, action, retries) => this._discard(error, action, retries),
      retry: (action, retries) => this._retry(action, retries),
      queue: {
        enqueue: (array, item, context) => this._enqueue(array, item, context),
        dequeue: (array, item, context) => this._dequeue(array, item, context),
        peek: (array, item, context) => this._peek(array, item, context)
      },
      persist: false // Handled in store
    });

    store.addMiddleware(middleware);
    store.addEnhanceReducer("offline", enhanceReducer, state => this._serialize(state), state => this._deserialize(state));
    store.addEnhancer(enhanceStore);
    store.subscribe(() => this._onUpdate());
    this.syncMethod = POST;
    this.batchService = null;
    this.batchSizeMin = 2;
    this.batchSizeMax = 50;
    this.applyState = ON_SUCCESS;
    this.cleanOutbox = true;
    this.maxRetries = 10;
    this.csrftoken = null;
    this.csrftokenField = "csrfmiddlewaretoken";
    this._memoryItems = {};
    this._waiting = {};
    this._lastOutbox = [];
  }
  init(opts) {
    var optlist = [
    // Default to store values but allow overriding
    "service", "formatKeyword", "defaults", "debugNetwork", "debugValues",
    // Outbox-specific options
    "syncMethod", "applyState", "cleanOutbox", "maxRetries", "batchService", "batchSizeMin", "batchSizeMax", "csrftokenField",
    // Outbox functions
    "applyResult", "updateModels"];
    optlist.forEach(opt => {
      if (this.store.hasOwnProperty(opt)) {
        this[opt] = this.store[opt];
      }
      if (opts && opts.hasOwnProperty(opt)) {
        this[opt] = opts[opt];
      }
    });
    if (opts && opts.parseBatchResult) {
      throw new Error("parseBatchResult() no longer supported.  Use an ajax() plugin instead.");
    }
    if (opts && opts.validate) {
      throw new Error("config.outbox.validate() no longer supported.  Use a validate() plugin instead");
    }
    if (this.cleanOutbox) {
      // Clear out successfully synced items from previous runs, if any
      // FIXME: should we hold up init until this is done?
      this.loadItems().then(items => {
        this.removeItems(items.list.filter(item => item.synced || item.options.storage === "temporary" && !item.options.desiredStorage).map(item => item.id));
      }).then(() => this._cleanUpItemData);
    }
    if (this.batchService) {
      this.store.addThunk(BATCH_SUCCESS, (dispatch, getState, bag) => this._dispatchBatchResponse(bag.action, dispatch));
      this.store.addThunk(BATCH_ERROR, (dispatch, getState, bag) => this._dispatchBatchResponse(bag.action, dispatch));
    }
  }
  setCSRFToken(csrftoken) {
    this.csrftoken = csrftoken;
  }

  // Queue data for server use; use outbox to cache unsynced items
  async save(data, options, noSend) {
    if (noSend) {
      throw new Error("outbox.save() noSend arg no longer supported; use outbox.pause() instead");
    }
    if (options) {
      options = {
        ...options
      };
    } else {
      options = {};
    }
    if (options.storage === "inline") {
      delete options.storage;
    }
    if (options.storage === "temporary") {
      options.once = true;
    }

    // FIXME: What if next id changes during await?
    const outboxId = options.id || (this.store.getState().offline.lastTransaction || 0) + 1;
    const item = await this._updateItemData({
      id: outboxId,
      data,
      options
    });
    var currentId;
    if (data && data.id) {
      currentId = data.id;
    } else if (options.url && options.modelConf && options.modelConf.url) {
      const match = options.url.match(options.modelConf.url + "/(.+)");
      if (match) {
        if (!isNaN(+match[1])) {
          currentId = +match[1];
        } else {
          currentId = match[1];
        }
      }
    }
    options = item.options;
    data = item.data;
    var type, payload, commitType, rollbackType;
    const model = this._getModel(options.modelConf);
    if (model) {
      const applyState = options.applyState || this.applyState;
      if (options.method === DELETE && currentId) {
        if (applyState === ON_SUCCESS) {
          commitType = model.expandActionType(DELETE);
          type = commitType + SUBMIT;
          rollbackType = commitType + ERROR;
        } else if (applyState === IMMEDIATE) {
          type = model.expandActionType(DELETE);
          commitType = type + SUCCESS;
          rollbackType = type + ERROR;
        } else if (applyState === LOCAL_ONLY) {
          type = model.expandActionType(DELETE);
          commitType = null;
          rollbackType = null;
        } else {
          throw new Error("Unknown applyState " + applyState);
        }
        payload = currentId;
      } else {
        if (applyState === ON_SUCCESS) {
          type = model.expandActionType(SUBMIT);
          commitType = model.expandActionType(UPDATE);
          rollbackType = model.expandActionType(ERROR);
          payload = null;
        } else if (applyState === IMMEDIATE) {
          type = model.expandActionType(UPDATE);
          commitType = model.expandActionType(SUCCESS);
          rollbackType = model.expandActionType(ERROR);
          payload = this._localUpdate(data, currentId, outboxId);
        } else if (applyState === LOCAL_ONLY) {
          type = model.expandActionType(UPDATE);
          commitType = null;
          rollbackType = null;
          payload = this._localUpdate(data, currentId);
        } else {
          throw new Error("Unknown applyState " + applyState);
        }
      }
    } else if (options.modelConf) {
      const name = options.modelConf.name.toUpperCase();
      type = `${name}_${SUBMIT}`;
      commitType = `${name}_${SUCCESS}`;
      rollbackType = `${name}_${ERROR}`;
    } else {
      type = FORM_SUBMIT;
      commitType = FORM_SUCCESS;
      rollbackType = FORM_ERROR;
    }
    if (commitType) {
      this.store.dispatch({
        type,
        payload,
        meta: {
          offline: {
            effect: {
              data,
              options
            },
            commit: {
              type: commitType
            },
            rollback: {
              type: rollbackType
            }
          }
        }
      });
      const items = await this.loadItems(),
        item = items.list.find(item => item.id === outboxId);
      return item || items.list[0];
    } else {
      this.store.dispatch({
        type,
        payload
      });
      return null;
    }
  }
  _enqueue(array, action) {
    const {
        offline
      } = action.meta,
      {
        data,
        options
      } = offline.effect;
    if (options.id) {
      const exist = array.find(act => act.meta.outboxId === options.id);
      if (exist) {
        (options.preserve || []).forEach(field => {
          if (data[field] === undefined) {
            data[field] = exist.meta.offline.effect.data[field];
          }
        });
        array = array.filter(act => act.meta.outboxId !== options.id);
      }
    } else {
      options.id = action.meta.transaction;
    }
    action.meta.outboxId = options.id;
    if (!offline.commit) {
      offline.commit = {
        type: `${action.type}_${SUCCESS}`
      };
    }
    if (!offline.commit.meta) {
      offline.commit.meta = {};
    }
    if (!offline.rollback) {
      offline.rollback = {
        type: `${action.type}_${ERROR}`
      };
    }
    if (!offline.rollback.meta) {
      offline.rollback.meta = {};
    }

    // Copy action but exclude commit/rollback (to avoid recursive nesting)
    const offlineAction = {
      ...action,
      meta: {
        ...action.meta,
        offline: {
          effect: offline.effect
        }
      }
    };
    offline.commit.meta.offlineAction = offlineAction;
    offline.rollback.meta.offlineAction = offlineAction;
    const currentId = action.payload && action.payload.id;
    if (currentId) {
      offline.commit.meta.currentId = currentId;
      offline.rollback.meta.currentId = currentId;
    }
    Object.keys(data || {}).forEach(key => {
      var match = typeof data[key] === "string" && data[key].match(/^outbox-(\d+)$/);
      if (match) {
        if (!action.meta.parents) {
          action.meta.parents = [];
        }
        action.meta.parents.push(+match[1]);
      }
    });
    return [...array, action];
  }

  // Validate a record before adding it to the outbox
  validate(data, modelConf) {
    const errors = {};
    this.app.callPlugins("validate", [data, modelConf]).forEach(pluginErrors => {
      mergeErrors(errors, pluginErrors);
    });
    return errors;
  }

  // Send a single item from the outbox to the server
  sendItem() {
    throw new Error("sendItem() no longer supported; use waitForItem() instead");
  }
  _peek(array) {
    const pending = array.filter(act => {
      if (act.meta.completed) {
        return false;
      }
      if (act.meta.parents && act.meta.parents.length) {
        return false;
      }
      return true;
    });
    if (this.batchService && pending.length && pending.length >= this.batchSizeMin) {
      const action = this._createBatchAction(pending.slice(0, this.batchSizeMax));
      if (action) {
        return action;
      }
    }
    return pending[0];
  }
  async _effect({
    data,
    options
  }, action) {
    const item = await this._loadItemData({
      id: options.id,
      data,
      options
    });
    data = item.data;
    var url = this.service;
    if (options.url) {
      url = url + "/" + options.url;
    }
    var method = options.method || this.syncMethod;
    var headers = {};

    // Use current CSRF token in case it's changed since item was saved
    var csrftoken = this.csrftoken || options.csrftoken;
    if (csrftoken) {
      headers["X-CSRFToken"] = csrftoken;
      if (!options.json) {
        data = {
          ...data,
          [this.csrftokenField]: csrftoken
        };
      }
    }
    var defaults = {
      ...this.defaults
    };
    if (defaults.format && !this.formatKeyword) {
      url = url.replace(/\/$/, "");
      url += "." + defaults.format;
      delete defaults.format;
    }
    var urlObj = new URL(url, window.location);
    Object.entries(defaults).forEach(([key, value]) => urlObj.searchParams.append(key, value));
    if (this.debugNetwork) {
      console.log("Sending item to " + urlObj.href);
      if (this.debugValues) {
        console.log(data);
      }
    }
    if (options.json) {
      headers["Content-Type"] = "application/json";
      data = JSON.stringify(data);
    } else {
      data = this._createFormData(data);
    }
    return this.store.ajax(urlObj, data, method, headers).then(res => {
      if (!res && method === DELETE) {
        return action.payload;
      } else {
        return res;
      }
    });
  }
  _createFormData(data) {
    // Use a FormData object to submit
    var formData = new FormData();
    Object.entries(data).forEach(([key, val]) => {
      if (Array.isArray(val)) {
        val.forEach(appendValue.bind(this, key));
      } else {
        appendValue(key, val);
      }
    });
    function appendValue(key, val) {
      if (val && val.name && val.type && val.body) {
        // File (Blob) record; add with filename
        var blob = val.body;
        if (!blob.type) {
          // Serialized blobs lose their type
          var slice = blob.slice || blob.webkitSlice;
          blob = slice.call(blob, 0, blob.size, val.type);
        }
        formData.append(key, blob, val.name);
      } else if (val && val.name && val.type && val.uri) {
        // React native
        formData.append(key, val);
      } else {
        // Add regular form fields
        formData.append(key, val);
      }
    }
    return formData;
  }
  _createBatchAction(actions) {
    const loadEffect = action => {
      const {
          effect
        } = action.meta.offline,
        {
          options
        } = effect;
      let data;
      if (!options.storage) {
        data = effect.data;
      } else if (options.storage === "temporary") {
        data = this._memoryItems[options.id];
      } else {
        throw new Error("Binary submissions not currently supported in batch mode.");
      }
      data = this._parseJsonForm({
        data
      }).data;
      return {
        data,
        options
      };
    };
    let effects;
    try {
      effects = actions.map(loadEffect);
    } catch (e) {
      console.warn(e);
      return false;
    }
    return {
      type: BATCH_SUBMIT,
      meta: {
        offline: {
          effect: {
            data: effects.map(effect => {
              const {
                data,
                options
              } = effect;
              return {
                url: this.store.service + "/" + options.url,
                method: options.method || this.syncMethod,
                headers: {
                  "Content-Type": "application/json",
                  Accept: "application/json",
                  "X-CSRFToken": this.csrftoken
                },
                body: JSON.stringify(data)
              };
            }),
            options: {
              url: this.batchService,
              json: true
            }
          },
          commit: {
            type: BATCH_SUCCESS,
            meta: {
              actions
            }
          },
          rollback: {
            type: BATCH_ERROR,
            meta: {
              actions
            }
          }
        }
      }
    };
  }
  _processBatchResponse(batchAction) {
    let responses, batchError;
    if (batchAction.type == BATCH_SUCCESS) {
      if (Array.isArray(batchAction.payload)) {
        responses = batchAction.payload;
      }
    } else {
      // batchAction.type == BATCH_ERROR
      if (batchAction.payload) {
        batchError = batchAction.payload;
      } else {
        batchError = new Error("Batch submission error");
      }
    }
    return batchAction.meta.actions.map((action, i) => {
      const resp = responses ? responses[i] : null,
        {
          offline
        } = action.meta,
        {
          commit,
          rollback
        } = offline;
      let nextAction;
      if (resp && resp.status_code >= 200 && resp.status_code <= 299) {
        let payload;
        try {
          payload = JSON.parse(resp.body);
        } catch (e) {
          payload = resp.body;
        }
        nextAction = {
          ...commit,
          payload,
          meta: {
            ...commit.meta,
            success: true
          }
        };
      } else {
        let error;
        if (resp && resp.body) {
          error = new Error();
          try {
            error.json = JSON.parse(resp.body);
          } catch (e) {
            error.text = resp.body;
          }
          error.status = resp.status_code;
        } else if (batchError) {
          error = batchError;
        } else {
          error = new Error("Missing from batch response");
        }
        nextAction = {
          ...rollback,
          payload: error,
          meta: {
            ...rollback.meta,
            success: false
          }
        };
      }
      return nextAction;
    });
  }
  _dispatchBatchResponse(batchAction, dispatch) {
    this._processBatchResponse(batchAction).forEach(nextAction => {
      const action = {
        ...nextAction,
        meta: {
          ...nextAction.meta
        }
      };
      // Avoid double-dequeue
      delete action.meta.offlineAction;
      dispatch(action);
    });
  }
  _localUpdate(data, currentId, outboxId) {
    data = this._parseJsonForm({
      data
    }).data;
    if (!data.hasOwnProperty("id")) {
      if (currentId) {
        data.id = currentId;
      } else if (outboxId) {
        data.id = "outbox-" + outboxId;
      }
    }
    return data;
  }
  _updateParents(item, outboxId, resultId) {
    if (item.meta.parents.indexOf(outboxId) === -1) {
      return item;
    }
    const data = {
      ...item.meta.offline.effect.data
    };
    Object.keys(data).forEach(key => {
      if (data[key] === "outbox-" + outboxId) {
        data[key] = resultId;
      }
    });
    return {
      ...item,
      meta: {
        ...item.meta,
        offline: {
          ...item.meta.offline,
          effect: {
            ...item.meta.offline.effect,
            data
          }
        },
        parents: item.meta.parents.filter(pid => pid != outboxId)
      }
    };
  }
  _discard(error, action, retries) {
    const {
      options
    } = action.meta.offline.effect;
    if (this.debugNetwork) {
      console.warn("Error sending item to " + options.url);
      console.error(error);
    }
    return defaultDiscard(error, action, retries || 0);
  }
  _retry(action, retries) {
    const {
      options
    } = action.meta.offline.effect;
    if (options.once) {
      return null;
    } else if (retries > this.maxRetries) {
      return null;
    }
    return defaultRetry(action, retries);
  }
  removeItem(id) {
    return this.removeItems([id]);
  }
  removeItems(ids) {
    return this.store.dispatch({
      type: REMOVE_ITEMS,
      payload: ids,
      meta: {
        completed: true
      }
    });
  }
  async empty() {
    this.store.dispatch({
      type: RESET_STATE_1
    });
    await this._cleanUpItemData();
  }
  retryItem(id) {
    return this.retryItems([id]);
  }
  retryItems(ids) {
    return this.store.dispatch({
      type: RETRY_ITEMS,
      payload: ids,
      meta: {
        completed: true
      }
    });
  }
  async retryAll() {
    const unsynced = await this.unsyncedItems();
    this.retryItems(unsynced.map(item => item.id));
    await this.waitForAll();
  }
  sendAll() {
    throw new Error("sendall() no longer supported; use retryAll() and/or waitForAll() instead");
  }
  _dequeue(array, action) {
    if (action.type === REMOVE_ITEMS) {
      return array.filter(item => action.payload.indexOf(item.meta.outboxId) === -1);
    } else if (action.type === RETRY_ITEMS) {
      return array.map(item => {
        if (action.payload.indexOf(item.meta.outboxId) === -1) {
          return item;
        } else {
          return {
            ...item,
            meta: {
              ...item.meta,
              completed: false,
              success: undefined
            }
          };
        }
      });
    } else if (action.type == BATCH_SUCCESS || action.type == BATCH_ERROR) {
      this._processBatchResponse(action).forEach(nextAction => {
        array = this._dequeue(array, nextAction);
      });
      return array;
    } else if (action.meta.offlineAction) {
      // Mark status but don't remove item completely
      const outboxId = action.meta.offlineAction.meta.outboxId;
      if (!outboxId) {
        return array;
      }
      return array.map(item => {
        if (item.meta.outboxId === outboxId) {
          return this._applyResult(item, action);
        } else if (item.meta.parents && action.meta.success) {
          return this._updateParents(item, outboxId, action.payload.id);
        } else {
          return item;
        }
      });
    } else {
      return array;
    }
  }
  pause() {
    this.store.dispatch(busy_1(true));
  }
  resume() {
    this.store.dispatch(busy_1(false));
  }
  waitForAll() {
    return this.waitForItem("ALL");
  }
  waitForItem(id) {
    var resolve;
    const promise = new Promise(res => resolve = res);
    if (!this._waiting[id]) {
      this._waiting[id] = [];
    }
    this._waiting[id].push(resolve);
    return promise;
  }
  async _onUpdate() {
    const state = this.store.getState(),
      {
        offline
      } = state,
      {
        outbox
      } = offline;
    if (outbox === this._lastOutbox) {
      return;
    }
    const lastIds = {};
    this._lastOutbox.forEach(action => {
      lastIds[action.meta.offline.effect.options.id] = true;
    });
    this._lastOutbox = outbox;
    const pending = await this._allPendingItems();
    if (!pending.length && this._waiting["ALL"]) {
      this._resolveWaiting("ALL");
    }
    const pendingById = {};
    pending.forEach(item => pendingById[item.id] = true);
    const checkIds = Object.keys(lastIds).concat(Object.keys(this._waiting));
    checkIds.forEach(id => {
      if (!pendingById[id] && id != "ALL") {
        this._resolveWaiting(id);
      }
    });
  }
  async _resolveWaiting(id) {
    const waiting = this._waiting[id];
    if (!waiting && !(this.app && this.app.hasPlugin("onsync"))) {
      return;
    }
    const item = id === "ALL" ? null : await this.loadItem(+id);
    if (this.app && id != "ALL") {
      this.app.callPlugins("onsync", [item]);
    }
    if (waiting) {
      waiting.forEach(fn => fn(item));
      delete this._waiting[id];
    }
  }

  // Process service send() results
  _applyResult(item, action) {
    if (this.applyResult) {
      console.warn("applyResult() override no longer called");
    }
    const newItem = {
      ...item,
      meta: {
        ...item.meta,
        success: action.meta.success,
        completed: true
      }
    };
    if (newItem.meta.success) {
      if (this.debugNetwork) {
        console.log("Item successfully sent to " + item.meta.offline.effect.options.url);
      }
      newItem.meta.result = action.payload;
    } else {
      newItem.meta.error = action.payload;
    }
    return newItem;
  }
  _getModel(conf) {
    if (!conf || !conf.name || !conf.list) {
      return null;
    }
    return model({
      store: this.store,
      ...conf
    });
  }
  async loadItems() {
    const {
        outbox
      } = this.store.getState().offline,
      items = this.parseOutbox(outbox);
    return {
      list: items,
      count: items.length,
      pages: 1,
      per_page: items.length
    };
  }
  parseOutbox(outbox) {
    return outbox.map(action => {
      const {
        data,
        options
      } = action.meta.offline.effect;
      var item = {
        id: options.id,
        label: options.label || `Unsynced Item #${options.id}`,
        data: data,
        options: {
          ...options
        },
        synced: !!action.meta.success
      };
      delete item.options.id;
      if (item.options.method === DELETE) {
        item.deletedId = action.payload;
      }
      if (action.meta.parents) {
        item.parents = action.meta.parents;
      }
      if (action.meta.success) {
        item.result = action.meta.result;
      } else if (action.meta.completed) {
        const error = action.meta.error;
        if (error) {
          item.error = error.json || error.text || error.status || "" + error;
        } else {
          item.error = "Error";
        }
      }
      return item;
    }).sort((a, b) => {
      return b.id - a.id;
    });
  }

  // Count of unsynced outbox items (never synced, or sync was unsuccessful)
  async unsynced(modelConf) {
    const items = await this.unsyncedItems(modelConf);
    return items.length;
  }
  filterUnsynced(items, modelConf) {
    // Exclude synced & temporary items from list
    items = items.filter(item => {
      if (item.synced) {
        return false;
      } else if (item.options.storage == "temporary") {
        if (item.options.desiredStorage) {
          return true;
        }
        return false;
      } else {
        return true;
      }
    });
    if (modelConf) {
      // Only match items corresponding to the specified list
      items = items.filter(item => {
        if (!item.options.modelConf) {
          return false;
        }
        return item.options.modelConf.url === modelConf.url;
      });
    }
    return items;
  }

  // Actual unsynced items
  async unsyncedItems(modelConf, withData) {
    const {
        list
      } = await this.loadItems(),
      items = this.filterUnsynced(list, modelConf);
    if (withData) {
      return await Promise.all(items.map(item => this._loadItemData(item)));
    } else {
      return items;
    }
  }

  // Unsynced items that have not been attempted (or retried)
  async pendingItems(modelConf, withData) {
    const unsynced = await this.unsyncedItems(modelConf, withData);
    return unsynced.filter(item => {
      return !item.hasOwnProperty("error");
    });
  }
  async _pendingTempItems() {
    return (await this.loadItems()).list.filter(item => {
      return item.options.storage === "temporary" && !item.synced && !item.error;
    });
  }
  async _allPendingItems() {
    const pendingStore = await this.pendingItems(),
      pendingTemp = await this._pendingTempItems();
    return pendingStore.concat(pendingTemp);
  }
  async loadItem(itemId) {
    var item = (await this.loadItems()).list.find(item => item.id === itemId);
    item = await this._loadItemData(item);
    return this._parseJsonForm(item);
  }
  async _loadItemData(item) {
    if (!item || !item.options || !item.options.storage) {
      return item;
    } else if (item.options.storage == "temporary") {
      return setData(item, this._memoryItems[item.id]);
    } else {
      return this.store.lf.getItem("outbox_" + item.id).then(data => setData(item, data), () => setData(item, null));
    }
    function setData(obj, data) {
      if (data) {
        obj.data = data;
      } else {
        obj.label = "[Form Data Missing]";
        obj.missing = true;
      }
      return obj;
    }
  }
  _parseJsonForm(item) {
    if (!item || !item.data) {
      return item;
    }
    var values = [],
      key;
    for (key in item.data) {
      values.push({
        name: key,
        value: item.data[key]
      });
    }
    item.data = convert(values);
    return item;
  }
  async _updateItemData(item) {
    if (!item.data) {
      return item;
    }
    if (!item.options || !item.options.storage) {
      return item;
    }
    if (item.options.storage == "temporary") {
      this._memoryItems[item.id] = item.data;
      return this._withoutData(item);
    } else {
      return this.store.lf.setItem("outbox_" + item.id, item.data).then(() => this._withoutData(item), () => {
        console.warn("could not save form contents to storage");
        item.options.desiredStorage = item.options.storage;
        item.options.storage = "temporary";
        return this._updateItemData(item);
      });
    }
  }
  _withoutData(item) {
    if (!item.data) {
      return item;
    }
    if (!item.options || !item.options.storage) {
      return item;
    }
    var obj = {};
    Object.keys(item).filter(key => {
      return key != "data";
    }).forEach(key => {
      obj[key] = item[key];
    });
    return obj;
  }
  async _cleanUpItemData() {
    var validId = {};
    const validItems = (await this.loadItems()).list;
    validItems.forEach(item => {
      validId[item.id] = true;
    });
    Object.keys(this._memoryItems).forEach(itemId => {
      if (!validId[itemId]) {
        delete this._memoryItems[itemId];
      }
    });
    const keys = await this.store.lf.keys();
    await Promise.all(keys.filter(key => key.indexOf("outbox_") === 0).map(key => key.replace("outbox_", "")).filter(itemId => !validId[itemId]).map(itemId => this.store.lf.removeItem("outbox_" + itemId)));
  }
  _serialize(state) {
    return {
      ...state,
      outbox: state.outbox.map(action => this._serializeAction(action))
    };
  }
  _serializeAction(action) {
    if (!action.meta || !action.meta.error) {
      return action;
    }
    var error = {};
    ["json", "text", "status"].forEach(key => {
      if (key in action.meta.error) {
        error[key] = action.meta.error[key];
      }
    });
    if (!Object.keys(error).length) {
      error.text = "" + action.meta.error;
    }
    return {
      ...action,
      meta: {
        ...action.meta,
        error
      }
    };
  }
  _deserialize(state) {
    return state;
  }
}
function mergeErrors(errors, newErrors) {
  if (!newErrors || typeof newErrors !== "object" || !Object.keys(newErrors).length) {
    return errors;
  }
  Object.entries(newErrors).forEach(([key, newError]) => {
    const error = errors[key];
    if (!error || typeof error !== typeof newError || Array.isArray(error) !== Array.isArray(newError)) {
      errors[key] = newError;
    } else if (typeof error === "string") {
      errors[key] = error + " • " + newError;
    } else if (Array.isArray(error)) {
      errors[key] = error.map((err, i) => mergeErrors(err, newError[i])).concat(newError.slice(error.length));
    } else if (typeof error === "object") {
      errors[key] = mergeErrors(error, newError);
    }
  });
  return errors;
}
var outbox = new Outbox(ds);
function getOutbox(store) {
  if (_outboxes[store.name]) {
    return _outboxes[store.name];
  } else {
    return new Outbox(store);
  }
}
outbox.getOutbox = getOutbox;

/**
 * Copyright 2014-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
var warning$2 = function () {};
{
  warning$2 = function (condition, format, args) {
    var len = arguments.length;
    args = new Array(len > 2 ? len - 2 : 0);
    for (var key = 2; key < len; key++) {
      args[key - 2] = arguments[key];
    }
    if (format === undefined) {
      throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
    }
    if (format.length < 10 || /^[s\W]*$/.test(format)) {
      throw new Error('The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format);
    }
    if (!condition) {
      var argIndex = 0;
      var message = 'Warning: ' + format.replace(/%s/g, function () {
        return args[argIndex++];
      });
      if (typeof console !== 'undefined') {
        console.error(message);
      }
      try {
        // This error was thrown as a convenience so that you can use this stack
        // to find the callsite that caused this warning to fire.
        throw new Error(message);
      } catch (x) {}
    }
  };
}
var warning_1 = warning$2;

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var invariant = function (condition, format, a, b, c, d, e, f) {
  {
    if (format === undefined) {
      throw new Error('invariant requires an error message argument');
    }
  }
  if (!condition) {
    var error;
    if (format === undefined) {
      error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(format.replace(/%s/g, function () {
        return args[argIndex++];
      }));
      error.name = 'Invariant Violation';
    }
    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
};
var invariant_1 = invariant;

var LocationUtils = {};

function isAbsolute(pathname) {
  return pathname.charAt(0) === '/';
}

// About 1.5x faster than the two-arg version of Array#splice()
function spliceOne(list, index) {
  for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {
    list[i] = list[k];
  }
  list.pop();
}

// This implementation is based heavily on node's url.parse
function resolvePathname(to) {
  var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var toParts = to && to.split('/') || [];
  var fromParts = from && from.split('/') || [];
  var isToAbs = to && isAbsolute(to);
  var isFromAbs = from && isAbsolute(from);
  var mustEndAbs = isToAbs || isFromAbs;
  if (to && isAbsolute(to)) {
    // to is absolute
    fromParts = toParts;
  } else if (toParts.length) {
    // to is relative, drop the filename
    fromParts.pop();
    fromParts = fromParts.concat(toParts);
  }
  if (!fromParts.length) return '/';
  var hasTrailingSlash = void 0;
  if (fromParts.length) {
    var last = fromParts[fromParts.length - 1];
    hasTrailingSlash = last === '.' || last === '..' || last === '';
  } else {
    hasTrailingSlash = false;
  }
  var up = 0;
  for (var i = fromParts.length; i >= 0; i--) {
    var part = fromParts[i];
    if (part === '.') {
      spliceOne(fromParts, i);
    } else if (part === '..') {
      spliceOne(fromParts, i);
      up++;
    } else if (up) {
      spliceOne(fromParts, i);
      up--;
    }
  }
  if (!mustEndAbs) for (; up--; up) {
    fromParts.unshift('..');
  }
  if (mustEndAbs && fromParts[0] !== '' && (!fromParts[0] || !isAbsolute(fromParts[0]))) fromParts.unshift('');
  var result = fromParts.join('/');
  if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';
  return result;
}

var resolvePathname$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  default: resolvePathname
});

var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(resolvePathname$1);

var _typeof$5 = 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 valueEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (Array.isArray(a)) {
    return Array.isArray(b) && a.length === b.length && a.every(function (item, index) {
      return valueEqual(item, b[index]);
    });
  }
  var aType = typeof a === 'undefined' ? 'undefined' : _typeof$5(a);
  var bType = typeof b === 'undefined' ? 'undefined' : _typeof$5(b);
  if (aType !== bType) return false;
  if (aType === 'object') {
    var aValue = a.valueOf();
    var bValue = b.valueOf();
    if (aValue !== a || bValue !== b) return valueEqual(aValue, bValue);
    var aKeys = Object.keys(a);
    var bKeys = Object.keys(b);
    if (aKeys.length !== bKeys.length) return false;
    return aKeys.every(function (key) {
      return valueEqual(a[key], b[key]);
    });
  }
  return false;
}

var valueEqual$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  default: valueEqual
});

var require$$1 = /*@__PURE__*/getAugmentedNamespace(valueEqual$1);

var PathUtils$1 = {};

var createPath_1;
var parsePath_1;
var stripTrailingSlash_1;
var stripBasename_1;
var hasBasename_1;
var stripLeadingSlash_1;
var addLeadingSlash_1;

PathUtils$1.__esModule = true;
addLeadingSlash_1 = PathUtils$1.addLeadingSlash = function addLeadingSlash(path) {
  return path.charAt(0) === '/' ? path : '/' + path;
};
stripLeadingSlash_1 = PathUtils$1.stripLeadingSlash = function stripLeadingSlash(path) {
  return path.charAt(0) === '/' ? path.substr(1) : path;
};
var hasBasename = hasBasename_1 = PathUtils$1.hasBasename = function hasBasename(path, prefix) {
  return new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i').test(path);
};
stripBasename_1 = PathUtils$1.stripBasename = function stripBasename(path, prefix) {
  return hasBasename(path, prefix) ? path.substr(prefix.length) : path;
};
stripTrailingSlash_1 = PathUtils$1.stripTrailingSlash = function stripTrailingSlash(path) {
  return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;
};
parsePath_1 = PathUtils$1.parsePath = function parsePath(path) {
  var pathname = path || '/';
  var search = '';
  var hash = '';
  var hashIndex = pathname.indexOf('#');
  if (hashIndex !== -1) {
    hash = pathname.substr(hashIndex);
    pathname = pathname.substr(0, hashIndex);
  }
  var searchIndex = pathname.indexOf('?');
  if (searchIndex !== -1) {
    search = pathname.substr(searchIndex);
    pathname = pathname.substr(0, searchIndex);
  }
  return {
    pathname: pathname,
    search: search === '?' ? '' : search,
    hash: hash === '#' ? '' : hash
  };
};
createPath_1 = PathUtils$1.createPath = function createPath(location) {
  var pathname = location.pathname,
    search = location.search,
    hash = location.hash;
  var path = pathname || '/';
  if (search && search !== '?') path += search.charAt(0) === '?' ? search : '?' + search;
  if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : '#' + hash;
  return path;
};

var PathUtils = /*#__PURE__*/_mergeNamespaces({
  __proto__: null,
  get addLeadingSlash () { return addLeadingSlash_1; },
  get createPath () { return createPath_1; },
  default: PathUtils$1,
  get hasBasename () { return hasBasename_1; },
  get parsePath () { return parsePath_1; },
  get stripBasename () { return stripBasename_1; },
  get stripLeadingSlash () { return stripLeadingSlash_1; },
  get stripTrailingSlash () { return stripTrailingSlash_1; }
}, [PathUtils$1]);

LocationUtils.__esModule = true;
LocationUtils.locationsAreEqual = LocationUtils.createLocation = undefined;
var _extends$9 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var _resolvePathname = require$$0$1;
var _resolvePathname2 = _interopRequireDefault$c(_resolvePathname);
var _valueEqual = require$$1;
var _valueEqual2 = _interopRequireDefault$c(_valueEqual);
var _PathUtils$2 = PathUtils$1;
function _interopRequireDefault$c(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}
LocationUtils.createLocation = function createLocation(path, state, key, currentLocation) {
  var location = void 0;
  if (typeof path === 'string') {
    // Two-arg form: push(path, state)
    location = (0, _PathUtils$2.parsePath)(path);
    location.state = state;
  } else {
    // One-arg form: push(location)
    location = _extends$9({}, path);
    if (location.pathname === undefined) location.pathname = '';
    if (location.search) {
      if (location.search.charAt(0) !== '?') location.search = '?' + location.search;
    } else {
      location.search = '';
    }
    if (location.hash) {
      if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash;
    } else {
      location.hash = '';
    }
    if (state !== undefined && location.state === undefined) location.state = state;
  }
  try {
    location.pathname = decodeURI(location.pathname);
  } catch (e) {
    if (e instanceof URIError) {
      throw new URIError('Pathname "' + location.pathname + '" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.');
    } else {
      throw e;
    }
  }
  if (key) location.key = key;
  if (currentLocation) {
    // Resolve incomplete/relative pathname relative to current location.
    if (!location.pathname) {
      location.pathname = currentLocation.pathname;
    } else if (location.pathname.charAt(0) !== '/') {
      location.pathname = (0, _resolvePathname2.default)(location.pathname, currentLocation.pathname);
    }
  } else {
    // When there is no prior location and pathname is empty, set it to /
    if (!location.pathname) {
      location.pathname = '/';
    }
  }
  return location;
};
LocationUtils.locationsAreEqual = function locationsAreEqual(a, b) {
  return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && a.key === b.key && (0, _valueEqual2.default)(a.state, b.state);
};

var createTransitionManager$1 = {};

createTransitionManager$1.__esModule = true;
var _warning$2 = warning_1;
var _warning2$2 = _interopRequireDefault$b(_warning$2);
function _interopRequireDefault$b(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}
var createTransitionManager = function createTransitionManager() {
  var prompt = null;
  var setPrompt = function setPrompt(nextPrompt) {
    (0, _warning2$2.default)(prompt == null, 'A history supports only one prompt at a time');
    prompt = nextPrompt;
    return function () {
      if (prompt === nextPrompt) prompt = null;
    };
  };
  var confirmTransitionTo = function confirmTransitionTo(location, action, getUserConfirmation, callback) {
    // TODO: If another transition starts while we're still confirming
    // the previous one, we may end up in a weird state. Figure out the
    // best way to handle this.
    if (prompt != null) {
      var result = typeof prompt === 'function' ? prompt(location, action) : prompt;
      if (typeof result === 'string') {
        if (typeof getUserConfirmation === 'function') {
          getUserConfirmation(result, callback);
        } else {
          (0, _warning2$2.default)(false, 'A history needs a getUserConfirmation function in order to use a prompt message');
          callback(true);
        }
      } else {
        // Return false from a transition hook to cancel the transition.
        callback(result !== false);
      }
    } else {
      callback(true);
    }
  };
  var listeners = [];
  var appendListener = function appendListener(fn) {
    var isActive = true;
    var listener = function listener() {
      if (isActive) fn.apply(undefined, arguments);
    };
    listeners.push(listener);
    return function () {
      isActive = false;
      listeners = listeners.filter(function (item) {
        return item !== listener;
      });
    };
  };
  var notifyListeners = function notifyListeners() {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    listeners.forEach(function (listener) {
      return listener.apply(undefined, args);
    });
  };
  return {
    setPrompt: setPrompt,
    confirmTransitionTo: confirmTransitionTo,
    appendListener: appendListener,
    notifyListeners: notifyListeners
  };
};
createTransitionManager$1.default = createTransitionManager;

var DOMUtils = {};

DOMUtils.__esModule = true;
DOMUtils.canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
DOMUtils.addEventListener = function addEventListener(node, event, listener) {
  return node.addEventListener ? node.addEventListener(event, listener, false) : node.attachEvent('on' + event, listener);
};
DOMUtils.removeEventListener = function removeEventListener(node, event, listener) {
  return node.removeEventListener ? node.removeEventListener(event, listener, false) : node.detachEvent('on' + event, listener);
};
DOMUtils.getConfirmation = function getConfirmation(message, callback) {
  return callback(window.confirm(message));
}; // eslint-disable-line no-alert

/**
 * Returns true if the HTML5 history API is supported. Taken from Modernizr.
 *
 * https://github.com/Modernizr/Modernizr/blob/master/LICENSE
 * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
 * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586
 */
DOMUtils.supportsHistory = function supportsHistory() {
  var ua = window.navigator.userAgent;
  if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false;
  return window.history && 'pushState' in window.history;
};

/**
 * Returns true if browser fires popstate on hash change.
 * IE10 and IE11 do not.
 */
DOMUtils.supportsPopStateOnHashChange = function supportsPopStateOnHashChange() {
  return window.navigator.userAgent.indexOf('Trident') === -1;
};

/**
 * Returns false if using go(n) with hash history causes a full page reload.
 */
DOMUtils.supportsGoWithoutReloadUsingHash = function supportsGoWithoutReloadUsingHash() {
  return window.navigator.userAgent.indexOf('Firefox') === -1;
};

/**
 * Returns true if a given popstate event is an extraneous WebKit event.
 * Accounts for the fact that Chrome on iOS fires real popstate events
 * containing undefined state when pressing the back button.
 */
DOMUtils.isExtraneousPopstateEvent = function isExtraneousPopstateEvent(event) {
  return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1;
};

var _typeof$4 = 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;
};
var _extends$8 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var _warning$1 = warning_1;
var _warning2$1 = _interopRequireDefault$a(_warning$1);
var _invariant$1 = invariant_1;
var _invariant2$1 = _interopRequireDefault$a(_invariant$1);
var _LocationUtils$1 = LocationUtils;
var _PathUtils$1 = PathUtils$1;
var _createTransitionManager$1 = createTransitionManager$1;
var _createTransitionManager2$1 = _interopRequireDefault$a(_createTransitionManager$1);
var _DOMUtils = DOMUtils;
function _interopRequireDefault$a(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}
var PopStateEvent = 'popstate';
var HashChangeEvent = 'hashchange';
var getHistoryState = function getHistoryState() {
  try {
    return window.history.state || {};
  } catch (e) {
    // IE 11 sometimes throws when accessing window.history.state
    // See https://github.com/ReactTraining/history/pull/289
    return {};
  }
};

/**
 * Creates a history object that uses the HTML5 history API including
 * pushState, replaceState, and the popstate event.
 */
var createBrowserHistory = function createBrowserHistory() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  (0, _invariant2$1.default)(_DOMUtils.canUseDOM, 'Browser history needs a DOM');
  var globalHistory = window.history;
  var canUseHistory = (0, _DOMUtils.supportsHistory)();
  var needsHashChangeListener = !(0, _DOMUtils.supportsPopStateOnHashChange)();
  var _props$forceRefresh = props.forceRefresh,
    forceRefresh = _props$forceRefresh === undefined ? false : _props$forceRefresh,
    _props$getUserConfirm = props.getUserConfirmation,
    getUserConfirmation = _props$getUserConfirm === undefined ? _DOMUtils.getConfirmation : _props$getUserConfirm,
    _props$keyLength = props.keyLength,
    keyLength = _props$keyLength === undefined ? 6 : _props$keyLength;
  var basename = props.basename ? (0, _PathUtils$1.stripTrailingSlash)((0, _PathUtils$1.addLeadingSlash)(props.basename)) : '';
  var getDOMLocation = function getDOMLocation(historyState) {
    var _ref = historyState || {},
      key = _ref.key,
      state = _ref.state;
    var _window$location = window.location,
      pathname = _window$location.pathname,
      search = _window$location.search,
      hash = _window$location.hash;
    var path = pathname + search + hash;
    (0, _warning2$1.default)(!basename || (0, _PathUtils$1.hasBasename)(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path "' + path + '" to begin with "' + basename + '".');
    if (basename) path = (0, _PathUtils$1.stripBasename)(path, basename);
    return (0, _LocationUtils$1.createLocation)(path, state, key);
  };
  var createKey = function createKey() {
    return Math.random().toString(36).substr(2, keyLength);
  };
  var transitionManager = (0, _createTransitionManager2$1.default)();
  var setState = function setState(nextState) {
    _extends$8(history, nextState);
    history.length = globalHistory.length;
    transitionManager.notifyListeners(history.location, history.action);
  };
  var handlePopState = function handlePopState(event) {
    // Ignore extraneous popstate events in WebKit.
    if ((0, _DOMUtils.isExtraneousPopstateEvent)(event)) return;
    handlePop(getDOMLocation(event.state));
  };
  var handleHashChange = function handleHashChange() {
    handlePop(getDOMLocation(getHistoryState()));
  };
  var forceNextPop = false;
  var handlePop = function handlePop(location) {
    if (forceNextPop) {
      forceNextPop = false;
      setState();
    } else {
      var action = 'POP';
      transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
        if (ok) {
          setState({
            action: action,
            location: location
          });
        } else {
          revertPop(location);
        }
      });
    }
  };
  var revertPop = function revertPop(fromLocation) {
    var toLocation = history.location;

    // TODO: We could probably make this more reliable by
    // keeping a list of keys we've seen in sessionStorage.
    // Instead, we just default to 0 for keys we don't know.

    var toIndex = allKeys.indexOf(toLocation.key);
    if (toIndex === -1) toIndex = 0;
    var fromIndex = allKeys.indexOf(fromLocation.key);
    if (fromIndex === -1) fromIndex = 0;
    var delta = toIndex - fromIndex;
    if (delta) {
      forceNextPop = true;
      go(delta);
    }
  };
  var initialLocation = getDOMLocation(getHistoryState());
  var allKeys = [initialLocation.key];

  // Public interface

  var createHref = function createHref(location) {
    return basename + (0, _PathUtils$1.createPath)(location);
  };
  var push = function push(path, state) {
    (0, _warning2$1.default)(!((typeof path === 'undefined' ? 'undefined' : _typeof$4(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored');
    var action = 'PUSH';
    var location = (0, _LocationUtils$1.createLocation)(path, state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
      if (!ok) return;
      var href = createHref(location);
      var key = location.key,
        state = location.state;
      if (canUseHistory) {
        globalHistory.pushState({
          key: key,
          state: state
        }, null, href);
        if (forceRefresh) {
          window.location.href = href;
        } else {
          var prevIndex = allKeys.indexOf(history.location.key);
          var nextKeys = allKeys.slice(0, prevIndex === -1 ? 0 : prevIndex + 1);
          nextKeys.push(location.key);
          allKeys = nextKeys;
          setState({
            action: action,
            location: location
          });
        }
      } else {
        (0, _warning2$1.default)(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history');
        window.location.href = href;
      }
    });
  };
  var replace = function replace(path, state) {
    (0, _warning2$1.default)(!((typeof path === 'undefined' ? 'undefined' : _typeof$4(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored');
    var action = 'REPLACE';
    var location = (0, _LocationUtils$1.createLocation)(path, state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
      if (!ok) return;
      var href = createHref(location);
      var key = location.key,
        state = location.state;
      if (canUseHistory) {
        globalHistory.replaceState({
          key: key,
          state: state
        }, null, href);
        if (forceRefresh) {
          window.location.replace(href);
        } else {
          var prevIndex = allKeys.indexOf(history.location.key);
          if (prevIndex !== -1) allKeys[prevIndex] = location.key;
          setState({
            action: action,
            location: location
          });
        }
      } else {
        (0, _warning2$1.default)(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history');
        window.location.replace(href);
      }
    });
  };
  var go = function go(n) {
    globalHistory.go(n);
  };
  var goBack = function goBack() {
    return go(-1);
  };
  var goForward = function goForward() {
    return go(1);
  };
  var listenerCount = 0;
  var checkDOMListeners = function checkDOMListeners(delta) {
    listenerCount += delta;
    if (listenerCount === 1) {
      (0, _DOMUtils.addEventListener)(window, PopStateEvent, handlePopState);
      if (needsHashChangeListener) (0, _DOMUtils.addEventListener)(window, HashChangeEvent, handleHashChange);
    } else if (listenerCount === 0) {
      (0, _DOMUtils.removeEventListener)(window, PopStateEvent, handlePopState);
      if (needsHashChangeListener) (0, _DOMUtils.removeEventListener)(window, HashChangeEvent, handleHashChange);
    }
  };
  var isBlocked = false;
  var block = function block() {
    var prompt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var unblock = transitionManager.setPrompt(prompt);
    if (!isBlocked) {
      checkDOMListeners(1);
      isBlocked = true;
    }
    return function () {
      if (isBlocked) {
        isBlocked = false;
        checkDOMListeners(-1);
      }
      return unblock();
    };
  };
  var listen = function listen(listener) {
    var unlisten = transitionManager.appendListener(listener);
    checkDOMListeners(1);
    return function () {
      checkDOMListeners(-1);
      unlisten();
    };
  };
  var history = {
    length: globalHistory.length,
    action: 'POP',
    location: initialLocation,
    createHref: createHref,
    push: push,
    replace: replace,
    go: go,
    goBack: goBack,
    goForward: goForward,
    block: block,
    listen: listen
  };
  return history;
};
var _default$b = createBrowserHistory;

var _typeof$3 = 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;
};
var _extends$7 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var _warning = warning_1;
var _warning2 = _interopRequireDefault$9(_warning);
var _invariant = invariant_1;
var _invariant2 = _interopRequireDefault$9(_invariant);
var _PathUtils = PathUtils$1;
var _LocationUtils = LocationUtils;
var _createTransitionManager = createTransitionManager$1;
var _createTransitionManager2 = _interopRequireDefault$9(_createTransitionManager);
function _interopRequireDefault$9(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}
var clamp$1 = function clamp(n, lowerBound, upperBound) {
  return Math.min(Math.max(n, lowerBound), upperBound);
};
var hasConfirm = !!(typeof window !== 'undefined' && typeof window.confirm !== 'undefined');
var getConfirmation = function getConfirmation(message, callback) {
  (0, _invariant2.default)(hasConfirm, 'Environment needs a window + window.confirm function. You can provide' + 'your own confirmation UI via the getUserConfirmation option.');
  return callback(window.confirm(message)); // eslint-disable-line no-alert
};

/**
 * Creates a history object that stores locations in memory.
 */
var createMemoryHistory = function createMemoryHistory() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _props$getUserConfirm = props.getUserConfirmation,
    getUserConfirmation = _props$getUserConfirm === undefined ? getConfirmation : _props$getUserConfirm,
    _props$initialEntries = props.initialEntries,
    initialEntries = _props$initialEntries === undefined ? ['/'] : _props$initialEntries,
    _props$initialIndex = props.initialIndex,
    initialIndex = _props$initialIndex === undefined ? 0 : _props$initialIndex,
    _props$keyLength = props.keyLength,
    keyLength = _props$keyLength === undefined ? 6 : _props$keyLength;
  var basename = props.basename ? (0, _PathUtils.stripTrailingSlash)((0, _PathUtils.addLeadingSlash)(props.basename)) : '';
  var transitionManager = (0, _createTransitionManager2.default)();
  var setState = function setState(nextState) {
    _extends$7(history, nextState);
    history.length = history.entries.length;
    transitionManager.notifyListeners(history.location, history.action);
  };
  var createKey = function createKey() {
    return Math.random().toString(36).substr(2, keyLength);
  };
  var index = clamp$1(initialIndex, 0, initialEntries.length - 1);
  var getStrippedPath = function getStrippedPath(path) {
    return basename ? (0, _PathUtils.stripBasename)(path, basename) : path;
  };
  var entries = initialEntries.map(function (entry) {
    return typeof entry === 'string' ? (0, _LocationUtils.createLocation)(getStrippedPath(entry), undefined, createKey()) : (0, _LocationUtils.createLocation)(getStrippedPath(entry), undefined, entry.key || createKey());
  });

  // Public interface

  var createHref = function createHref(location) {
    return basename + (0, _PathUtils.createPath)(location);
  };
  var push = function push(path, state) {
    (0, _warning2.default)(!((typeof path === 'undefined' ? 'undefined' : _typeof$3(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored');
    var action = 'PUSH';
    var location = (0, _LocationUtils.createLocation)(getStrippedPath(path), state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
      if (!ok) return;
      var prevIndex = history.index;
      var nextIndex = prevIndex + 1;
      var nextEntries = history.entries.slice(0);
      if (nextEntries.length > nextIndex) {
        nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location);
      } else {
        nextEntries.push(location);
      }
      setState({
        action: action,
        location: location,
        index: nextIndex,
        entries: nextEntries
      });
    });
  };
  var replace = function replace(path, state) {
    (0, _warning2.default)(!((typeof path === 'undefined' ? 'undefined' : _typeof$3(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored');
    var action = 'REPLACE';
    var location = (0, _LocationUtils.createLocation)(getStrippedPath(path), state, createKey(), history.location);
    transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
      if (!ok) return;
      history.entries[history.index] = location;
      setState({
        action: action,
        location: location
      });
    });
  };
  var go = function go(n) {
    var nextIndex = clamp$1(history.index + n, 0, history.entries.length - 1);
    var action = 'POP';
    var location = history.entries[nextIndex];
    transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
      if (ok) {
        setState({
          action: action,
          location: location,
          index: nextIndex
        });
      } else {
        // Mimic the behavior of DOM histories by
        // causing a render after a cancelled POP.
        setState();
      }
    });
  };
  var goBack = function goBack() {
    return go(-1);
  };
  var goForward = function goForward() {
    return go(1);
  };
  var canGo = function canGo(n) {
    var nextIndex = history.index + n;
    return nextIndex >= 0 && nextIndex < history.entries.length;
  };
  var block = function block() {
    var prompt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    return transitionManager.setPrompt(prompt);
  };
  var listen = function listen(listener) {
    return transitionManager.appendListener(listener);
  };
  var history = {
    length: entries.length,
    action: 'POP',
    location: entries[index],
    index: index,
    entries: entries,
    createHref: createHref,
    push: push,
    replace: replace,
    go: go,
    goBack: goBack,
    goForward: goForward,
    canGo: canGo,
    block: block,
    listen: listen
  };
  return history;
};
var _default$a = createMemoryHistory;

var dist = {};

var pathToRegexp$1 = {exports: {}};

var isarray$1 = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};

var isarray = isarray$1;

/**
 * Expose `pathToRegexp`.
 */
pathToRegexp$1.exports = pathToRegexp;
pathToRegexp$1.exports.parse = parse$3;
pathToRegexp$1.exports.compile = compile$1;
pathToRegexp$1.exports.tokensToFunction = tokensToFunction;
pathToRegexp$1.exports.tokensToRegExp = tokensToRegExp;

/**
 * The main path matching regexp utility.
 *
 * @type {RegExp}
 */
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)"  => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*"            => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'].join('|'), 'g');

/**
 * Parse a string for the raw tokens.
 *
 * @param  {string}  str
 * @param  {Object=} options
 * @return {!Array}
 */
function parse$3(str, options) {
  var tokens = [];
  var key = 0;
  var index = 0;
  var path = '';
  var defaultDelimiter = options && options.delimiter || '/';
  var res;
  while ((res = PATH_REGEXP.exec(str)) != null) {
    var m = res[0];
    var escaped = res[1];
    var offset = res.index;
    path += str.slice(index, offset);
    index = offset + m.length;

    // Ignore already escaped sequences.
    if (escaped) {
      path += escaped[1];
      continue;
    }
    var next = str[index];
    var prefix = res[2];
    var name = res[3];
    var capture = res[4];
    var group = res[5];
    var modifier = res[6];
    var asterisk = res[7];

    // Push the current path onto the tokens.
    if (path) {
      tokens.push(path);
      path = '';
    }
    var partial = prefix != null && next != null && next !== prefix;
    var repeat = modifier === '+' || modifier === '*';
    var optional = modifier === '?' || modifier === '*';
    var delimiter = res[2] || defaultDelimiter;
    var pattern = capture || group;
    tokens.push({
      name: name || key++,
      prefix: prefix || '',
      delimiter: delimiter,
      optional: optional,
      repeat: repeat,
      partial: partial,
      asterisk: !!asterisk,
      pattern: pattern ? escapeGroup(pattern) : asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?'
    });
  }

  // Match any characters still remaining.
  if (index < str.length) {
    path += str.substr(index);
  }

  // If the path exists, push it onto the end.
  if (path) {
    tokens.push(path);
  }
  return tokens;
}

/**
 * Compile a string to a template function for the path.
 *
 * @param  {string}             str
 * @param  {Object=}            options
 * @return {!function(Object=, Object=)}
 */
function compile$1(str, options) {
  return tokensToFunction(parse$3(str, options), options);
}

/**
 * Prettier encoding of URI path segments.
 *
 * @param  {string}
 * @return {string}
 */
function encodeURIComponentPretty(str) {
  return encodeURI(str).replace(/[\/?#]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase();
  });
}

/**
 * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
 *
 * @param  {string}
 * @return {string}
 */
function encodeAsterisk(str) {
  return encodeURI(str).replace(/[?#]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase();
  });
}

/**
 * Expose a method for transforming tokens into the path function.
 */
function tokensToFunction(tokens, options) {
  // Compile all the tokens into regexps.
  var matches = new Array(tokens.length);

  // Compile all the patterns before compilation.
  for (var i = 0; i < tokens.length; i++) {
    if (typeof tokens[i] === 'object') {
      matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
    }
  }
  return function (obj, opts) {
    var path = '';
    var data = obj || {};
    var options = opts || {};
    var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
    for (var i = 0; i < tokens.length; i++) {
      var token = tokens[i];
      if (typeof token === 'string') {
        path += token;
        continue;
      }
      var value = data[token.name];
      var segment;
      if (value == null) {
        if (token.optional) {
          // Prepend partial segment prefixes.
          if (token.partial) {
            path += token.prefix;
          }
          continue;
        } else {
          throw new TypeError('Expected "' + token.name + '" to be defined');
        }
      }
      if (isarray(value)) {
        if (!token.repeat) {
          throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`');
        }
        if (value.length === 0) {
          if (token.optional) {
            continue;
          } else {
            throw new TypeError('Expected "' + token.name + '" to not be empty');
          }
        }
        for (var j = 0; j < value.length; j++) {
          segment = encode(value[j]);
          if (!matches[i].test(segment)) {
            throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`');
          }
          path += (j === 0 ? token.prefix : token.delimiter) + segment;
        }
        continue;
      }
      segment = token.asterisk ? encodeAsterisk(value) : encode(value);
      if (!matches[i].test(segment)) {
        throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"');
      }
      path += token.prefix + segment;
    }
    return path;
  };
}

/**
 * Escape a regular expression string.
 *
 * @param  {string} str
 * @return {string}
 */
function escapeString(str) {
  return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1');
}

/**
 * Escape the capturing group by escaping special characters and meaning.
 *
 * @param  {string} group
 * @return {string}
 */
function escapeGroup(group) {
  return group.replace(/([=!:$\/()])/g, '\\$1');
}

/**
 * Attach the keys as a property of the regexp.
 *
 * @param  {!RegExp} re
 * @param  {Array}   keys
 * @return {!RegExp}
 */
function attachKeys(re, keys) {
  re.keys = keys;
  return re;
}

/**
 * Get the flags for a regexp from the options.
 *
 * @param  {Object} options
 * @return {string}
 */
function flags(options) {
  return options && options.sensitive ? '' : 'i';
}

/**
 * Pull out keys from a regexp.
 *
 * @param  {!RegExp} path
 * @param  {!Array}  keys
 * @return {!RegExp}
 */
function regexpToRegexp(path, keys) {
  // Use a negative lookahead to match only capturing groups.
  var groups = path.source.match(/\((?!\?)/g);
  if (groups) {
    for (var i = 0; i < groups.length; i++) {
      keys.push({
        name: i,
        prefix: null,
        delimiter: null,
        optional: false,
        repeat: false,
        partial: false,
        asterisk: false,
        pattern: null
      });
    }
  }
  return attachKeys(path, keys);
}

/**
 * Transform an array into a regexp.
 *
 * @param  {!Array}  path
 * @param  {Array}   keys
 * @param  {!Object} options
 * @return {!RegExp}
 */
function arrayToRegexp(path, keys, options) {
  var parts = [];
  for (var i = 0; i < path.length; i++) {
    parts.push(pathToRegexp(path[i], keys, options).source);
  }
  var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
  return attachKeys(regexp, keys);
}

/**
 * Create a path regexp from string input.
 *
 * @param  {string}  path
 * @param  {!Array}  keys
 * @param  {!Object} options
 * @return {!RegExp}
 */
function stringToRegexp(path, keys, options) {
  return tokensToRegExp(parse$3(path, options), keys, options);
}

/**
 * Expose a function for taking tokens and returning a RegExp.
 *
 * @param  {!Array}          tokens
 * @param  {(Array|Object)=} keys
 * @param  {Object=}         options
 * @return {!RegExp}
 */
function tokensToRegExp(tokens, keys, options) {
  if (!isarray(keys)) {
    options = /** @type {!Object} */keys || options;
    keys = [];
  }
  options = options || {};
  var strict = options.strict;
  var end = options.end !== false;
  var route = '';

  // Iterate over the tokens and create our regexp string.
  for (var i = 0; i < tokens.length; i++) {
    var token = tokens[i];
    if (typeof token === 'string') {
      route += escapeString(token);
    } else {
      var prefix = escapeString(token.prefix);
      var capture = '(?:' + token.pattern + ')';
      keys.push(token);
      if (token.repeat) {
        capture += '(?:' + prefix + capture + ')*';
      }
      if (token.optional) {
        if (!token.partial) {
          capture = '(?:' + prefix + '(' + capture + '))?';
        } else {
          capture = prefix + '(' + capture + ')?';
        }
      } else {
        capture = prefix + '(' + capture + ')';
      }
      route += capture;
    }
  }
  var delimiter = escapeString(options.delimiter || '/');
  var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;

  // In non-strict mode we allow a slash at the end of match. If the path to
  // match already ends with a slash, we remove it for consistency. The slash
  // is valid at the end of a path match, not in the middle. This is important
  // in non-ending mode, where "/test/" shouldn't match "/test//route".
  if (!strict) {
    route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
  }
  if (end) {
    route += '$';
  } else {
    // In non-ending mode, we need the capturing groups to match as much as
    // possible by using a positive lookahead to the end or next path segment.
    route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
  }
  return attachKeys(new RegExp('^' + route, flags(options)), keys);
}

/**
 * Normalize the given path string, returning a regular expression.
 *
 * An empty array can be passed in for the keys, which will hold the
 * placeholder key descriptions. For example, using `/user/:id`, `keys` will
 * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
 *
 * @param  {(string|RegExp|Array)} path
 * @param  {(Array|Object)=}       keys
 * @param  {Object=}               options
 * @return {!RegExp}
 */
function pathToRegexp(path, keys, options) {
  if (!isarray(keys)) {
    options = /** @type {!Object} */keys || options;
    keys = [];
  }
  options = options || {};
  if (path instanceof RegExp) {
    return regexpToRegexp(path, /** @type {!Array} */keys);
  }
  if (isarray(path)) {
    return arrayToRegexp( /** @type {!Array} */path, /** @type {!Array} */keys, options);
  }
  return stringToRegexp( /** @type {string} */path, /** @type {!Array} */keys, options);
}

var pathToRegexpExports = pathToRegexp$1.exports;

var compilePath_1;

Object.defineProperty(dist, "__esModule", {
  value: true
});
var compileParamsToPath_1 = dist.compileParamsToPath = compilePath_1 = dist.compilePath = undefined;
var _pathToRegexp = pathToRegexpExports;
var _pathToRegexp2 = _interopRequireDefault$8(_pathToRegexp);
function _interopRequireDefault$8(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}
function _toArray(arr) {
  return Array.isArray(arr) ? arr : Array.from(arr);
}
var patternCache = {};
var cacheLimit = 10000;
var cacheCount = 0;
var compilePath = compilePath_1 = dist.compilePath = function compilePath(pattern) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$end = options.end,
    end = _options$end === undefined ? true : _options$end,
    _options$strict = options.strict,
    strict = _options$strict === undefined ? false : _options$strict;
  var cacheKey = '' + (end ? 't' : 'f') + (strict ? 't' : 'f');
  var cache = patternCache[cacheKey] || (patternCache[cacheKey] = {});
  if (cache[pattern]) return cache[pattern];
  var keys = [];
  var re = (0, _pathToRegexp2.default)(pattern, keys, options);
  var compiledPattern = {
    re: re,
    keys: keys
  };
  if (cacheCount < cacheLimit) {
    cache[pattern] = compiledPattern;
    cacheCount++;
  }
  return compiledPattern;
};
var toPathCache = {};
compileParamsToPath_1 = dist.compileParamsToPath = function compileParamsToPath(path) {
  var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var toPath = toPathCache[path] || _pathToRegexp2.default.compile(path);
  toPathCache[path] = toPath;
  return toPath(params);
};
var matchPath$1 = function matchPath(pathname) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (typeof options === 'string') {
    options = {
      path: options,
      exact: false,
      strict: false
    };
  }
  var _options = options,
    _options$path = _options.path,
    path = _options$path === undefined ? '/' : _options$path,
    _options$exact = _options.exact,
    exact = _options$exact === undefined ? false : _options$exact,
    _options$strict2 = _options.strict,
    strict = _options$strict2 === undefined ? false : _options$strict2;
  var _compilePath = compilePath(path, {
      end: exact,
      strict: strict
    }),
    re = _compilePath.re,
    keys = _compilePath.keys;
  var match = re.exec(pathname);
  if (!match) return null;
  var _match = _toArray(match),
    url = _match[0],
    values = _match.slice(1);
  var isExact = pathname === url;
  if (exact && !isExact) return null;
  return {
    path: path,
    // the path pattern used to match
    url: path === '/' && url === '' ? '/' : url,
    // the matched portion of the URL
    isExact: isExact,
    // whether or not we matched exactly
    params: keys.reduce(function (memo, key, index) {
      memo[key.name] = values[index];
      return memo;
    }, {})
  };
};
var _default$9 = dist.default = matchPath$1;

var objectValues = (function (routes) {
  return Object.keys(routes).map(function (key) {
    return routes[key];
  });
});

var _extends$6 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var _typeof$2 = 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;
};
var pathToAction$2 = (function (pathname, routesMap, serializer) {
  var basename = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : getOptions$2().basename;
  var strict = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : getOptions$2().strict;
  var parts = pathname.split('?');
  var search = parts[1];
  var query = search && serializer && serializer.parse(search);
  var routes = objectValues(routesMap);
  var routeTypes = Object.keys(routesMap);
  pathname = basename ? stripBasename_1(parts[0], basename) : parts[0];
  var i = 0;
  var match = void 0;
  var keys = void 0;
  while (!match && i < routes.length) {
    var regPath = typeof routes[i] === 'string' ? routes[i] : routes[i].path; // route may be an object containing a route or a route string itself

    if (!regPath) {
      i++;
      continue;
    }
    var _compilePath = compilePath_1(regPath, {
        strict: strict
      }),
      re = _compilePath.re,
      k = _compilePath.keys;
    match = re.exec(pathname);
    keys = k;
    i++;
  }
  if (match) {
    i--;
    var capitalizedWords = _typeof$2(routes[i]) === 'object' && routes[i].capitalizedWords;
    var coerceNumbers = _typeof$2(routes[i]) === 'object' && routes[i].coerceNumbers;
    var fromPath = routes[i] && typeof routes[i].fromPath === 'function' && routes[i].fromPath;
    var userMeta = _typeof$2(routes[i]) === 'object' && routes[i].meta;
    var type = routeTypes[i];
    var payload = (keys || []).reduce(function (payload, key, index) {
      var val = match && match[index + 1]; // item at index 0 is the overall match, whereas those after correspond to the key's index

      if (typeof val === 'string') {
        if (fromPath) {
          val = fromPath && fromPath(val, key.name);
        } else if (coerceNumbers && isNumber$1(val)) {
          val = parseFloat(val);
        } else if (capitalizedWords) {
          val = val.replace(/-/g, ' ').replace(/\b\w/g, function (l) {
            return l.toUpperCase();
          }); // 'my-category' -> 'My Category'
        }
      }

      payload[key.name] = val;
      return payload;
    }, {});
    var _meta = _extends$6({}, userMeta ? {
      meta: userMeta
    } : {}, query ? {
      query: query
    } : {});
    return {
      type: type,
      payload: payload,
      meta: _meta
    };
  }

  // This will basically will only end up being called if the developer is manually calling history.push().
  // Or, if visitors visit an invalid URL, the developer can use the NOT_FOUND type to show a not-found page to
  var meta = _extends$6({
    notFoundPath: pathname
  }, query ? {
    query: query
  } : {});
  return {
    type: NOT_FOUND$1,
    payload: {},
    meta: meta
  };
});
var isNumber$1 = function isNumber(val) {
  return /^\d+$/.test(val);
};

var _extends$5 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var nestAction = (function (pathname, action, prev, history, kind) {
  var type = action.type,
    _action$payload = action.payload,
    payload = _action$payload === undefined ? {} : _action$payload,
    _action$meta = action.meta,
    meta = _action$meta === undefined ? {} : _action$meta;
  var query = action.query || meta.query || payload.query;
  var parts = pathname.split('?');
  var search = parts[1];
  return _extends$5({}, action, action.query && {
    query: query
  }, {
    type: type,
    payload: payload,
    meta: _extends$5({}, meta, meta.query && {
      query: query
    }, {
      location: {
        current: _extends$5({
          pathname: parts[0],
          type: type,
          payload: payload
        }, query && {
          query: query,
          search: search
        }),
        prev: prev,
        kind: kind,
        history: undefined
      }
    })
  });
});
var nestHistory = function nestHistory(history) {
  return history.entries ? {
    index: history.index,
    length: history.entries.length,
    entries: history.entries.slice(0) // history.entries.map(entry => entry.pathname)
  } : undefined;
};

var isLocationAction = (function (action) {
  return !!(action.meta && action.meta.location && action.meta.location.current);
});

var isRedirectAction = (function (action) {
  return !!(action && action.meta && action.meta.location && action.meta.location.kind === 'redirect');
});

var isServer = (function () {
  return typeof window === 'undefined' || !!window.SSRtest;
});

var isReactNative = (function () {
  return typeof window !== 'undefined' && typeof window.navigator !== 'undefined' && window.navigator.product === 'ReactNative';
});

var changePageTitle = (function (doc, title) {
  if (typeof title === 'string' && doc.title !== title) {
    return doc.title = title;
  }
  return null;
});
var getDocument = function getDocument() {
  var isSSRTest = "development" === 'test'  ;
  return typeof document !== 'undefined' && !isSSRTest ? document : {};
};

var attemptCallRouteThunk = (function (dispatch, getState, route, selectLocationState, bag) {
  if (typeof window !== 'undefined') {
    var thunk = route.thunk;
    if (typeof thunk === 'function') {
      var _selectLocationState = selectLocationState(getState()),
        kind = _selectLocationState.kind,
        hasSSR = _selectLocationState.hasSSR;

      // call thunks always if it's not initial load of the app or only if it's load
      // without SSR setup yet, so app state is setup on client when prototyping,
      // such as with with webpack-dev-server before server infrastructure is built.
      // NEW: if there is no path, it's assumed to be a pathless route, which is always called.

      if (kind !== 'load' || kind === 'load' && !hasSSR || !route.path) {
        var prom = thunk(dispatch, getState, bag);
        if (prom && typeof prom.next === 'function') {
          prom.next(updateScroll);
        }
      }
    }
  }
});

var createThunk = (function (routesMap, selectLocationState, bag) {
  return function (_ref) {
    var dispatch = _ref.dispatch,
      getState = _ref.getState;
    var _selectLocationState = selectLocationState(getState()),
      type = _selectLocationState.type;
    var route = routesMap[type];
    if (route && typeof route.thunk === 'function') {
      return Promise.resolve(route.thunk(dispatch, getState, bag));
    }
    return Promise.resolve();
  };
});

var pathnamePlusSearch = (function (_ref) {
  var pathname = _ref.pathname,
    search = _ref.search;
  if (search) {
    if (search.indexOf('?') !== 0) {
      search = '?' + search;
    }
    return '' + pathname + search;
  }
  return pathname;
});

var canUseDom = typeof window !== 'undefined' && window.document && window.document.createElement;

var _unblock = void 0;
var _removeConfirmBlocking = void 0;
var _displayConfirmLeave = void 0;
var clearBlocking = function clearBlocking() {
  _unblock && _unblock();
  _removeConfirmBlocking && _removeConfirmBlocking();
};

// This is the default `displayConfirmLeave` handler.
// It receives the message to display and a callback to call when complete.
// Pass `true` to the callback to proceed with leaving the current route.

var defaultDisplayConfirmLeave = function defaultDisplayConfirmLeave(message, callback) {
  var hasConfirm = typeof window !== 'undefined' && window.confirm;
  if (!hasConfirm) {
    throw new Error('[rudy] environment requires `displayConfirmLeave` option');
  }
  var canLeave = window.confirm(message);
  callback(canLeave);
};

// createConfirm is called whenever you enter a route that has a `confirmLeave`
// option. It tells the history package to block via `history.block`, but
// to determine to do so based on our redux state-centric `confirm` handler.
// This handler is also returned for use in the middleware to block when
// leaving the current route via actions (i.e. as opposed to browser buttons)

var createConfirm = function createConfirm(confirmLeave, store, selectLocationState, history, querySerializer, removeConfirmBlocking) {
  var confirm = function confirm(location) {
    var state = store.getState();
    var routesMap = selectLocationState(state).routesMap;
    var pathname = location.pathname;
    var action = pathToAction$2(pathname, routesMap, querySerializer);
    var response = confirmLeave(state, action);

    // we use the confirmLeave function manually in onBeforeChange, so we must
    // manually clear blocking that history.block would otherwise handle, plus
    // we remove additional onBeforeChange blocking via _removeConfirmBlocking
    if (!response) clearBlocking();
    return response;
  };
  _unblock = history.block(confirm);
  _removeConfirmBlocking = removeConfirmBlocking;
  return confirm;
};

// confirmUI here is triggered only by onBeforeChange:

var confirmUI = function confirmUI(message, store, action) {
  var cb = function cb(canLeave) {
    if (canLeave) {
      clearBlocking();
      store.dispatch(action);
    }
  };
  _displayConfirmLeave(message, cb);
};
var getUserConfirmation = function getUserConfirmation(message, cb) {
  _displayConfirmLeave(message, function (canLeave) {
    if (canLeave) clearBlocking();
    cb(canLeave);
  });
};
var setDisplayConfirmLeave = function setDisplayConfirmLeave(displayConfirmLeave) {
  _displayConfirmLeave = displayConfirmLeave || defaultDisplayConfirmLeave;
};

var historyCreateAction = (function (pathname, routesMap, prevLocation, history, kind, serializer, prevPath, prevLength) {
  var action = pathToAction$2(pathname, routesMap, serializer);
  kind = getKind$1(!!history.entries, history, kind, prevPath, prevLength);
  return nestAction(pathname, action, prevLocation, history, kind);
});
var getKind$1 = function getKind(isMemoryHistory, history, kind, prevPath, prevLength) {
  if (!isMemoryHistory || !prevPath || kind !== 'pop') {
    return kind;
  }
  if (isBack(history, prevPath)) {
    return 'back';
  } else if (isNext(history, prevPath, prevLength)) {
    return 'next';
  }
  return kind;
};
var isBack = function isBack(hist, path) {
  var next = hist.entries[hist.index + 1];
  return next && next.pathname === path;
};
var isNext = function isNext(hist, path, length) {
  var prev = hist.entries[hist.index - 1];
  var notPushed = length === hist.length;
  return prev && prev.pathname === path && notPushed;
};

var _typeof$1 = 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;
};
var actionToPath$1 = (function (action, routesMap, serializer) {
  var route = routesMap[action.type];
  var routePath = (typeof route === 'undefined' ? 'undefined' : _typeof$1(route)) === 'object' ? route.path : route;
  var params = _payloadToParams(route, action.payload);
  var path = compileParamsToPath_1(routePath, params) || '/';
  var query = action.query || action.meta && action.meta.query || action.payload && action.payload.query;
  var search = query && serializer && serializer.stringify(query);
  return search ? path + '?' + search : path;
});
var _payloadToParams = function _payloadToParams(route) {
  var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return Object.keys(params).reduce(function (sluggifedParams, key) {
    var segment = params[key];
    // $FlowFixMe
    sluggifedParams[key] = transformSegment(segment, route, key);
    return sluggifedParams;
  }, {});
};
var transformSegment = function transformSegment(segment, route, key) {
  if (typeof route.toPath === 'function') {
    return route.toPath(segment, key);
  } else if (typeof segment === 'string') {
    // Ask James "should it return arrays?"
    if (segment.includes('/')) {
      return segment.split('/');
    }
    if (route.capitalizedWords === true) {
      return segment.replace(/ /g, '-').toLowerCase();
    }
    return segment;
  } else if (typeof segment === 'number') {
    return segment;
  }
};

var _extends$4 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var middlewareCreateAction = (function (action, routesMap, prevLocation, history, notFoundPath, serializer) {
  try {
    var pathname = actionToPath$1(action, routesMap, serializer);
    var kind = getKind(!!history.entries, pathname, history, action);
    return nestAction(pathname, action, prevLocation, history, kind);
  } catch (e) {
    {
      console.error('[redux-first-router] Internal exception when parsing action, fallback to NOT_FOUND. Original exception: ', e);
    }
    var payload = _extends$4({}, action.payload);
    return nestAction(notFoundPath || prevLocation.pathname || '/', _extends$4({}, action, {
      type: NOT_FOUND$1,
      payload: payload
    }), prevLocation);
  }
});

// REACT NATIVE FEATURE:
// emulate npm `history` package and `historyCreateAction`  so that actions
// and state indicate the user went back or forward. The idea is if you are
// going back or forward to a route you were just at, apps can determine
// from `state.location.kind === 'back|next'` and `action.kind` that things like
// scroll position should be restored.
// NOTE: for testability, history is also returned to make this a pure function
var getKind = function getKind(isMemoryHistory, pathname, history, action) {
  var kind = action.meta && action.meta.location && action.meta.location.kind;
  if (kind) {
    return kind;
  } else if (!isMemoryHistory) {
    return 'push';
  }
  if (goingBack(history, pathname)) {
    history.index--;
    return 'back';
  } else if (goingForward(history, pathname)) {
    history.index++;
    return 'next';
  }
  return 'push';
};
var goingBack = function goingBack(hist, path) {
  var prev = hist.entries[hist.index - 1];
  return prev && prev.pathname === path;
};
var goingForward = function goingForward(hist, path) {
  var next = hist.entries[hist.index + 1];
  return next && next.pathname === path;
};

var middlewareCreateNotFoundAction = (function (action, location, prevLocation, history, notFoundPath) {
  var payload = action.payload;
  var meta = action.meta;
  var prevPath = location.pathname;
  var kind = meta && meta.location && meta.location.kind ||
  // use case: kind === 'redirect'
  location.kind === 'load' && 'load' || 'push';
  var pathname = meta && meta.notFoundPath || kind === 'redirect' && notFoundPath || prevPath || '/';
  return nestAction(pathname, {
    type: NOT_FOUND$1,
    payload: payload
  }, prevLocation, history, kind);
});

var _extends$3 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};
var createLocationReducer = (function (initialState, routesMap) {
  return function () {
    var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
    var action = arguments[1];
    routesMap = state.routesMap || routesMap;
    var route = routesMap[action.type];
    if (action.type === NOT_FOUND$1 || route && !action.error && (typeof route === 'string' || route.path) && (action.meta.location.current.pathname !== state.pathname || action.meta.location.current.search !== state.search || action.meta.location.kind === 'load')) {
      var _query = action.meta.location.current.query;
      var _search = action.meta.location.current.search;
      return _extends$3({
        pathname: action.meta.location.current.pathname,
        type: action.type,
        payload: _extends$3({}, action.payload)
      }, _query && {
        query: _query,
        search: _search
      }, {
        prev: action.meta.location.prev,
        kind: action.meta.location.kind,
        history: action.meta.location.history,
        hasSSR: state.hasSSR,
        routesMap: routesMap
      });
    } else if (route && !action.error && (typeof route === 'string' || route.path) && action.meta.location.current.pathname === state.pathname && action.meta.location.current.search === state.search && action.meta.location.kind !== state.kind) {
      return _extends$3({}, state, {
        kind: action.meta.location.kind
      });
    } else if (action.type === ADD_ROUTES$1) {
      return _extends$3({}, state, {
        routesMap: _extends$3({}, state.routesMap, action.payload.routes)
      });
    }
    return state;
  };
});
var getInitialState = function getInitialState(currentPathname, meta, type, payload, routesMap, history) {
  return _extends$3({
    search: currentPathname.split('?')[1],
    pathname: currentPathname.split('?')[0],
    type: type,
    payload: payload
  }, meta, {
    prev: {
      pathname: '',
      type: '',
      payload: {}
    },
    kind: undefined,
    history: nestHistory(history),
    hasSSR: isServer() ? true : undefined,
    // client uses initial server `hasSSR` state setup here
    routesMap: routesMap
  });
};

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;
};
var _extends$2 = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};

/** PRIMARY EXPORT - `connectRoutes(history, routeMap, options)`:
 *
 *  PURPOSE: to provide set-it-forget-it syncing of actions to the address bar and vice
 *  versa, using the pairing of action types to express-style routePaths bi-directionally.
 *
 *  EXAMPLE:
 *  with routeMap `{ FOO: '/foo/:paramName' }`,
 *
 *  pathname '/foo/bar' would become:
 *  `{ type: 'FOO', payload: { paramName: 'bar' } }`
 *
 *  AND
 *
 *  action `{ type: 'FOO', payload: { paramName: 'bar' } }`
 *  becomes: pathname '/foo/bar'
 *
 *
 *  HOW: Firstly, the middleware listens to received actions and then converts them to the
 *  pathnames it applies to the address bar (via `history.push({ pathname })`. It also formats
 *  the action to be location-aware, primarily by including a matching pathname, which the
 *  location reducer listens to, and which user reducers can also make use of.
 *
 *  However, user reducers typically only need to  be concerned with the type
 *  and payload like they are accustomed to. That's the whole purpose of this package.
 *  The idea is by matching action types to routePaths, it's set it and forget it!
 *
 *  Secondly, a history listener listens to URL changes and dispatches actions with
 *  types and payloads that match the pathname. Hurray! Browse back/next buttons now work!
 *
 *  Both the history listener and middleware are made to not get into each other's way, i.e.
 *  avoiding double dispatching and double address bar changes.
 *
 *
 *  VERY IMPORTANT NOTE ON SSR: if you're wondering, `connectRoutes()` when called returns
 *  functions in a closure that provide access to variables in a private
 *  "per instance" fashion in order to be used in SSR without leaking
 *  state between SSR requests :).
 *
 *  As much as possible has been refactored out of this file into pure or
 *  near-pure utility functions.
*/

var connectRoutes$1 = (function () {
  var routesMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  {
    if (options.restoreScroll && typeof options.restoreScroll !== 'function') {
      throw new Error('[redux-first-router] invalid `restoreScroll` option. Using\n        https://github.com/faceyspacey/redux-first-router-restore-scroll\n        please call `restoreScroll` and assign it the option key\n        of the same name.');
    }
  }

  /** INTERNAL ENCLOSED STATE (PER INSTANCE FOR SSR!) */

  var _options$notFoundPath = options.notFoundPath,
    notFoundPath = _options$notFoundPath === undefined ? '/not-found' : _options$notFoundPath,
    _options$scrollTop = options.scrollTop,
    scrollTop = _options$scrollTop === undefined ? false : _options$scrollTop,
    location = options.location,
    title = options.title,
    onBeforeChange = options.onBeforeChange,
    onAfterChange = options.onAfterChange,
    onBackNext = options.onBackNext,
    restoreScroll = options.restoreScroll,
    _options$initialDispa = options.initialDispatch,
    shouldPerformInitialDispatch = _options$initialDispa === undefined ? true : _options$initialDispa,
    querySerializer = options.querySerializer,
    displayConfirmLeave = options.displayConfirmLeave,
    extra = options.extra;

  // The options must be initialized ASAP to prevent empty options being
  // received in `getOptions` after the initial events emitted

  _options = options;
  setDisplayConfirmLeave(displayConfirmLeave);
  if (options.basename) {
    options.basename = stripTrailingSlash_1(addLeadingSlash_1(options.basename));
  }
  var isBrowser = canUseDom && "development" !== 'test';
  var standard = isBrowser ? _default$b : _default$a;
  var createHistory = options.createHistory || standard;
  var entries = options.initialEntries || '/'; // fyi only memoryHistory needs initialEntries
  var initialEntries = typeof entries === 'string' ? [entries] : entries;
  var history = createHistory({
    basename: options.basename,
    initialEntries: initialEntries,
    getUserConfirmation: getUserConfirmation
  });

  // very important: used for comparison to determine address bar changes
  var currentPath = pathnamePlusSearch(history.location);
  var prevLocation = {
    // maintains previous location state in location reducer
    pathname: '',
    type: '',
    payload: {}
  };
  var selectLocationState = typeof location === 'function' ? location : location ? function (state) {
    return state[location];
  } : function (state) {
    return state.location;
  };
  var selectTitleState = typeof title === 'function' ? title : title ? function (state) {
    return state[title];
  } : function (state) {
    return state.title;
  };
  var scrollBehavior = restoreScroll && restoreScroll(history);
  var initialAction = pathToAction$2(currentPath, routesMap, querySerializer);
  var type = initialAction.type,
    payload = initialAction.payload,
    meta = initialAction.meta;
  var INITIAL_LOCATION_STATE = getInitialState(currentPath, meta, type, payload, routesMap, history);
  var prevState = INITIAL_LOCATION_STATE; // used only to pass  as 1st arg to `scrollBehavior.updateScroll` if used
  var nextState = {}; // used as 2nd arg to `scrollBehavior.updateScroll` and to change `document.title`
  var prevLength = 1; // used by `historyCreateAction` to calculate if moving along history.entries track

  var reducer = createLocationReducer(INITIAL_LOCATION_STATE, routesMap);
  var initialBag = {
    action: initialAction,
    extra: extra
  };
  var thunk = createThunk(routesMap, selectLocationState, initialBag);
  var initialDispatch = function initialDispatch() {
    return _initialDispatch && _initialDispatch();
  };
  var windowDocument = getDocument(); // get plain object for window.document if server side

  var navigators = void 0;
  var patchNavigators = void 0;
  var actionToNavigation = void 0;
  var navigationToAction = void 0;

  // this value is used to hold temp state between consecutive runs through
  // the middleware (i.e. from new dispatches triggered within the middleware)
  var tempVal = void 0;
  if (options.navigators) {
    // redux-first-router-navigation reformats the `navigators` option
    // to have the navigators nested one depth deeper, so as to include
    // the various helper functions from its package
    if (!options.navigators.navigators) {
      throw new Error('[redux-first-router] invalid `navigators` option. Pass your map\n        of navigators to the default import from \'redux-first-router-navigation\'.\n        Don\'t forget: the keys are your redux state keys.');
    }
    navigators = options.navigators.navigators;
    patchNavigators = options.navigators.patchNavigators;
    actionToNavigation = options.navigators.actionToNavigation;
    navigationToAction = options.navigators.navigationToAction;
    patchNavigators(navigators);
  }

  /** MIDDLEWARE
   *  1)  dispatches actions with location info in the `meta` key by matching the received action
   *      type + payload to express style routePaths (which also results in location reducer state updating)
   *  2)  changes the address bar url and page title if the currentPathName changes, while
   *      avoiding collisions with simultaneous browser history changes
  */

  var middleware = function middleware(store) {
    return function (next) {
      return function (action) {
        // We have chosen to not change routes on errors, while letting other middleware
        // handle it. Perhaps in the future we will explicitly handle it (as an option)
        if (action.error) return next(action);

        // code-splitting functionliaty to add routes after store is initially configured
        if (action.type === ADD_ROUTES$1) {
          var _selectLocationState2 = selectLocationState(store.getState()),
            _type = _selectLocationState2.type;
          var _route = routesMap[_type];
          routesMap = _extends$2({}, routesMap, action.payload.routes);
          var result = next(action);
          var nextRoute = routesMap[_type];
          if (_route !== nextRoute) {
            if (_confirm !== null) {
              clearBlocking();
            }
            if ((typeof nextRoute === 'undefined' ? 'undefined' : _typeof(nextRoute)) === 'object' && nextRoute.confirmLeave) {
              _confirm = createConfirm(nextRoute.confirmLeave, store, selectLocationState, history, querySerializer, function () {
                return _confirm = null;
              });
            }
          }
          return result;
        }

        // navigation transformation specific to React Navigation
        var navigationAction = void 0;
        if (navigators && action.type.indexOf('Navigation/') === 0) {
          var _navigationToAction = navigationToAction(navigators, store, routesMap, action);
          navigationAction = _navigationToAction.navigationAction;
          action = _navigationToAction.action;
        }
        var route = routesMap[action.type];

        // We now support "routes" without paths for the purpose of dispatching thunks according
        // to the same idiom as full-fledged routes. The purpose is uniformity of async actions.
        // The URLs will NOT change.
        if ((typeof route === 'undefined' ? 'undefined' : _typeof(route)) === 'object' && !route.path) {
          var _nextAction = next(action);
          attemptCallRouteThunk(store.dispatch, store.getState, route, selectLocationState, {
            action: _nextAction,
            extra: extra
          });
          return _nextAction;
        }

        // START THE TYPICAL FLOW:

        if (action.type === NOT_FOUND$1 && !isLocationAction(action)) {
          // user decided to dispatch `NOT_FOUND`, so we fill in the missing location info
          action = middlewareCreateNotFoundAction(action, selectLocationState(store.getState()), prevLocation, history, notFoundPath);
        } else if (route && !isLocationAction(action)) {
          // THE MAGIC: dispatched action matches a connected type, so we generate a
          // location-aware action and also as a result update location reducer state.
          action = middlewareCreateAction(action, routesMap, prevLocation, history, notFoundPath, querySerializer);
        }
        if (navigators) {
          action = actionToNavigation(navigators, action, navigationAction, route);
        }

        // DISPATCH LIFECYLE:
        var skip = void 0;
        if ((route || action.type === NOT_FOUND$1) && action.meta) {
          // satisify flow with `action.meta` check
          skip = _beforeRouteChange(store, history, action);
        }
        if (skip) return;
        var nextAction = next(action);
        if (route || action.type === NOT_FOUND$1) {
          _afterRouteChange(store, route, nextAction);
        }
        return nextAction;
      };
    };
  };
  var _beforeRouteChange = function _beforeRouteChange(store, history, action) {
    var location = action.meta.location;
    if (_confirm) {
      var message = _confirm(location.current);
      if (message) {
        confirmUI(message, store, action);
        return true; // skip if there's a message to show in the confirm UI
      }

      _confirm = null;
    }
    if (onBeforeChange) {
      var skip = void 0;
      var redirectAwareDispatch = function redirectAwareDispatch(action) {
        if (isRedirectAction(action)) {
          skip = true;
          prevLocation = location.current;
          var _nextPath = pathnamePlusSearch(location.current);
          var isHistoryChange = _nextPath === currentPath;

          // this insures a `history.push` is called instead of `history.replace`
          // even though it's a redirect, since unlike route changes triggered
          // from the browser buttons, the URL did not change yet.
          if (!isHistoryChange && !isServer()) {
            tempVal = 'onBeforeChange';
          }
        }
        return store.dispatch(action);
      };
      var bag = {
        action: action,
        extra: extra
      };
      onBeforeChange(redirectAwareDispatch, store.getState, bag);
      if (skip) return true;
    }
    prevState = selectLocationState(store.getState());
    prevLocation = location.current;
    prevLength = history.length;

    // addressbar updated before action dispatched like in history.listener
    _middlewareAttemptChangeUrl(location, history);

    // now we can finally set the history on the action since we get its
    // value from the `history` whose value only changes after `push()`
    if (isReactNative()) {
      location.history = nestHistory(history);
    }
  };
  var _afterRouteChange = function _afterRouteChange(store, route, action) {
    var dispatch = store.dispatch;
    var state = store.getState();
    var kind = selectLocationState(state).kind;
    var title = selectTitleState(state);
    var bag = {
      action: action,
      extra: extra
    };
    nextState = selectLocationState(state);
    if ((typeof route === 'undefined' ? 'undefined' : _typeof(route)) === 'object') {
      var skip = false;
      var redirectAwareDispatch = function redirectAwareDispatch(action) {
        if (isRedirectAction(action)) skip = true;
        return store.dispatch(action);
      };
      attemptCallRouteThunk(redirectAwareDispatch, store.getState, route, selectLocationState, bag);
      if (skip) return;
    }
    if (onAfterChange) {
      onAfterChange(dispatch, store.getState, bag);
    }
    if (!isServer()) {
      if (kind) {
        if (typeof onBackNext === 'function' && /back|next|pop/.test(kind)) {
          onBackNext(dispatch, store.getState, bag);
        }
        setTimeout(function () {
          changePageTitle(windowDocument, title);
          if (scrollTop) {
            return window.scrollTo(0, 0);
          }
          _updateScroll(false);
        });
      }
      if ((typeof route === 'undefined' ? 'undefined' : _typeof(route)) === 'object' && route.confirmLeave) {
        _confirm = createConfirm(route.confirmLeave, store, selectLocationState, history, querySerializer, function () {
          return _confirm = null;
        });
      }
    }
  };
  var _middlewareAttemptChangeUrl = function _middlewareAttemptChangeUrl(location, history) {
    // IMPORTANT: insure history hasn't already handled location change
    var nextPath = pathnamePlusSearch(location.current);
    if (nextPath !== currentPath) {
      // keep currentPath up to date for comparison to prevent double dispatches
      // between BROWSER back/forward button usage vs middleware-generated actions
      currentPath = nextPath; // IMPORTANT: must happen before history.push() (to prevent double handling)

      // for React Native, in the case `back` or `next` is
      // not called directly, `middlewareCreateAction` may emulate
      // `history` backNext actions to support features such
      // as scroll restoration. In those cases, we need to prevent
      // pushing new routes on to the entries array. `stealth` is
      // a React Navigation feature for changing StackNavigators
      // without triggering other navigators (such as a TabNavigator)
      // to change as well. It allows you to reset hidden StackNavigators.
      var kind = location.kind;
      var manuallyInvoked = kind && /back|next|pop|stealth/.test(kind);
      if (!manuallyInvoked) {
        var isRedirect = kind === 'redirect' && tempVal !== 'onBeforeChange';
        var method = isRedirect ? 'replace' : 'push';
        history[method](currentPath); // change address bar corresponding to matched actions from middleware
      }
    }
  };

  /** ENHANCER
   *  1)  dispatches actions with types and payload extracted from the URL pattern
   *      when the browser history changes
   *  2)  on load of the app dispatches an action corresponding to the initial url
   */

  var enhancer = function enhancer(createStore) {
    return function (reducer, preloadedState, enhancer) {
      // routesMap stored in location reducer will be stringified as it goes from the server to client
      // and as a result functions in route objects will be removed--here's how we insure we bring them back
      if (!isServer() && preloadedState && selectLocationState(preloadedState)) {
        selectLocationState(preloadedState).routesMap = routesMap;
      }
      var store = createStore(reducer, preloadedState, enhancer);
      var state = store.getState();
      var location = state && selectLocationState(state);
      if (!location || !location.pathname) {
        throw new Error('[redux-first-router] you must provide the key of the location\n        reducer state and properly assigned the location reducer to that key.');
      }
      history.listen(_historyAttemptDispatchAction.bind(null, store));

      // dispatch the first location-aware action so initial app state is based on the url on load
      if (!location.hasSSR || isServer()) {
        // only dispatch on client before SSR is setup, which passes state on to the client
        _initialDispatch = function _initialDispatch() {
          var action = historyCreateAction(currentPath, routesMap, prevLocation, history, 'load', querySerializer);
          store.dispatch(action);
        };
        if (shouldPerformInitialDispatch !== false) {
          _initialDispatch();
        }
      } else {
        // set correct prevLocation on client that has SSR so that it will be
        // assigned to `action.meta.location.prev` and the corresponding state
        prevLocation = location;
        var route = routesMap[location.type];
        if ((typeof route === 'undefined' ? 'undefined' : _typeof(route)) === 'object' && route.confirmLeave) {
          _confirm = createConfirm(route.confirmLeave, store, selectLocationState, history, querySerializer, function () {
            return _confirm = null;
          });
        }
      }

      // update the scroll position after initial rendering of page
      if (!isServer()) setTimeout(function () {
        return _updateScroll(false);
      });
      return store;
    };
  };
  var _historyAttemptDispatchAction = function _historyAttemptDispatchAction(store, location, historyAction) {
    // IMPORTANT: insure middleware hasn't already handled location change:
    var nextPath = pathnamePlusSearch(location);
    if (nextPath !== currentPath) {
      var kind = historyAction === 'REPLACE' ? 'redirect' : historyAction;

      // THE MAGIC: parse the address bar path into a matched action
      var action = historyCreateAction(nextPath, routesMap, prevLocation, history, kind.toLowerCase(), querySerializer, currentPath, prevLength);
      currentPath = nextPath; // IMPORTANT: must happen before dispatch (to prevent double handling)

      store.dispatch(action); // dispatch route type + payload corresponding to browser back/forward usage
    }
  };

  /* SIDE_EFFECTS - client-only state that must escape closure */

  _history = history;
  _scrollBehavior = scrollBehavior;
  _selectLocationState = selectLocationState;
  var _initialDispatch = void 0;
  var _confirm = null;
  _updateScroll = function _updateScroll() {
    var performedByUser = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
    if (scrollBehavior) {
      if (performedByUser || !scrollBehavior.manual) {
        scrollBehavior.updateScroll(prevState, nextState);
      }
    } else if (performedByUser) {
      throw new Error('[redux-first-router] you must set the `restoreScroll` option before\n        you can call `updateScroll`');
    }
  };

  /* RETURN  */

  return {
    reducer: reducer,
    middleware: middleware,
    enhancer: enhancer,
    thunk: thunk,
    initialDispatch: initialDispatch,
    // returned only for tests (not for use in application code)
    _middlewareAttemptChangeUrl: _middlewareAttemptChangeUrl,
    _afterRouteChange: _afterRouteChange,
    _historyAttemptDispatchAction: _historyAttemptDispatchAction,
    windowDocument: windowDocument,
    history: history
  };
});

/** SIDE EFFECTS:
 *  Client code needs a simple `push`,`back` + `next` functions because it's convenient for
 *  prototyping. It will not harm SSR, so long as you don't use it server side. So if you use it, that means DO NOT
 *  simulate clicking links server side--and dont do that, dispatch actions to setup state instead.
 *
 *  THE IDIOMATIC WAY: instead use https://github.com/faceyspacey/redux-first-router-link 's `<Link />`
 *  component to generate SEO friendly urls. As its `href` prop, you pass it a path, array of path
 *  segments or action, and internally it will use `connectRoutes` to change the address bar and
 *  dispatch the correct final action from middleware.
 *
 *  NOTE ON BACK FUNCTIONALITY: The better way to accomplish a back button is to use your redux state to determine
 *  the previous URL. The location reducer will also contain relevant info. But if you must,
 *  this is here for convenience and it basically simulates the user pressing the browser
 *  back button, which of course the system picks up and parses into an action.
 */

var _history = void 0;
var _scrollBehavior = void 0;
var _updateScroll = void 0;
var _selectLocationState = void 0;
var _options = void 0;
var push$1 = function push(pathname) {
  return _history.push(pathname);
};
var replace$3 = function replace(pathname) {
  return _history.replace(pathname);
};
var back = function back() {
  return _history.goBack();
};
var next$1 = function next() {
  return _history.goForward();
};
var go = function go(n) {
  return _history.go(n);
};
var canGo = function canGo(n) {
  return _history.canGo(n);
};
var canGoBack = function canGoBack() {
  return !!(_history.entries && _history.entries[_history.index - 1]);
};
var canGoForward = function canGoForward() {
  return !!(_history.entries && _history.entries[_history.index + 1]);
};
var prevPath = function prevPath() {
  var entry = _history.entries[_history.index - 1];
  return entry && entry.pathname;
};
var nextPath = function nextPath() {
  var entry = _history.entries[_history.index + 1];
  return entry && entry.pathname;
};
var history$1 = function history() {
  return _history;
};
var scrollBehavior = function scrollBehavior() {
  return _scrollBehavior;
};
var updateScroll = function updateScroll() {
  return _updateScroll && _updateScroll();
};
var selectLocationState$2 = function selectLocationState(state) {
  return _selectLocationState(state);
};
var getOptions$2 = function getOptions() {
  return _options || {};
};

var setKind = (function (action, kind) {
  action.meta = action.meta || {};
  action.meta.location = action.meta.location || {};
  action.meta.location.kind = kind;
  return action;
});

var redirect$1 = (function (action, type, payload) {
  action = setKind(action, 'redirect');
  if (type) {
    action.type = type;
  }
  if (payload) {
    action.payload = payload;
  }
  return action;
});

var addRoutes = (function (routes) {
  return function (dispatch) {
    return dispatch({
      type: ADD_ROUTES$1,
      payload: {
        routes: routes
      }
    });
  };
});

var NOT_FOUND$1 = '@@redux-first-router/NOT_FOUND';
var ADD_ROUTES$1 = '@@redux-first-router/ADD_ROUTES';

var ReduxFirstRouter = /*#__PURE__*/Object.freeze({
  __proto__: null,
  ADD_ROUTES: ADD_ROUTES$1,
  NOT_FOUND: NOT_FOUND$1,
  actionToPath: actionToPath$1,
  addRoutes: addRoutes,
  back: back,
  canGo: canGo,
  canGoBack: canGoBack,
  canGoForward: canGoForward,
  connectRoutes: connectRoutes$1,
  getOptions: getOptions$2,
  go: go,
  history: history$1,
  isLocationAction: isLocationAction,
  next: next$1,
  nextPath: nextPath,
  pathToAction: pathToAction$2,
  prevPath: prevPath,
  push: push$1,
  redirect: redirect$1,
  replace: replace$3,
  scrollBehavior: scrollBehavior,
  selectLocationState: selectLocationState$2,
  setKind: setKind,
  updateScroll: updateScroll
});

const token$1 = '%[a-f0-9]{2}';
const singleMatcher = new RegExp('(' + token$1 + ')|([^%]+?)', 'gi');
const multiMatcher = new RegExp('(' + token$1 + ')+', 'gi');
function decodeComponents(components, split) {
  try {
    // Try to decode the entire string first
    return [decodeURIComponent(components.join(''))];
  } catch {
    // Do nothing
  }
  if (components.length === 1) {
    return components;
  }
  split = split || 1;

  // Split the array in 2 parts
  const left = components.slice(0, split);
  const right = components.slice(split);
  return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
}
function decode$1(input) {
  try {
    return decodeURIComponent(input);
  } catch {
    let tokens = input.match(singleMatcher) || [];
    for (let i = 1; i < tokens.length; i++) {
      input = decodeComponents(tokens, i).join('');
      tokens = input.match(singleMatcher) || [];
    }
    return input;
  }
}
function customDecodeURIComponent(input) {
  // Keep track of all the replacements and prefill the map with the `BOM`
  const replaceMap = {
    '%FE%FF': '\uFFFD\uFFFD',
    '%FF%FE': '\uFFFD\uFFFD'
  };
  let match = multiMatcher.exec(input);
  while (match) {
    try {
      // Decode as big chunks as possible
      replaceMap[match[0]] = decodeURIComponent(match[0]);
    } catch {
      const result = decode$1(match[0]);
      if (result !== match[0]) {
        replaceMap[match[0]] = result;
      }
    }
    match = multiMatcher.exec(input);
  }

  // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
  replaceMap['%C2'] = '\uFFFD';
  const entries = Object.keys(replaceMap);
  for (const key of entries) {
    // Replace all decoded components
    input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
  }
  return input;
}
function decodeUriComponent(encodedURI) {
  if (typeof encodedURI !== 'string') {
    throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
  }
  try {
    // Try the built in decoder first
    return decodeURIComponent(encodedURI);
  } catch {
    // Fallback to a more advanced decoder
    return customDecodeURIComponent(encodedURI);
  }
}

function splitOnFirst(string, separator) {
  if (!(typeof string === 'string' && typeof separator === 'string')) {
    throw new TypeError('Expected the arguments to be of type `string`');
  }
  if (string === '' || separator === '') {
    return [];
  }
  const separatorIndex = string.indexOf(separator);
  if (separatorIndex === -1) {
    return [];
  }
  return [string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length)];
}

function includeKeys(object, predicate) {
  const result = {};
  if (Array.isArray(predicate)) {
    for (const key of predicate) {
      const descriptor = Object.getOwnPropertyDescriptor(object, key);
      if (descriptor?.enumerable) {
        Object.defineProperty(result, key, descriptor);
      }
    }
  } else {
    // `Reflect.ownKeys()` is required to retrieve symbol properties
    for (const key of Reflect.ownKeys(object)) {
      const descriptor = Object.getOwnPropertyDescriptor(object, key);
      if (descriptor.enumerable) {
        const value = object[key];
        if (predicate(key, value, object)) {
          Object.defineProperty(result, key, descriptor);
        }
      }
    }
  }
  return result;
}

const isNullOrUndefined = value => value === null || value === undefined;

// eslint-disable-next-line unicorn/prefer-code-point
const strictUriEncode = string => encodeURIComponent(string).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);
const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');
function encoderForArrayFormat(options) {
  switch (options.arrayFormat) {
    case 'index':
      {
        return key => (result, value) => {
          const index = result.length;
          if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
            return result;
          }
          if (value === null) {
            return [...result, [encode(key, options), '[', index, ']'].join('')];
          }
          return [...result, [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')];
        };
      }
    case 'bracket':
      {
        return key => (result, value) => {
          if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
            return result;
          }
          if (value === null) {
            return [...result, [encode(key, options), '[]'].join('')];
          }
          return [...result, [encode(key, options), '[]=', encode(value, options)].join('')];
        };
      }
    case 'colon-list-separator':
      {
        return key => (result, value) => {
          if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
            return result;
          }
          if (value === null) {
            return [...result, [encode(key, options), ':list='].join('')];
          }
          return [...result, [encode(key, options), ':list=', encode(value, options)].join('')];
        };
      }
    case 'comma':
    case 'separator':
    case 'bracket-separator':
      {
        const keyValueSep = options.arrayFormat === 'bracket-separator' ? '[]=' : '=';
        return key => (result, value) => {
          if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
            return result;
          }

          // Translate null to an empty string so that it doesn't serialize as 'null'
          value = value === null ? '' : value;
          if (result.length === 0) {
            return [[encode(key, options), keyValueSep, encode(value, options)].join('')];
          }
          return [[result, encode(value, options)].join(options.arrayFormatSeparator)];
        };
      }
    default:
      {
        return key => (result, value) => {
          if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
            return result;
          }
          if (value === null) {
            return [...result, encode(key, options)];
          }
          return [...result, [encode(key, options), '=', encode(value, options)].join('')];
        };
      }
  }
}
function parserForArrayFormat(options) {
  let result;
  switch (options.arrayFormat) {
    case 'index':
      {
        return (key, value, accumulator) => {
          result = /\[(\d*)]$/.exec(key);
          key = key.replace(/\[\d*]$/, '');
          if (!result) {
            accumulator[key] = value;
            return;
          }
          if (accumulator[key] === undefined) {
            accumulator[key] = {};
          }
          accumulator[key][result[1]] = value;
        };
      }
    case 'bracket':
      {
        return (key, value, accumulator) => {
          result = /(\[])$/.exec(key);
          key = key.replace(/\[]$/, '');
          if (!result) {
            accumulator[key] = value;
            return;
          }
          if (accumulator[key] === undefined) {
            accumulator[key] = [value];
            return;
          }
          accumulator[key] = [...accumulator[key], value];
        };
      }
    case 'colon-list-separator':
      {
        return (key, value, accumulator) => {
          result = /(:list)$/.exec(key);
          key = key.replace(/:list$/, '');
          if (!result) {
            accumulator[key] = value;
            return;
          }
          if (accumulator[key] === undefined) {
            accumulator[key] = [value];
            return;
          }
          accumulator[key] = [...accumulator[key], value];
        };
      }
    case 'comma':
    case 'separator':
      {
        return (key, value, accumulator) => {
          const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
          const isEncodedArray = typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator);
          value = isEncodedArray ? decode(value, options) : value;
          const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options);
          accumulator[key] = newValue;
        };
      }
    case 'bracket-separator':
      {
        return (key, value, accumulator) => {
          const isArray = /(\[])$/.test(key);
          key = key.replace(/\[]$/, '');
          if (!isArray) {
            accumulator[key] = value ? decode(value, options) : value;
            return;
          }
          const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map(item => decode(item, options));
          if (accumulator[key] === undefined) {
            accumulator[key] = arrayValue;
            return;
          }
          accumulator[key] = [...accumulator[key], ...arrayValue];
        };
      }
    default:
      {
        return (key, value, accumulator) => {
          if (accumulator[key] === undefined) {
            accumulator[key] = value;
            return;
          }
          accumulator[key] = [...[accumulator[key]].flat(), value];
        };
      }
  }
}
function validateArrayFormatSeparator(value) {
  if (typeof value !== 'string' || value.length !== 1) {
    throw new TypeError('arrayFormatSeparator must be single character string');
  }
}
function encode(value, options) {
  if (options.encode) {
    return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
  }
  return value;
}
function decode(value, options) {
  if (options.decode) {
    return decodeUriComponent(value);
  }
  return value;
}
function keysSorter(input) {
  if (Array.isArray(input)) {
    return input.sort();
  }
  if (typeof input === 'object') {
    return keysSorter(Object.keys(input)).sort((a, b) => Number(a) - Number(b)).map(key => input[key]);
  }
  return input;
}
function removeHash(input) {
  const hashStart = input.indexOf('#');
  if (hashStart !== -1) {
    input = input.slice(0, hashStart);
  }
  return input;
}
function getHash(url) {
  let hash = '';
  const hashStart = url.indexOf('#');
  if (hashStart !== -1) {
    hash = url.slice(hashStart);
  }
  return hash;
}
function parseValue(value, options) {
  if (options.parseNumbers && !Number.isNaN(Number(value)) && typeof value === 'string' && value.trim() !== '') {
    value = Number(value);
  } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
    value = value.toLowerCase() === 'true';
  }
  return value;
}
function extract(input) {
  input = removeHash(input);
  const queryStart = input.indexOf('?');
  if (queryStart === -1) {
    return '';
  }
  return input.slice(queryStart + 1);
}
function parse$2(query, options) {
  options = {
    decode: true,
    sort: true,
    arrayFormat: 'none',
    arrayFormatSeparator: ',',
    parseNumbers: false,
    parseBooleans: false,
    ...options
  };
  validateArrayFormatSeparator(options.arrayFormatSeparator);
  const formatter = parserForArrayFormat(options);

  // Create an object with no prototype
  const returnValue = Object.create(null);
  if (typeof query !== 'string') {
    return returnValue;
  }
  query = query.trim().replace(/^[?#&]/, '');
  if (!query) {
    return returnValue;
  }
  for (const parameter of query.split('&')) {
    if (parameter === '') {
      continue;
    }
    const parameter_ = options.decode ? parameter.replace(/\+/g, ' ') : parameter;
    let [key, value] = splitOnFirst(parameter_, '=');
    if (key === undefined) {
      key = parameter_;
    }

    // Missing `=` should be `null`:
    // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
    value = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options);
    formatter(decode(key, options), value, returnValue);
  }
  for (const [key, value] of Object.entries(returnValue)) {
    if (typeof value === 'object' && value !== null) {
      for (const [key2, value2] of Object.entries(value)) {
        value[key2] = parseValue(value2, options);
      }
    } else {
      returnValue[key] = parseValue(value, options);
    }
  }
  if (options.sort === false) {
    return returnValue;
  }

  // TODO: Remove the use of `reduce`.
  // eslint-disable-next-line unicorn/no-array-reduce
  return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => {
    const value = returnValue[key];
    if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {
      // Sort object keys, not values
      result[key] = keysSorter(value);
    } else {
      result[key] = value;
    }
    return result;
  }, Object.create(null));
}
function stringify$1(object, options) {
  if (!object) {
    return '';
  }
  options = {
    encode: true,
    strict: true,
    arrayFormat: 'none',
    arrayFormatSeparator: ',',
    ...options
  };
  validateArrayFormatSeparator(options.arrayFormatSeparator);
  const shouldFilter = key => options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === '';
  const formatter = encoderForArrayFormat(options);
  const objectCopy = {};
  for (const [key, value] of Object.entries(object)) {
    if (!shouldFilter(key)) {
      objectCopy[key] = value;
    }
  }
  const keys = Object.keys(objectCopy);
  if (options.sort !== false) {
    keys.sort(options.sort);
  }
  return keys.map(key => {
    const value = object[key];
    if (value === undefined) {
      return '';
    }
    if (value === null) {
      return encode(key, options);
    }
    if (Array.isArray(value)) {
      if (value.length === 0 && options.arrayFormat === 'bracket-separator') {
        return encode(key, options) + '[]';
      }
      return value.reduce(formatter(key), []).join('&');
    }
    return encode(key, options) + '=' + encode(value, options);
  }).filter(x => x.length > 0).join('&');
}
function parseUrl(url, options) {
  options = {
    decode: true,
    ...options
  };
  let [url_, hash] = splitOnFirst(url, '#');
  if (url_ === undefined) {
    url_ = url;
  }
  return {
    url: url_?.split('?')?.[0] ?? '',
    query: parse$2(extract(url), options),
    ...(options && options.parseFragmentIdentifier && hash ? {
      fragmentIdentifier: decode(hash, options)
    } : {})
  };
}
function stringifyUrl(object, options) {
  options = {
    encode: true,
    strict: true,
    [encodeFragmentIdentifier]: true,
    ...options
  };
  const url = removeHash(object.url).split('?')[0] || '';
  const queryFromUrl = extract(object.url);
  const query = {
    ...parse$2(queryFromUrl, {
      sort: false
    }),
    ...object.query
  };
  let queryString = stringify$1(query, options);
  if (queryString) {
    queryString = `?${queryString}`;
  }
  let hash = getHash(object.url);
  if (object.fragmentIdentifier) {
    const urlObjectForFragmentEncode = new URL(url);
    urlObjectForFragmentEncode.hash = object.fragmentIdentifier;
    hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`;
  }
  return `${url}${queryString}${hash}`;
}
function pick(input, filter, options) {
  options = {
    parseFragmentIdentifier: true,
    [encodeFragmentIdentifier]: false,
    ...options
  };
  const {
    url,
    query,
    fragmentIdentifier
  } = parseUrl(input, options);
  return stringifyUrl({
    url,
    query: includeKeys(query, filter),
    fragmentIdentifier
  }, options);
}
function exclude(input, filter, options) {
  const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);
  return pick(input, exclusionFilter, options);
}

var queryString = /*#__PURE__*/Object.freeze({
  __proto__: null,
  exclude: exclude,
  extract: extract,
  parse: parse$2,
  parseUrl: parseUrl,
  pick: pick,
  stringify: stringify$1,
  stringifyUrl: stringifyUrl
});

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var __assign$4 = function () {
  __assign$4 = Object.assign || function __assign(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign$4.apply(this, arguments);
};

/**
 * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
 */
/**
 * Lower case as a function.
 */
function lowerCase(str) {
  return str.toLowerCase();
}

// Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case").
var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
// Remove all non-word characters.
var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
/**
 * Normalize the string into something other libraries can manipulate easier.
 */
function noCase(input, options) {
  if (options === void 0) {
    options = {};
  }
  var _a = options.splitRegexp,
    splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a,
    _b = options.stripRegexp,
    stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b,
    _c = options.transform,
    transform = _c === void 0 ? lowerCase : _c,
    _d = options.delimiter,
    delimiter = _d === void 0 ? " " : _d;
  var result = replace$2(replace$2(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
  var start = 0;
  var end = result.length;
  // Trim the delimiter from around the output string.
  while (result.charAt(start) === "\0") start++;
  while (result.charAt(end - 1) === "\0") end--;
  // Transform each token independently.
  return result.slice(start, end).split("\0").map(transform).join(delimiter);
}
/**
 * Replace `re` in the input string with the replacement value.
 */
function replace$2(input, re, value) {
  if (re instanceof RegExp) return input.replace(re, value);
  return re.reduce(function (input, re) {
    return input.replace(re, value);
  }, input);
}

/**
 * Upper case the first character of an input string.
 */
function upperCaseFirst(input) {
  return input.charAt(0).toUpperCase() + input.substr(1);
}

function capitalCaseTransform(input) {
  return upperCaseFirst(input.toLowerCase());
}
function capitalCase(input, options) {
  if (options === void 0) {
    options = {};
  }
  return noCase(input, __assign$4({
    delimiter: " ",
    transform: capitalCaseTransform
  }, options));
}

const {
  connectRoutes,
  push,
  NOT_FOUND,
  ADD_ROUTES
} = ReduxFirstRouter;
const HTML$2 = "@@HTML",
  RENDER$1 = "RENDER",
  FIRST = "@@FIRST",
  DEFAULT = "@@DEFAULT",
  LAST = "@@LAST",
  CURRENT$1 = "@@CURRENT",
  validOrder = {
    [FIRST]: true,
    [DEFAULT]: true,
    [LAST]: true
  };
const defaultQuerySerializer = {
  parse(str) {
    return queryString.parse(str, {
      arrayFormat: "comma"
    });
  },
  stringify(obj) {
    return queryString.stringify(obj, {
      arrayFormat: "comma"
    });
  }
};

// Exported module object
var router = {
  config: {
    store: "main",
    tmpl404: "404",
    debug: false,
    getTemplateName: name => name,
    querySerializer: defaultQuerySerializer
  },
  routesMap: {},
  routeInfoFn: [],
  contextProcessors: []
};

// Configuration
router.init = function (config) {
  // Define baseurl (without trailing slash) if it is not /
  if (config && config.base_url) {
    router.base_url = config.base_url;
  }
  router.config = {
    ...router.config,
    ...config
  };

  // Configuration options:
  // Define `tmpl404` if there is not a template named '404'
  // Set `debug` to true to log template & context information
  // Set getTemplateName to change how route names are resolved.

  const {
    reducer: routeReducer,
    middleware,
    enhancer,
    initialDispatch
  } = connectRoutes({}, {
    querySerializer: router.config.querySerializer,
    initialDispatch: false
  });
  router.store = getStore(router.config.store);
  router.store.addReducer("location", routeReducer);
  router.store.addReducer("context", contextReducer);
  router.store.addReducer("routeInfo", routeInfoReducer);
  router.store.addEnhancer(enhancer);
  router.store.addMiddleware(middleware);
  router.store.setThunkHandler(router.addThunk);
  router._initialDispatch = initialDispatch;
};
router.start = function () {
  if (!router.config) {
    throw new Error("Initialize router first!");
  }
  var orderedRoutes = {};
  [FIRST, DEFAULT, LAST].forEach(function (order) {
    Object.entries(router.routesMap).forEach(([name, path]) => {
      if (path.order === order) {
        orderedRoutes[name] = path;
      }
    });
  });
  router.store.dispatch({
    type: ADD_ROUTES,
    payload: {
      routes: orderedRoutes
    }
  });
  router._initialDispatch();
};
function contextReducer(context = {}, action) {
  if (action.type != RENDER$1 && action.type != NOT_FOUND) {
    return context;
  }
  let current;
  if (action.type === RENDER$1) {
    current = action.payload;
  } else if (action.type === NOT_FOUND) {
    const routeInfo = _routeInfo(action.meta.location);
    current = {
      router_info: {
        ...routeInfo,
        template: router.config.tmpl404
      },
      rt: router.base_url,
      url: routeInfo.full_path
    };
  }
  return {
    ...context,
    [current.router_info.name]: current,
    [CURRENT$1]: current
  };
}
function routeInfoReducer(routeInfo = {}, action) {
  if (action.meta && action.meta.location) {
    const current = _routeInfo(action.meta.location);
    return {
      ...routeInfo,
      [current.name]: current,
      [CURRENT$1]: current
    };
  } else {
    return routeInfo;
  }
}
async function _generateContext(dispatch, getState, refresh = false) {
  const location = getState().location;
  var context = {
    router_info: _routeInfo(location),
    rt: router.base_url
  };
  for (var i = 0; i < router.contextProcessors.length; i++) {
    var fn = router.contextProcessors[i];
    context = {
      ...context,
      ...((await fn(context)) || {})
    };
  }
  if (context[NOT_FOUND]) {
    context.router_info.template = router.config.tmpl404;
    context.url = context.router_info.full_path;
  }
  return router.render(context, refresh);
}
router.register = function (path, nameOrContext, context, order = DEFAULT, thunk = null) {
  var name;
  const newUsage = " Usage: router.register(path[, name[, contextFn]])";
  if (!validOrder[order]) {
    // Assume old-style prevent() callback was passed
    throw new Error("prevent() no longer supported." + newUsage);
  }
  if (context) {
    if (typeof context !== "function") {
      throw new Error("Unexpected " + context + " for contextFn." + newUsage);
    }
  } else if (typeof nameOrContext === "function") {
    context = nameOrContext;
    nameOrContext = null;
  }
  if (nameOrContext) {
    name = nameOrContext;
    if (typeof name !== "string") {
      throw new Error("Unexpected " + name + " for route name." + newUsage);
    }
  } else {
    if (path.indexOf("/") > -1) {
      throw new Error("router.register() now requires a route name if path contains /." + newUsage);
    }
    // Assume there is a template with the same name
    name = path;
  }
  if (context && context.length > 1) {
    throw new Error("contextFn should take a single argument (the existing context) and return a new context for merging.");
  }
  function thunkFn(dispatch, getState, bag) {
    _generateContext(dispatch, getState);
    if (thunk) {
      thunk(dispatch, getState, bag);
    }
  }
  router.routesMap[name.toUpperCase()] = {
    path: _normalizePath(path),
    thunk: thunkFn,
    order
  };
  if (context) {
    router.addContextForRoute(name, context);
  }
  return name;
};
router.registerFirst = function (path, name, context) {
  router.register(path, name, context, FIRST);
};
router.registerLast = function (path, name, context) {
  router.register(path, name, context, LAST);
};
router.addThunk = function (name, thunk) {
  router.routesMap[name] = {
    thunk,
    order: FIRST
  };
};
router.addThunks = function (thunks, thisObj) {
  Object.entries(thunks).forEach(([name, thunk]) => {
    if (thisObj) {
      thunk = thunk.bind(thisObj);
    }
    router.addThunk(name, thunk);
  });
};
router.addContext = function (fn) {
  router.contextProcessors.push(fn);
};
router.addContextForRoute = function (pathOrName, fn) {
  const name = _getRouteName(pathOrName);
  function contextForRoute(context) {
    if (context.router_info.name == name) {
      return fn(context);
    } else {
      return {};
    }
  }
  router.addContext(contextForRoute);
};
router.onShow = function () {
  throw new Error("router.onShow() is removed.  Use a run() plugin instead");
};
router.addRoute = function () {
  throw new Error("router.addRoute() is removed.  Use a run() plugin instead");
};
router.push = function (path) {
  push(path);
};
router.render = function (context, refresh) {
  if (refresh) {
    if (refresh === true) {
      refresh = (context._refreshCount || 0) + 1;
    }
    context = {
      ...context,
      _refreshCount: refresh
    };
  }
  const {
    site_title
  } = router.config;
  let title = router.getContextTitle(context, context.router_info);
  if (site_title && title !== site_title) {
    title = `${title} - ${site_title}`;
  }
  if (window.document) window.document.title = title;
  return router.store.dispatch({
    type: RENDER$1,
    payload: context
  });
};
router.getContext = function () {
  const {
    context = {}
  } = router.store.getState();
  return context[CURRENT$1];
};

// Re-render existing context
router.refresh = function () {
  const context = router.getContext();
  router.render(context, true);
};

// Regenerate context, then re-render page
router.reload = function () {
  const context = router.getContext(),
    refresh = (context._refreshCount || 0) + 1;
  return _generateContext(action => router.store.dispatch(action), () => router.store.getState(), refresh);
};

// Simple 404 page helper
router.notFound = function () {
  return {
    [NOT_FOUND]: true
  };
};

// Use when loading HTML from server
router.rawHTML = function (html) {
  return {
    [HTML$2]: html
  };
};
router.base_url = "";
router.addRouteInfo = function (fn) {
  router.routeInfoFn.push(fn);
};
router.getRouteInfo = function (context, routeInfo) {
  const {
    router_info: ctxRouteInfo
  } = context;
  if (routeInfo) {
    if (!ctxRouteInfo || ["name", "mode", "variant", "item_id"].some(key => ctxRouteInfo[key] != routeInfo[key])) {
      return {
        ...routeInfo,
        pending: true
      };
    } else {
      return ctxRouteInfo;
    }
  } else {
    return NO_ROUTE_INFO;
  }
};
const NO_ROUTE_INFO = {
  pending: true
};
router.getContextTitle = function (context, routeInfo) {
  var title;
  if (routeInfo && !routeInfo.pending) {
    title = context.title || context.label;
  }
  if (!title && routeInfo) {
    title = router.getRouteTitle(routeInfo);
  }
  if (!title) {
    title = "Loading...";
  }
  return title;
};
router.getRouteTitle = function (routeInfo) {
  const {
      page_config = {},
      mode,
      variant
    } = routeInfo,
    verbose_name = page_config.verbose_name || page_config.name || routeInfo.name,
    verbose_name_plural = page_config.verbose_name_plural || page_config.url || `${verbose_name}s`;
  let title,
    prefix = "";
  if (mode === "list" && verbose_name === "outbox") {
    title = "outbox";
  } else if (mode === "list") {
    title = verbose_name_plural;
  } else if (mode === "edit") {
    title = verbose_name;
    if (variant === "new") {
      prefix = "New ";
    } else {
      prefix = "Edit ";
    }
  } else if (mode && mode !== "detail") {
    title = `${verbose_name} - ${mode}`;
  } else {
    title = verbose_name;
  }
  if (title && title === title.toLowerCase()) {
    title = capitalCase(title);
  }
  return prefix + title;
};
function _normalizePath(path) {
  path = path.replace("<slug>", ":slug");
  return router.base_url + "/" + path;
}
function _getRouteName(pathOrName) {
  var name;
  if (router.routesMap[pathOrName.toUpperCase()]) {
    name = pathOrName;
  } else {
    Object.entries(router.routesMap).forEach(([rname, rpath]) => {
      if (_normalizePath(pathOrName) === rpath.path) {
        name = rname;
      }
    });
  }
  if (!name) {
    throw new Error("Unrecognized route: " + pathOrName);
  }
  return name.toLowerCase();
}
function _removeBase(pathname) {
  return pathname.replace(router.base_url + "/", "");
}
var _lastRouteInfo$1 = null;
function _routeInfo(location) {
  const info = _computeRouteInfo(location);
  if (JSON.stringify(info) !== JSON.stringify(_lastRouteInfo$1)) {
    _lastRouteInfo$1 = info;
  }
  return _lastRouteInfo$1;
}
function _computeRouteInfo(location) {
  if (location.current && location.prev) {
    location = {
      ...location.current,
      prev: location.prev
    };
  }
  var info = {};
  info.name = location.type.toLowerCase();
  info.template = router.config.getTemplateName(info.name);
  info.prev_path = _removeBase(location.prev.pathname);
  info.path = _removeBase(location.pathname);
  info.path_enc = escape(info.path);
  info.full_path = location.pathname + (location.search ? "?" + location.search : "");
  info.full_path_enc = escape(info.full_path);
  info.params = location.query;
  info.slugs = location.payload;
  info.base_url = router.base_url;
  router.routeInfoFn.forEach(fn => info = fn(info));
  return info;
}

const SPIN_START = "SPIN_START";
const SPIN_DURATION = "@@SPIN_DURATION";
const SPIN_STOP = "SPIN_STOP";
var spinner = {
  name: "spinner",
  actions: {
    start: (message, duration, type) => ({
      type: SPIN_START,
      payload: {
        message,
        duration,
        type
      }
    }),
    alert: message => ({
      type: SPIN_DURATION,
      payload: {
        message,
        duration: 1.5,
        type: "alert"
      }
    }),
    stop: message => ({
      type: SPIN_STOP,
      payload: {
        message
      }
    })
  },
  thunks: {
    SPIN_DURATION: async (dispatch, getState, bag) => {
      const {
          action
        } = bag,
        {
          message,
          duration,
          type
        } = action.payload;
      dispatch({
        type: SPIN_START,
        payload: {
          message,
          type
        }
      });
      if (duration) {
        await new Promise(resolve => setTimeout(resolve, duration * 1000));
        dispatch({
          type: SPIN_STOP,
          payload: {
            message
          }
        });
      }
    }
  },
  reducer(state, action) {
    if (action.type !== SPIN_START && action.type !== SPIN_STOP) {
      return state || {
        active: false
      };
    }
    const message = action.payload.message || "",
      messages = (state.messages || []).filter(msg => msg != message);
    if (action.type === SPIN_START) {
      messages.push(message);
      return {
        active: true,
        type: action.payload.type,
        message,
        messages
      };
    } else if (action.type === SPIN_STOP) {
      if (messages.length > 0) {
        return {
          ...state,
          messages
        };
      } else {
        return {
          active: false
        };
      }
    }
  }
};

const LOGIN_SUCCESS = "LOGIN_SUCCESS",
  LOGIN_CHECK = "LOGIN_CHECK",
  LOGIN_RELOAD = "LOGIN_RELOAD",
  LOGOUT_SUBMIT = "LOGOUT_SUBMIT",
  LOGOUT_SUCCESS = "LOGOUT_SUCCESS",
  CSRFTOKEN = "CSRFTOKEN";
var auth = {
  name: "auth",
  persist: true,
  pages: {
    login: {
      url: "login",
      show_in_index: "not_authenticated",
      order: 1000,
      icon: "login"
    },
    logout: {
      url: "logout",
      show_in_index: "is_authenticated",
      order: 1000,
      icon: "logout",
      thunk(dispatch, getState) {
        if (!getState().auth.user) {
          return;
        }
        dispatch({
          type: LOGOUT_SUBMIT
        });
      }
    }
  },
  start() {
    this.refreshCSRFToken();
    this.app.store.dispatch({
      type: LOGIN_CHECK
    });
  },
  getState() {
    return this.app.store.getState().auth || {};
  },
  reducer(state = {}, action) {
    switch (action.type) {
      case LOGIN_SUCCESS:
      case LOGIN_RELOAD:
        {
          const {
            user,
            config,
            csrftoken
          } = action.payload;
          return {
            user,
            config,
            csrftoken
          };
        }
      case LOGOUT_SUBMIT:
        {
          return {};
        }
      case LOGOUT_SUCCESS:
        {
          const {
            csrftoken
          } = action.payload || {};
          if (csrftoken) {
            return {
              csrftoken
            };
          } else {
            return {};
          }
        }
      case CSRFTOKEN:
        {
          const {
            csrftoken
          } = action.payload;
          return {
            ...state,
            csrftoken
          };
        }
      default:
        {
          return state;
        }
    }
  },
  thunks: {
    CSRFTOKEN() {
      this.refreshCSRFToken();
    },
    // LOGIN_SUBMIT handled automatically by @wq/outbox form logic

    LOGIN_SUCCESS() {
      this.refreshUserInfo();
    },
    LOGIN_RELOAD() {
      this.refreshUserInfo();
    },
    LOGIN_CHECK(dispatch, getState) {
      const user = getState().auth.user,
        ds = this.app.store;
      setTimeout(function () {
        ds.fetch("/login").then(function (result) {
          if (result && result.user && result.config) {
            dispatch({
              type: LOGIN_RELOAD,
              payload: result
            });
          } else {
            const {
              csrftoken
            } = result || {};
            dispatch({
              type: user ? LOGOUT_SUCCESS : CSRFTOKEN,
              payload: {
                csrftoken
              }
            });
          }
        });
      }, 10);
    },
    LOGOUT_SUBMIT(dispatch) {
      this.app.store.fetch("/logout").then(function (result) {
        dispatch({
          type: LOGOUT_SUCCESS,
          payload: result
        });
      });
    },
    LOGOUT_SUCCESS() {
      this.refreshUserInfo();
    }
  },
  context(ctx) {
    return this.userInfo(ctx);
  },
  userInfo(ctx = {}) {
    const {
        user,
        config,
        csrftoken
      } = this.getState(),
      pageConf = ctx && ctx.router_info && ctx.router_info.page_config || {},
      wqPageConf = config && config.pages && config.pages[pageConf.name] || {};
    return {
      user,
      is_authenticated: !!user,
      app_config: this.app.config,
      user_config: config,
      csrf_token: csrftoken,
      router_info: {
        ...(ctx && ctx.router_info),
        page_config: {
          ...pageConf,
          can_view: wqPageConf.can_view !== false,
          can_add: wqPageConf.can_add || false,
          can_change: wqPageConf.can_change || false,
          can_delete: wqPageConf.can_delete || false
        }
      }
    };
  },
  async refreshUserInfo() {
    await this.refreshCSRFToken();
    const app = this.app,
      context = app.router.getContext();
    if (context) {
      app.router.render({
        ...context,
        ...this.userInfo(context)
      }, true);
    }
    // FIXME: Better way to do this?
    app.spin.start();
    await app.prefetchAll();
    app.spin.stop();
    await app.router.reload();
  },
  async refreshCSRFToken() {
    const {
      csrftoken
    } = this.getState();
    this.app.outbox.setCSRFToken(csrftoken);
  }
};

const defaults = {
  name: "defaults",
  async context(ctx, routeInfo) {
    const fields = (routeInfo.page_config.form || []).filter(field => field.type === "repeat" && field.initial);
    if (routeInfo.variant === "new" && fields.length > 0) {
      const defaults = {};
      for (let field of fields) {
        defaults[field.name] = await defaultAttachments(field, ctx, this.app);
      }
      return defaults;
    }
  }
};

// List of empty annotations for new objects
async function defaultAttachments(field, context, app) {
  if (field.type != "repeat" || !field.initial) {
    return [];
  }
  if (typeof field.initial == "string" || typeof field.initial == "number") {
    const attachments = [];
    for (let i = 0; i < +field.initial; i++) {
      attachments.push({});
    }
    return attachments;
  }
  let typeField;
  field.children.forEach(function (tf) {
    if (tf.name == field.initial.type_field) {
      typeField = tf;
    }
  });
  if (!typeField) {
    return [];
  }
  const model = app.models[typeField["wq:ForeignKey"]];
  let filterConf = field.initial.filter;
  if (!filterConf || !Object.keys(filterConf).length) {
    if (typeField.filter) {
      filterConf = typeField.filter;
    }
  }
  const filter = computeFilter(filterConf, context);
  const types = await model.filter(filter);
  return types.map(type => ({
    [typeField.name + "_id"]: type.id
  }));
}
function computeFilter(filterConf, context) {
  const filter = {};
  Object.entries(filterConf).forEach(([key, value]) => {
    filter[key] = context[value] || value;
  });
  return filter;
}

/*!
 * mustache.js - Logic-less {{mustache}} templates with JavaScript
 * http://github.com/janl/mustache.js
 */

var objectToString = Object.prototype.toString;
var isArray$3 = Array.isArray || function isArrayPolyfill (object) {
  return objectToString.call(object) === '[object Array]';
};

function isFunction$2 (object) {
  return typeof object === 'function';
}

/**
 * More correct typeof string handling array
 * which normally returns typeof 'object'
 */
function typeStr (obj) {
  return isArray$3(obj) ? 'array' : typeof obj;
}

function escapeRegExp (string) {
  return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
}

/**
 * Null safe way of checking whether or not an object,
 * including its prototype, has a given property
 */
function hasProperty (obj, propName) {
  return obj != null && typeof obj === 'object' && (propName in obj);
}

/**
 * Safe way of detecting whether or not the given thing is a primitive and
 * whether it has the given property
 */
function primitiveHasOwnProperty (primitive, propName) {
  return (
    primitive != null
    && typeof primitive !== 'object'
    && primitive.hasOwnProperty
    && primitive.hasOwnProperty(propName)
  );
}

// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
// See https://github.com/janl/mustache.js/issues/189
var regExpTest = RegExp.prototype.test;
function testRegExp (re, string) {
  return regExpTest.call(re, string);
}

var nonSpaceRe = /\S/;
function isWhitespace (string) {
  return !testRegExp(nonSpaceRe, string);
}

var entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
    return entityMap[s];
  });
}

var whiteRe = /\s*/;
var spaceRe = /\s+/;
var equalsRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;

/**
 * Breaks up the given `template` string into a tree of tokens. If the `tags`
 * argument is given here it must be an array with two string values: the
 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
 * course, the default is to use mustaches (i.e. mustache.tags).
 *
 * A token is an array with at least 4 elements. The first element is the
 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
 * all text that appears outside a symbol this element is "text".
 *
 * The second element of a token is its "value". For mustache tags this is
 * whatever else was inside the tag besides the opening symbol. For text tokens
 * this is the text itself.
 *
 * The third and fourth elements of the token are the start and end indices,
 * respectively, of the token in the original template.
 *
 * Tokens that are the root node of a subtree contain two more elements: 1) an
 * array of tokens in the subtree and 2) the index in the original template at
 * which the closing tag for that section begins.
 *
 * Tokens for partials also contain two more elements: 1) a string value of
 * indendation prior to that tag and 2) the index of that tag on that line -
 * eg a value of 2 indicates the partial is the third tag on this line.
 */
function parseTemplate (template, tags) {
  if (!template)
    return [];
  var lineHasNonSpace = false;
  var sections = [];     // Stack to hold section tokens
  var tokens = [];       // Buffer to hold the tokens
  var spaces = [];       // Indices of whitespace tokens on the current line
  var hasTag = false;    // Is there a {{tag}} on the current line?
  var nonSpace = false;  // Is there a non-space char on the current line?
  var indentation = '';  // Tracks indentation for tags that use it
  var tagIndex = 0;      // Stores a count of number of tags encountered on a line

  // Strips all whitespace tokens array for the current line
  // if there was a {{#tag}} on it and otherwise only space.
  function stripSpace () {
    if (hasTag && !nonSpace) {
      while (spaces.length)
        delete tokens[spaces.pop()];
    } else {
      spaces = [];
    }

    hasTag = false;
    nonSpace = false;
  }

  var openingTagRe, closingTagRe, closingCurlyRe;
  function compileTags (tagsToCompile) {
    if (typeof tagsToCompile === 'string')
      tagsToCompile = tagsToCompile.split(spaceRe, 2);

    if (!isArray$3(tagsToCompile) || tagsToCompile.length !== 2)
      throw new Error('Invalid tags: ' + tagsToCompile);

    openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
    closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
    closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
  }

  compileTags(tags || mustache.tags);

  var scanner = new Scanner(template);

  var start, type, value, chr, token, openSection;
  while (!scanner.eos()) {
    start = scanner.pos;

    // Match any text between tags.
    value = scanner.scanUntil(openingTagRe);

    if (value) {
      for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
        chr = value.charAt(i);

        if (isWhitespace(chr)) {
          spaces.push(tokens.length);
          indentation += chr;
        } else {
          nonSpace = true;
          lineHasNonSpace = true;
          indentation += ' ';
        }

        tokens.push([ 'text', chr, start, start + 1 ]);
        start += 1;

        // Check for whitespace on the current line.
        if (chr === '\n') {
          stripSpace();
          indentation = '';
          tagIndex = 0;
          lineHasNonSpace = false;
        }
      }
    }

    // Match the opening tag.
    if (!scanner.scan(openingTagRe))
      break;

    hasTag = true;

    // Get the tag type.
    type = scanner.scan(tagRe) || 'name';
    scanner.scan(whiteRe);

    // Get the tag value.
    if (type === '=') {
      value = scanner.scanUntil(equalsRe);
      scanner.scan(equalsRe);
      scanner.scanUntil(closingTagRe);
    } else if (type === '{') {
      value = scanner.scanUntil(closingCurlyRe);
      scanner.scan(curlyRe);
      scanner.scanUntil(closingTagRe);
      type = '&';
    } else {
      value = scanner.scanUntil(closingTagRe);
    }

    // Match the closing tag.
    if (!scanner.scan(closingTagRe))
      throw new Error('Unclosed tag at ' + scanner.pos);

    if (type == '>') {
      token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ];
    } else {
      token = [ type, value, start, scanner.pos ];
    }
    tagIndex++;
    tokens.push(token);

    if (type === '#' || type === '^') {
      sections.push(token);
    } else if (type === '/') {
      // Check section nesting.
      openSection = sections.pop();

      if (!openSection)
        throw new Error('Unopened section "' + value + '" at ' + start);

      if (openSection[1] !== value)
        throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
    } else if (type === 'name' || type === '{' || type === '&') {
      nonSpace = true;
    } else if (type === '=') {
      // Set the tags for the next time around.
      compileTags(value);
    }
  }

  stripSpace();

  // Make sure there are no open sections when we're done.
  openSection = sections.pop();

  if (openSection)
    throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);

  return nestTokens(squashTokens(tokens));
}

/**
 * Combines the values of consecutive text tokens in the given `tokens` array
 * to a single token.
 */
function squashTokens (tokens) {
  var squashedTokens = [];

  var token, lastToken;
  for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
    token = tokens[i];

    if (token) {
      if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
        lastToken[1] += token[1];
        lastToken[3] = token[3];
      } else {
        squashedTokens.push(token);
        lastToken = token;
      }
    }
  }

  return squashedTokens;
}

/**
 * Forms the given array of `tokens` into a nested tree structure where
 * tokens that represent a section have two additional items: 1) an array of
 * all tokens that appear in that section and 2) the index in the original
 * template that represents the end of that section.
 */
function nestTokens (tokens) {
  var nestedTokens = [];
  var collector = nestedTokens;
  var sections = [];

  var token, section;
  for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
    token = tokens[i];

    switch (token[0]) {
      case '#':
      case '^':
        collector.push(token);
        sections.push(token);
        collector = token[4] = [];
        break;
      case '/':
        section = sections.pop();
        section[5] = token[2];
        collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
        break;
      default:
        collector.push(token);
    }
  }

  return nestedTokens;
}

/**
 * A simple string scanner that is used by the template parser to find
 * tokens in template strings.
 */
function Scanner (string) {
  this.string = string;
  this.tail = string;
  this.pos = 0;
}

/**
 * Returns `true` if the tail is empty (end of string).
 */
Scanner.prototype.eos = function eos () {
  return this.tail === '';
};

/**
 * Tries to match the given regular expression at the current position.
 * Returns the matched text if it can match, the empty string otherwise.
 */
Scanner.prototype.scan = function scan (re) {
  var match = this.tail.match(re);

  if (!match || match.index !== 0)
    return '';

  var string = match[0];

  this.tail = this.tail.substring(string.length);
  this.pos += string.length;

  return string;
};

/**
 * Skips all text until the given regular expression can be matched. Returns
 * the skipped string, which is the entire tail if no match can be made.
 */
Scanner.prototype.scanUntil = function scanUntil (re) {
  var index = this.tail.search(re), match;

  switch (index) {
    case -1:
      match = this.tail;
      this.tail = '';
      break;
    case 0:
      match = '';
      break;
    default:
      match = this.tail.substring(0, index);
      this.tail = this.tail.substring(index);
  }

  this.pos += match.length;

  return match;
};

/**
 * Represents a rendering context by wrapping a view object and
 * maintaining a reference to the parent context.
 */
function Context (view, parentContext) {
  this.view = view;
  this.cache = { '.': this.view };
  this.parent = parentContext;
}

/**
 * Creates a new context using the given view with this context
 * as the parent.
 */
Context.prototype.push = function push (view) {
  return new Context(view, this);
};

/**
 * Returns the value of the given name in this context, traversing
 * up the context hierarchy if the value is absent in this context's view.
 */
Context.prototype.lookup = function lookup (name) {
  var cache = this.cache;

  var value;
  if (cache.hasOwnProperty(name)) {
    value = cache[name];
  } else {
    var context = this, intermediateValue, names, index, lookupHit = false;

    while (context) {
      if (name.indexOf('.') > 0) {
        intermediateValue = context.view;
        names = name.split('.');
        index = 0;

        /**
         * Using the dot notion path in `name`, we descend through the
         * nested objects.
         *
         * To be certain that the lookup has been successful, we have to
         * check if the last object in the path actually has the property
         * we are looking for. We store the result in `lookupHit`.
         *
         * This is specially necessary for when the value has been set to
         * `undefined` and we want to avoid looking up parent contexts.
         *
         * In the case where dot notation is used, we consider the lookup
         * to be successful even if the last "object" in the path is
         * not actually an object but a primitive (e.g., a string, or an
         * integer), because it is sometimes useful to access a property
         * of an autoboxed primitive, such as the length of a string.
         **/
        while (intermediateValue != null && index < names.length) {
          if (index === names.length - 1)
            lookupHit = (
              hasProperty(intermediateValue, names[index])
              || primitiveHasOwnProperty(intermediateValue, names[index])
            );

          intermediateValue = intermediateValue[names[index++]];
        }
      } else {
        intermediateValue = context.view[name];

        /**
         * Only checking against `hasProperty`, which always returns `false` if
         * `context.view` is not an object. Deliberately omitting the check
         * against `primitiveHasOwnProperty` if dot notation is not used.
         *
         * Consider this example:
         * ```
         * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
         * ```
         *
         * If we were to check also against `primitiveHasOwnProperty`, as we do
         * in the dot notation case, then render call would return:
         *
         * "The length of a football field is 9."
         *
         * rather than the expected:
         *
         * "The length of a football field is 100 yards."
         **/
        lookupHit = hasProperty(context.view, name);
      }

      if (lookupHit) {
        value = intermediateValue;
        break;
      }

      context = context.parent;
    }

    cache[name] = value;
  }

  if (isFunction$2(value))
    value = value.call(this.view);

  return value;
};

/**
 * A Writer knows how to take a stream of tokens and render them to a
 * string, given a context. It also maintains a cache of templates to
 * avoid the need to parse the same template twice.
 */
function Writer () {
  this.templateCache = {
    _cache: {},
    set: function set (key, value) {
      this._cache[key] = value;
    },
    get: function get (key) {
      return this._cache[key];
    },
    clear: function clear () {
      this._cache = {};
    }
  };
}

/**
 * Clears all cached templates in this writer.
 */
Writer.prototype.clearCache = function clearCache () {
  if (typeof this.templateCache !== 'undefined') {
    this.templateCache.clear();
  }
};

/**
 * Parses and caches the given `template` according to the given `tags` or
 * `mustache.tags` if `tags` is omitted,  and returns the array of tokens
 * that is generated from the parse.
 */
Writer.prototype.parse = function parse (template, tags) {
  var cache = this.templateCache;
  var cacheKey = template + ':' + (tags || mustache.tags).join(':');
  var isCacheEnabled = typeof cache !== 'undefined';
  var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;

  if (tokens == undefined) {
    tokens = parseTemplate(template, tags);
    isCacheEnabled && cache.set(cacheKey, tokens);
  }
  return tokens;
};

/**
 * High-level method that is used to render the given `template` with
 * the given `view`.
 *
 * The optional `partials` argument may be an object that contains the
 * names and templates of partials that are used in the template. It may
 * also be a function that is used to load partial templates on the fly
 * that takes a single argument: the name of the partial.
 *
 * If the optional `config` argument is given here, then it should be an
 * object with a `tags` attribute or an `escape` attribute or both.
 * If an array is passed, then it will be interpreted the same way as
 * a `tags` attribute on a `config` object.
 *
 * The `tags` attribute of a `config` object must be an array with two
 * string values: the opening and closing tags used in the template (e.g.
 * [ "<%", "%>" ]). The default is to mustache.tags.
 *
 * The `escape` attribute of a `config` object must be a function which
 * accepts a string as input and outputs a safely escaped string.
 * If an `escape` function is not provided, then an HTML-safe string
 * escaping function is used as the default.
 */
Writer.prototype.render = function render (template, view, partials, config) {
  var tags = this.getConfigTags(config);
  var tokens = this.parse(template, tags);
  var context = (view instanceof Context) ? view : new Context(view, undefined);
  return this.renderTokens(tokens, context, partials, template, config);
};

/**
 * Low-level method that renders the given array of `tokens` using
 * the given `context` and `partials`.
 *
 * Note: The `originalTemplate` is only ever used to extract the portion
 * of the original template that was contained in a higher-order section.
 * If the template doesn't use higher-order sections, this argument may
 * be omitted.
 */
Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) {
  var buffer = '';

  var token, symbol, value;
  for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
    value = undefined;
    token = tokens[i];
    symbol = token[0];

    if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config);
    else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config);
    else if (symbol === '>') value = this.renderPartial(token, context, partials, config);
    else if (symbol === '&') value = this.unescapedValue(token, context);
    else if (symbol === 'name') value = this.escapedValue(token, context, config);
    else if (symbol === 'text') value = this.rawValue(token);

    if (value !== undefined)
      buffer += value;
  }

  return buffer;
};

Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) {
  var self = this;
  var buffer = '';
  var value = context.lookup(token[1]);

  // This function is used to render an arbitrary template
  // in the current context by higher-order sections.
  function subRender (template) {
    return self.render(template, context, partials, config);
  }

  if (!value) return;

  if (isArray$3(value)) {
    for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
      buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config);
    }
  } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
    buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);
  } else if (isFunction$2(value)) {
    if (typeof originalTemplate !== 'string')
      throw new Error('Cannot use higher-order sections without the original template');

    // Extract the portion of the original template that the section contains.
    value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);

    if (value != null)
      buffer += value;
  } else {
    buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);
  }
  return buffer;
};

Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) {
  var value = context.lookup(token[1]);

  // Use JavaScript's definition of falsy. Include empty arrays.
  // See https://github.com/janl/mustache.js/issues/186
  if (!value || (isArray$3(value) && value.length === 0))
    return this.renderTokens(token[4], context, partials, originalTemplate, config);
};

Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {
  var filteredIndentation = indentation.replace(/[^ \t]/g, '');
  var partialByNl = partial.split('\n');
  for (var i = 0; i < partialByNl.length; i++) {
    if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {
      partialByNl[i] = filteredIndentation + partialByNl[i];
    }
  }
  return partialByNl.join('\n');
};

Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) {
  if (!partials) return;
  var tags = this.getConfigTags(config);

  var value = isFunction$2(partials) ? partials(token[1]) : partials[token[1]];
  if (value != null) {
    var lineHasNonSpace = token[6];
    var tagIndex = token[5];
    var indentation = token[4];
    var indentedValue = value;
    if (tagIndex == 0 && indentation) {
      indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
    }
    var tokens = this.parse(indentedValue, tags);
    return this.renderTokens(tokens, context, partials, indentedValue, config);
  }
};

Writer.prototype.unescapedValue = function unescapedValue (token, context) {
  var value = context.lookup(token[1]);
  if (value != null)
    return value;
};

Writer.prototype.escapedValue = function escapedValue (token, context, config) {
  var escape = this.getConfigEscape(config) || mustache.escape;
  var value = context.lookup(token[1]);
  if (value != null)
    return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value);
};

Writer.prototype.rawValue = function rawValue (token) {
  return token[1];
};

Writer.prototype.getConfigTags = function getConfigTags (config) {
  if (isArray$3(config)) {
    return config;
  }
  else if (config && typeof config === 'object') {
    return config.tags;
  }
  else {
    return undefined;
  }
};

Writer.prototype.getConfigEscape = function getConfigEscape (config) {
  if (config && typeof config === 'object' && !isArray$3(config)) {
    return config.escape;
  }
  else {
    return undefined;
  }
};

var mustache = {
  name: 'mustache.js',
  version: '4.2.0',
  tags: [ '{{', '}}' ],
  clearCache: undefined,
  escape: undefined,
  parse: undefined,
  render: undefined,
  Scanner: undefined,
  Context: undefined,
  Writer: undefined,
  /**
   * Allows a user to override the default caching strategy, by providing an
   * object with set, get and clear methods. This can also be used to disable
   * the cache by setting it to the literal `undefined`.
   */
  set templateCache (cache) {
    defaultWriter.templateCache = cache;
  },
  /**
   * Gets the default or overridden caching object from the default writer.
   */
  get templateCache () {
    return defaultWriter.templateCache;
  }
};

// All high-level mustache.* functions use this writer.
var defaultWriter = new Writer();

/**
 * Clears all cached templates in the default writer.
 */
mustache.clearCache = function clearCache () {
  return defaultWriter.clearCache();
};

/**
 * Parses and caches the given template in the default writer and returns the
 * array of tokens it contains. Doing this ahead of time avoids the need to
 * parse templates on the fly as they are rendered.
 */
mustache.parse = function parse (template, tags) {
  return defaultWriter.parse(template, tags);
};

/**
 * Renders the `template` with the given `view`, `partials`, and `config`
 * using the default writer.
 */
mustache.render = function render (template, view, partials, config) {
  if (typeof template !== 'string') {
    throw new TypeError('Invalid template! Template should be a "string" ' +
                        'but "' + typeStr(template) + '" was given as the first ' +
                        'argument for mustache#render(template, view, partials)');
  }

  return defaultWriter.render(template, view, partials, config);
};

// Export the escaping function so that the user may override it.
// See https://github.com/janl/mustache.js/issues/244
mustache.escape = escapeHtml;

// Export these mainly for testing, but also for advanced usage.
mustache.Scanner = Scanner;
mustache.Context = Context;
mustache.Writer = Writer;

var isMergeableObject = function isMergeableObject(value) {
  return isNonNullObject(value) && !isSpecial(value);
};
function isNonNullObject(value) {
  return !!value && typeof value === 'object';
}
function isSpecial(value) {
  var stringValue = Object.prototype.toString.call(value);
  return stringValue === '[object RegExp]' || stringValue === '[object Date]' || isReactElement(value);
}

// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
function isReactElement(value) {
  return value.$$typeof === REACT_ELEMENT_TYPE;
}
function emptyTarget(val) {
  return Array.isArray(val) ? [] : {};
}
function cloneUnlessOtherwiseSpecified(value, options) {
  return options.clone !== false && options.isMergeableObject(value) ? deepmerge$1(emptyTarget(value), value, options) : value;
}
function defaultArrayMerge(target, source, options) {
  return target.concat(source).map(function (element) {
    return cloneUnlessOtherwiseSpecified(element, options);
  });
}
function mergeObject(target, source, options) {
  var destination = {};
  if (options.isMergeableObject(target)) {
    Object.keys(target).forEach(function (key) {
      destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
    });
  }
  Object.keys(source).forEach(function (key) {
    if (!options.isMergeableObject(source[key]) || !target[key]) {
      destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
    } else {
      destination[key] = deepmerge$1(target[key], source[key], options);
    }
  });
  return destination;
}
function deepmerge$1(target, source, options) {
  options = options || {};
  options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  var sourceIsArray = Array.isArray(source);
  var targetIsArray = Array.isArray(target);
  var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  if (!sourceAndTargetTypesMatch) {
    return cloneUnlessOtherwiseSpecified(source, options);
  } else if (sourceIsArray) {
    return options.arrayMerge(target, source, options);
  } else {
    return mergeObject(target, source, options);
  }
}
deepmerge$1.all = function deepmergeAll(array, options) {
  if (!Array.isArray(array)) {
    throw new Error('first argument should be an array');
  }
  return array.reduce(function (prev, next) {
    return deepmerge$1(prev, next, options);
  }, {});
};
var deepmerge_1 = deepmerge$1;

var react$1 = {exports: {}};

var react_development = {exports: {}};

/**
 * @license React
 * react.development.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.
 */
react_development.exports;

(function (module, exports) {

	{
	  (function () {

	    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
	    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function') {
	      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
	    }
	    var ReactVersion = '18.2.0';

	    // ATTENTION
	    // When adding new symbols to this file,
	    // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
	    // The Symbol used to tag the ReactElement-like types.
	    var REACT_ELEMENT_TYPE = Symbol.for('react.element');
	    var REACT_PORTAL_TYPE = Symbol.for('react.portal');
	    var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
	    var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
	    var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
	    var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
	    var REACT_CONTEXT_TYPE = Symbol.for('react.context');
	    var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
	    var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
	    var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
	    var REACT_MEMO_TYPE = Symbol.for('react.memo');
	    var REACT_LAZY_TYPE = Symbol.for('react.lazy');
	    var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
	    var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
	    var FAUX_ITERATOR_SYMBOL = '@@iterator';
	    function getIteratorFn(maybeIterable) {
	      if (maybeIterable === null || typeof maybeIterable !== 'object') {
	        return null;
	      }
	      var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
	      if (typeof maybeIterator === 'function') {
	        return maybeIterator;
	      }
	      return null;
	    }

	    /**
	     * Keeps track of the current dispatcher.
	     */
	    var ReactCurrentDispatcher = {
	      /**
	       * @internal
	       * @type {ReactComponent}
	       */
	      current: null
	    };

	    /**
	     * Keeps track of the current batch's configuration such as how long an update
	     * should suspend for if it needs to.
	     */
	    var ReactCurrentBatchConfig = {
	      transition: null
	    };
	    var ReactCurrentActQueue = {
	      current: null,
	      // Used to reproduce behavior of `batchedUpdates` in legacy mode.
	      isBatchingLegacy: false,
	      didScheduleLegacyUpdate: false
	    };

	    /**
	     * Keeps track of the current owner.
	     *
	     * The current owner is the component who should own any components that are
	     * currently being constructed.
	     */
	    var ReactCurrentOwner = {
	      /**
	       * @internal
	       * @type {ReactComponent}
	       */
	      current: null
	    };
	    var ReactDebugCurrentFrame = {};
	    var currentExtraStackFrame = null;
	    function setExtraStackFrame(stack) {
	      {
	        currentExtraStackFrame = stack;
	      }
	    }
	    {
	      ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
	        {
	          currentExtraStackFrame = stack;
	        }
	      }; // Stack implementation injected by the current renderer.

	      ReactDebugCurrentFrame.getCurrentStack = null;
	      ReactDebugCurrentFrame.getStackAddendum = function () {
	        var stack = ''; // Add an extra top frame while an element is being validated

	        if (currentExtraStackFrame) {
	          stack += currentExtraStackFrame;
	        } // Delegate to the injected renderer-specific implementation

	        var impl = ReactDebugCurrentFrame.getCurrentStack;
	        if (impl) {
	          stack += impl() || '';
	        }
	        return stack;
	      };
	    }

	    // -----------------------------------------------------------------------------

	    var enableScopeAPI = false; // Experimental Create Event Handle API.
	    var enableCacheElement = false;
	    var enableTransitionTracing = false; // No known bugs, but needs performance testing

	    var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
	    // stuff. Intended to enable React core members to more easily debug scheduling
	    // issues in DEV builds.

	    var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

	    var ReactSharedInternals = {
	      ReactCurrentDispatcher: ReactCurrentDispatcher,
	      ReactCurrentBatchConfig: ReactCurrentBatchConfig,
	      ReactCurrentOwner: ReactCurrentOwner
	    };
	    {
	      ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
	      ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
	    }

	    // by calls to these methods by a Babel plugin.
	    //
	    // In PROD (or in packages without access to React internals),
	    // they are left as they are instead.

	    function warn(format) {
	      {
	        {
	          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
	            args[_key - 1] = arguments[_key];
	          }
	          printWarning('warn', format, args);
	        }
	      }
	    }
	    function error(format) {
	      {
	        {
	          for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
	            args[_key2 - 1] = arguments[_key2];
	          }
	          printWarning('error', format, args);
	        }
	      }
	    }
	    function printWarning(level, format, args) {
	      // When changing this logic, you might want to also
	      // update consoleWithStackDev.www.js as well.
	      {
	        var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
	        var stack = ReactDebugCurrentFrame.getStackAddendum();
	        if (stack !== '') {
	          format += '%s';
	          args = args.concat([stack]);
	        } // eslint-disable-next-line react-internal/safe-string-coercion

	        var argsWithFormat = args.map(function (item) {
	          return String(item);
	        }); // Careful: RN currently depends on this prefix

	        argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
	        // breaks IE9: https://github.com/facebook/react/issues/13610
	        // eslint-disable-next-line react-internal/no-production-logging

	        Function.prototype.apply.call(console[level], console, argsWithFormat);
	      }
	    }
	    var didWarnStateUpdateForUnmountedComponent = {};
	    function warnNoop(publicInstance, callerName) {
	      {
	        var _constructor = publicInstance.constructor;
	        var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
	        var warningKey = componentName + "." + callerName;
	        if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
	          return;
	        }
	        error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
	        didWarnStateUpdateForUnmountedComponent[warningKey] = true;
	      }
	    }
	    /**
	     * This is the abstract API for an update queue.
	     */

	    var ReactNoopUpdateQueue = {
	      /**
	       * Checks whether or not this composite component is mounted.
	       * @param {ReactClass} publicInstance The instance we want to test.
	       * @return {boolean} True if mounted, false otherwise.
	       * @protected
	       * @final
	       */
	      isMounted: function (publicInstance) {
	        return false;
	      },
	      /**
	       * Forces an update. This should only be invoked when it is known with
	       * certainty that we are **not** in a DOM transaction.
	       *
	       * You may want to call this when you know that some deeper aspect of the
	       * component's state has changed but `setState` was not called.
	       *
	       * This will not invoke `shouldComponentUpdate`, but it will invoke
	       * `componentWillUpdate` and `componentDidUpdate`.
	       *
	       * @param {ReactClass} publicInstance The instance that should rerender.
	       * @param {?function} callback Called after component is updated.
	       * @param {?string} callerName name of the calling function in the public API.
	       * @internal
	       */
	      enqueueForceUpdate: function (publicInstance, callback, callerName) {
	        warnNoop(publicInstance, 'forceUpdate');
	      },
	      /**
	       * Replaces all of the state. Always use this or `setState` to mutate state.
	       * You should treat `this.state` as immutable.
	       *
	       * There is no guarantee that `this.state` will be immediately updated, so
	       * accessing `this.state` after calling this method may return the old value.
	       *
	       * @param {ReactClass} publicInstance The instance that should rerender.
	       * @param {object} completeState Next state.
	       * @param {?function} callback Called after component is updated.
	       * @param {?string} callerName name of the calling function in the public API.
	       * @internal
	       */
	      enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
	        warnNoop(publicInstance, 'replaceState');
	      },
	      /**
	       * Sets a subset of the state. This only exists because _pendingState is
	       * internal. This provides a merging strategy that is not available to deep
	       * properties which is confusing. TODO: Expose pendingState or don't use it
	       * during the merge.
	       *
	       * @param {ReactClass} publicInstance The instance that should rerender.
	       * @param {object} partialState Next partial state to be merged with state.
	       * @param {?function} callback Called after component is updated.
	       * @param {?string} Name of the calling function in the public API.
	       * @internal
	       */
	      enqueueSetState: function (publicInstance, partialState, callback, callerName) {
	        warnNoop(publicInstance, 'setState');
	      }
	    };
	    var assign = Object.assign;
	    var emptyObject = {};
	    {
	      Object.freeze(emptyObject);
	    }
	    /**
	     * Base class helpers for the updating state of a component.
	     */

	    function Component(props, context, updater) {
	      this.props = props;
	      this.context = context; // If a component has string refs, we will assign a different object later.

	      this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
	      // renderer.

	      this.updater = updater || ReactNoopUpdateQueue;
	    }
	    Component.prototype.isReactComponent = {};
	    /**
	     * Sets a subset of the state. Always use this to mutate
	     * state. You should treat `this.state` as immutable.
	     *
	     * There is no guarantee that `this.state` will be immediately updated, so
	     * accessing `this.state` after calling this method may return the old value.
	     *
	     * There is no guarantee that calls to `setState` will run synchronously,
	     * as they may eventually be batched together.  You can provide an optional
	     * callback that will be executed when the call to setState is actually
	     * completed.
	     *
	     * When a function is provided to setState, it will be called at some point in
	     * the future (not synchronously). It will be called with the up to date
	     * component arguments (state, props, context). These values can be different
	     * from this.* because your function may be called after receiveProps but before
	     * shouldComponentUpdate, and this new state, props, and context will not yet be
	     * assigned to this.
	     *
	     * @param {object|function} partialState Next partial state or function to
	     *        produce next partial state to be merged with current state.
	     * @param {?function} callback Called after state is updated.
	     * @final
	     * @protected
	     */

	    Component.prototype.setState = function (partialState, callback) {
	      if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
	        throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');
	      }
	      this.updater.enqueueSetState(this, partialState, callback, 'setState');
	    };
	    /**
	     * Forces an update. This should only be invoked when it is known with
	     * certainty that we are **not** in a DOM transaction.
	     *
	     * You may want to call this when you know that some deeper aspect of the
	     * component's state has changed but `setState` was not called.
	     *
	     * This will not invoke `shouldComponentUpdate`, but it will invoke
	     * `componentWillUpdate` and `componentDidUpdate`.
	     *
	     * @param {?function} callback Called after update is complete.
	     * @final
	     * @protected
	     */

	    Component.prototype.forceUpdate = function (callback) {
	      this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
	    };
	    /**
	     * Deprecated APIs. These APIs used to exist on classic React classes but since
	     * we would like to deprecate them, we're not going to move them over to this
	     * modern base class. Instead, we define a getter that warns if it's accessed.
	     */

	    {
	      var deprecatedAPIs = {
	        isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
	        replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
	      };
	      var defineDeprecationWarning = function (methodName, info) {
	        Object.defineProperty(Component.prototype, methodName, {
	          get: function () {
	            warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
	            return undefined;
	          }
	        });
	      };
	      for (var fnName in deprecatedAPIs) {
	        if (deprecatedAPIs.hasOwnProperty(fnName)) {
	          defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
	        }
	      }
	    }
	    function ComponentDummy() {}
	    ComponentDummy.prototype = Component.prototype;
	    /**
	     * Convenience component with default shallow equality check for sCU.
	     */

	    function PureComponent(props, context, updater) {
	      this.props = props;
	      this.context = context; // If a component has string refs, we will assign a different object later.

	      this.refs = emptyObject;
	      this.updater = updater || ReactNoopUpdateQueue;
	    }
	    var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
	    pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.

	    assign(pureComponentPrototype, Component.prototype);
	    pureComponentPrototype.isPureReactComponent = true;

	    // an immutable object with a single mutable value
	    function createRef() {
	      var refObject = {
	        current: null
	      };
	      {
	        Object.seal(refObject);
	      }
	      return refObject;
	    }
	    var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

	    function isArray(a) {
	      return isArrayImpl(a);
	    }

	    /*
	     * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
	     * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
	     *
	     * The functions in this module will throw an easier-to-understand,
	     * easier-to-debug exception with a clear errors message message explaining the
	     * problem. (Instead of a confusing exception thrown inside the implementation
	     * of the `value` object).
	     */
	    // $FlowFixMe only called in DEV, so void return is not possible.
	    function typeName(value) {
	      {
	        // toStringTag is needed for namespaced types like Temporal.Instant
	        var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
	        var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
	        return type;
	      }
	    } // $FlowFixMe only called in DEV, so void return is not possible.

	    function willCoercionThrow(value) {
	      {
	        try {
	          testStringCoercion(value);
	          return false;
	        } catch (e) {
	          return true;
	        }
	      }
	    }
	    function testStringCoercion(value) {
	      // If you ended up here by following an exception call stack, here's what's
	      // happened: you supplied an object or symbol value to React (as a prop, key,
	      // DOM attribute, CSS property, string ref, etc.) and when React tried to
	      // coerce it to a string using `'' + value`, an exception was thrown.
	      //
	      // The most common types that will cause this exception are `Symbol` instances
	      // and Temporal objects like `Temporal.Instant`. But any object that has a
	      // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
	      // exception. (Library authors do this to prevent users from using built-in
	      // numeric operators like `+` or comparison operators like `>=` because custom
	      // methods are needed to perform accurate arithmetic or comparison.)
	      //
	      // To fix the problem, coerce this object or symbol value to a string before
	      // passing it to React. The most reliable way is usually `String(value)`.
	      //
	      // To find which value is throwing, check the browser or debugger console.
	      // Before this exception was thrown, there should be `console.error` output
	      // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
	      // problem and how that type was used: key, atrribute, input value prop, etc.
	      // In most cases, this console output also shows the component and its
	      // ancestor components where the exception happened.
	      //
	      // eslint-disable-next-line react-internal/safe-string-coercion
	      return '' + value;
	    }
	    function checkKeyStringCoercion(value) {
	      {
	        if (willCoercionThrow(value)) {
	          error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
	          return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
	        }
	      }
	    }

	    function getWrappedName(outerType, innerType, wrapperName) {
	      var displayName = outerType.displayName;
	      if (displayName) {
	        return displayName;
	      }
	      var functionName = innerType.displayName || innerType.name || '';
	      return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
	    } // Keep in sync with react-reconciler/getComponentNameFromFiber

	    function getContextName(type) {
	      return type.displayName || 'Context';
	    } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.

	    function getComponentNameFromType(type) {
	      if (type == null) {
	        // Host root, text node or just invalid type.
	        return null;
	      }
	      {
	        if (typeof type.tag === 'number') {
	          error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
	        }
	      }
	      if (typeof type === 'function') {
	        return type.displayName || type.name || null;
	      }
	      if (typeof type === 'string') {
	        return type;
	      }
	      switch (type) {
	        case REACT_FRAGMENT_TYPE:
	          return 'Fragment';
	        case REACT_PORTAL_TYPE:
	          return 'Portal';
	        case REACT_PROFILER_TYPE:
	          return 'Profiler';
	        case REACT_STRICT_MODE_TYPE:
	          return 'StrictMode';
	        case REACT_SUSPENSE_TYPE:
	          return 'Suspense';
	        case REACT_SUSPENSE_LIST_TYPE:
	          return 'SuspenseList';
	      }
	      if (typeof type === 'object') {
	        switch (type.$$typeof) {
	          case REACT_CONTEXT_TYPE:
	            var context = type;
	            return getContextName(context) + '.Consumer';
	          case REACT_PROVIDER_TYPE:
	            var provider = type;
	            return getContextName(provider._context) + '.Provider';
	          case REACT_FORWARD_REF_TYPE:
	            return getWrappedName(type, type.render, 'ForwardRef');
	          case REACT_MEMO_TYPE:
	            var outerName = type.displayName || null;
	            if (outerName !== null) {
	              return outerName;
	            }
	            return getComponentNameFromType(type.type) || 'Memo';
	          case REACT_LAZY_TYPE:
	            {
	              var lazyComponent = type;
	              var payload = lazyComponent._payload;
	              var init = lazyComponent._init;
	              try {
	                return getComponentNameFromType(init(payload));
	              } catch (x) {
	                return null;
	              }
	            }

	          // eslint-disable-next-line no-fallthrough
	        }
	      }

	      return null;
	    }
	    var hasOwnProperty = Object.prototype.hasOwnProperty;
	    var RESERVED_PROPS = {
	      key: true,
	      ref: true,
	      __self: true,
	      __source: true
	    };
	    var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
	    {
	      didWarnAboutStringRefs = {};
	    }
	    function hasValidRef(config) {
	      {
	        if (hasOwnProperty.call(config, 'ref')) {
	          var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
	          if (getter && getter.isReactWarning) {
	            return false;
	          }
	        }
	      }
	      return config.ref !== undefined;
	    }
	    function hasValidKey(config) {
	      {
	        if (hasOwnProperty.call(config, 'key')) {
	          var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
	          if (getter && getter.isReactWarning) {
	            return false;
	          }
	        }
	      }
	      return config.key !== undefined;
	    }
	    function defineKeyPropWarningGetter(props, displayName) {
	      var warnAboutAccessingKey = function () {
	        {
	          if (!specialPropKeyWarningShown) {
	            specialPropKeyWarningShown = true;
	            error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
	          }
	        }
	      };
	      warnAboutAccessingKey.isReactWarning = true;
	      Object.defineProperty(props, 'key', {
	        get: warnAboutAccessingKey,
	        configurable: true
	      });
	    }
	    function defineRefPropWarningGetter(props, displayName) {
	      var warnAboutAccessingRef = function () {
	        {
	          if (!specialPropRefWarningShown) {
	            specialPropRefWarningShown = true;
	            error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
	          }
	        }
	      };
	      warnAboutAccessingRef.isReactWarning = true;
	      Object.defineProperty(props, 'ref', {
	        get: warnAboutAccessingRef,
	        configurable: true
	      });
	    }
	    function warnIfStringRefCannotBeAutoConverted(config) {
	      {
	        if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
	          var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
	          if (!didWarnAboutStringRefs[componentName]) {
	            error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
	            didWarnAboutStringRefs[componentName] = true;
	          }
	        }
	      }
	    }
	    /**
	     * Factory method to create a new React element. This no longer adheres to
	     * the class pattern, so do not use new to call it. Also, instanceof check
	     * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
	     * if something is a React Element.
	     *
	     * @param {*} type
	     * @param {*} props
	     * @param {*} key
	     * @param {string|object} ref
	     * @param {*} owner
	     * @param {*} self A *temporary* helper to detect places where `this` is
	     * different from the `owner` when React.createElement is called, so that we
	     * can warn. We want to get rid of owner and replace string `ref`s with arrow
	     * functions, and as long as `this` and owner are the same, there will be no
	     * change in behavior.
	     * @param {*} source An annotation object (added by a transpiler or otherwise)
	     * indicating filename, line number, and/or other information.
	     * @internal
	     */

	    var ReactElement = function (type, key, ref, self, source, owner, props) {
	      var element = {
	        // This tag allows us to uniquely identify this as a React Element
	        $$typeof: REACT_ELEMENT_TYPE,
	        // Built-in properties that belong on the element
	        type: type,
	        key: key,
	        ref: ref,
	        props: props,
	        // Record the component responsible for creating this element.
	        _owner: owner
	      };
	      {
	        // The validation flag is currently mutative. We put it on
	        // an external backing store so that we can freeze the whole object.
	        // This can be replaced with a WeakMap once they are implemented in
	        // commonly used development environments.
	        element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
	        // the validation flag non-enumerable (where possible, which should
	        // include every environment we run tests in), so the test framework
	        // ignores it.

	        Object.defineProperty(element._store, 'validated', {
	          configurable: false,
	          enumerable: false,
	          writable: true,
	          value: false
	        }); // self and source are DEV only properties.

	        Object.defineProperty(element, '_self', {
	          configurable: false,
	          enumerable: false,
	          writable: false,
	          value: self
	        }); // Two elements created in two different places should be considered
	        // equal for testing purposes and therefore we hide it from enumeration.

	        Object.defineProperty(element, '_source', {
	          configurable: false,
	          enumerable: false,
	          writable: false,
	          value: source
	        });
	        if (Object.freeze) {
	          Object.freeze(element.props);
	          Object.freeze(element);
	        }
	      }
	      return element;
	    };
	    /**
	     * Create and return a new ReactElement of the given type.
	     * See https://reactjs.org/docs/react-api.html#createelement
	     */

	    function createElement(type, config, children) {
	      var propName; // Reserved names are extracted

	      var props = {};
	      var key = null;
	      var ref = null;
	      var self = null;
	      var source = null;
	      if (config != null) {
	        if (hasValidRef(config)) {
	          ref = config.ref;
	          {
	            warnIfStringRefCannotBeAutoConverted(config);
	          }
	        }
	        if (hasValidKey(config)) {
	          {
	            checkKeyStringCoercion(config.key);
	          }
	          key = '' + config.key;
	        }
	        self = config.__self === undefined ? null : config.__self;
	        source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object

	        for (propName in config) {
	          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
	            props[propName] = config[propName];
	          }
	        }
	      } // Children can be more than one argument, and those are transferred onto
	      // the newly allocated props object.

	      var childrenLength = arguments.length - 2;
	      if (childrenLength === 1) {
	        props.children = children;
	      } else if (childrenLength > 1) {
	        var childArray = Array(childrenLength);
	        for (var i = 0; i < childrenLength; i++) {
	          childArray[i] = arguments[i + 2];
	        }
	        {
	          if (Object.freeze) {
	            Object.freeze(childArray);
	          }
	        }
	        props.children = childArray;
	      } // Resolve default props

	      if (type && type.defaultProps) {
	        var defaultProps = type.defaultProps;
	        for (propName in defaultProps) {
	          if (props[propName] === undefined) {
	            props[propName] = defaultProps[propName];
	          }
	        }
	      }
	      {
	        if (key || ref) {
	          var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
	          if (key) {
	            defineKeyPropWarningGetter(props, displayName);
	          }
	          if (ref) {
	            defineRefPropWarningGetter(props, displayName);
	          }
	        }
	      }
	      return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
	    }
	    function cloneAndReplaceKey(oldElement, newKey) {
	      var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
	      return newElement;
	    }
	    /**
	     * Clone and return a new ReactElement using element as the starting point.
	     * See https://reactjs.org/docs/react-api.html#cloneelement
	     */

	    function cloneElement(element, config, children) {
	      if (element === null || element === undefined) {
	        throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
	      }
	      var propName; // Original props are copied

	      var props = assign({}, element.props); // Reserved names are extracted

	      var key = element.key;
	      var ref = element.ref; // Self is preserved since the owner is preserved.

	      var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
	      // transpiler, and the original source is probably a better indicator of the
	      // true owner.

	      var source = element._source; // Owner will be preserved, unless ref is overridden

	      var owner = element._owner;
	      if (config != null) {
	        if (hasValidRef(config)) {
	          // Silently steal the ref from the parent.
	          ref = config.ref;
	          owner = ReactCurrentOwner.current;
	        }
	        if (hasValidKey(config)) {
	          {
	            checkKeyStringCoercion(config.key);
	          }
	          key = '' + config.key;
	        } // Remaining properties override existing props

	        var defaultProps;
	        if (element.type && element.type.defaultProps) {
	          defaultProps = element.type.defaultProps;
	        }
	        for (propName in config) {
	          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
	            if (config[propName] === undefined && defaultProps !== undefined) {
	              // Resolve default props
	              props[propName] = defaultProps[propName];
	            } else {
	              props[propName] = config[propName];
	            }
	          }
	        }
	      } // Children can be more than one argument, and those are transferred onto
	      // the newly allocated props object.

	      var childrenLength = arguments.length - 2;
	      if (childrenLength === 1) {
	        props.children = children;
	      } else if (childrenLength > 1) {
	        var childArray = Array(childrenLength);
	        for (var i = 0; i < childrenLength; i++) {
	          childArray[i] = arguments[i + 2];
	        }
	        props.children = childArray;
	      }
	      return ReactElement(element.type, key, ref, self, source, owner, props);
	    }
	    /**
	     * Verifies the object is a ReactElement.
	     * See https://reactjs.org/docs/react-api.html#isvalidelement
	     * @param {?object} object
	     * @return {boolean} True if `object` is a ReactElement.
	     * @final
	     */

	    function isValidElement(object) {
	      return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
	    }
	    var SEPARATOR = '.';
	    var SUBSEPARATOR = ':';
	    /**
	     * Escape and wrap key so it is safe to use as a reactid
	     *
	     * @param {string} key to be escaped.
	     * @return {string} the escaped key.
	     */

	    function escape(key) {
	      var escapeRegex = /[=:]/g;
	      var escaperLookup = {
	        '=': '=0',
	        ':': '=2'
	      };
	      var escapedString = key.replace(escapeRegex, function (match) {
	        return escaperLookup[match];
	      });
	      return '$' + escapedString;
	    }
	    /**
	     * TODO: Test that a single child and an array with one item have the same key
	     * pattern.
	     */

	    var didWarnAboutMaps = false;
	    var userProvidedKeyEscapeRegex = /\/+/g;
	    function escapeUserProvidedKey(text) {
	      return text.replace(userProvidedKeyEscapeRegex, '$&/');
	    }
	    /**
	     * Generate a key string that identifies a element within a set.
	     *
	     * @param {*} element A element that could contain a manual key.
	     * @param {number} index Index that is used if a manual key is not provided.
	     * @return {string}
	     */

	    function getElementKey(element, index) {
	      // Do some typechecking here since we call this blindly. We want to ensure
	      // that we don't block potential future ES APIs.
	      if (typeof element === 'object' && element !== null && element.key != null) {
	        // Explicit key
	        {
	          checkKeyStringCoercion(element.key);
	        }
	        return escape('' + element.key);
	      } // Implicit key determined by the index in the set

	      return index.toString(36);
	    }
	    function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
	      var type = typeof children;
	      if (type === 'undefined' || type === 'boolean') {
	        // All of the above are perceived as null.
	        children = null;
	      }
	      var invokeCallback = false;
	      if (children === null) {
	        invokeCallback = true;
	      } else {
	        switch (type) {
	          case 'string':
	          case 'number':
	            invokeCallback = true;
	            break;
	          case 'object':
	            switch (children.$$typeof) {
	              case REACT_ELEMENT_TYPE:
	              case REACT_PORTAL_TYPE:
	                invokeCallback = true;
	            }
	        }
	      }
	      if (invokeCallback) {
	        var _child = children;
	        var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
	        // so that it's consistent if the number of children grows:

	        var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
	        if (isArray(mappedChild)) {
	          var escapedChildKey = '';
	          if (childKey != null) {
	            escapedChildKey = escapeUserProvidedKey(childKey) + '/';
	          }
	          mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
	            return c;
	          });
	        } else if (mappedChild != null) {
	          if (isValidElement(mappedChild)) {
	            {
	              // The `if` statement here prevents auto-disabling of the safe
	              // coercion ESLint rule, so we must manually disable it below.
	              // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
	              if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
	                checkKeyStringCoercion(mappedChild.key);
	              }
	            }
	            mappedChild = cloneAndReplaceKey(mappedChild,
	            // Keep both the (mapped) and old keys if they differ, just as
	            // traverseAllChildren used to do for objects as children
	            escapedPrefix + (
	            // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
	            mappedChild.key && (!_child || _child.key !== mappedChild.key) ?
	            // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
	            // eslint-disable-next-line react-internal/safe-string-coercion
	            escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
	          }
	          array.push(mappedChild);
	        }
	        return 1;
	      }
	      var child;
	      var nextName;
	      var subtreeCount = 0; // Count of children found in the current subtree.

	      var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
	      if (isArray(children)) {
	        for (var i = 0; i < children.length; i++) {
	          child = children[i];
	          nextName = nextNamePrefix + getElementKey(child, i);
	          subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
	        }
	      } else {
	        var iteratorFn = getIteratorFn(children);
	        if (typeof iteratorFn === 'function') {
	          var iterableChildren = children;
	          {
	            // Warn about using Maps as children
	            if (iteratorFn === iterableChildren.entries) {
	              if (!didWarnAboutMaps) {
	                warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
	              }
	              didWarnAboutMaps = true;
	            }
	          }
	          var iterator = iteratorFn.call(iterableChildren);
	          var step;
	          var ii = 0;
	          while (!(step = iterator.next()).done) {
	            child = step.value;
	            nextName = nextNamePrefix + getElementKey(child, ii++);
	            subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
	          }
	        } else if (type === 'object') {
	          // eslint-disable-next-line react-internal/safe-string-coercion
	          var childrenString = String(children);
	          throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
	        }
	      }
	      return subtreeCount;
	    }

	    /**
	     * Maps children that are typically specified as `props.children`.
	     *
	     * See https://reactjs.org/docs/react-api.html#reactchildrenmap
	     *
	     * The provided mapFunction(child, index) will be called for each
	     * leaf child.
	     *
	     * @param {?*} children Children tree container.
	     * @param {function(*, int)} func The map function.
	     * @param {*} context Context for mapFunction.
	     * @return {object} Object containing the ordered map of results.
	     */
	    function mapChildren(children, func, context) {
	      if (children == null) {
	        return children;
	      }
	      var result = [];
	      var count = 0;
	      mapIntoArray(children, result, '', '', function (child) {
	        return func.call(context, child, count++);
	      });
	      return result;
	    }
	    /**
	     * Count the number of children that are typically specified as
	     * `props.children`.
	     *
	     * See https://reactjs.org/docs/react-api.html#reactchildrencount
	     *
	     * @param {?*} children Children tree container.
	     * @return {number} The number of children.
	     */

	    function countChildren(children) {
	      var n = 0;
	      mapChildren(children, function () {
	        n++; // Don't return anything
	      });

	      return n;
	    }

	    /**
	     * Iterates through children that are typically specified as `props.children`.
	     *
	     * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
	     *
	     * The provided forEachFunc(child, index) will be called for each
	     * leaf child.
	     *
	     * @param {?*} children Children tree container.
	     * @param {function(*, int)} forEachFunc
	     * @param {*} forEachContext Context for forEachContext.
	     */
	    function forEachChildren(children, forEachFunc, forEachContext) {
	      mapChildren(children, function () {
	        forEachFunc.apply(this, arguments); // Don't return anything.
	      }, forEachContext);
	    }
	    /**
	     * Flatten a children object (typically specified as `props.children`) and
	     * return an array with appropriately re-keyed children.
	     *
	     * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
	     */

	    function toArray(children) {
	      return mapChildren(children, function (child) {
	        return child;
	      }) || [];
	    }
	    /**
	     * Returns the first child in a collection of children and verifies that there
	     * is only one child in the collection.
	     *
	     * See https://reactjs.org/docs/react-api.html#reactchildrenonly
	     *
	     * The current implementation of this function assumes that a single child gets
	     * passed without a wrapper, but the purpose of this helper function is to
	     * abstract away the particular structure of children.
	     *
	     * @param {?object} children Child collection structure.
	     * @return {ReactElement} The first and only `ReactElement` contained in the
	     * structure.
	     */

	    function onlyChild(children) {
	      if (!isValidElement(children)) {
	        throw new Error('React.Children.only expected to receive a single React element child.');
	      }
	      return children;
	    }
	    function createContext(defaultValue) {
	      // TODO: Second argument used to be an optional `calculateChangedBits`
	      // function. Warn to reserve for future use?
	      var context = {
	        $$typeof: REACT_CONTEXT_TYPE,
	        // As a workaround to support multiple concurrent renderers, we categorize
	        // some renderers as primary and others as secondary. We only expect
	        // there to be two concurrent renderers at most: React Native (primary) and
	        // Fabric (secondary); React DOM (primary) and React ART (secondary).
	        // Secondary renderers store their context values on separate fields.
	        _currentValue: defaultValue,
	        _currentValue2: defaultValue,
	        // Used to track how many concurrent renderers this context currently
	        // supports within in a single renderer. Such as parallel server rendering.
	        _threadCount: 0,
	        // These are circular
	        Provider: null,
	        Consumer: null,
	        // Add these to use same hidden class in VM as ServerContext
	        _defaultValue: null,
	        _globalName: null
	      };
	      context.Provider = {
	        $$typeof: REACT_PROVIDER_TYPE,
	        _context: context
	      };
	      var hasWarnedAboutUsingNestedContextConsumers = false;
	      var hasWarnedAboutUsingConsumerProvider = false;
	      var hasWarnedAboutDisplayNameOnConsumer = false;
	      {
	        // A separate object, but proxies back to the original context object for
	        // backwards compatibility. It has a different $$typeof, so we can properly
	        // warn for the incorrect usage of Context as a Consumer.
	        var Consumer = {
	          $$typeof: REACT_CONTEXT_TYPE,
	          _context: context
	        }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here

	        Object.defineProperties(Consumer, {
	          Provider: {
	            get: function () {
	              if (!hasWarnedAboutUsingConsumerProvider) {
	                hasWarnedAboutUsingConsumerProvider = true;
	                error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
	              }
	              return context.Provider;
	            },
	            set: function (_Provider) {
	              context.Provider = _Provider;
	            }
	          },
	          _currentValue: {
	            get: function () {
	              return context._currentValue;
	            },
	            set: function (_currentValue) {
	              context._currentValue = _currentValue;
	            }
	          },
	          _currentValue2: {
	            get: function () {
	              return context._currentValue2;
	            },
	            set: function (_currentValue2) {
	              context._currentValue2 = _currentValue2;
	            }
	          },
	          _threadCount: {
	            get: function () {
	              return context._threadCount;
	            },
	            set: function (_threadCount) {
	              context._threadCount = _threadCount;
	            }
	          },
	          Consumer: {
	            get: function () {
	              if (!hasWarnedAboutUsingNestedContextConsumers) {
	                hasWarnedAboutUsingNestedContextConsumers = true;
	                error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
	              }
	              return context.Consumer;
	            }
	          },
	          displayName: {
	            get: function () {
	              return context.displayName;
	            },
	            set: function (displayName) {
	              if (!hasWarnedAboutDisplayNameOnConsumer) {
	                warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
	                hasWarnedAboutDisplayNameOnConsumer = true;
	              }
	            }
	          }
	        }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty

	        context.Consumer = Consumer;
	      }
	      {
	        context._currentRenderer = null;
	        context._currentRenderer2 = null;
	      }
	      return context;
	    }
	    var Uninitialized = -1;
	    var Pending = 0;
	    var Resolved = 1;
	    var Rejected = 2;
	    function lazyInitializer(payload) {
	      if (payload._status === Uninitialized) {
	        var ctor = payload._result;
	        var thenable = ctor(); // Transition to the next state.
	        // This might throw either because it's missing or throws. If so, we treat it
	        // as still uninitialized and try again next time. Which is the same as what
	        // happens if the ctor or any wrappers processing the ctor throws. This might
	        // end up fixing it if the resolution was a concurrency bug.

	        thenable.then(function (moduleObject) {
	          if (payload._status === Pending || payload._status === Uninitialized) {
	            // Transition to the next state.
	            var resolved = payload;
	            resolved._status = Resolved;
	            resolved._result = moduleObject;
	          }
	        }, function (error) {
	          if (payload._status === Pending || payload._status === Uninitialized) {
	            // Transition to the next state.
	            var rejected = payload;
	            rejected._status = Rejected;
	            rejected._result = error;
	          }
	        });
	        if (payload._status === Uninitialized) {
	          // In case, we're still uninitialized, then we're waiting for the thenable
	          // to resolve. Set it as pending in the meantime.
	          var pending = payload;
	          pending._status = Pending;
	          pending._result = thenable;
	        }
	      }
	      if (payload._status === Resolved) {
	        var moduleObject = payload._result;
	        {
	          if (moduleObject === undefined) {
	            error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' +
	            // Break up imports to avoid accidentally parsing them as dependencies.
	            'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
	          }
	        }
	        {
	          if (!('default' in moduleObject)) {
	            error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n  ' +
	            // Break up imports to avoid accidentally parsing them as dependencies.
	            'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
	          }
	        }
	        return moduleObject.default;
	      } else {
	        throw payload._result;
	      }
	    }
	    function lazy(ctor) {
	      var payload = {
	        // We use these fields to store the result.
	        _status: Uninitialized,
	        _result: ctor
	      };
	      var lazyType = {
	        $$typeof: REACT_LAZY_TYPE,
	        _payload: payload,
	        _init: lazyInitializer
	      };
	      {
	        // In production, this would just set it on the object.
	        var defaultProps;
	        var propTypes; // $FlowFixMe

	        Object.defineProperties(lazyType, {
	          defaultProps: {
	            configurable: true,
	            get: function () {
	              return defaultProps;
	            },
	            set: function (newDefaultProps) {
	              error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
	              defaultProps = newDefaultProps; // Match production behavior more closely:
	              // $FlowFixMe

	              Object.defineProperty(lazyType, 'defaultProps', {
	                enumerable: true
	              });
	            }
	          },
	          propTypes: {
	            configurable: true,
	            get: function () {
	              return propTypes;
	            },
	            set: function (newPropTypes) {
	              error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
	              propTypes = newPropTypes; // Match production behavior more closely:
	              // $FlowFixMe

	              Object.defineProperty(lazyType, 'propTypes', {
	                enumerable: true
	              });
	            }
	          }
	        });
	      }
	      return lazyType;
	    }
	    function forwardRef(render) {
	      {
	        if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
	          error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
	        } else if (typeof render !== 'function') {
	          error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
	        } else {
	          if (render.length !== 0 && render.length !== 2) {
	            error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
	          }
	        }
	        if (render != null) {
	          if (render.defaultProps != null || render.propTypes != null) {
	            error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
	          }
	        }
	      }
	      var elementType = {
	        $$typeof: REACT_FORWARD_REF_TYPE,
	        render: render
	      };
	      {
	        var ownName;
	        Object.defineProperty(elementType, 'displayName', {
	          enumerable: false,
	          configurable: true,
	          get: function () {
	            return ownName;
	          },
	          set: function (name) {
	            ownName = name; // The inner component shouldn't inherit this display name in most cases,
	            // because the component may be used elsewhere.
	            // But it's nice for anonymous functions to inherit the name,
	            // so that our component-stack generation logic will display their frames.
	            // An anonymous function generally suggests a pattern like:
	            //   React.forwardRef((props, ref) => {...});
	            // This kind of inner function is not used elsewhere so the side effect is okay.

	            if (!render.name && !render.displayName) {
	              render.displayName = name;
	            }
	          }
	        });
	      }
	      return elementType;
	    }
	    var REACT_MODULE_REFERENCE;
	    {
	      REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
	    }
	    function isValidElementType(type) {
	      if (typeof type === 'string' || typeof type === 'function') {
	        return true;
	      } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).

	      if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
	        return true;
	      }
	      if (typeof type === 'object' && type !== null) {
	        if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE ||
	        // This needs to include all possible module reference object
	        // types supported by any Flight configuration anywhere since
	        // we don't know which Flight build this will end up being used
	        // with.
	        type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
	          return true;
	        }
	      }
	      return false;
	    }
	    function memo(type, compare) {
	      {
	        if (!isValidElementType(type)) {
	          error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
	        }
	      }
	      var elementType = {
	        $$typeof: REACT_MEMO_TYPE,
	        type: type,
	        compare: compare === undefined ? null : compare
	      };
	      {
	        var ownName;
	        Object.defineProperty(elementType, 'displayName', {
	          enumerable: false,
	          configurable: true,
	          get: function () {
	            return ownName;
	          },
	          set: function (name) {
	            ownName = name; // The inner component shouldn't inherit this display name in most cases,
	            // because the component may be used elsewhere.
	            // But it's nice for anonymous functions to inherit the name,
	            // so that our component-stack generation logic will display their frames.
	            // An anonymous function generally suggests a pattern like:
	            //   React.memo((props) => {...});
	            // This kind of inner function is not used elsewhere so the side effect is okay.

	            if (!type.name && !type.displayName) {
	              type.displayName = name;
	            }
	          }
	        });
	      }
	      return elementType;
	    }
	    function resolveDispatcher() {
	      var dispatcher = ReactCurrentDispatcher.current;
	      {
	        if (dispatcher === null) {
	          error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
	        }
	      } // Will result in a null access error if accessed outside render phase. We
	      // intentionally don't throw our own error because this is in a hot path.
	      // Also helps ensure this is inlined.

	      return dispatcher;
	    }
	    function useContext(Context) {
	      var dispatcher = resolveDispatcher();
	      {
	        // TODO: add a more generic warning for invalid values.
	        if (Context._context !== undefined) {
	          var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
	          // and nobody should be using this in existing code.

	          if (realContext.Consumer === Context) {
	            error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
	          } else if (realContext.Provider === Context) {
	            error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
	          }
	        }
	      }
	      return dispatcher.useContext(Context);
	    }
	    function useState(initialState) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useState(initialState);
	    }
	    function useReducer(reducer, initialArg, init) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useReducer(reducer, initialArg, init);
	    }
	    function useRef(initialValue) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useRef(initialValue);
	    }
	    function useEffect(create, deps) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useEffect(create, deps);
	    }
	    function useInsertionEffect(create, deps) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useInsertionEffect(create, deps);
	    }
	    function useLayoutEffect(create, deps) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useLayoutEffect(create, deps);
	    }
	    function useCallback(callback, deps) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useCallback(callback, deps);
	    }
	    function useMemo(create, deps) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useMemo(create, deps);
	    }
	    function useImperativeHandle(ref, create, deps) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useImperativeHandle(ref, create, deps);
	    }
	    function useDebugValue(value, formatterFn) {
	      {
	        var dispatcher = resolveDispatcher();
	        return dispatcher.useDebugValue(value, formatterFn);
	      }
	    }
	    function useTransition() {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useTransition();
	    }
	    function useDeferredValue(value) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useDeferredValue(value);
	    }
	    function useId() {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useId();
	    }
	    function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
	      var dispatcher = resolveDispatcher();
	      return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
	    }

	    // Helpers to patch console.logs to avoid logging during side-effect free
	    // replaying on render function. This currently only patches the object
	    // lazily which won't cover if the log function was extracted eagerly.
	    // We could also eagerly patch the method.
	    var disabledDepth = 0;
	    var prevLog;
	    var prevInfo;
	    var prevWarn;
	    var prevError;
	    var prevGroup;
	    var prevGroupCollapsed;
	    var prevGroupEnd;
	    function disabledLog() {}
	    disabledLog.__reactDisabledLog = true;
	    function disableLogs() {
	      {
	        if (disabledDepth === 0) {
	          /* eslint-disable react-internal/no-production-logging */
	          prevLog = console.log;
	          prevInfo = console.info;
	          prevWarn = console.warn;
	          prevError = console.error;
	          prevGroup = console.group;
	          prevGroupCollapsed = console.groupCollapsed;
	          prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

	          var props = {
	            configurable: true,
	            enumerable: true,
	            value: disabledLog,
	            writable: true
	          }; // $FlowFixMe Flow thinks console is immutable.

	          Object.defineProperties(console, {
	            info: props,
	            log: props,
	            warn: props,
	            error: props,
	            group: props,
	            groupCollapsed: props,
	            groupEnd: props
	          });
	          /* eslint-enable react-internal/no-production-logging */
	        }

	        disabledDepth++;
	      }
	    }
	    function reenableLogs() {
	      {
	        disabledDepth--;
	        if (disabledDepth === 0) {
	          /* eslint-disable react-internal/no-production-logging */
	          var props = {
	            configurable: true,
	            enumerable: true,
	            writable: true
	          }; // $FlowFixMe Flow thinks console is immutable.

	          Object.defineProperties(console, {
	            log: assign({}, props, {
	              value: prevLog
	            }),
	            info: assign({}, props, {
	              value: prevInfo
	            }),
	            warn: assign({}, props, {
	              value: prevWarn
	            }),
	            error: assign({}, props, {
	              value: prevError
	            }),
	            group: assign({}, props, {
	              value: prevGroup
	            }),
	            groupCollapsed: assign({}, props, {
	              value: prevGroupCollapsed
	            }),
	            groupEnd: assign({}, props, {
	              value: prevGroupEnd
	            })
	          });
	          /* eslint-enable react-internal/no-production-logging */
	        }

	        if (disabledDepth < 0) {
	          error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
	        }
	      }
	    }
	    var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
	    var prefix;
	    function describeBuiltInComponentFrame(name, source, ownerFn) {
	      {
	        if (prefix === undefined) {
	          // Extract the VM specific prefix used by each line.
	          try {
	            throw Error();
	          } catch (x) {
	            var match = x.stack.trim().match(/\n( *(at )?)/);
	            prefix = match && match[1] || '';
	          }
	        } // We use the prefix to ensure our stacks line up with native stack frames.

	        return '\n' + prefix + name;
	      }
	    }
	    var reentry = false;
	    var componentFrameCache;
	    {
	      var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
	      componentFrameCache = new PossiblyWeakMap();
	    }
	    function describeNativeComponentFrame(fn, construct) {
	      // If something asked for a stack inside a fake render, it should get ignored.
	      if (!fn || reentry) {
	        return '';
	      }
	      {
	        var frame = componentFrameCache.get(fn);
	        if (frame !== undefined) {
	          return frame;
	        }
	      }
	      var control;
	      reentry = true;
	      var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

	      Error.prepareStackTrace = undefined;
	      var previousDispatcher;
	      {
	        previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
	        // for warnings.

	        ReactCurrentDispatcher$1.current = null;
	        disableLogs();
	      }
	      try {
	        // This should throw.
	        if (construct) {
	          // Something should be setting the props in the constructor.
	          var Fake = function () {
	            throw Error();
	          }; // $FlowFixMe

	          Object.defineProperty(Fake.prototype, 'props', {
	            set: function () {
	              // We use a throwing setter instead of frozen or non-writable props
	              // because that won't throw in a non-strict mode function.
	              throw Error();
	            }
	          });
	          if (typeof Reflect === 'object' && Reflect.construct) {
	            // We construct a different control for this case to include any extra
	            // frames added by the construct call.
	            try {
	              Reflect.construct(Fake, []);
	            } catch (x) {
	              control = x;
	            }
	            Reflect.construct(fn, [], Fake);
	          } else {
	            try {
	              Fake.call();
	            } catch (x) {
	              control = x;
	            }
	            fn.call(Fake.prototype);
	          }
	        } else {
	          try {
	            throw Error();
	          } catch (x) {
	            control = x;
	          }
	          fn();
	        }
	      } catch (sample) {
	        // This is inlined manually because closure doesn't do it for us.
	        if (sample && control && typeof sample.stack === 'string') {
	          // This extracts the first frame from the sample that isn't also in the control.
	          // Skipping one frame that we assume is the frame that calls the two.
	          var sampleLines = sample.stack.split('\n');
	          var controlLines = control.stack.split('\n');
	          var s = sampleLines.length - 1;
	          var c = controlLines.length - 1;
	          while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
	            // We expect at least one stack frame to be shared.
	            // Typically this will be the root most one. However, stack frames may be
	            // cut off due to maximum stack limits. In this case, one maybe cut off
	            // earlier than the other. We assume that the sample is longer or the same
	            // and there for cut off earlier. So we should find the root most frame in
	            // the sample somewhere in the control.
	            c--;
	          }
	          for (; s >= 1 && c >= 0; s--, c--) {
	            // Next we find the first one that isn't the same which should be the
	            // frame that called our sample function and the control.
	            if (sampleLines[s] !== controlLines[c]) {
	              // In V8, the first line is describing the message but other VMs don't.
	              // If we're about to return the first line, and the control is also on the same
	              // line, that's a pretty good indicator that our sample threw at same line as
	              // the control. I.e. before we entered the sample frame. So we ignore this result.
	              // This can happen if you passed a class to function component, or non-function.
	              if (s !== 1 || c !== 1) {
	                do {
	                  s--;
	                  c--; // We may still have similar intermediate frames from the construct call.
	                  // The next one that isn't the same should be our match though.

	                  if (c < 0 || sampleLines[s] !== controlLines[c]) {
	                    // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
	                    var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
	                    // but we have a user-provided "displayName"
	                    // splice it in to make the stack more readable.

	                    if (fn.displayName && _frame.includes('<anonymous>')) {
	                      _frame = _frame.replace('<anonymous>', fn.displayName);
	                    }
	                    {
	                      if (typeof fn === 'function') {
	                        componentFrameCache.set(fn, _frame);
	                      }
	                    } // Return the line we found.

	                    return _frame;
	                  }
	                } while (s >= 1 && c >= 0);
	              }
	              break;
	            }
	          }
	        }
	      } finally {
	        reentry = false;
	        {
	          ReactCurrentDispatcher$1.current = previousDispatcher;
	          reenableLogs();
	        }
	        Error.prepareStackTrace = previousPrepareStackTrace;
	      } // Fallback to just using the name if we couldn't make it throw.

	      var name = fn ? fn.displayName || fn.name : '';
	      var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
	      {
	        if (typeof fn === 'function') {
	          componentFrameCache.set(fn, syntheticFrame);
	        }
	      }
	      return syntheticFrame;
	    }
	    function describeFunctionComponentFrame(fn, source, ownerFn) {
	      {
	        return describeNativeComponentFrame(fn, false);
	      }
	    }
	    function shouldConstruct(Component) {
	      var prototype = Component.prototype;
	      return !!(prototype && prototype.isReactComponent);
	    }
	    function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
	      if (type == null) {
	        return '';
	      }
	      if (typeof type === 'function') {
	        {
	          return describeNativeComponentFrame(type, shouldConstruct(type));
	        }
	      }
	      if (typeof type === 'string') {
	        return describeBuiltInComponentFrame(type);
	      }
	      switch (type) {
	        case REACT_SUSPENSE_TYPE:
	          return describeBuiltInComponentFrame('Suspense');
	        case REACT_SUSPENSE_LIST_TYPE:
	          return describeBuiltInComponentFrame('SuspenseList');
	      }
	      if (typeof type === 'object') {
	        switch (type.$$typeof) {
	          case REACT_FORWARD_REF_TYPE:
	            return describeFunctionComponentFrame(type.render);
	          case REACT_MEMO_TYPE:
	            // Memo may contain any component type so we recursively resolve it.
	            return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
	          case REACT_LAZY_TYPE:
	            {
	              var lazyComponent = type;
	              var payload = lazyComponent._payload;
	              var init = lazyComponent._init;
	              try {
	                // Lazy may contain any component type so we recursively resolve it.
	                return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
	              } catch (x) {}
	            }
	        }
	      }
	      return '';
	    }
	    var loggedTypeFailures = {};
	    var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
	    function setCurrentlyValidatingElement(element) {
	      {
	        if (element) {
	          var owner = element._owner;
	          var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
	          ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
	        } else {
	          ReactDebugCurrentFrame$1.setExtraStackFrame(null);
	        }
	      }
	    }
	    function checkPropTypes(typeSpecs, values, location, componentName, element) {
	      {
	        // $FlowFixMe This is okay but Flow doesn't know it.
	        var has = Function.call.bind(hasOwnProperty);
	        for (var typeSpecName in typeSpecs) {
	          if (has(typeSpecs, typeSpecName)) {
	            var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
	            // fail the render phase where it didn't fail before. So we log it.
	            // After these have been cleaned up, we'll let them throw.

	            try {
	              // This is intentionally an invariant that gets caught. It's the same
	              // behavior as without this statement except with a better message.
	              if (typeof typeSpecs[typeSpecName] !== 'function') {
	                // eslint-disable-next-line react-internal/prod-error-codes
	                var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
	                err.name = 'Invariant Violation';
	                throw err;
	              }
	              error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
	            } catch (ex) {
	              error$1 = ex;
	            }
	            if (error$1 && !(error$1 instanceof Error)) {
	              setCurrentlyValidatingElement(element);
	              error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
	              setCurrentlyValidatingElement(null);
	            }
	            if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
	              // Only monitor this failure once because there tends to be a lot of the
	              // same error.
	              loggedTypeFailures[error$1.message] = true;
	              setCurrentlyValidatingElement(element);
	              error('Failed %s type: %s', location, error$1.message);
	              setCurrentlyValidatingElement(null);
	            }
	          }
	        }
	      }
	    }
	    function setCurrentlyValidatingElement$1(element) {
	      {
	        if (element) {
	          var owner = element._owner;
	          var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
	          setExtraStackFrame(stack);
	        } else {
	          setExtraStackFrame(null);
	        }
	      }
	    }
	    var propTypesMisspellWarningShown;
	    {
	      propTypesMisspellWarningShown = false;
	    }
	    function getDeclarationErrorAddendum() {
	      if (ReactCurrentOwner.current) {
	        var name = getComponentNameFromType(ReactCurrentOwner.current.type);
	        if (name) {
	          return '\n\nCheck the render method of `' + name + '`.';
	        }
	      }
	      return '';
	    }
	    function getSourceInfoErrorAddendum(source) {
	      if (source !== undefined) {
	        var fileName = source.fileName.replace(/^.*[\\\/]/, '');
	        var lineNumber = source.lineNumber;
	        return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
	      }
	      return '';
	    }
	    function getSourceInfoErrorAddendumForProps(elementProps) {
	      if (elementProps !== null && elementProps !== undefined) {
	        return getSourceInfoErrorAddendum(elementProps.__source);
	      }
	      return '';
	    }
	    /**
	     * Warn if there's no key explicitly set on dynamic arrays of children or
	     * object keys are not valid. This allows us to keep track of children between
	     * updates.
	     */

	    var ownerHasKeyUseWarning = {};
	    function getCurrentComponentErrorInfo(parentType) {
	      var info = getDeclarationErrorAddendum();
	      if (!info) {
	        var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
	        if (parentName) {
	          info = "\n\nCheck the top-level render call using <" + parentName + ">.";
	        }
	      }
	      return info;
	    }
	    /**
	     * Warn if the element doesn't have an explicit key assigned to it.
	     * This element is in an array. The array could grow and shrink or be
	     * reordered. All children that haven't already been validated are required to
	     * have a "key" property assigned to it. Error statuses are cached so a warning
	     * will only be shown once.
	     *
	     * @internal
	     * @param {ReactElement} element Element that requires a key.
	     * @param {*} parentType element's parent's type.
	     */

	    function validateExplicitKey(element, parentType) {
	      if (!element._store || element._store.validated || element.key != null) {
	        return;
	      }
	      element._store.validated = true;
	      var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
	      if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
	        return;
	      }
	      ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
	      // property, it may be the creator of the child that's responsible for
	      // assigning it a key.

	      var childOwner = '';
	      if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
	        // Give the component that originally created this child.
	        childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
	      }
	      {
	        setCurrentlyValidatingElement$1(element);
	        error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
	        setCurrentlyValidatingElement$1(null);
	      }
	    }
	    /**
	     * Ensure that every element either is passed in a static location, in an
	     * array with an explicit keys property defined, or in an object literal
	     * with valid key property.
	     *
	     * @internal
	     * @param {ReactNode} node Statically passed child of any type.
	     * @param {*} parentType node's parent's type.
	     */

	    function validateChildKeys(node, parentType) {
	      if (typeof node !== 'object') {
	        return;
	      }
	      if (isArray(node)) {
	        for (var i = 0; i < node.length; i++) {
	          var child = node[i];
	          if (isValidElement(child)) {
	            validateExplicitKey(child, parentType);
	          }
	        }
	      } else if (isValidElement(node)) {
	        // This element was passed in a valid location.
	        if (node._store) {
	          node._store.validated = true;
	        }
	      } else if (node) {
	        var iteratorFn = getIteratorFn(node);
	        if (typeof iteratorFn === 'function') {
	          // Entry iterators used to provide implicit keys,
	          // but now we print a separate warning for them later.
	          if (iteratorFn !== node.entries) {
	            var iterator = iteratorFn.call(node);
	            var step;
	            while (!(step = iterator.next()).done) {
	              if (isValidElement(step.value)) {
	                validateExplicitKey(step.value, parentType);
	              }
	            }
	          }
	        }
	      }
	    }
	    /**
	     * Given an element, validate that its props follow the propTypes definition,
	     * provided by the type.
	     *
	     * @param {ReactElement} element
	     */

	    function validatePropTypes(element) {
	      {
	        var type = element.type;
	        if (type === null || type === undefined || typeof type === 'string') {
	          return;
	        }
	        var propTypes;
	        if (typeof type === 'function') {
	          propTypes = type.propTypes;
	        } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE ||
	        // Note: Memo only checks outer props here.
	        // Inner props are checked in the reconciler.
	        type.$$typeof === REACT_MEMO_TYPE)) {
	          propTypes = type.propTypes;
	        } else {
	          return;
	        }
	        if (propTypes) {
	          // Intentionally inside to avoid triggering lazy initializers:
	          var name = getComponentNameFromType(type);
	          checkPropTypes(propTypes, element.props, 'prop', name, element);
	        } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
	          propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:

	          var _name = getComponentNameFromType(type);
	          error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
	        }
	        if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
	          error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
	        }
	      }
	    }
	    /**
	     * Given a fragment, validate that it can only be provided with fragment props
	     * @param {ReactElement} fragment
	     */

	    function validateFragmentProps(fragment) {
	      {
	        var keys = Object.keys(fragment.props);
	        for (var i = 0; i < keys.length; i++) {
	          var key = keys[i];
	          if (key !== 'children' && key !== 'key') {
	            setCurrentlyValidatingElement$1(fragment);
	            error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
	            setCurrentlyValidatingElement$1(null);
	            break;
	          }
	        }
	        if (fragment.ref !== null) {
	          setCurrentlyValidatingElement$1(fragment);
	          error('Invalid attribute `ref` supplied to `React.Fragment`.');
	          setCurrentlyValidatingElement$1(null);
	        }
	      }
	    }
	    function createElementWithValidation(type, props, children) {
	      var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
	      // succeed and there will likely be errors in render.

	      if (!validType) {
	        var info = '';
	        if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
	          info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
	        }
	        var sourceInfo = getSourceInfoErrorAddendumForProps(props);
	        if (sourceInfo) {
	          info += sourceInfo;
	        } else {
	          info += getDeclarationErrorAddendum();
	        }
	        var typeString;
	        if (type === null) {
	          typeString = 'null';
	        } else if (isArray(type)) {
	          typeString = 'array';
	        } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
	          typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
	          info = ' Did you accidentally export a JSX literal instead of a component?';
	        } else {
	          typeString = typeof type;
	        }
	        {
	          error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
	        }
	      }
	      var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
	      // TODO: Drop this when these are no longer allowed as the type argument.

	      if (element == null) {
	        return element;
	      } // Skip key warning if the type isn't valid since our key validation logic
	      // doesn't expect a non-string/function type and can throw confusing errors.
	      // We don't want exception behavior to differ between dev and prod.
	      // (Rendering will throw with a helpful message and as soon as the type is
	      // fixed, the key warnings will appear.)

	      if (validType) {
	        for (var i = 2; i < arguments.length; i++) {
	          validateChildKeys(arguments[i], type);
	        }
	      }
	      if (type === REACT_FRAGMENT_TYPE) {
	        validateFragmentProps(element);
	      } else {
	        validatePropTypes(element);
	      }
	      return element;
	    }
	    var didWarnAboutDeprecatedCreateFactory = false;
	    function createFactoryWithValidation(type) {
	      var validatedFactory = createElementWithValidation.bind(null, type);
	      validatedFactory.type = type;
	      {
	        if (!didWarnAboutDeprecatedCreateFactory) {
	          didWarnAboutDeprecatedCreateFactory = true;
	          warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
	        } // Legacy hook: remove it

	        Object.defineProperty(validatedFactory, 'type', {
	          enumerable: false,
	          get: function () {
	            warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
	            Object.defineProperty(this, 'type', {
	              value: type
	            });
	            return type;
	          }
	        });
	      }
	      return validatedFactory;
	    }
	    function cloneElementWithValidation(element, props, children) {
	      var newElement = cloneElement.apply(this, arguments);
	      for (var i = 2; i < arguments.length; i++) {
	        validateChildKeys(arguments[i], newElement.type);
	      }
	      validatePropTypes(newElement);
	      return newElement;
	    }
	    function startTransition(scope, options) {
	      var prevTransition = ReactCurrentBatchConfig.transition;
	      ReactCurrentBatchConfig.transition = {};
	      var currentTransition = ReactCurrentBatchConfig.transition;
	      {
	        ReactCurrentBatchConfig.transition._updatedFibers = new Set();
	      }
	      try {
	        scope();
	      } finally {
	        ReactCurrentBatchConfig.transition = prevTransition;
	        {
	          if (prevTransition === null && currentTransition._updatedFibers) {
	            var updatedFibersCount = currentTransition._updatedFibers.size;
	            if (updatedFibersCount > 10) {
	              warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
	            }
	            currentTransition._updatedFibers.clear();
	          }
	        }
	      }
	    }
	    var didWarnAboutMessageChannel = false;
	    var enqueueTaskImpl = null;
	    function enqueueTask(task) {
	      if (enqueueTaskImpl === null) {
	        try {
	          // read require off the module object to get around the bundlers.
	          // we don't want them to detect a require and bundle a Node polyfill.
	          var requireString = ('require' + Math.random()).slice(0, 7);
	          var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
	          // version of setImmediate, bypassing fake timers if any.

	          enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
	        } catch (_err) {
	          // we're in a browser
	          // we can't use regular timers because they may still be faked
	          // so we try MessageChannel+postMessage instead
	          enqueueTaskImpl = function (callback) {
	            {
	              if (didWarnAboutMessageChannel === false) {
	                didWarnAboutMessageChannel = true;
	                if (typeof MessageChannel === 'undefined') {
	                  error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
	                }
	              }
	            }
	            var channel = new MessageChannel();
	            channel.port1.onmessage = callback;
	            channel.port2.postMessage(undefined);
	          };
	        }
	      }
	      return enqueueTaskImpl(task);
	    }
	    var actScopeDepth = 0;
	    var didWarnNoAwaitAct = false;
	    function act(callback) {
	      {
	        // `act` calls can be nested, so we track the depth. This represents the
	        // number of `act` scopes on the stack.
	        var prevActScopeDepth = actScopeDepth;
	        actScopeDepth++;
	        if (ReactCurrentActQueue.current === null) {
	          // This is the outermost `act` scope. Initialize the queue. The reconciler
	          // will detect the queue and use it instead of Scheduler.
	          ReactCurrentActQueue.current = [];
	        }
	        var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
	        var result;
	        try {
	          // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
	          // set to `true` while the given callback is executed, not for updates
	          // triggered during an async event, because this is how the legacy
	          // implementation of `act` behaved.
	          ReactCurrentActQueue.isBatchingLegacy = true;
	          result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
	          // which flushed updates immediately after the scope function exits, even
	          // if it's an async function.

	          if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
	            var queue = ReactCurrentActQueue.current;
	            if (queue !== null) {
	              ReactCurrentActQueue.didScheduleLegacyUpdate = false;
	              flushActQueue(queue);
	            }
	          }
	        } catch (error) {
	          popActScope(prevActScopeDepth);
	          throw error;
	        } finally {
	          ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
	        }
	        if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
	          var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
	          // for it to resolve before exiting the current scope.

	          var wasAwaited = false;
	          var thenable = {
	            then: function (resolve, reject) {
	              wasAwaited = true;
	              thenableResult.then(function (returnValue) {
	                popActScope(prevActScopeDepth);
	                if (actScopeDepth === 0) {
	                  // We've exited the outermost act scope. Recursively flush the
	                  // queue until there's no remaining work.
	                  recursivelyFlushAsyncActWork(returnValue, resolve, reject);
	                } else {
	                  resolve(returnValue);
	                }
	              }, function (error) {
	                // The callback threw an error.
	                popActScope(prevActScopeDepth);
	                reject(error);
	              });
	            }
	          };
	          {
	            if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
	              // eslint-disable-next-line no-undef
	              Promise.resolve().then(function () {}).then(function () {
	                if (!wasAwaited) {
	                  didWarnNoAwaitAct = true;
	                  error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
	                }
	              });
	            }
	          }
	          return thenable;
	        } else {
	          var returnValue = result; // The callback is not an async function. Exit the current scope
	          // immediately, without awaiting.

	          popActScope(prevActScopeDepth);
	          if (actScopeDepth === 0) {
	            // Exiting the outermost act scope. Flush the queue.
	            var _queue = ReactCurrentActQueue.current;
	            if (_queue !== null) {
	              flushActQueue(_queue);
	              ReactCurrentActQueue.current = null;
	            } // Return a thenable. If the user awaits it, we'll flush again in
	            // case additional work was scheduled by a microtask.

	            var _thenable = {
	              then: function (resolve, reject) {
	                // Confirm we haven't re-entered another `act` scope, in case
	                // the user does something weird like await the thenable
	                // multiple times.
	                if (ReactCurrentActQueue.current === null) {
	                  // Recursively flush the queue until there's no remaining work.
	                  ReactCurrentActQueue.current = [];
	                  recursivelyFlushAsyncActWork(returnValue, resolve, reject);
	                } else {
	                  resolve(returnValue);
	                }
	              }
	            };
	            return _thenable;
	          } else {
	            // Since we're inside a nested `act` scope, the returned thenable
	            // immediately resolves. The outer scope will flush the queue.
	            var _thenable2 = {
	              then: function (resolve, reject) {
	                resolve(returnValue);
	              }
	            };
	            return _thenable2;
	          }
	        }
	      }
	    }
	    function popActScope(prevActScopeDepth) {
	      {
	        if (prevActScopeDepth !== actScopeDepth - 1) {
	          error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
	        }
	        actScopeDepth = prevActScopeDepth;
	      }
	    }
	    function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
	      {
	        var queue = ReactCurrentActQueue.current;
	        if (queue !== null) {
	          try {
	            flushActQueue(queue);
	            enqueueTask(function () {
	              if (queue.length === 0) {
	                // No additional work was scheduled. Finish.
	                ReactCurrentActQueue.current = null;
	                resolve(returnValue);
	              } else {
	                // Keep flushing work until there's none left.
	                recursivelyFlushAsyncActWork(returnValue, resolve, reject);
	              }
	            });
	          } catch (error) {
	            reject(error);
	          }
	        } else {
	          resolve(returnValue);
	        }
	      }
	    }
	    var isFlushing = false;
	    function flushActQueue(queue) {
	      {
	        if (!isFlushing) {
	          // Prevent re-entrance.
	          isFlushing = true;
	          var i = 0;
	          try {
	            for (; i < queue.length; i++) {
	              var callback = queue[i];
	              do {
	                callback = callback(true);
	              } while (callback !== null);
	            }
	            queue.length = 0;
	          } catch (error) {
	            // If something throws, leave the remaining callbacks on the queue.
	            queue = queue.slice(i + 1);
	            throw error;
	          } finally {
	            isFlushing = false;
	          }
	        }
	      }
	    }
	    var createElement$1 = createElementWithValidation;
	    var cloneElement$1 = cloneElementWithValidation;
	    var createFactory = createFactoryWithValidation;
	    var Children = {
	      map: mapChildren,
	      forEach: forEachChildren,
	      count: countChildren,
	      toArray: toArray,
	      only: onlyChild
	    };
	    exports.Children = Children;
	    exports.Component = Component;
	    exports.Fragment = REACT_FRAGMENT_TYPE;
	    exports.Profiler = REACT_PROFILER_TYPE;
	    exports.PureComponent = PureComponent;
	    exports.StrictMode = REACT_STRICT_MODE_TYPE;
	    exports.Suspense = REACT_SUSPENSE_TYPE;
	    exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
	    exports.cloneElement = cloneElement$1;
	    exports.createContext = createContext;
	    exports.createElement = createElement$1;
	    exports.createFactory = createFactory;
	    exports.createRef = createRef;
	    exports.forwardRef = forwardRef;
	    exports.isValidElement = isValidElement;
	    exports.lazy = lazy;
	    exports.memo = memo;
	    exports.startTransition = startTransition;
	    exports.unstable_act = act;
	    exports.useCallback = useCallback;
	    exports.useContext = useContext;
	    exports.useDebugValue = useDebugValue;
	    exports.useDeferredValue = useDeferredValue;
	    exports.useEffect = useEffect;
	    exports.useId = useId;
	    exports.useImperativeHandle = useImperativeHandle;
	    exports.useInsertionEffect = useInsertionEffect;
	    exports.useLayoutEffect = useLayoutEffect;
	    exports.useMemo = useMemo;
	    exports.useReducer = useReducer;
	    exports.useRef = useRef;
	    exports.useState = useState;
	    exports.useSyncExternalStore = useSyncExternalStore;
	    exports.useTransition = useTransition;
	    exports.version = ReactVersion;
	    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
	    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function') {
	      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
	    }
	  })();
	} 
} (react_development, react_development.exports));

var react_developmentExports = react_development.exports;

{
  react$1.exports = react_developmentExports;
}

var reactExports$1 = react$1.exports;
var React = /*@__PURE__*/getDefaultExportFromCjs(reactExports$1);

var React$1 = /*#__PURE__*/_mergeNamespaces({
  __proto__: null,
  default: React
}, [reactExports$1]);

var isArray$2 = Array.isArray;
var keyList = Object.keys;
var hasProp = Object.prototype.hasOwnProperty;
var hasElementType = typeof Element !== 'undefined';
function equal(a, b) {
  // fast-deep-equal index.js 2.0.1
  if (a === b) return true;
  if (a && b && typeof a == 'object' && typeof b == 'object') {
    var arrA = isArray$2(a),
      arrB = isArray$2(b),
      i,
      length,
      key;
    if (arrA && arrB) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
      return true;
    }
    if (arrA != arrB) return false;
    var dateA = a instanceof Date,
      dateB = b instanceof Date;
    if (dateA != dateB) return false;
    if (dateA && dateB) return a.getTime() == b.getTime();
    var regexpA = a instanceof RegExp,
      regexpB = b instanceof RegExp;
    if (regexpA != regexpB) return false;
    if (regexpA && regexpB) return a.toString() == b.toString();
    var keys = keyList(a);
    length = keys.length;
    if (length !== keyList(b).length) return false;
    for (i = length; i-- !== 0;) if (!hasProp.call(b, keys[i])) return false;
    // end fast-deep-equal

    // start react-fast-compare
    // custom handling for DOM elements
    if (hasElementType && a instanceof Element && b instanceof Element) return a === b;

    // custom handling for React
    for (i = length; i-- !== 0;) {
      key = keys[i];
      if (key === '_owner' && a.$$typeof) {
        // React-specific: avoid traversing React elements' _owner.
        //  _owner contains circular references
        // and is not needed when comparing the actual elements (and not their owners)
        // .$$typeof and ._store on just reasonable markers of a react element
        continue;
      } else {
        // all other properties should be traversed as usual
        if (!equal(a[key], b[key])) return false;
      }
    }
    // end react-fast-compare

    // fast-deep-equal index.js 2.0.1
    return true;
  }
  return a !== a && b !== b;
}
// end fast-deep-equal

var reactFastCompare = function exportedEqual(a, b) {
  try {
    return equal(a, b);
  } catch (error) {
    if (error.message && error.message.match(/stack|recursion/i) || error.number === -2146828260) {
      // warn on circular references, don't crash
      // browsers give this different errors name and messages:
      // chrome/safari: "RangeError", "Maximum call stack size exceeded"
      // firefox: "InternalError", too much recursion"
      // edge: "Error", "Out of stack space"
      console.warn('Warning: react-fast-compare does not handle circular references.', error.name, error.message);
      return false;
    }
    // some other error. we should definitely know about these
    throw error;
  }
};

var isEqual = /*@__PURE__*/getDefaultExportFromCjs(reactFastCompare);

var isProduction = "development" === 'production';
function warning$1(condition, message) {
  if (!isProduction) {
    if (condition) {
      return;
    }
    var text = "Warning: " + message;
    if (typeof console !== 'undefined') {
      console.warn(text);
    }
    try {
      throw Error(text);
    } catch (x) {}
  }
}

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || value !== value && other !== other;
}

/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}

/** Used for built-in method references. */
var arrayProto = Array.prototype;

/** Built-in value references. */
var splice = arrayProto.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
    index = assocIndexOf(data, key);
  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}

/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
    index = assocIndexOf(data, key);
  return index < 0 ? undefined : data[index][1];
}

/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}

/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
    index = assocIndexOf(data, key);
  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}

/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache();
  this.size = 0;
}

/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
    result = data['delete'](key);
  this.size = data.size;
  return result;
}

/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject$1(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
  funcTag$2 = '[object Function]',
  genTag$1 = '[object GeneratorFunction]',
  proxyTag = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction$1(value) {
  if (!isObject$1(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = baseGetTag(value);
  return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
}

/** Used to detect overreaching core-js shims. */
var coreJsData = root$1['__core-js_shared__'];
var coreJsData$1 = coreJsData;

/** Used to detect methods masquerading as native. */
var maskSrcKey = function () {
  var uid = /[^.]+$/.exec(coreJsData$1 && coreJsData$1.keys && coreJsData$1.keys.IE_PROTO || '');
  return uid ? 'Symbol(src)_1.' + uid : '';
}();

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && maskSrcKey in func;
}

/** Used for built-in method references. */
var funcProto$1 = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString$1.call(func);
    } catch (e) {}
    try {
      return func + '';
    } catch (e) {}
  }
  return '';
}

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var funcProto = Function.prototype,
  objectProto$a = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty$a = objectProto$a.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$a).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!isObject$1(value) || isMasked(value)) {
    return false;
  }
  var pattern = isFunction$1(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue$1(object, key) {
  return object == null ? undefined : object[key];
}

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue$1(object, key);
  return baseIsNative(value) ? value : undefined;
}

/* Built-in method references that are verified to be native. */
var Map$6 = getNative(root$1, 'Map');
var Map$7 = Map$6;

/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
var nativeCreate$1 = nativeCreate;

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate$1 ? nativeCreate$1(null) : {};
  this.size = 0;
}

/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var objectProto$9 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$9.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate$1) {
    var result = data[key];
    return result === HASH_UNDEFINED$1 ? undefined : result;
  }
  return hasOwnProperty$9.call(data, key) ? data[key] : undefined;
}

/** Used for built-in method references. */
var objectProto$8 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$8.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate$1 ? data[key] !== undefined : hasOwnProperty$8.call(data, key);
}

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = nativeCreate$1 && value === undefined ? HASH_UNDEFINED : value;
  return this;
}

/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;

/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new Hash(),
    'map': new (Map$7 || ListCache)(),
    'string': new Hash()
  };
}

/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
}

/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
}

/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  var result = getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}

/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}

/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  var data = getMapData(this, key),
    size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
    length = entries == null ? 0 : entries.length;
  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache) {
    var pairs = data.__data__;
    if (!Map$7 || pairs.length < LARGE_ARRAY_SIZE - 1) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}

/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  var data = this.__data__ = new ListCache(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;

/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
    length = array == null ? 0 : array.length;
  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}

var defineProperty$1 = function () {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}();
var defineProperty$2 = defineProperty$1;

/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function baseAssignValue(object, key, value) {
  if (key == '__proto__' && defineProperty$2) {
    defineProperty$2(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}

/** Used for built-in method references. */
var objectProto$7 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$7.hasOwnProperty;

/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignValue(object, key, value) {
  var objValue = object[key];
  if (!(hasOwnProperty$7.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) {
    baseAssignValue(object, key, value);
  }
}

/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */
function copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});
  var index = -1,
    length = props.length;
  while (++index < length) {
    var key = props[index];
    var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;
    if (newValue === undefined) {
      newValue = source[key];
    }
    if (isNew) {
      baseAssignValue(object, key, newValue);
    } else {
      assignValue(object, key, newValue);
    }
  }
  return object;
}

/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
    result = Array(n);
  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}

/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments(value) {
  return isObjectLike(value) && baseGetTag(value) == argsTag$2;
}

/** Used for built-in method references. */
var objectProto$6 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$6.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments = baseIsArguments(function () {
  return arguments;
}()) ? baseIsArguments : function (value) {
  return isObjectLike(value) && hasOwnProperty$6.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee');
};
var isArguments$1 = isArguments;

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;
var isArray$1 = isArray;

/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

/** Detect free variable `exports`. */
var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;

/** Built-in value references. */
var Buffer$2 = moduleExports$2 ? root$1.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer$2 ? Buffer$2.isBuffer : undefined;

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || stubFalse;
var isBuffer$1 = isBuffer;

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER$1 : length;
  return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]',
  arrayTag$1 = '[object Array]',
  boolTag$2 = '[object Boolean]',
  dateTag$2 = '[object Date]',
  errorTag$1 = '[object Error]',
  funcTag$1 = '[object Function]',
  mapTag$4 = '[object Map]',
  numberTag$2 = '[object Number]',
  objectTag$2 = '[object Object]',
  regexpTag$2 = '[object RegExp]',
  setTag$4 = '[object Set]',
  stringTag$2 = '[object String]',
  weakMapTag$2 = '[object WeakMap]';
var arrayBufferTag$2 = '[object ArrayBuffer]',
  dataViewTag$3 = '[object DataView]',
  float32Tag$2 = '[object Float32Array]',
  float64Tag$2 = '[object Float64Array]',
  int8Tag$2 = '[object Int8Array]',
  int16Tag$2 = '[object Int16Array]',
  int32Tag$2 = '[object Int32Array]',
  uint8Tag$2 = '[object Uint8Array]',
  uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  uint16Tag$2 = '[object Uint16Array]',
  uint32Tag$2 = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = typedArrayTags[uint32Tag$2] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag$1] = typedArrayTags[arrayBufferTag$2] = typedArrayTags[boolTag$2] = typedArrayTags[dataViewTag$3] = typedArrayTags[dateTag$2] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$4] = typedArrayTags[numberTag$2] = typedArrayTags[objectTag$2] = typedArrayTags[regexpTag$2] = typedArrayTags[setTag$4] = typedArrayTags[stringTag$2] = typedArrayTags[weakMapTag$2] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray(value) {
  return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}

/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function (value) {
    return func(value);
  };
}

/** Detect free variable `exports`. */
var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;

/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports$1 && freeGlobal$1.process;

/** Used to access faster Node.js helpers. */
var nodeUtil = function () {
  try {
    // Use `util.types` for Node.js 10+.
    var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
    if (types) {
      return types;
    }

    // Legacy `process.binding('util')` for Node.js < 10.
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}();
var nodeUtil$1 = nodeUtil;

/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil$1 && nodeUtil$1.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
var isTypedArray$1 = isTypedArray;

/** Used for built-in method references. */
var objectProto$5 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$5.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  var isArr = isArray$1(value),
    isArg = !isArr && isArguments$1(value),
    isBuff = !isArr && !isArg && isBuffer$1(value),
    isType = !isArr && !isArg && !isBuff && isTypedArray$1(value),
    skipIndexes = isArr || isArg || isBuff || isType,
    result = skipIndexes ? baseTimes(value.length, String) : [],
    length = result.length;
  for (var key in value) {
    if ((inherited || hasOwnProperty$5.call(value, key)) && !(skipIndexes && (
    // Safari 9 has enumerable `arguments.length` in strict mode.
    key == 'length' ||
    // Node.js 0.10 has enumerable non-index properties on buffers.
    isBuff && (key == 'offset' || key == 'parent') ||
    // PhantomJS 2 has enumerable non-index properties on typed arrays.
    isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') ||
    // Skip index properties.
    isIndex(key, length)))) {
      result.push(key);
    }
  }
  return result;
}

/** Used for built-in method references. */
var objectProto$4 = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
    proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$4;
  return value === proto;
}

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
var nativeKeys$1 = nativeKeys;

/** Used for built-in method references. */
var objectProto$3 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$3.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!isPrototype(object)) {
    return nativeKeys$1(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty$4.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction$1(value);
}

/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}

/**
 * The base implementation of `_.assign` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssign(object, source) {
  return object && copyObject(source, keys(source), object);
}

/**
 * This function is like
 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * except that it includes inherited enumerable properties.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function nativeKeysIn(object) {
  var result = [];
  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }
  return result;
}

/** Used for built-in method references. */
var objectProto$2 = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$2.hasOwnProperty;

/**
 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeysIn(object) {
  if (!isObject$1(object)) {
    return nativeKeysIn(object);
  }
  var isProto = isPrototype(object),
    result = [];
  for (var key in object) {
    if (!(key == 'constructor' && (isProto || !hasOwnProperty$3.call(object, key)))) {
      result.push(key);
    }
  }
  return result;
}

/**
 * Creates an array of the own and inherited enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keysIn(new Foo);
 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
 */
function keysIn(object) {
  return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}

/**
 * The base implementation of `_.assignIn` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssignIn(object, source) {
  return object && copyObject(source, keysIn(source), object);
}

/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer$1 = moduleExports ? root$1.Buffer : undefined,
  allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined;

/**
 * Creates a clone of  `buffer`.
 *
 * @private
 * @param {Buffer} buffer The buffer to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Buffer} Returns the cloned buffer.
 */
function cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice();
  }
  var length = buffer.length,
    result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  buffer.copy(result);
  return result;
}

/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
    length = source.length;
  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}

/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
    length = array == null ? 0 : array.length,
    resIndex = 0,
    result = [];
  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}

/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

/** Used for built-in method references. */
var objectProto$1 = Object.prototype;

/** Built-in value references. */
var propertyIsEnumerable = objectProto$1.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = !nativeGetSymbols$1 ? stubArray : function (object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter(nativeGetSymbols$1(object), function (symbol) {
    return propertyIsEnumerable.call(object, symbol);
  });
};
var getSymbols$1 = getSymbols;

/**
 * Copies own symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbols(source, object) {
  return copyObject(source, getSymbols$1(source), object);
}

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
    length = values.length,
    offset = array.length;
  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own and inherited enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbolsIn = !nativeGetSymbols ? stubArray : function (object) {
  var result = [];
  while (object) {
    arrayPush(result, getSymbols$1(object));
    object = getPrototype$1(object);
  }
  return result;
};
var getSymbolsIn$1 = getSymbolsIn;

/**
 * Copies own and inherited symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbolsIn(source, object) {
  return copyObject(source, getSymbolsIn$1(source), object);
}

/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray$1(object) ? result : arrayPush(result, symbolsFunc(object));
}

/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return baseGetAllKeys(object, keys, getSymbols$1);
}

/**
 * Creates an array of own and inherited enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeysIn(object) {
  return baseGetAllKeys(object, keysIn, getSymbolsIn$1);
}

/* Built-in method references that are verified to be native. */
var DataView$1 = getNative(root$1, 'DataView');
var DataView$2 = DataView$1;

/* Built-in method references that are verified to be native. */
var Promise$1 = getNative(root$1, 'Promise');
var Promise$2 = Promise$1;

/* Built-in method references that are verified to be native. */
var Set$1 = getNative(root$1, 'Set');
var Set$2 = Set$1;

/* Built-in method references that are verified to be native. */
var WeakMap$1 = getNative(root$1, 'WeakMap');
var WeakMap$2 = WeakMap$1;

/** `Object#toString` result references. */
var mapTag$3 = '[object Map]',
  objectTag$1 = '[object Object]',
  promiseTag = '[object Promise]',
  setTag$3 = '[object Set]',
  weakMapTag$1 = '[object WeakMap]';
var dataViewTag$2 = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView$2),
  mapCtorString = toSource(Map$7),
  promiseCtorString = toSource(Promise$2),
  setCtorString = toSource(Set$2),
  weakMapCtorString = toSource(WeakMap$2);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if (DataView$2 && getTag(new DataView$2(new ArrayBuffer(1))) != dataViewTag$2 || Map$7 && getTag(new Map$7()) != mapTag$3 || Promise$2 && getTag(Promise$2.resolve()) != promiseTag || Set$2 && getTag(new Set$2()) != setTag$3 || WeakMap$2 && getTag(new WeakMap$2()) != weakMapTag$1) {
  getTag = function (value) {
    var result = baseGetTag(value),
      Ctor = result == objectTag$1 ? value.constructor : undefined,
      ctorString = Ctor ? toSource(Ctor) : '';
    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return dataViewTag$2;
        case mapCtorString:
          return mapTag$3;
        case promiseCtorString:
          return promiseTag;
        case setCtorString:
          return setTag$3;
        case weakMapCtorString:
          return weakMapTag$1;
      }
    }
    return result;
  };
}
var getTag$1 = getTag;

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto.hasOwnProperty;

/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */
function initCloneArray(array) {
  var length = array.length,
    result = new array.constructor(length);

  // Add properties assigned by `RegExp#exec`.
  if (length && typeof array[0] == 'string' && hasOwnProperty$2.call(array, 'index')) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}

/** Built-in value references. */
var Uint8Array$1 = root$1.Uint8Array;
var Uint8Array$2 = Uint8Array$1;

/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */
function cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new Uint8Array$2(result).set(new Uint8Array$2(arrayBuffer));
  return result;
}

/**
 * Creates a clone of `dataView`.
 *
 * @private
 * @param {Object} dataView The data view to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned data view.
 */
function cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}

/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;

/**
 * Creates a clone of `regexp`.
 *
 * @private
 * @param {Object} regexp The regexp to clone.
 * @returns {Object} Returns the cloned regexp.
 */
function cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}

/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = Symbol$2 ? Symbol$2.prototype : undefined,
  symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;

/**
 * Creates a clone of the `symbol` object.
 *
 * @private
 * @param {Object} symbol The symbol object to clone.
 * @returns {Object} Returns the cloned symbol object.
 */
function cloneSymbol(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}

/**
 * Creates a clone of `typedArray`.
 *
 * @private
 * @param {Object} typedArray The typed array to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned typed array.
 */
function cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}

/** `Object#toString` result references. */
var boolTag$1 = '[object Boolean]',
  dateTag$1 = '[object Date]',
  mapTag$2 = '[object Map]',
  numberTag$1 = '[object Number]',
  regexpTag$1 = '[object RegExp]',
  setTag$2 = '[object Set]',
  stringTag$1 = '[object String]',
  symbolTag$2 = '[object Symbol]';
var arrayBufferTag$1 = '[object ArrayBuffer]',
  dataViewTag$1 = '[object DataView]',
  float32Tag$1 = '[object Float32Array]',
  float64Tag$1 = '[object Float64Array]',
  int8Tag$1 = '[object Int8Array]',
  int16Tag$1 = '[object Int16Array]',
  int32Tag$1 = '[object Int32Array]',
  uint8Tag$1 = '[object Uint8Array]',
  uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  uint16Tag$1 = '[object Uint16Array]',
  uint32Tag$1 = '[object Uint32Array]';

/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneByTag(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case arrayBufferTag$1:
      return cloneArrayBuffer(object);
    case boolTag$1:
    case dateTag$1:
      return new Ctor(+object);
    case dataViewTag$1:
      return cloneDataView(object, isDeep);
    case float32Tag$1:
    case float64Tag$1:
    case int8Tag$1:
    case int16Tag$1:
    case int32Tag$1:
    case uint8Tag$1:
    case uint8ClampedTag$1:
    case uint16Tag$1:
    case uint32Tag$1:
      return cloneTypedArray(object, isDeep);
    case mapTag$2:
      return new Ctor();
    case numberTag$1:
    case stringTag$1:
      return new Ctor(object);
    case regexpTag$1:
      return cloneRegExp(object);
    case setTag$2:
      return new Ctor();
    case symbolTag$2:
      return cloneSymbol(object);
  }
}

/** Built-in value references. */
var objectCreate = Object.create;

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} proto The object to inherit from.
 * @returns {Object} Returns the new object.
 */
var baseCreate = function () {
  function object() {}
  return function (proto) {
    if (!isObject$1(proto)) {
      return {};
    }
    if (objectCreate) {
      return objectCreate(proto);
    }
    object.prototype = proto;
    var result = new object();
    object.prototype = undefined;
    return result;
  };
}();
var baseCreate$1 = baseCreate;

/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneObject(object) {
  return typeof object.constructor == 'function' && !isPrototype(object) ? baseCreate$1(getPrototype$1(object)) : {};
}

/** `Object#toString` result references. */
var mapTag$1 = '[object Map]';

/**
 * The base implementation of `_.isMap` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 */
function baseIsMap(value) {
  return isObjectLike(value) && getTag$1(value) == mapTag$1;
}

/* Node.js helper references. */
var nodeIsMap = nodeUtil$1 && nodeUtil$1.isMap;

/**
 * Checks if `value` is classified as a `Map` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 * @example
 *
 * _.isMap(new Map);
 * // => true
 *
 * _.isMap(new WeakMap);
 * // => false
 */
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
var isMap$1 = isMap;

/** `Object#toString` result references. */
var setTag$1 = '[object Set]';

/**
 * The base implementation of `_.isSet` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 */
function baseIsSet(value) {
  return isObjectLike(value) && getTag$1(value) == setTag$1;
}

/* Node.js helper references. */
var nodeIsSet = nodeUtil$1 && nodeUtil$1.isSet;

/**
 * Checks if `value` is classified as a `Set` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 * @example
 *
 * _.isSet(new Set);
 * // => true
 *
 * _.isSet(new WeakSet);
 * // => false
 */
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
var isSet$1 = isSet;

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 1,
  CLONE_FLAT_FLAG = 2,
  CLONE_SYMBOLS_FLAG$2 = 4;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
  arrayTag = '[object Array]',
  boolTag = '[object Boolean]',
  dateTag = '[object Date]',
  errorTag = '[object Error]',
  funcTag = '[object Function]',
  genTag = '[object GeneratorFunction]',
  mapTag = '[object Map]',
  numberTag = '[object Number]',
  objectTag = '[object Object]',
  regexpTag = '[object RegExp]',
  setTag = '[object Set]',
  stringTag = '[object String]',
  symbolTag$1 = '[object Symbol]',
  weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
  dataViewTag = '[object DataView]',
  float32Tag = '[object Float32Array]',
  float64Tag = '[object Float64Array]',
  int8Tag = '[object Int8Array]',
  int16Tag = '[object Int16Array]',
  int32Tag = '[object Int32Array]',
  uint8Tag = '[object Uint8Array]',
  uint8ClampedTag = '[object Uint8ClampedArray]',
  uint16Tag = '[object Uint16Array]',
  uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;

/**
 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Deep clone
 *  2 - Flatten inherited properties
 *  4 - Clone symbols
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */
function baseClone(value, bitmask, customizer, key, object, stack) {
  var result,
    isDeep = bitmask & CLONE_DEEP_FLAG$1,
    isFlat = bitmask & CLONE_FLAT_FLAG,
    isFull = bitmask & CLONE_SYMBOLS_FLAG$2;
  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== undefined) {
    return result;
  }
  if (!isObject$1(value)) {
    return value;
  }
  var isArr = isArray$1(value);
  if (isArr) {
    result = initCloneArray(value);
    if (!isDeep) {
      return copyArray(value, result);
    }
  } else {
    var tag = getTag$1(value),
      isFunc = tag == funcTag || tag == genTag;
    if (isBuffer$1(value)) {
      return cloneBuffer(value, isDeep);
    }
    if (tag == objectTag || tag == argsTag || isFunc && !object) {
      result = isFlat || isFunc ? {} : initCloneObject(value);
      if (!isDeep) {
        return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = initCloneByTag(value, tag, isDeep);
    }
  }
  // Check for circular references and return its corresponding clone.
  stack || (stack = new Stack());
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);
  if (isSet$1(value)) {
    value.forEach(function (subValue) {
      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (isMap$1(value)) {
    value.forEach(function (subValue, key) {
      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
    });
  }
  var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys;
  var props = isArr ? undefined : keysFunc(value);
  arrayEach(props || value, function (subValue, key) {
    if (props) {
      key = subValue;
      subValue = value[key];
    }
    // Recursively populate clone (susceptible to call stack limits).
    assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  });
  return result;
}

/** Used to compose bitmasks for cloning. */
var CLONE_SYMBOLS_FLAG$1 = 4;

/**
 * Creates a shallow clone of `value`.
 *
 * **Note:** This method is loosely based on the
 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
 * and supports cloning arrays, array buffers, booleans, date objects, maps,
 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
 * arrays. The own enumerable properties of `arguments` objects are cloned
 * as plain objects. An empty object is returned for uncloneable values such
 * as error objects, functions, DOM nodes, and WeakMaps.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to clone.
 * @returns {*} Returns the cloned value.
 * @see _.cloneDeep
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var shallow = _.clone(objects);
 * console.log(shallow[0] === objects[0]);
 * // => true
 */
function clone(value) {
  return baseClone(value, CLONE_SYMBOLS_FLAG$1);
}

/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
    length = array == null ? 0 : array.length,
    result = Array(length);
  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
}

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function memoize$2(func, resolver) {
  if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function () {
    var args = arguments,
      key = resolver ? resolver.apply(this, args) : args[0],
      cache = memoized.cache;
    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize$2.Cache || MapCache)();
  return memoized;
}

// Expose `MapCache`.
memoize$2.Cache = MapCache;

/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped(func) {
  var result = memoize$2(func, function (key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });
  var cache = result.cache;
  return result;
}

/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var stringToPath = memoizeCapped(function (string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(rePropName, function (match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
  });
  return result;
});
var stringToPath$1 = stringToPath;

/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function toKey(value) {
  if (typeof value == 'string' || isSymbol(value)) {
    return value;
  }
  var result = value + '';
  return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
}

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol$2 ? Symbol$2.prototype : undefined,
  symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (isArray$1(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return arrayMap(value, baseToString) + '';
  }
  if (isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = value + '';
  return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString(value) {
  return value == null ? '' : baseToString(value);
}

/**
 * Converts `value` to a property path array.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Util
 * @param {*} value The value to convert.
 * @returns {Array} Returns the new property path array.
 * @example
 *
 * _.toPath('a.b.c');
 * // => ['a', 'b', 'c']
 *
 * _.toPath('a[0].b.c');
 * // => ['a', '0', 'b', 'c']
 */
function toPath(value) {
  if (isArray$1(value)) {
    return arrayMap(value, toKey);
  }
  return isSymbol(value) ? [value] : copyArray(stringToPath$1(toString(value)));
}

var reactIs$3 = {exports: {}};

var reactIs_development$2 = {};

/** @license React v16.13.1
 * react-is.development.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 () {

    // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
    // nor polyfill, then a plain number is used for performance.
    var hasSymbol = typeof Symbol === 'function' && Symbol.for;
    var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
    var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
    var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
    var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
    var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
    var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
    var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
    // (unstable) APIs that have been removed. Can we remove the symbols?

    var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
    var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
    var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
    var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
    var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
    var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
    var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
    var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
    var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
    var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
    var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
    function isValidElementType(type) {
      return typeof type === 'string' || typeof type === 'function' ||
      // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
      type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
    }
    function typeOf(object) {
      if (typeof object === 'object' && object !== null) {
        var $$typeof = object.$$typeof;
        switch ($$typeof) {
          case REACT_ELEMENT_TYPE:
            var type = object.type;
            switch (type) {
              case REACT_ASYNC_MODE_TYPE:
              case REACT_CONCURRENT_MODE_TYPE:
              case REACT_FRAGMENT_TYPE:
              case REACT_PROFILER_TYPE:
              case REACT_STRICT_MODE_TYPE:
              case REACT_SUSPENSE_TYPE:
                return type;
              default:
                var $$typeofType = type && type.$$typeof;
                switch ($$typeofType) {
                  case REACT_CONTEXT_TYPE:
                  case REACT_FORWARD_REF_TYPE:
                  case REACT_LAZY_TYPE:
                  case REACT_MEMO_TYPE:
                  case REACT_PROVIDER_TYPE:
                    return $$typeofType;
                  default:
                    return $$typeof;
                }
            }
          case REACT_PORTAL_TYPE:
            return $$typeof;
        }
      }
      return undefined;
    } // AsyncMode is deprecated along with isAsyncMode

    var AsyncMode = REACT_ASYNC_MODE_TYPE;
    var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
    var ContextConsumer = REACT_CONTEXT_TYPE;
    var ContextProvider = REACT_PROVIDER_TYPE;
    var Element = REACT_ELEMENT_TYPE;
    var ForwardRef = REACT_FORWARD_REF_TYPE;
    var Fragment = REACT_FRAGMENT_TYPE;
    var Lazy = REACT_LAZY_TYPE;
    var Memo = REACT_MEMO_TYPE;
    var Portal = REACT_PORTAL_TYPE;
    var Profiler = REACT_PROFILER_TYPE;
    var StrictMode = REACT_STRICT_MODE_TYPE;
    var Suspense = REACT_SUSPENSE_TYPE;
    var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated

    function isAsyncMode(object) {
      {
        if (!hasWarnedAboutDeprecatedIsAsyncMode) {
          hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint

          console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
        }
      }
      return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
    }
    function isConcurrentMode(object) {
      return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
    }
    function isContextConsumer(object) {
      return typeOf(object) === REACT_CONTEXT_TYPE;
    }
    function isContextProvider(object) {
      return typeOf(object) === REACT_PROVIDER_TYPE;
    }
    function isElement(object) {
      return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
    }
    function isForwardRef(object) {
      return typeOf(object) === REACT_FORWARD_REF_TYPE;
    }
    function isFragment(object) {
      return typeOf(object) === REACT_FRAGMENT_TYPE;
    }
    function isLazy(object) {
      return typeOf(object) === REACT_LAZY_TYPE;
    }
    function isMemo(object) {
      return typeOf(object) === REACT_MEMO_TYPE;
    }
    function isPortal(object) {
      return typeOf(object) === REACT_PORTAL_TYPE;
    }
    function isProfiler(object) {
      return typeOf(object) === REACT_PROFILER_TYPE;
    }
    function isStrictMode(object) {
      return typeOf(object) === REACT_STRICT_MODE_TYPE;
    }
    function isSuspense(object) {
      return typeOf(object) === REACT_SUSPENSE_TYPE;
    }
    reactIs_development$2.AsyncMode = AsyncMode;
    reactIs_development$2.ConcurrentMode = ConcurrentMode;
    reactIs_development$2.ContextConsumer = ContextConsumer;
    reactIs_development$2.ContextProvider = ContextProvider;
    reactIs_development$2.Element = Element;
    reactIs_development$2.ForwardRef = ForwardRef;
    reactIs_development$2.Fragment = Fragment;
    reactIs_development$2.Lazy = Lazy;
    reactIs_development$2.Memo = Memo;
    reactIs_development$2.Portal = Portal;
    reactIs_development$2.Profiler = Profiler;
    reactIs_development$2.StrictMode = StrictMode;
    reactIs_development$2.Suspense = Suspense;
    reactIs_development$2.isAsyncMode = isAsyncMode;
    reactIs_development$2.isConcurrentMode = isConcurrentMode;
    reactIs_development$2.isContextConsumer = isContextConsumer;
    reactIs_development$2.isContextProvider = isContextProvider;
    reactIs_development$2.isElement = isElement;
    reactIs_development$2.isForwardRef = isForwardRef;
    reactIs_development$2.isFragment = isFragment;
    reactIs_development$2.isLazy = isLazy;
    reactIs_development$2.isMemo = isMemo;
    reactIs_development$2.isPortal = isPortal;
    reactIs_development$2.isProfiler = isProfiler;
    reactIs_development$2.isStrictMode = isStrictMode;
    reactIs_development$2.isSuspense = isSuspense;
    reactIs_development$2.isValidElementType = isValidElementType;
    reactIs_development$2.typeOf = typeOf;
  })();
}

{
  reactIs$3.exports = reactIs_development$2;
}

var reactIsExports$2 = reactIs$3.exports;

var reactIs$2 = reactIsExports$2;

/**
 * Copyright 2015, Yahoo! Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
var REACT_STATICS = {
  childContextTypes: true,
  contextType: true,
  contextTypes: true,
  defaultProps: true,
  displayName: true,
  getDefaultProps: true,
  getDerivedStateFromError: true,
  getDerivedStateFromProps: true,
  mixins: true,
  propTypes: true,
  type: true
};
var KNOWN_STATICS = {
  name: true,
  length: true,
  prototype: true,
  caller: true,
  callee: true,
  arguments: true,
  arity: true
};
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$2.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs$2.Memo] = MEMO_STATICS;
function getStatics(component) {
  // React v16.11 and below
  if (reactIs$2.isMemo(component)) {
    return MEMO_STATICS;
  } // React v16.12 and above

  return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics$1(targetComponent, sourceComponent, blacklist) {
  if (typeof sourceComponent !== 'string') {
    // don't hoist over string (html) components
    if (objectPrototype) {
      var inheritedComponent = getPrototypeOf(sourceComponent);
      if (inheritedComponent && inheritedComponent !== objectPrototype) {
        hoistNonReactStatics$1(targetComponent, inheritedComponent, blacklist);
      }
    }
    var keys = getOwnPropertyNames(sourceComponent);
    if (getOwnPropertySymbols$1) {
      keys = keys.concat(getOwnPropertySymbols$1(sourceComponent));
    }
    var targetStatics = getStatics(targetComponent);
    var sourceStatics = getStatics(sourceComponent);
    for (var i = 0; i < keys.length; ++i) {
      var key = keys[i];
      if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
        var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
        try {
          // Avoid failures from read-only properties
          defineProperty(targetComponent, key, descriptor);
        } catch (e) {}
      }
    }
  }
  return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics$1;

var hoistNonReactStatics$1$1 = /*@__PURE__*/getDefaultExportFromCjs(hoistNonReactStatics_cjs);

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
  CLONE_SYMBOLS_FLAG = 4;

/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */
function cloneDeep(value) {
  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}

function _extends$1() {
  _extends$1 = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends$1.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}
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;
}
function _assertThisInitialized$1(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
var FormikContext = /*#__PURE__*/reactExports$1.createContext(undefined);
FormikContext.displayName = 'FormikContext';
var FormikProvider = FormikContext.Provider;
var FormikConsumer = FormikContext.Consumer;
function useFormikContext() {
  var formik = reactExports$1.useContext(FormikContext);
  !!!formik ? warning$1(false, "Formik context is undefined, please verify you are calling useFormikContext() as child of a <Formik> component.")  : void 0;
  return formik;
}

/** @private is the value an empty array? */

var isEmptyArray = function isEmptyArray(value) {
  return Array.isArray(value) && value.length === 0;
};
/** @private is the given object a Function? */

var isFunction = function isFunction(obj) {
  return typeof obj === 'function';
};
/** @private is the given object an Object? */

var isObject = function isObject(obj) {
  return obj !== null && typeof obj === 'object';
};
/** @private is the given object an integer? */

var isInteger$1 = function isInteger(obj) {
  return String(Math.floor(Number(obj))) === obj;
};
/** @private is the given object a string? */

var isString = function isString(obj) {
  return Object.prototype.toString.call(obj) === '[object String]';
};
/** @private is the given object a NaN? */
// eslint-disable-next-line no-self-compare

var isNaN$1 = function isNaN(obj) {
  return obj !== obj;
};
/** @private Does a React component have exactly 0 children? */

var isEmptyChildren = function isEmptyChildren(children) {
  return reactExports$1.Children.count(children) === 0;
};
/** @private is the given object/value a promise? */

var isPromise = function isPromise(value) {
  return isObject(value) && isFunction(value.then);
};
/** @private is the given object/value a type of synthetic event? */

var isInputEvent = function isInputEvent(value) {
  return value && isObject(value) && isObject(value.target);
};
/**
 * Same as document.activeElement but wraps in a try-catch block. In IE it is
 * not safe to call document.activeElement if there is nothing focused.
 *
 * The activeElement will be null only if the document or document body is not
 * yet defined.
 *
 * @param {?Document} doc Defaults to current document.
 * @return {Element | null}
 * @see https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/dom/getActiveElement.js
 */

function getActiveElement(doc) {
  doc = doc || (typeof document !== 'undefined' ? document : undefined);
  if (typeof doc === 'undefined') {
    return null;
  }
  try {
    return doc.activeElement || doc.body;
  } catch (e) {
    return doc.body;
  }
}
/**
 * Deeply get a value from an object via its path.
 */

function getIn(obj, key, def, p) {
  if (p === void 0) {
    p = 0;
  }
  var path = toPath(key);
  while (obj && p < path.length) {
    obj = obj[path[p++]];
  } // check if path is not in the end

  if (p !== path.length && !obj) {
    return def;
  }
  return obj === undefined ? def : obj;
}
/**
 * Deeply set a value from in object via it's path. If the value at `path`
 * has changed, return a shallow copy of obj with `value` set at `path`.
 * If `value` has not changed, return the original `obj`.
 *
 * Existing objects / arrays along `path` are also shallow copied. Sibling
 * objects along path retain the same internal js reference. Since new
 * objects / arrays are only created along `path`, we can test if anything
 * changed in a nested structure by comparing the object's reference in
 * the old and new object, similar to how russian doll cache invalidation
 * works.
 *
 * In earlier versions of this function, which used cloneDeep, there were
 * issues whereby settings a nested value would mutate the parent
 * instead of creating a new object. `clone` avoids that bug making a
 * shallow copy of the objects along the update path
 * so no object is mutated in place.
 *
 * Before changing this function, please read through the following
 * discussions.
 *
 * @see https://github.com/developit/linkstate
 * @see https://github.com/jaredpalmer/formik/pull/123
 */

function setIn(obj, path, value) {
  var res = clone(obj); // this keeps inheritance when obj is a class

  var resVal = res;
  var i = 0;
  var pathArray = toPath(path);
  for (; i < pathArray.length - 1; i++) {
    var currentPath = pathArray[i];
    var currentObj = getIn(obj, pathArray.slice(0, i + 1));
    if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) {
      resVal = resVal[currentPath] = clone(currentObj);
    } else {
      var nextPath = pathArray[i + 1];
      resVal = resVal[currentPath] = isInteger$1(nextPath) && Number(nextPath) >= 0 ? [] : {};
    }
  } // Return original object if new value is the same as current

  if ((i === 0 ? obj : resVal)[pathArray[i]] === value) {
    return obj;
  }
  if (value === undefined) {
    delete resVal[pathArray[i]];
  } else {
    resVal[pathArray[i]] = value;
  } // If the path array has a single element, the loop did not run.
  // Deleting on `resVal` had no effect in this scenario, so we delete on the result instead.

  if (i === 0 && value === undefined) {
    delete res[pathArray[i]];
  }
  return res;
}
/**
 * Recursively a set the same value for all keys and arrays nested object, cloning
 * @param object
 * @param value
 * @param visited
 * @param response
 */

function setNestedObjectValues(object, value, visited, response) {
  if (visited === void 0) {
    visited = new WeakMap();
  }
  if (response === void 0) {
    response = {};
  }
  for (var _i = 0, _Object$keys = Object.keys(object); _i < _Object$keys.length; _i++) {
    var k = _Object$keys[_i];
    var val = object[k];
    if (isObject(val)) {
      if (!visited.get(val)) {
        visited.set(val, true); // In order to keep array values consistent for both dot path  and
        // bracket syntax, we need to check if this is an array so that
        // this will output  { friends: [true] } and not { friends: { "0": true } }

        response[k] = Array.isArray(val) ? [] : {};
        setNestedObjectValues(val, value, visited, response[k]);
      }
    } else {
      response[k] = value;
    }
  }
  return response;
}
function formikReducer(state, msg) {
  switch (msg.type) {
    case 'SET_VALUES':
      return _extends$1({}, state, {
        values: msg.payload
      });
    case 'SET_TOUCHED':
      return _extends$1({}, state, {
        touched: msg.payload
      });
    case 'SET_ERRORS':
      if (isEqual(state.errors, msg.payload)) {
        return state;
      }
      return _extends$1({}, state, {
        errors: msg.payload
      });
    case 'SET_STATUS':
      return _extends$1({}, state, {
        status: msg.payload
      });
    case 'SET_ISSUBMITTING':
      return _extends$1({}, state, {
        isSubmitting: msg.payload
      });
    case 'SET_ISVALIDATING':
      return _extends$1({}, state, {
        isValidating: msg.payload
      });
    case 'SET_FIELD_VALUE':
      return _extends$1({}, state, {
        values: setIn(state.values, msg.payload.field, msg.payload.value)
      });
    case 'SET_FIELD_TOUCHED':
      return _extends$1({}, state, {
        touched: setIn(state.touched, msg.payload.field, msg.payload.value)
      });
    case 'SET_FIELD_ERROR':
      return _extends$1({}, state, {
        errors: setIn(state.errors, msg.payload.field, msg.payload.value)
      });
    case 'RESET_FORM':
      return _extends$1({}, state, msg.payload);
    case 'SET_FORMIK_STATE':
      return msg.payload(state);
    case 'SUBMIT_ATTEMPT':
      return _extends$1({}, state, {
        touched: setNestedObjectValues(state.values, true),
        isSubmitting: true,
        submitCount: state.submitCount + 1
      });
    case 'SUBMIT_FAILURE':
      return _extends$1({}, state, {
        isSubmitting: false
      });
    case 'SUBMIT_SUCCESS':
      return _extends$1({}, state, {
        isSubmitting: false
      });
    default:
      return state;
  }
} // Initial empty states // objects

var emptyErrors = {};
var emptyTouched = {};
function useFormik(_ref) {
  var _ref$validateOnChange = _ref.validateOnChange,
    validateOnChange = _ref$validateOnChange === void 0 ? true : _ref$validateOnChange,
    _ref$validateOnBlur = _ref.validateOnBlur,
    validateOnBlur = _ref$validateOnBlur === void 0 ? true : _ref$validateOnBlur,
    _ref$validateOnMount = _ref.validateOnMount,
    validateOnMount = _ref$validateOnMount === void 0 ? false : _ref$validateOnMount,
    isInitialValid = _ref.isInitialValid,
    _ref$enableReinitiali = _ref.enableReinitialize,
    enableReinitialize = _ref$enableReinitiali === void 0 ? false : _ref$enableReinitiali,
    onSubmit = _ref.onSubmit,
    rest = _objectWithoutPropertiesLoose$1(_ref, ["validateOnChange", "validateOnBlur", "validateOnMount", "isInitialValid", "enableReinitialize", "onSubmit"]);
  var props = _extends$1({
    validateOnChange: validateOnChange,
    validateOnBlur: validateOnBlur,
    validateOnMount: validateOnMount,
    onSubmit: onSubmit
  }, rest);
  var initialValues = reactExports$1.useRef(props.initialValues);
  var initialErrors = reactExports$1.useRef(props.initialErrors || emptyErrors);
  var initialTouched = reactExports$1.useRef(props.initialTouched || emptyTouched);
  var initialStatus = reactExports$1.useRef(props.initialStatus);
  var isMounted = reactExports$1.useRef(false);
  var fieldRegistry = reactExports$1.useRef({});
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(function () {
      !(typeof isInitialValid === 'undefined') ? warning$1(false, 'isInitialValid has been deprecated and will be removed in future versions of Formik. Please use initialErrors or validateOnMount instead.')  : void 0; // eslint-disable-next-line
    }, []);
  }
  reactExports$1.useEffect(function () {
    isMounted.current = true;
    return function () {
      isMounted.current = false;
    };
  }, []);
  var _React$useState = reactExports$1.useState(0),
    setIteration = _React$useState[1];
  var stateRef = reactExports$1.useRef({
    values: props.initialValues,
    errors: props.initialErrors || emptyErrors,
    touched: props.initialTouched || emptyTouched,
    status: props.initialStatus,
    isSubmitting: false,
    isValidating: false,
    submitCount: 0
  });
  var state = stateRef.current;
  var dispatch = reactExports$1.useCallback(function (action) {
    var prev = stateRef.current;
    stateRef.current = formikReducer(prev, action); // force rerender

    if (prev !== stateRef.current) setIteration(function (x) {
      return x + 1;
    });
  }, []);
  var runValidateHandler = reactExports$1.useCallback(function (values, field) {
    return new Promise(function (resolve, reject) {
      var maybePromisedErrors = props.validate(values, field);
      if (maybePromisedErrors == null) {
        // use loose null check here on purpose
        resolve(emptyErrors);
      } else if (isPromise(maybePromisedErrors)) {
        maybePromisedErrors.then(function (errors) {
          resolve(errors || emptyErrors);
        }, function (actualException) {
          {
            console.warn("Warning: An unhandled error was caught during validation in <Formik validate />", actualException);
          }
          reject(actualException);
        });
      } else {
        resolve(maybePromisedErrors);
      }
    });
  }, [props.validate]);
  /**
   * Run validation against a Yup schema and optionally run a function if successful
   */

  var runValidationSchema = reactExports$1.useCallback(function (values, field) {
    var validationSchema = props.validationSchema;
    var schema = isFunction(validationSchema) ? validationSchema(field) : validationSchema;
    var promise = field && schema.validateAt ? schema.validateAt(field, values) : validateYupSchema(values, schema);
    return new Promise(function (resolve, reject) {
      promise.then(function () {
        resolve(emptyErrors);
      }, function (err) {
        // Yup will throw a validation error if validation fails. We catch those and
        // resolve them into Formik errors. We can sniff if something is a Yup error
        // by checking error.name.
        // @see https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string
        if (err.name === 'ValidationError') {
          resolve(yupToFormErrors(err));
        } else {
          // We throw any other errors
          {
            console.warn("Warning: An unhandled error was caught during validation in <Formik validationSchema />", err);
          }
          reject(err);
        }
      });
    });
  }, [props.validationSchema]);
  var runSingleFieldLevelValidation = reactExports$1.useCallback(function (field, value) {
    return new Promise(function (resolve) {
      return resolve(fieldRegistry.current[field].validate(value));
    });
  }, []);
  var runFieldLevelValidations = reactExports$1.useCallback(function (values) {
    var fieldKeysWithValidation = Object.keys(fieldRegistry.current).filter(function (f) {
      return isFunction(fieldRegistry.current[f].validate);
    }); // Construct an array with all of the field validation functions

    var fieldValidations = fieldKeysWithValidation.length > 0 ? fieldKeysWithValidation.map(function (f) {
      return runSingleFieldLevelValidation(f, getIn(values, f));
    }) : [Promise.resolve('DO_NOT_DELETE_YOU_WILL_BE_FIRED')]; // use special case ;)

    return Promise.all(fieldValidations).then(function (fieldErrorsList) {
      return fieldErrorsList.reduce(function (prev, curr, index) {
        if (curr === 'DO_NOT_DELETE_YOU_WILL_BE_FIRED') {
          return prev;
        }
        if (curr) {
          prev = setIn(prev, fieldKeysWithValidation[index], curr);
        }
        return prev;
      }, {});
    });
  }, [runSingleFieldLevelValidation]); // Run all validations and return the result

  var runAllValidations = reactExports$1.useCallback(function (values) {
    return Promise.all([runFieldLevelValidations(values), props.validationSchema ? runValidationSchema(values) : {}, props.validate ? runValidateHandler(values) : {}]).then(function (_ref2) {
      var fieldErrors = _ref2[0],
        schemaErrors = _ref2[1],
        validateErrors = _ref2[2];
      var combinedErrors = deepmerge_1.all([fieldErrors, schemaErrors, validateErrors], {
        arrayMerge: arrayMerge
      });
      return combinedErrors;
    });
  }, [props.validate, props.validationSchema, runFieldLevelValidations, runValidateHandler, runValidationSchema]); // Run all validations methods and update state accordingly

  var validateFormWithHighPriority = useEventCallback$1(function (values) {
    if (values === void 0) {
      values = state.values;
    }
    dispatch({
      type: 'SET_ISVALIDATING',
      payload: true
    });
    return runAllValidations(values).then(function (combinedErrors) {
      if (!!isMounted.current) {
        dispatch({
          type: 'SET_ISVALIDATING',
          payload: false
        });
        dispatch({
          type: 'SET_ERRORS',
          payload: combinedErrors
        });
      }
      return combinedErrors;
    });
  });
  reactExports$1.useEffect(function () {
    if (validateOnMount && isMounted.current === true && isEqual(initialValues.current, props.initialValues)) {
      validateFormWithHighPriority(initialValues.current);
    }
  }, [validateOnMount, validateFormWithHighPriority]);
  var resetForm = reactExports$1.useCallback(function (nextState) {
    var values = nextState && nextState.values ? nextState.values : initialValues.current;
    var errors = nextState && nextState.errors ? nextState.errors : initialErrors.current ? initialErrors.current : props.initialErrors || {};
    var touched = nextState && nextState.touched ? nextState.touched : initialTouched.current ? initialTouched.current : props.initialTouched || {};
    var status = nextState && nextState.status ? nextState.status : initialStatus.current ? initialStatus.current : props.initialStatus;
    initialValues.current = values;
    initialErrors.current = errors;
    initialTouched.current = touched;
    initialStatus.current = status;
    var dispatchFn = function dispatchFn() {
      dispatch({
        type: 'RESET_FORM',
        payload: {
          isSubmitting: !!nextState && !!nextState.isSubmitting,
          errors: errors,
          touched: touched,
          status: status,
          values: values,
          isValidating: !!nextState && !!nextState.isValidating,
          submitCount: !!nextState && !!nextState.submitCount && typeof nextState.submitCount === 'number' ? nextState.submitCount : 0
        }
      });
    };
    if (props.onReset) {
      var maybePromisedOnReset = props.onReset(state.values, imperativeMethods);
      if (isPromise(maybePromisedOnReset)) {
        maybePromisedOnReset.then(dispatchFn);
      } else {
        dispatchFn();
      }
    } else {
      dispatchFn();
    }
  }, [props.initialErrors, props.initialStatus, props.initialTouched]);
  reactExports$1.useEffect(function () {
    if (isMounted.current === true && !isEqual(initialValues.current, props.initialValues)) {
      if (enableReinitialize) {
        initialValues.current = props.initialValues;
        resetForm();
        if (validateOnMount) {
          validateFormWithHighPriority(initialValues.current);
        }
      }
    }
  }, [enableReinitialize, props.initialValues, resetForm, validateOnMount, validateFormWithHighPriority]);
  reactExports$1.useEffect(function () {
    if (enableReinitialize && isMounted.current === true && !isEqual(initialErrors.current, props.initialErrors)) {
      initialErrors.current = props.initialErrors || emptyErrors;
      dispatch({
        type: 'SET_ERRORS',
        payload: props.initialErrors || emptyErrors
      });
    }
  }, [enableReinitialize, props.initialErrors]);
  reactExports$1.useEffect(function () {
    if (enableReinitialize && isMounted.current === true && !isEqual(initialTouched.current, props.initialTouched)) {
      initialTouched.current = props.initialTouched || emptyTouched;
      dispatch({
        type: 'SET_TOUCHED',
        payload: props.initialTouched || emptyTouched
      });
    }
  }, [enableReinitialize, props.initialTouched]);
  reactExports$1.useEffect(function () {
    if (enableReinitialize && isMounted.current === true && !isEqual(initialStatus.current, props.initialStatus)) {
      initialStatus.current = props.initialStatus;
      dispatch({
        type: 'SET_STATUS',
        payload: props.initialStatus
      });
    }
  }, [enableReinitialize, props.initialStatus, props.initialTouched]);
  var validateField = useEventCallback$1(function (name) {
    // This will efficiently validate a single field by avoiding state
    // changes if the validation function is synchronous. It's different from
    // what is called when using validateForm.
    if (fieldRegistry.current[name] && isFunction(fieldRegistry.current[name].validate)) {
      var value = getIn(state.values, name);
      var maybePromise = fieldRegistry.current[name].validate(value);
      if (isPromise(maybePromise)) {
        // Only flip isValidating if the function is async.
        dispatch({
          type: 'SET_ISVALIDATING',
          payload: true
        });
        return maybePromise.then(function (x) {
          return x;
        }).then(function (error) {
          dispatch({
            type: 'SET_FIELD_ERROR',
            payload: {
              field: name,
              value: error
            }
          });
          dispatch({
            type: 'SET_ISVALIDATING',
            payload: false
          });
        });
      } else {
        dispatch({
          type: 'SET_FIELD_ERROR',
          payload: {
            field: name,
            value: maybePromise
          }
        });
        return Promise.resolve(maybePromise);
      }
    } else if (props.validationSchema) {
      dispatch({
        type: 'SET_ISVALIDATING',
        payload: true
      });
      return runValidationSchema(state.values, name).then(function (x) {
        return x;
      }).then(function (error) {
        dispatch({
          type: 'SET_FIELD_ERROR',
          payload: {
            field: name,
            value: getIn(error, name)
          }
        });
        dispatch({
          type: 'SET_ISVALIDATING',
          payload: false
        });
      });
    }
    return Promise.resolve();
  });
  var registerField = reactExports$1.useCallback(function (name, _ref3) {
    var validate = _ref3.validate;
    fieldRegistry.current[name] = {
      validate: validate
    };
  }, []);
  var unregisterField = reactExports$1.useCallback(function (name) {
    delete fieldRegistry.current[name];
  }, []);
  var setTouched = useEventCallback$1(function (touched, shouldValidate) {
    dispatch({
      type: 'SET_TOUCHED',
      payload: touched
    });
    var willValidate = shouldValidate === undefined ? validateOnBlur : shouldValidate;
    return willValidate ? validateFormWithHighPriority(state.values) : Promise.resolve();
  });
  var setErrors = reactExports$1.useCallback(function (errors) {
    dispatch({
      type: 'SET_ERRORS',
      payload: errors
    });
  }, []);
  var setValues = useEventCallback$1(function (values, shouldValidate) {
    var resolvedValues = isFunction(values) ? values(state.values) : values;
    dispatch({
      type: 'SET_VALUES',
      payload: resolvedValues
    });
    var willValidate = shouldValidate === undefined ? validateOnChange : shouldValidate;
    return willValidate ? validateFormWithHighPriority(resolvedValues) : Promise.resolve();
  });
  var setFieldError = reactExports$1.useCallback(function (field, value) {
    dispatch({
      type: 'SET_FIELD_ERROR',
      payload: {
        field: field,
        value: value
      }
    });
  }, []);
  var setFieldValue = useEventCallback$1(function (field, value, shouldValidate) {
    dispatch({
      type: 'SET_FIELD_VALUE',
      payload: {
        field: field,
        value: value
      }
    });
    var willValidate = shouldValidate === undefined ? validateOnChange : shouldValidate;
    return willValidate ? validateFormWithHighPriority(setIn(state.values, field, value)) : Promise.resolve();
  });
  var executeChange = reactExports$1.useCallback(function (eventOrTextValue, maybePath) {
    // By default, assume that the first argument is a string. This allows us to use
    // handleChange with React Native and React Native Web's onChangeText prop which
    // provides just the value of the input.
    var field = maybePath;
    var val = eventOrTextValue;
    var parsed; // If the first argument is not a string though, it has to be a synthetic React Event (or a fake one),
    // so we handle like we would a normal HTML change event.

    if (!isString(eventOrTextValue)) {
      // If we can, persist the event
      // @see https://reactjs.org/docs/events.html#event-pooling
      if (eventOrTextValue.persist) {
        eventOrTextValue.persist();
      }
      var target = eventOrTextValue.target ? eventOrTextValue.target : eventOrTextValue.currentTarget;
      var type = target.type,
        name = target.name,
        id = target.id,
        value = target.value,
        checked = target.checked,
        outerHTML = target.outerHTML,
        options = target.options,
        multiple = target.multiple;
      field = maybePath ? maybePath : name ? name : id;
      if (!field && "development" !== "production") {
        warnAboutMissingIdentifier({
          htmlContent: outerHTML,
          documentationAnchorLink: 'handlechange-e-reactchangeeventany--void',
          handlerName: 'handleChange'
        });
      }
      val = /number|range/.test(type) ? (parsed = parseFloat(value), isNaN(parsed) ? '' : parsed) : /checkbox/.test(type) // checkboxes
      ? getValueForCheckbox(getIn(state.values, field), checked, value) : options && multiple // <select multiple>
      ? getSelectedValues(options) : value;
    }
    if (field) {
      // Set form fields by name
      setFieldValue(field, val);
    }
  }, [setFieldValue, state.values]);
  var handleChange = useEventCallback$1(function (eventOrPath) {
    if (isString(eventOrPath)) {
      return function (event) {
        return executeChange(event, eventOrPath);
      };
    } else {
      executeChange(eventOrPath);
    }
  });
  var setFieldTouched = useEventCallback$1(function (field, touched, shouldValidate) {
    if (touched === void 0) {
      touched = true;
    }
    dispatch({
      type: 'SET_FIELD_TOUCHED',
      payload: {
        field: field,
        value: touched
      }
    });
    var willValidate = shouldValidate === undefined ? validateOnBlur : shouldValidate;
    return willValidate ? validateFormWithHighPriority(state.values) : Promise.resolve();
  });
  var executeBlur = reactExports$1.useCallback(function (e, path) {
    if (e.persist) {
      e.persist();
    }
    var _e$target = e.target,
      name = _e$target.name,
      id = _e$target.id,
      outerHTML = _e$target.outerHTML;
    var field = path ? path : name ? name : id;
    if (!field && "development" !== "production") {
      warnAboutMissingIdentifier({
        htmlContent: outerHTML,
        documentationAnchorLink: 'handleblur-e-any--void',
        handlerName: 'handleBlur'
      });
    }
    setFieldTouched(field, true);
  }, [setFieldTouched]);
  var handleBlur = useEventCallback$1(function (eventOrString) {
    if (isString(eventOrString)) {
      return function (event) {
        return executeBlur(event, eventOrString);
      };
    } else {
      executeBlur(eventOrString);
    }
  });
  var setFormikState = reactExports$1.useCallback(function (stateOrCb) {
    if (isFunction(stateOrCb)) {
      dispatch({
        type: 'SET_FORMIK_STATE',
        payload: stateOrCb
      });
    } else {
      dispatch({
        type: 'SET_FORMIK_STATE',
        payload: function payload() {
          return stateOrCb;
        }
      });
    }
  }, []);
  var setStatus = reactExports$1.useCallback(function (status) {
    dispatch({
      type: 'SET_STATUS',
      payload: status
    });
  }, []);
  var setSubmitting = reactExports$1.useCallback(function (isSubmitting) {
    dispatch({
      type: 'SET_ISSUBMITTING',
      payload: isSubmitting
    });
  }, []);
  var submitForm = useEventCallback$1(function () {
    dispatch({
      type: 'SUBMIT_ATTEMPT'
    });
    return validateFormWithHighPriority().then(function (combinedErrors) {
      // In case an error was thrown and passed to the resolved Promise,
      // `combinedErrors` can be an instance of an Error. We need to check
      // that and abort the submit.
      // If we don't do that, calling `Object.keys(new Error())` yields an
      // empty array, which causes the validation to pass and the form
      // to be submitted.
      var isInstanceOfError = combinedErrors instanceof Error;
      var isActuallyValid = !isInstanceOfError && Object.keys(combinedErrors).length === 0;
      if (isActuallyValid) {
        // Proceed with submit...
        //
        // To respect sync submit fns, we can't simply wrap executeSubmit in a promise and
        // _always_ dispatch SUBMIT_SUCCESS because isSubmitting would then always be false.
        // This would be fine in simple cases, but make it impossible to disable submit
        // buttons where people use callbacks or promises as side effects (which is basically
        // all of v1 Formik code). Instead, recall that we are inside of a promise chain already,
        //  so we can try/catch executeSubmit(), if it returns undefined, then just bail.
        // If there are errors, throw em. Otherwise, wrap executeSubmit in a promise and handle
        // cleanup of isSubmitting on behalf of the consumer.
        var promiseOrUndefined;
        try {
          promiseOrUndefined = executeSubmit(); // Bail if it's sync, consumer is responsible for cleaning up
          // via setSubmitting(false)

          if (promiseOrUndefined === undefined) {
            return;
          }
        } catch (error) {
          throw error;
        }
        return Promise.resolve(promiseOrUndefined).then(function (result) {
          if (!!isMounted.current) {
            dispatch({
              type: 'SUBMIT_SUCCESS'
            });
          }
          return result;
        })["catch"](function (_errors) {
          if (!!isMounted.current) {
            dispatch({
              type: 'SUBMIT_FAILURE'
            }); // This is a legit error rejected by the onSubmit fn
            // so we don't want to break the promise chain

            throw _errors;
          }
        });
      } else if (!!isMounted.current) {
        // ^^^ Make sure Formik is still mounted before updating state
        dispatch({
          type: 'SUBMIT_FAILURE'
        }); // throw combinedErrors;

        if (isInstanceOfError) {
          throw combinedErrors;
        }
      }
      return;
    });
  });
  var handleSubmit = useEventCallback$1(function (e) {
    if (e && e.preventDefault && isFunction(e.preventDefault)) {
      e.preventDefault();
    }
    if (e && e.stopPropagation && isFunction(e.stopPropagation)) {
      e.stopPropagation();
    } // Warn if form submission is triggered by a <button> without a
    // specified `type` attribute during development. This mitigates
    // a common gotcha in forms with both reset and submit buttons,
    // where the dev forgets to add type="button" to the reset button.

    if (typeof document !== 'undefined') {
      // Safely get the active element (works with IE)
      var activeElement = getActiveElement();
      if (activeElement !== null && activeElement instanceof HTMLButtonElement) {
        !(activeElement.attributes && activeElement.attributes.getNamedItem('type')) ? warning$1(false, 'You submitted a Formik form using a button with an unspecified `type` attribute.  Most browsers default button elements to `type="submit"`. If this is not a submit button, please add `type="button"`.')  : void 0;
      }
    }
    submitForm()["catch"](function (reason) {
      console.warn("Warning: An unhandled error was caught from submitForm()", reason);
    });
  });
  var imperativeMethods = {
    resetForm: resetForm,
    validateForm: validateFormWithHighPriority,
    validateField: validateField,
    setErrors: setErrors,
    setFieldError: setFieldError,
    setFieldTouched: setFieldTouched,
    setFieldValue: setFieldValue,
    setStatus: setStatus,
    setSubmitting: setSubmitting,
    setTouched: setTouched,
    setValues: setValues,
    setFormikState: setFormikState,
    submitForm: submitForm
  };
  var executeSubmit = useEventCallback$1(function () {
    return onSubmit(state.values, imperativeMethods);
  });
  var handleReset = useEventCallback$1(function (e) {
    if (e && e.preventDefault && isFunction(e.preventDefault)) {
      e.preventDefault();
    }
    if (e && e.stopPropagation && isFunction(e.stopPropagation)) {
      e.stopPropagation();
    }
    resetForm();
  });
  var getFieldMeta = reactExports$1.useCallback(function (name) {
    return {
      value: getIn(state.values, name),
      error: getIn(state.errors, name),
      touched: !!getIn(state.touched, name),
      initialValue: getIn(initialValues.current, name),
      initialTouched: !!getIn(initialTouched.current, name),
      initialError: getIn(initialErrors.current, name)
    };
  }, [state.errors, state.touched, state.values]);
  var getFieldHelpers = reactExports$1.useCallback(function (name) {
    return {
      setValue: function setValue(value, shouldValidate) {
        return setFieldValue(name, value, shouldValidate);
      },
      setTouched: function setTouched(value, shouldValidate) {
        return setFieldTouched(name, value, shouldValidate);
      },
      setError: function setError(value) {
        return setFieldError(name, value);
      }
    };
  }, [setFieldValue, setFieldTouched, setFieldError]);
  var getFieldProps = reactExports$1.useCallback(function (nameOrOptions) {
    var isAnObject = isObject(nameOrOptions);
    var name = isAnObject ? nameOrOptions.name : nameOrOptions;
    var valueState = getIn(state.values, name);
    var field = {
      name: name,
      value: valueState,
      onChange: handleChange,
      onBlur: handleBlur
    };
    if (isAnObject) {
      var type = nameOrOptions.type,
        valueProp = nameOrOptions.value,
        is = nameOrOptions.as,
        multiple = nameOrOptions.multiple;
      if (type === 'checkbox') {
        if (valueProp === undefined) {
          field.checked = !!valueState;
        } else {
          field.checked = !!(Array.isArray(valueState) && ~valueState.indexOf(valueProp));
          field.value = valueProp;
        }
      } else if (type === 'radio') {
        field.checked = valueState === valueProp;
        field.value = valueProp;
      } else if (is === 'select' && multiple) {
        field.value = field.value || [];
        field.multiple = true;
      }
    }
    return field;
  }, [handleBlur, handleChange, state.values]);
  var dirty = reactExports$1.useMemo(function () {
    return !isEqual(initialValues.current, state.values);
  }, [initialValues.current, state.values]);
  var isValid = reactExports$1.useMemo(function () {
    return typeof isInitialValid !== 'undefined' ? dirty ? state.errors && Object.keys(state.errors).length === 0 : isInitialValid !== false && isFunction(isInitialValid) ? isInitialValid(props) : isInitialValid : state.errors && Object.keys(state.errors).length === 0;
  }, [isInitialValid, dirty, state.errors, props]);
  var ctx = _extends$1({}, state, {
    initialValues: initialValues.current,
    initialErrors: initialErrors.current,
    initialTouched: initialTouched.current,
    initialStatus: initialStatus.current,
    handleBlur: handleBlur,
    handleChange: handleChange,
    handleReset: handleReset,
    handleSubmit: handleSubmit,
    resetForm: resetForm,
    setErrors: setErrors,
    setFormikState: setFormikState,
    setFieldTouched: setFieldTouched,
    setFieldValue: setFieldValue,
    setFieldError: setFieldError,
    setStatus: setStatus,
    setSubmitting: setSubmitting,
    setTouched: setTouched,
    setValues: setValues,
    submitForm: submitForm,
    validateForm: validateFormWithHighPriority,
    validateField: validateField,
    isValid: isValid,
    dirty: dirty,
    unregisterField: unregisterField,
    registerField: registerField,
    getFieldProps: getFieldProps,
    getFieldMeta: getFieldMeta,
    getFieldHelpers: getFieldHelpers,
    validateOnBlur: validateOnBlur,
    validateOnChange: validateOnChange,
    validateOnMount: validateOnMount
  });
  return ctx;
}
function Formik(props) {
  var formikbag = useFormik(props);
  var component = props.component,
    children = props.children,
    render = props.render,
    innerRef = props.innerRef; // This allows folks to pass a ref to <Formik />

  reactExports$1.useImperativeHandle(innerRef, function () {
    return formikbag;
  });
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(function () {
      !!props.render ? warning$1(false, "<Formik render> has been deprecated and will be removed in future versions of Formik. Please use a child callback function instead. To get rid of this warning, replace <Formik render={(props) => ...} /> with <Formik>{(props) => ...}</Formik>")  : void 0; // eslint-disable-next-line
    }, []);
  }
  return reactExports$1.createElement(FormikProvider, {
    value: formikbag
  }, component ? reactExports$1.createElement(component, formikbag) : render ? render(formikbag) : children // children come last, always called
  ? isFunction(children) ? children(formikbag) : !isEmptyChildren(children) ? reactExports$1.Children.only(children) : null : null);
}
function warnAboutMissingIdentifier(_ref4) {
  var htmlContent = _ref4.htmlContent,
    documentationAnchorLink = _ref4.documentationAnchorLink,
    handlerName = _ref4.handlerName;
  console.warn("Warning: Formik called `" + handlerName + "`, but you forgot to pass an `id` or `name` attribute to your input:\n    " + htmlContent + "\n    Formik cannot determine which value to update. For more info see https://formik.org/docs/api/formik#" + documentationAnchorLink + "\n  ");
}
/**
 * Transform Yup ValidationError to a more usable object
 */

function yupToFormErrors(yupError) {
  var errors = {};
  if (yupError.inner) {
    if (yupError.inner.length === 0) {
      return setIn(errors, yupError.path, yupError.message);
    }
    for (var _iterator = yupError.inner, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
      var _ref5;
      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref5 = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref5 = _i.value;
      }
      var err = _ref5;
      if (!getIn(errors, err.path)) {
        errors = setIn(errors, err.path, err.message);
      }
    }
  }
  return errors;
}
/**
 * Validate a yup schema.
 */

function validateYupSchema(values, schema, sync, context) {
  if (sync === void 0) {
    sync = false;
  }
  var normalizedValues = prepareDataForValidation(values);
  return schema[sync ? 'validateSync' : 'validate'](normalizedValues, {
    abortEarly: false,
    context: context || normalizedValues
  });
}
/**
 * Recursively prepare values.
 */

function prepareDataForValidation(values) {
  var data = Array.isArray(values) ? [] : {};
  for (var k in values) {
    if (Object.prototype.hasOwnProperty.call(values, k)) {
      var key = String(k);
      if (Array.isArray(values[key]) === true) {
        data[key] = values[key].map(function (value) {
          if (Array.isArray(value) === true || isPlainObject$2(value)) {
            return prepareDataForValidation(value);
          } else {
            return value !== '' ? value : undefined;
          }
        });
      } else if (isPlainObject$2(values[key])) {
        data[key] = prepareDataForValidation(values[key]);
      } else {
        data[key] = values[key] !== '' ? values[key] : undefined;
      }
    }
  }
  return data;
}
/**
 * deepmerge array merging algorithm
 * https://github.com/KyleAMathews/deepmerge#combine-array
 */

function arrayMerge(target, source, options) {
  var destination = target.slice();
  source.forEach(function merge(e, i) {
    if (typeof destination[i] === 'undefined') {
      var cloneRequested = options.clone !== false;
      var shouldClone = cloneRequested && options.isMergeableObject(e);
      destination[i] = shouldClone ? deepmerge_1(Array.isArray(e) ? [] : {}, e, options) : e;
    } else if (options.isMergeableObject(e)) {
      destination[i] = deepmerge_1(target[i], e, options);
    } else if (target.indexOf(e) === -1) {
      destination.push(e);
    }
  });
  return destination;
}
/** Return multi select values based on an array of options */

function getSelectedValues(options) {
  return Array.from(options).filter(function (el) {
    return el.selected;
  }).map(function (el) {
    return el.value;
  });
}
/** Return the next value for a checkbox */

function getValueForCheckbox(currentValue, checked, valueProp) {
  // If the current value was a boolean, return a boolean
  if (typeof currentValue === 'boolean') {
    return Boolean(checked);
  } // If the currentValue was not a boolean we want to return an array

  var currentArrayOfValues = [];
  var isValueInArray = false;
  var index = -1;
  if (!Array.isArray(currentValue)) {
    // eslint-disable-next-line eqeqeq
    if (!valueProp || valueProp == 'true' || valueProp == 'false') {
      return Boolean(checked);
    }
  } else {
    // If the current value is already an array, use it
    currentArrayOfValues = currentValue;
    index = currentValue.indexOf(valueProp);
    isValueInArray = index >= 0;
  } // If the checkbox was checked and the value is not already present in the aray we want to add the new value to the array of values

  if (checked && valueProp && !isValueInArray) {
    return currentArrayOfValues.concat(valueProp);
  } // If the checkbox was unchecked and the value is not in the array, simply return the already existing array of values

  if (!isValueInArray) {
    return currentArrayOfValues;
  } // If the checkbox was unchecked and the value is in the array, remove the value and return the array

  return currentArrayOfValues.slice(0, index).concat(currentArrayOfValues.slice(index + 1));
} // React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser.
// @see https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85

var useIsomorphicLayoutEffect$2 = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? reactExports$1.useLayoutEffect : reactExports$1.useEffect;
function useEventCallback$1(fn) {
  var ref = reactExports$1.useRef(fn); // we copy a ref to the callback scoped to the current state/props on each render

  useIsomorphicLayoutEffect$2(function () {
    ref.current = fn;
  });
  return reactExports$1.useCallback(function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    return ref.current.apply(void 0, args);
  }, []);
}
function useField(propsOrFieldName) {
  var formik = useFormikContext();
  var getFieldProps = formik.getFieldProps,
    getFieldMeta = formik.getFieldMeta,
    getFieldHelpers = formik.getFieldHelpers,
    registerField = formik.registerField,
    unregisterField = formik.unregisterField;
  var isAnObject = isObject(propsOrFieldName); // Normalize propsOrFieldName to FieldHookConfig<Val>

  var props = isAnObject ? propsOrFieldName : {
    name: propsOrFieldName
  };
  var fieldName = props.name,
    validateFn = props.validate;
  reactExports$1.useEffect(function () {
    if (fieldName) {
      registerField(fieldName, {
        validate: validateFn
      });
    }
    return function () {
      if (fieldName) {
        unregisterField(fieldName);
      }
    };
  }, [registerField, unregisterField, fieldName, validateFn]);
  {
    !formik ? warning$1(false, 'useField() / <Field /> must be used underneath a <Formik> component or withFormik() higher order component')  : void 0;
  }
  !fieldName ? warning$1(false, 'Invalid field name. Either pass `useField` a string or an object containing a `name` key.')  : void 0;
  var fieldHelpers = reactExports$1.useMemo(function () {
    return getFieldHelpers(fieldName);
  }, [getFieldHelpers, fieldName]);
  return [getFieldProps(props), getFieldMeta(fieldName), fieldHelpers];
}
function Field(_ref) {
  var validate = _ref.validate,
    name = _ref.name,
    render = _ref.render,
    children = _ref.children,
    is = _ref.as,
    component = _ref.component,
    props = _objectWithoutPropertiesLoose$1(_ref, ["validate", "name", "render", "children", "as", "component"]);
  var _useFormikContext = useFormikContext(),
    formik = _objectWithoutPropertiesLoose$1(_useFormikContext, ["validate", "validationSchema"]);
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(function () {
      !!render ? warning$1(false, "<Field render> has been deprecated and will be removed in future versions of Formik. Please use a child callback function instead. To get rid of this warning, replace <Field name=\"" + name + "\" render={({field, form}) => ...} /> with <Field name=\"" + name + "\">{({field, form, meta}) => ...}</Field>")  : void 0;
      !!(is && children && isFunction(children)) ? warning$1(false, 'You should not use <Field as> and <Field children> as a function in the same <Field> component; <Field as> will be ignored.')  : void 0;
      !!(component && children && isFunction(children)) ? warning$1(false, 'You should not use <Field component> and <Field children> as a function in the same <Field> component; <Field component> will be ignored.')  : void 0;
      !!(render && children && !isEmptyChildren(children)) ? warning$1(false, 'You should not use <Field render> and <Field children> in the same <Field> component; <Field children> will be ignored')  : void 0; // eslint-disable-next-line
    }, []);
  } // Register field and field-level validation with parent <Formik>

  var registerField = formik.registerField,
    unregisterField = formik.unregisterField;
  reactExports$1.useEffect(function () {
    registerField(name, {
      validate: validate
    });
    return function () {
      unregisterField(name);
    };
  }, [registerField, unregisterField, name, validate]);
  var field = formik.getFieldProps(_extends$1({
    name: name
  }, props));
  var meta = formik.getFieldMeta(name);
  var legacyBag = {
    field: field,
    form: formik
  };
  if (render) {
    return render(_extends$1({}, legacyBag, {
      meta: meta
    }));
  }
  if (isFunction(children)) {
    return children(_extends$1({}, legacyBag, {
      meta: meta
    }));
  }
  if (component) {
    // This behavior is backwards compat with earlier Formik 0.9 to 1.x
    if (typeof component === 'string') {
      var innerRef = props.innerRef,
        rest = _objectWithoutPropertiesLoose$1(props, ["innerRef"]);
      return reactExports$1.createElement(component, _extends$1({
        ref: innerRef
      }, field, rest), children);
    } // We don't pass `meta` for backwards compat

    return reactExports$1.createElement(component, _extends$1({
      field: field,
      form: formik
    }, props), children);
  } // default to input here so we can check for both `as` and `children` above

  var asElement = is || 'input';
  if (typeof asElement === 'string') {
    var _innerRef = props.innerRef,
      _rest = _objectWithoutPropertiesLoose$1(props, ["innerRef"]);
    return reactExports$1.createElement(asElement, _extends$1({
      ref: _innerRef
    }, field, _rest), children);
  }
  return reactExports$1.createElement(asElement, _extends$1({}, field, props), children);
}
var Form$2 = /*#__PURE__*/reactExports$1.forwardRef(function (props, ref) {
  // iOS needs an "action" attribute for nice input: https://stackoverflow.com/a/39485162/406725
  // We default the action to "#" in case the preventDefault fails (just updates the URL hash)
  var action = props.action,
    rest = _objectWithoutPropertiesLoose$1(props, ["action"]);
  var _action = action != null ? action : '#';
  var _useFormikContext = useFormikContext(),
    handleReset = _useFormikContext.handleReset,
    handleSubmit = _useFormikContext.handleSubmit;
  return reactExports$1.createElement("form", _extends$1({
    onSubmit: handleSubmit,
    ref: ref,
    onReset: handleReset,
    action: _action
  }, rest));
});
Form$2.displayName = 'Form';

/**
 * A public higher-order component to access the imperative API
 */

function withFormik(_ref) {
  var _ref$mapPropsToValues = _ref.mapPropsToValues,
    mapPropsToValues = _ref$mapPropsToValues === void 0 ? function (vanillaProps) {
      var val = {};
      for (var k in vanillaProps) {
        if (vanillaProps.hasOwnProperty(k) && typeof vanillaProps[k] !== 'function') {
          // @todo TypeScript fix
          val[k] = vanillaProps[k];
        }
      }
      return val;
    } : _ref$mapPropsToValues,
    config = _objectWithoutPropertiesLoose$1(_ref, ["mapPropsToValues"]);
  return function createFormik(Component$1) {
    var componentDisplayName = Component$1.displayName || Component$1.name || Component$1.constructor && Component$1.constructor.name || 'Component';
    /**
     * We need to use closures here for to provide the wrapped component's props to
     * the respective withFormik config methods.
     */

    var C = /*#__PURE__*/function (_React$Component) {
      _inheritsLoose(C, _React$Component);
      function C() {
        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.validate = function (values) {
          return config.validate(values, _this.props);
        };
        _this.validationSchema = function () {
          return isFunction(config.validationSchema) ? config.validationSchema(_this.props) : config.validationSchema;
        };
        _this.handleSubmit = function (values, actions) {
          return config.handleSubmit(values, _extends$1({}, actions, {
            props: _this.props
          }));
        };
        _this.renderFormComponent = function (formikProps) {
          return reactExports$1.createElement(Component$1, _extends$1({}, _this.props, formikProps));
        };
        return _this;
      }
      var _proto = C.prototype;
      _proto.render = function render() {
        var _this$props = this.props,
          props = _objectWithoutPropertiesLoose$1(_this$props, ["children"]);
        return reactExports$1.createElement(Formik, _extends$1({}, props, config, {
          validate: config.validate && this.validate,
          validationSchema: config.validationSchema && this.validationSchema,
          initialValues: mapPropsToValues(this.props),
          initialStatus: config.mapPropsToStatus && config.mapPropsToStatus(this.props),
          initialErrors: config.mapPropsToErrors && config.mapPropsToErrors(this.props),
          initialTouched: config.mapPropsToTouched && config.mapPropsToTouched(this.props),
          onSubmit: this.handleSubmit,
          children: this.renderFormComponent
        }));
      };
      return C;
    }(reactExports$1.Component);
    C.displayName = "WithFormik(" + componentDisplayName + ")";
    return hoistNonReactStatics$1$1(C, Component$1 // cast type to ComponentClass (even if SFC)
    );
  };
}

/**
 * Connect any component to Formik context, and inject as a prop called `formik`;
 * @param Comp React Component
 */

function connect$1(Comp) {
  var C = function C(props) {
    return reactExports$1.createElement(FormikConsumer, null, function (formik) {
      !!!formik ? warning$1(false, "Formik context is undefined, please verify you are rendering <Form>, <Field>, <FastField>, <FieldArray>, or your custom context-using component as a child of a <Formik> component. Component name: " + Comp.name)  : void 0;
      return reactExports$1.createElement(Comp, _extends$1({}, props, {
        formik: formik
      }));
    });
  };
  var componentDisplayName = Comp.displayName || Comp.name || Comp.constructor && Comp.constructor.name || 'Component'; // Assign Comp to C.WrappedComponent so we can access the inner component in tests
  // For example, <Field.WrappedComponent /> gets us <FieldInner/>

  C.WrappedComponent = Comp;
  C.displayName = "FormikConnect(" + componentDisplayName + ")";
  return hoistNonReactStatics$1$1(C, Comp // cast type to ComponentClass (even if SFC)
  );
}

/**
 * Some array helpers!
 */

var move = function move(array, from, to) {
  var copy = copyArrayLike(array);
  var value = copy[from];
  copy.splice(from, 1);
  copy.splice(to, 0, value);
  return copy;
};
var swap = function swap(arrayLike, indexA, indexB) {
  var copy = copyArrayLike(arrayLike);
  var a = copy[indexA];
  copy[indexA] = copy[indexB];
  copy[indexB] = a;
  return copy;
};
var insert = function insert(arrayLike, index, value) {
  var copy = copyArrayLike(arrayLike);
  copy.splice(index, 0, value);
  return copy;
};
var replace$1 = function replace(arrayLike, index, value) {
  var copy = copyArrayLike(arrayLike);
  copy[index] = value;
  return copy;
};
var copyArrayLike = function copyArrayLike(arrayLike) {
  if (!arrayLike) {
    return [];
  } else if (Array.isArray(arrayLike)) {
    return [].concat(arrayLike);
  } else {
    var maxIndex = Object.keys(arrayLike).map(function (key) {
      return parseInt(key);
    }).reduce(function (max, el) {
      return el > max ? el : max;
    }, 0);
    return Array.from(_extends$1({}, arrayLike, {
      length: maxIndex + 1
    }));
  }
};
var createAlterationHandler = function createAlterationHandler(alteration, defaultFunction) {
  var fn = typeof alteration === 'function' ? alteration : defaultFunction;
  return function (data) {
    if (Array.isArray(data) || isObject(data)) {
      var clone = copyArrayLike(data);
      return fn(clone);
    } // This can be assumed to be a primitive, which
    // is a case for top level validation errors

    return data;
  };
};
var FieldArrayInner = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose(FieldArrayInner, _React$Component);
  function FieldArrayInner(props) {
    var _this;
    _this = _React$Component.call(this, props) || this; // We need TypeScript generics on these, so we'll bind them in the constructor
    // @todo Fix TS 3.2.1

    _this.updateArrayField = function (fn, alterTouched, alterErrors) {
      var _this$props = _this.props,
        name = _this$props.name,
        setFormikState = _this$props.formik.setFormikState;
      setFormikState(function (prevState) {
        var updateErrors = createAlterationHandler(alterErrors, fn);
        var updateTouched = createAlterationHandler(alterTouched, fn); // values fn should be executed before updateErrors and updateTouched,
        // otherwise it causes an error with unshift.

        var values = setIn(prevState.values, name, fn(getIn(prevState.values, name)));
        var fieldError = alterErrors ? updateErrors(getIn(prevState.errors, name)) : undefined;
        var fieldTouched = alterTouched ? updateTouched(getIn(prevState.touched, name)) : undefined;
        if (isEmptyArray(fieldError)) {
          fieldError = undefined;
        }
        if (isEmptyArray(fieldTouched)) {
          fieldTouched = undefined;
        }
        return _extends$1({}, prevState, {
          values: values,
          errors: alterErrors ? setIn(prevState.errors, name, fieldError) : prevState.errors,
          touched: alterTouched ? setIn(prevState.touched, name, fieldTouched) : prevState.touched
        });
      });
    };
    _this.push = function (value) {
      return _this.updateArrayField(function (arrayLike) {
        return [].concat(copyArrayLike(arrayLike), [cloneDeep(value)]);
      }, false, false);
    };
    _this.handlePush = function (value) {
      return function () {
        return _this.push(value);
      };
    };
    _this.swap = function (indexA, indexB) {
      return _this.updateArrayField(function (array) {
        return swap(array, indexA, indexB);
      }, true, true);
    };
    _this.handleSwap = function (indexA, indexB) {
      return function () {
        return _this.swap(indexA, indexB);
      };
    };
    _this.move = function (from, to) {
      return _this.updateArrayField(function (array) {
        return move(array, from, to);
      }, true, true);
    };
    _this.handleMove = function (from, to) {
      return function () {
        return _this.move(from, to);
      };
    };
    _this.insert = function (index, value) {
      return _this.updateArrayField(function (array) {
        return insert(array, index, value);
      }, function (array) {
        return insert(array, index, null);
      }, function (array) {
        return insert(array, index, null);
      });
    };
    _this.handleInsert = function (index, value) {
      return function () {
        return _this.insert(index, value);
      };
    };
    _this.replace = function (index, value) {
      return _this.updateArrayField(function (array) {
        return replace$1(array, index, value);
      }, false, false);
    };
    _this.handleReplace = function (index, value) {
      return function () {
        return _this.replace(index, value);
      };
    };
    _this.unshift = function (value) {
      var length = -1;
      _this.updateArrayField(function (array) {
        var arr = array ? [value].concat(array) : [value];
        length = arr.length;
        return arr;
      }, function (array) {
        return array ? [null].concat(array) : [null];
      }, function (array) {
        return array ? [null].concat(array) : [null];
      });
      return length;
    };
    _this.handleUnshift = function (value) {
      return function () {
        return _this.unshift(value);
      };
    };
    _this.handleRemove = function (index) {
      return function () {
        return _this.remove(index);
      };
    };
    _this.handlePop = function () {
      return function () {
        return _this.pop();
      };
    };
    _this.remove = _this.remove.bind(_assertThisInitialized$1(_this));
    _this.pop = _this.pop.bind(_assertThisInitialized$1(_this));
    return _this;
  }
  var _proto = FieldArrayInner.prototype;
  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    if (this.props.validateOnChange && this.props.formik.validateOnChange && !isEqual(getIn(prevProps.formik.values, prevProps.name), getIn(this.props.formik.values, this.props.name))) {
      this.props.formik.validateForm(this.props.formik.values);
    }
  };
  _proto.remove = function remove(index) {
    // We need to make sure we also remove relevant pieces of `touched` and `errors`
    var result;
    this.updateArrayField(
    // so this gets call 3 times
    function (array) {
      var copy = array ? copyArrayLike(array) : [];
      if (!result) {
        result = copy[index];
      }
      if (isFunction(copy.splice)) {
        copy.splice(index, 1);
      } // if the array only includes undefined values we have to return an empty array

      return isFunction(copy.every) ? copy.every(function (v) {
        return v === undefined;
      }) ? [] : copy : copy;
    }, true, true);
    return result;
  };
  _proto.pop = function pop() {
    // Remove relevant pieces of `touched` and `errors` too!
    var result;
    this.updateArrayField(
    // so this gets call 3 times
    function (array) {
      var tmp = array.slice();
      if (!result) {
        result = tmp && tmp.pop && tmp.pop();
      }
      return tmp;
    }, true, true);
    return result;
  };
  _proto.render = function render() {
    var arrayHelpers = {
      push: this.push,
      pop: this.pop,
      swap: this.swap,
      move: this.move,
      insert: this.insert,
      replace: this.replace,
      unshift: this.unshift,
      remove: this.remove,
      handlePush: this.handlePush,
      handlePop: this.handlePop,
      handleSwap: this.handleSwap,
      handleMove: this.handleMove,
      handleInsert: this.handleInsert,
      handleReplace: this.handleReplace,
      handleUnshift: this.handleUnshift,
      handleRemove: this.handleRemove
    };
    var _this$props2 = this.props,
      component = _this$props2.component,
      render = _this$props2.render,
      children = _this$props2.children,
      name = _this$props2.name,
      _this$props2$formik = _this$props2.formik,
      restOfFormik = _objectWithoutPropertiesLoose$1(_this$props2$formik, ["validate", "validationSchema"]);
    var props = _extends$1({}, arrayHelpers, {
      form: restOfFormik,
      name: name
    });
    return component ? reactExports$1.createElement(component, props) : render ? render(props) : children // children come last, always called
    ? typeof children === 'function' ? children(props) : !isEmptyChildren(children) ? reactExports$1.Children.only(children) : null : null;
  };
  return FieldArrayInner;
}(reactExports$1.Component);
FieldArrayInner.defaultProps = {
  validateOnChange: true
};
var FieldArray = /*#__PURE__*/connect$1(FieldArrayInner);
var ErrorMessageImpl = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose(ErrorMessageImpl, _React$Component);
  function ErrorMessageImpl() {
    return _React$Component.apply(this, arguments) || this;
  }
  var _proto = ErrorMessageImpl.prototype;
  _proto.shouldComponentUpdate = function shouldComponentUpdate(props) {
    if (getIn(this.props.formik.errors, this.props.name) !== getIn(props.formik.errors, this.props.name) || getIn(this.props.formik.touched, this.props.name) !== getIn(props.formik.touched, this.props.name) || Object.keys(this.props).length !== Object.keys(props).length) {
      return true;
    } else {
      return false;
    }
  };
  _proto.render = function render() {
    var _this$props = this.props,
      component = _this$props.component,
      formik = _this$props.formik,
      render = _this$props.render,
      children = _this$props.children,
      name = _this$props.name,
      rest = _objectWithoutPropertiesLoose$1(_this$props, ["component", "formik", "render", "children", "name"]);
    var touch = getIn(formik.touched, name);
    var error = getIn(formik.errors, name);
    return !!touch && !!error ? render ? isFunction(render) ? render(error) : null : children ? isFunction(children) ? children(error) : null : component ? reactExports$1.createElement(component, rest, error) : error : null;
  };
  return ErrorMessageImpl;
}(reactExports$1.Component);
var ErrorMessage = /*#__PURE__*/connect$1(ErrorMessageImpl);

/**
 * Custom Field component for quickly hooking into Formik
 * context and wiring up forms.
 */

var FastFieldInner = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose(FastFieldInner, _React$Component);
  function FastFieldInner(props) {
    var _this;
    _this = _React$Component.call(this, props) || this;
    var render = props.render,
      children = props.children,
      component = props.component,
      is = props.as,
      name = props.name;
    !!render ? warning$1(false, "<FastField render> has been deprecated. Please use a child callback function instead: <FastField name={" + name + "}>{props => ...}</FastField> instead.")  : void 0;
    !!(component && render) ? warning$1(false, 'You should not use <FastField component> and <FastField render> in the same <FastField> component; <FastField component> will be ignored')  : void 0;
    !!(is && children && isFunction(children)) ? warning$1(false, 'You should not use <FastField as> and <FastField children> as a function in the same <FastField> component; <FastField as> will be ignored.')  : void 0;
    !!(component && children && isFunction(children)) ? warning$1(false, 'You should not use <FastField component> and <FastField children> as a function in the same <FastField> component; <FastField component> will be ignored.')  : void 0;
    !!(render && children && !isEmptyChildren(children)) ? warning$1(false, 'You should not use <FastField render> and <FastField children> in the same <FastField> component; <FastField children> will be ignored')  : void 0;
    return _this;
  }
  var _proto = FastFieldInner.prototype;
  _proto.shouldComponentUpdate = function shouldComponentUpdate(props) {
    if (this.props.shouldUpdate) {
      return this.props.shouldUpdate(props, this.props);
    } else if (props.name !== this.props.name || getIn(props.formik.values, this.props.name) !== getIn(this.props.formik.values, this.props.name) || getIn(props.formik.errors, this.props.name) !== getIn(this.props.formik.errors, this.props.name) || getIn(props.formik.touched, this.props.name) !== getIn(this.props.formik.touched, this.props.name) || Object.keys(this.props).length !== Object.keys(props).length || props.formik.isSubmitting !== this.props.formik.isSubmitting) {
      return true;
    } else {
      return false;
    }
  };
  _proto.componentDidMount = function componentDidMount() {
    // Register the Field with the parent Formik. Parent will cycle through
    // registered Field's validate fns right prior to submit
    this.props.formik.registerField(this.props.name, {
      validate: this.props.validate
    });
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    if (this.props.name !== prevProps.name) {
      this.props.formik.unregisterField(prevProps.name);
      this.props.formik.registerField(this.props.name, {
        validate: this.props.validate
      });
    }
    if (this.props.validate !== prevProps.validate) {
      this.props.formik.registerField(this.props.name, {
        validate: this.props.validate
      });
    }
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    this.props.formik.unregisterField(this.props.name);
  };
  _proto.render = function render() {
    var _this$props = this.props,
      name = _this$props.name,
      render = _this$props.render,
      is = _this$props.as,
      children = _this$props.children,
      component = _this$props.component,
      formik = _this$props.formik,
      props = _objectWithoutPropertiesLoose$1(_this$props, ["validate", "name", "render", "as", "children", "component", "shouldUpdate", "formik"]);
    var restOfFormik = _objectWithoutPropertiesLoose$1(formik, ["validate", "validationSchema"]);
    var field = formik.getFieldProps(_extends$1({
      name: name
    }, props));
    var meta = {
      value: getIn(formik.values, name),
      error: getIn(formik.errors, name),
      touched: !!getIn(formik.touched, name),
      initialValue: getIn(formik.initialValues, name),
      initialTouched: !!getIn(formik.initialTouched, name),
      initialError: getIn(formik.initialErrors, name)
    };
    var bag = {
      field: field,
      meta: meta,
      form: restOfFormik
    };
    if (render) {
      return render(bag);
    }
    if (isFunction(children)) {
      return children(bag);
    }
    if (component) {
      // This behavior is backwards compat with earlier Formik 0.9 to 1.x
      if (typeof component === 'string') {
        var innerRef = props.innerRef,
          rest = _objectWithoutPropertiesLoose$1(props, ["innerRef"]);
        return reactExports$1.createElement(component, _extends$1({
          ref: innerRef
        }, field, rest), children);
      } // We don't pass `meta` for backwards compat

      return reactExports$1.createElement(component, _extends$1({
        field: field,
        form: formik
      }, props), children);
    } // default to input here so we can check for both `as` and `children` above

    var asElement = is || 'input';
    if (typeof asElement === 'string') {
      var _innerRef = props.innerRef,
        _rest = _objectWithoutPropertiesLoose$1(props, ["innerRef"]);
      return reactExports$1.createElement(asElement, _extends$1({
        ref: _innerRef
      }, field, _rest), children);
    }
    return reactExports$1.createElement(asElement, _extends$1({}, field, props), children);
  };
  return FastFieldInner;
}(reactExports$1.Component);
var FastField = /*#__PURE__*/connect$1(FastFieldInner);

var formik = /*#__PURE__*/Object.freeze({
  __proto__: null,
  ErrorMessage: ErrorMessage,
  FastField: FastField,
  Field: Field,
  FieldArray: FieldArray,
  Form: Form$2,
  Formik: Formik,
  FormikConsumer: FormikConsumer,
  FormikContext: FormikContext,
  FormikProvider: FormikProvider,
  connect: connect$1,
  getActiveElement: getActiveElement,
  getIn: getIn,
  insert: insert,
  isEmptyArray: isEmptyArray,
  isEmptyChildren: isEmptyChildren,
  isFunction: isFunction,
  isInputEvent: isInputEvent,
  isInteger: isInteger$1,
  isNaN: isNaN$1,
  isObject: isObject,
  isPromise: isPromise,
  isString: isString,
  move: move,
  prepareDataForValidation: prepareDataForValidation,
  replace: replace$1,
  setIn: setIn,
  setNestedObjectValues: setNestedObjectValues,
  swap: swap,
  useField: useField,
  useFormik: useFormik,
  useFormikContext: useFormikContext,
  validateYupSchema: validateYupSchema,
  withFormik: withFormik,
  yupToFormErrors: yupToFormErrors
});

var app = {
  OFFLINE: "offline",
  FAILURE: "failure",
  ERROR: "error",
  get user() {
    return this.getAuthState().user;
  },
  get csrftoken() {
    return this.getAuthState().csrftoken;
  }
};
const SERVER = "@@SERVER";
const CORE_PLUGINS = ["orm", "renderer"];
app.plugins = {};
var _register = {};
app.init = function (config) {
  if (!config) {
    config = {};
  }
  if (!config.pages) {
    config.pages = {};
  }
  CORE_PLUGINS.forEach(type => {
    if (!app[type]) {
      throw new Error(`Register a ${type} with app.use()`);
    }
  });
  app.use(spinner);
  app.use(defaults);
  app.use(syncUpdateUrl);
  if (config.pages.login && !app.plugins.auth) {
    // FIXME: Require explicit auth registration in 2.0
    app.use(auth);
  }
  router.addRouteInfo(_extendRouteInfo);
  router.addContext(() => spinner.start() && {});
  router.addContext(_getSyncInfo);

  // Router (wq/router.js) configuration
  if (!config.router) {
    config.router = {
      base_url: ""
    };
  }
  config.router.getTemplateName = name => {
    name = name.split(":")[0];
    if (app.config.pages[name] && app.config.pages[name].template) {
      name = app.config.pages[name].template;
    }
    return name;
  };
  if (config.site_title && !config.router.site_title) {
    config.router.site_title = config.site_title;
  }

  // Store (wq/store.js) configuration
  if (!config.store) {
    config.store = {
      service: config.router.base_url,
      defaults: {
        format: "json"
      }
    };
  }
  if (!config.store.fetchFail) {
    config.fetchFail = _fetchFail;
  }
  Object.entries(app.plugins).forEach(([name, plugin]) => {
    if (plugin.ajax) {
      config.store.ajax = plugin.ajax.bind(plugin);
    }
    if (plugin.reducer) {
      let persist = false,
        restore = null;
      if (typeof plugin.persist === "function") {
        persist = plugin.persist.bind(plugin);
        restore = plugin.restore ? plugin.restore.bind(plugin) : state => state;
      } else if (plugin.persist) {
        persist = true;
      }
      ds.addReducer(name, (state, action) => plugin.reducer(state, action), persist, restore);
    }
    if (plugin.actions) {
      Object.assign(plugin, ds.bindActionCreators(plugin.actions));
    }
    if (plugin.thunks) {
      router.addThunks(plugin.thunks, plugin);
    }
    if (plugin.subscriber) {
      ds.subscribe(() => plugin.subscriber(ds.getState()));
    }
    if (plugin.pages) {
      Object.assign(config.pages, plugin.pages);
    }
  });
  app.spin = {
    start: (msg, duration, opts) => spinner.start(msg, duration, opts),
    forSeconds: duration => spinner.start(null, duration),
    stop: msg => spinner.stop(msg)
  };

  // Outbox (wq/outbox.js) configuration
  if (!config.outbox) {
    config.outbox = {};
  }

  // Propagate debug setting to other modules
  if (config.debug) {
    config.router.debug = config.debug;
    config.store.debug = config.debug;
    CORE_PLUGINS.forEach(type => {
      if (config[type]) {
        config[type].debug = config.debug;
      }
    });
  }

  // Load missing (non-local) content as JSON, or as server-rendered HTML?
  // Default (as of 1.0) is to load JSON and render on client.
  config.loadMissingAsJson = config.loadMissingAsJson || !config.loadMissingAsHtml;
  config.loadMissingAsHtml = !config.loadMissingAsJson;

  // After a form submission, sync in the background, or wait before
  // continuing?  Default is to sync in the background.
  if (config.backgroundSync === undefined) {
    config.backgroundSync = true;
  }
  app.config = config;

  // Initialize wq/router.js
  router.init(config.router);
  app.base_url = router.base_url;
  app.store = ds;
  app.outbox = outbox;
  outbox.app = app;
  app.router = router;

  // Option to submit forms in the background rather than wait for each post
  if (config.backgroundSync) {
    if (config.backgroundSync === -1) {
      outbox.pause();
    } else if (config.backgroundSync > 1) {
      console.warn("Sync interval is now controlled by redux-offline");
    }
  }

  // Deprecated hooks
  const deprecated = {
    noBackgroundSync: "backgroundSync: false",
    postsave: "a postsaveurl() plugin hook or a postsave page config",
    saveerror: "an onsync() plugin hook",
    showOutboxErrors: "an onsync() and/or run() hook",
    _addOutboxItemsToContext: "@wq/outbox's IMMEDIATE mode",
    presync: "the template context",
    postsync: "the template context or an onsync() plugin hook"
  };
  Object.entries(deprecated).forEach(([hook, alternative]) => {
    // TODO: Make this an error in 2.0
    if (config[hook]) {
      console.warn(new Error(`config.${hook} has no effect.  Use ${alternative} instead.  See wq.app 1.2 release notes for more info.`));
    }
  });
  if (app.hasPlugin("onsave")) {
    console.warn(new Error("An onsave() plugin hook has no effect.  Use an onsync() hook instead.  See wq.app 1.2 release notes for more info."));
  }
  Object.keys(app.config.pages).forEach(function (page) {
    app.config.pages[page].name = page;
  });
  app.callPlugins("init");

  // Register routes with wq/router.js
  var root = false;
  Object.keys(app.config.pages).forEach(function (page) {
    var conf = _getConf(page);
    if (!conf.url) {
      root = true;
    }
    if (conf.list) {
      conf.modes.forEach(function (mode) {
        var register = _register[mode] || _register.detail;
        register(page, mode);
      });
      (conf.server_modes || []).forEach(function (mode) {
        _register.detail(page, mode, _serverContext);
      });
    } else if (conf) {
      _registerOther(page);
    }
  });

  // Register outbox
  router.register("outbox/", "outbox_list", () => outbox.loadItems());
  router.register("outbox/<slug>", "outbox_detail", _renderOutboxItem);
  router.register("outbox/<slug>/edit", "outbox_edit", _renderOutboxItem);

  // Fallback index page
  if (!root && !app.config.pages.index) {
    router.registerLast("", "index");
  }

  // Fallback for all other URLs
  router.registerLast(":path*", SERVER, _serverContext);
  Object.entries(app.plugins).forEach(([name, plugin]) => {
    if (plugin.context) {
      router.addContext(ctx => {
        return plugin.context(ctx, ctx.router_info);
      });
    }
  });
  router.addContext(() => spinner.stop() && {});

  // Initialize wq/store.js and wq/outbox.js
  ds.init(config.store);
  app.service = ds.service;
  var ready = ds.ready.then(() => outbox.init(config.outbox));
  if (app.config.autoStart !== false) {
    ready = ready.then(app.start);
  }
  return ready;
};
var pcount = 0;
app.use = function (plugin) {
  if (Array.isArray(plugin)) {
    plugin.forEach(p => app.use(p));
    return;
  }
  if (plugin.dependencies) {
    app.use(plugin.dependencies);
  }
  if (app.plugins[plugin.name]) {
    if (app.plugins[plugin.name] === plugin) {
      return;
    } else {
      throw new Error(`App already has a plugin named ${plugin.name}!`);
    }
  }
  pcount++;
  if (!plugin.name) {
    plugin.name = "plugin" + pcount;
  }
  app.plugins[plugin.name] = plugin;
  plugin.app = app;
  if (plugin.type) {
    if (app[plugin.type]) {
      throw new Error(`App already has a ${plugin.type} (${app[plugin.type].name})`);
    }
    app[plugin.type] = plugin;
  }
};
app.start = function () {
  router.start();
  app.callPlugins("start");
};
async function _getSyncInfo() {
  const unsynced = await outbox.unsynced();
  return {
    svc: app.service,
    native: app["native"],
    syncing: app.syncing,
    unsynced: unsynced
  };
}
app.retryAll = function () {
  app.outbox.unsynced().then(function (unsynced) {
    if (!unsynced) {
      return;
    }
    app.outbox.retryAll();
  });
};
app.emptyOutbox = function (confirmFirst) {
  /* global confirm */
  if (confirmFirst) {
    if (navigator.notification && navigator.notification.confirm) {
      navigator.notification.confirm("Empty Outbox?", function (button) {
        if (button == 1) {
          app.emptyOutbox();
        }
      });
      return;
    } else {
      if (!confirm("Empty Outbox?")) {
        return;
      }
    }
  }
  return outbox.empty();
};
app.confirmSubmit = function (form, message) {
  /* global confirm */
  if (navigator.notification && navigator.notification.confirm) {
    if (form.dataset.wqConfirmSubmit) {
      return true;
    }
    navigator.notification.confirm(message, function (button) {
      if (button == 1) {
        form.dataset.wqConfirmSubmit = true;
        form.submit();
      }
    });
  } else {
    if (confirm(message)) {
      return true;
    }
  }
  return false;
};

// Handle navigation after form submission
app.postSaveNav = function (item, alreadySynced) {
  var url;
  const pluginUrl = app.callPlugins("postsaveurl", [item, alreadySynced]).filter(item => !!item);
  if (pluginUrl.length) {
    url = pluginUrl[0];
  } else {
    url = app.postsaveurl(item, alreadySynced);
  }

  // Navigate to computed URL
  if (app.config.debug) {
    console.log("Successfully saved; continuing to " + url);
  }
  router.push(url);
};
app.postsaveurl = function (item, alreadySynced) {
  var postsave, pconf, match, mode, url, itemid, modelConf;

  // conf.postsave can be set redirect to another page
  modelConf = item.options.modelConf;
  if (item.deletedId) {
    postsave = modelConf.postdelete;
  } else {
    postsave = modelConf.postsave;
  }
  if (!postsave) {
    // Otherwise, default is to return the page for the item just saved
    if (!alreadySynced || item.deletedId) {
      // If backgroundSync, return to list view while syncing
      postsave = modelConf.name + "_list";
    } else {
      // If !backgroundSync, return to the newly synced item
      postsave = modelConf.name + "_detail";
    }
  }

  // conf.postsave should explicitly indicate which template mode to use
  /* eslint no-useless-escape: off */
  match = postsave.match(/^([^\/]+)_([^_\/]+)$/);
  if (match) {
    postsave = match[1];
    mode = match[2];
  }

  // Retrieve configuration for postsave page, if any
  pconf = _getConf(postsave, true);

  // Compute URL
  if (!pconf) {
    // If conf.postsave is not the name of a list page, assume it's a
    // simple page or a URL
    var urlContext;
    if (item.deletedId) {
      urlContext = {
        deleted: true,
        ...router.getContext()
      };
    } else {
      urlContext = {
        ...item.data,
        ...item.result
      };
    }
    url = app.base_url + "/" + mustache.render(postsave, urlContext);
  } else if (!pconf.list) {
    url = app.base_url + "/" + pconf.url;
  } else {
    if (pconf.modes.concat(pconf.server_modes || []).indexOf(mode) == -1) {
      throw "Unknown template mode!";
    }

    // For list pages, the url can differ depending on the mode
    url = app.base_url + "/" + pconf.url + "/";
    if (mode != "list") {
      // Detail or edit view; determine item id and add to url
      if (postsave == modelConf.name && !item.synced) {
        // Config indicates return to detail/edit view of the model
        // that was just saved, but the item hasn't been synced yet.
        // Navigate to outbox URL instead.
        url = app.base_url + "/outbox/" + item.id;
        if (mode != "edit" && item.error) {
          // Return to edit form if there was an error
          mode = "edit";
        }
      } else {
        // Item has been successfully synced
        if (postsave == modelConf.name) {
          // If postsave page is the same as the item's page, use the
          // new id
          itemid = item.result && item.result.id;
        } else {
          // Otherwise, look for a foreign key reference
          // FIXME: what if the foreign key has a different name?
          itemid = item.result && item.result[postsave + "_id"];
        }
        if (!itemid) {
          throw "Could not find " + postsave + " id in result!";
        }
        url += itemid;
      }
      if (mode != "detail") {
        url += "/" + mode;
      }
    }
  }
  return url;
};
const syncUpdateUrl = {
  name: "syncUpdateUrl",
  onsync(obitem) {
    const context = router.getContext() || {},
      {
        router_info: routeInfo = {}
      } = context,
      {
        page,
        mode,
        outbox_id: routeOutboxId,
        base_url,
        page_config,
        full_path,
        item_id,
        parent_id
      } = routeInfo,
      {
        id: outboxId,
        result
      } = obitem || {},
      {
        id: resultId
      } = result || {},
      outboxSlug = `outbox-${outboxId}`;
    if (!resultId) {
      return;
    }
    if (routeOutboxId === outboxId && page === "outbox" && page_config && page_config.url) {
      const modePath = mode === "detail" ? "" : `/${mode}`;
      router.push(`${base_url}/${page_config.url}/${resultId}${modePath}`);
    }
    if (item_id === outboxSlug || parent_id === outboxSlug) {
      router.push(full_path.replace(outboxSlug, resultId));
    }
  }
};

// Return a list of all foreign key fields
app.getParents = function (page) {
  var conf = _getConf(page);
  return conf.form.filter(function (field) {
    return field["wq:ForeignKey"];
  }).map(function (field) {
    return field["wq:ForeignKey"];
  });
};

// Shortcuts for $.mobile.changePage
app.nav = function (url) {
  url = app.base_url + "/" + url;
  router.push(url);
};
app.refresh = function () {
  router.refresh();
};
app.hasPlugin = function (method) {
  var plugin,
    fn,
    hasPlugin = false;
  for (plugin in app.plugins) {
    fn = app.plugins[plugin][method];
    if (fn) {
      hasPlugin = true;
    }
  }
  return hasPlugin;
};
app.callPlugins = function (method, args) {
  var plugin,
    fn,
    fnArgs,
    queue = [];
  for (plugin in app.plugins) {
    fn = app.plugins[plugin][method];
    if (args) {
      fnArgs = args;
    } else {
      fnArgs = [app.config[plugin]];
    }
    if (fn) {
      queue.push(fn.apply(app.plugins[plugin], fnArgs));
    }
  }
  return queue;
};

// Internal variables and functions
app.splitRoute = function (routeName) {
  const match = routeName.match(/^(.+)_([^_]+)$/);
  let page, mode, variant;
  if (match) {
    page = match[1];
    mode = match[2];
    if (mode.indexOf(":") > -1) {
      [mode, variant] = mode.split(":");
    } else {
      variant = null;
    }
  } else {
    page = routeName;
    mode = null;
    variant = null;
  }
  return [page, mode, variant];
};
function _joinRoute(page, mode, variant) {
  if (variant) {
    return page + "_" + mode + ":" + variant;
  } else if (mode) {
    return page + "_" + mode;
  } else {
    return page;
  }
}
function _extendRouteInfo(routeInfo) {
  const routeName = routeInfo.name,
    itemid = page !== "outbox" && routeInfo.slugs.slug || null;
  var [page, mode, variant] = app.splitRoute(routeName),
    conf = _getConf(page, true),
    pageid = null;
  if (conf) {
    if (mode && mode !== "list") {
      pageid = page + "_" + mode + (variant ? "_" + variant : "") + (itemid ? "_" + itemid : "") + "-page";
    }
  } else if (page === "outbox") {
    conf = {
      name: "outbox",
      url: "outbox",
      page: "outbox",
      form: [],
      modes: ["list", "detail", "edit"]
    };
  } else {
    page = routeName;
    mode = null;
    conf = {
      name: page,
      page: page,
      form: [],
      modes: []
    };
  }
  return {
    ...routeInfo,
    page: page,
    page_config: conf,
    mode: mode,
    variant: variant,
    item_id: itemid,
    dom_id: pageid
  };
}

// Generate list view context and render with [url]_list template;
// handles requests for [url] and [url]/
_register.list = function (page) {
  const conf = _getConf(page),
    register = conf.url === "" ? router.registerLast : router.register,
    url = conf.url === "" ? "" : conf.url + "/";
  register(url, _joinRoute(page, "list"), ctx => _displayList(ctx));

  // Special handling for /[parent_list_url]/[parent_id]/[url]
  app.getParents(page).forEach(function (ppage) {
    var pconf = _getConf(ppage);
    var url = pconf.url;
    var registerParent;
    if (url === "") {
      registerParent = router.registerLast;
    } else {
      registerParent = router.register;
      url += "/";
    }
    url += ":parent_id/" + conf.url;
    registerParent(url, _joinRoute(page, "list", ppage), parentContext);
  });
  async function parentContext(ctx) {
    const {
        router_info: routeInfo
      } = ctx,
      {
        page,
        variant: ppage
      } = routeInfo,
      parent_id = routeInfo.slugs.parent_id,
      pconf = _getConf(ppage),
      pitem = await app.models[ppage].find(parent_id);
    var parentUrl;
    if (pitem) {
      parentUrl = pconf.url + "/" + pitem.id;
    } else if (parent_id.indexOf("outbox-") == -1) {
      parentUrl = "outbox/" + parent_id.split("-")[1];
    } else {
      parentUrl = null;
    }
    var parentInfo = {
      parent_id,
      parent_url: parentUrl,
      parent_label: pitem && pitem.label,
      parent_page: ppage,
      parent_conf: pconf
    };
    parentInfo["parent_is_" + ppage] = true;
    return _displayList(ctx, {
      ...parentInfo,
      router_info: {
        ...routeInfo,
        ...parentInfo
      }
    });
  }
};
app._addOutboxItemsToContext = function (context, unsyncedItems) {
  // Add any outbox items to context
  context.unsynced = unsyncedItems.length;
  context.unsyncedItems = unsyncedItems;
};
async function _displayList(ctx, parentInfo) {
  const {
      router_info: routeInfo
    } = ctx,
    {
      page,
      params,
      full_path: url
    } = routeInfo,
    conf = _getConf(page),
    model = app.models[page];
  var pnum = model.opts.page,
    limit = null,
    next = null,
    prev = null,
    filter;
  if (params || parentInfo) {
    if (params && params.page) {
      pnum = params.page;
    }
    if (params && params.limit) {
      limit = params.limit;
    }
    filter = {};
    for (var key in params || {}) {
      if (key != "page") {
        filter[key] = params[key];
      }
    }
    if (parentInfo) {
      conf.form.forEach(function (field) {
        if (field["wq:ForeignKey"] == parentInfo.parent_page) {
          filter[field.name + "_id"] = parentInfo.parent_id;
        }
      });
    }
  }
  if (filter && !Object.keys(filter).length) {
    filter = null;
  }

  // Load from server if data might not exist locally
  if (app.config.loadMissingAsHtml) {
    if (!model.opts.client) {
      return _loadFromServer(url);
    }
    if (filter && model.opts.server) {
      return _loadFromServer(url);
    }
    if (pnum > model.opts.page) {
      return _loadFromServer(url);
    }
  } else if (filter && pnum > model.opts.page) {
    filter.page = pnum;
    if (limit) {
      filter.limit = limit;
    }
  }
  if (!pnum && (!model.opts.client || filter)) {
    pnum = 1;
  }
  const showUnsynced = pnum == model.opts.page || pnum == 1 && !model.opts.client;
  function getData() {
    if (filter) {
      return model.filterPage(filter);
    } else if (pnum > model.opts.page) {
      return model.page(pnum, limit);
    } else {
      return model.load();
    }
  }
  async function getUnsynced() {
    if (showUnsynced) {
      return model.unsyncedItems();
    } else {
      return [];
    }
  }

  // If the number of unsynced records changes while loading the data,
  // load the data a second time to make sure the list is up to date.
  // (this is rare except for cache=none lists with background sync)
  const unsynced1 = await getUnsynced();
  const data1 = await getData();
  const unsynced2 = await getUnsynced();
  var data;
  if (unsynced1 && unsynced2 && unsynced1.length != unsynced2.length) {
    data = await getData();
  } else {
    data = data1;
  }
  const unsyncedItems = unsynced2;
  var prevIsLocal, currentIsLocal;
  if (pnum > model.opts.page && (model.opts.client || pnum > 1)) {
    if (+pnum - 1 > model.opts.page && (model.opts.client || pnum > 2)) {
      let prevp = filter ? {
        ...filter
      } : {};
      prevp.page = +pnum - 1;
      prev = conf.url + "/?" + new URLSearchParams(prevp).toString();
    } else if (+pnum - 1 == model.opts.page && !filter) {
      prev = conf.url + "/";
      prevIsLocal = true;
    }
  }
  if (pnum < data.pages && (model.opts.server || pnum)) {
    let nextp = filter ? {
      ...filter
    } : {};
    nextp.page = +pnum + 1;
    next = conf.url + "/?" + new URLSearchParams(nextp).toString();
    if (nextp.page == 1) {
      currentIsLocal = true;
    }
  }
  var context = {
    ...data,
    ...parentInfo,
    previous: prev ? "/" + prev : null,
    next: next ? "/" + next : null,
    multiple: prev || next ? true : false,
    page: pnum,
    show_unsynced: showUnsynced,
    previous_is_local: prevIsLocal,
    current_is_local: currentIsLocal
  };
  app._addOutboxItemsToContext(context, unsyncedItems);
  return context;
}

// Generate item detail view context and render with [url]_detail template;
// handles requests for [url]/[id]
_register.detail = function (page, mode, contextFn = _displayItem) {
  var conf = _getConf(page);
  var url = _getDetailUrl(conf.url, mode);
  const register = conf.url === "" ? router.registerLast : router.register;
  register(url, _joinRoute(page, mode), contextFn);
};
function _getDetailUrl(url, mode) {
  if (url) {
    url += "/";
  }
  url += "<slug>";
  if (mode != "detail") {
    url += "/" + mode;
  }
  return url;
}

// Generate item edit context and render with [url]_edit template;
// handles requests for [url]/[id]/edit and [url]/new
_register.edit = function (page) {
  var conf = _getConf(page);
  const register = conf.url === "" ? router.registerLast : router.register;
  register(_getDetailUrl(conf.url, "edit"), _joinRoute(page, "edit"), _displayItem);
  router.registerFirst(conf.url + "/new", _joinRoute(page, "edit", "new"), _displayItem);
};
async function _displayItem(ctx) {
  const {
      router_info: routeInfo
    } = ctx,
    {
      item_id: itemid,
      page,
      mode,
      variant,
      full_path: url
    } = routeInfo,
    conf = _getConf(page),
    model = app.models[page];
  var item;
  if (mode == "edit" && variant == "new") {
    item = {};
    Object.entries({
      ...routeInfo.params,
      ...conf.defaults
    }).forEach(([key, value]) => {
      item = setIn(item, key, value);
    });
  } else {
    const localOnly = !app.config.loadMissingAsJson;
    item = await model.find(itemid, localOnly);
    if (!item) {
      if (model.opts.server && app.config.loadMissingAsHtml) {
        return _loadFromServer(url);
      } else {
        return router.notFound();
      }
    }
  }
  if (item) {
    item.local = true;
    _addFKLabels(item, model.config.form);
    return item;
  } else {
    if (model.opts.server && app.config.loadMissingAsHtml) {
      // opts.server indicates that the local list does not represent
      // the entire dataset; if an item is not found, attempt to load
      // HTML directly from the server.
      return _loadFromServer(url);
    } else {
      // If opts.server is false, locally stored list is assumed to
      // contain the entire dataset, so the item probably does not exist.
      return router.notFound();
    }
  }
}
function _addFKLabels(item, form) {
  for (const field of form) {
    const modelName = field["wq:ForeignKey"],
      idName = `${field.name}_id`,
      labelName = `${field.name}_label`;
    if (!modelName || !app.models[modelName] || !item[idName] || item[labelName]) {
      continue;
    }
    const relItem = app.models[modelName].model.withId(item[idName]);
    if (relItem && relItem.label) {
      item[labelName] = relItem.label;
    }
  }
  for (const field of form) {
    let data = item[field.name];
    if (field.children && data) {
      if (!Array.isArray(data)) {
        data = [data];
      }
      for (const row of data) {
        _addFKLabels(row, field.children);
      }
    }
  }
}

// Render non-list pages with with [url] template;
// handles requests for [url] and [url]/
function _registerOther(page) {
  var conf = _getConf(page);
  router.register(conf.url, page, conf.context || _displayOther, undefined, conf.thunk || null);
  async function _displayOther() {
    if (conf.server_only) {
      return _loadFromServer(app.base_url + "/" + conf.url);
    } else {
      return {};
    }
  }
}
async function _renderOutboxItem(ctx) {
  // Display outbox item using model-specific detail/edit view
  const {
      router_info: routeInfo
    } = ctx,
    mode = routeInfo.mode,
    item = await outbox.loadItem(+routeInfo.slugs.slug);
  if (!item || !item.options || !item.options.modelConf) {
    return router.notFound();
  }
  var id,
    page = item.options.modelConf.name,
    template = page + "_" + mode,
    idMatch = item.options.url.match(new RegExp(item.options.modelConf.url + "/([^/]+)$"));
  if (item.data.id) {
    id = item.data.id;
  } else if (idMatch) {
    id = idMatch[1];
  } else {
    id = "new";
  }
  var context = {
    outbox_id: item.id,
    label: item.label,
    error: item.error,
    router_info: {
      ...routeInfo,
      page_config: item.options.modelConf,
      template: template,
      outbox_id: item.id
    },
    ...deepcopy(item.data)
  };
  if (id != "new") {
    context.id = id;
  }
  return context;
}
app.isRegistered = function (url) {
  if (_getConfByUrl(url, true)) {
    return true;
  } else {
    return false;
  }
};
app.submitForm = async function ({
  url,
  storage,
  backgroundSync,
  has_files,
  outboxId,
  preserve,
  data: vals
}) {
  const conf = _getConfByUrl(url, true);
  var options = {
    url: url
  };
  if (storage) {
    options.storage = storage;
  } else if (!backgroundSync) {
    options.storage = "temporary";
  } else if (has_files && navigator.product !== "ReactNative") {
    options.storage = "store";
  }
  if (_hasNestedObject(vals)) {
    if (has_files) {
      vals = _flattenJson(vals);
    } else {
      options.json = true;
    }
  }
  if (outboxId) {
    options.id = outboxId;
    if (preserve && preserve.split) {
      options.preserve = preserve.split(/,/);
    }
  }
  if (vals._method) {
    options.method = vals._method;
    delete vals._method;
  } else {
    options.method = "POST";
  }
  if (conf) {
    options.modelConf = conf;
    if (conf.label_template) {
      if (typeof conf.label_template === "function") {
        options.label = conf.label_template(vals);
      } else {
        options.label = mustache.render(conf.label_template, vals);
      }
    }
  }
  options.csrftoken = app.csrftoken;
  var item = await outbox.save(vals, options);
  if (backgroundSync) {
    // Send user to next screen while app syncs in background
    app.postSaveNav(item, false);
    return [item, null];
  }

  // Submit form immediately and wait for server to respond
  app.spin.start();
  item = await outbox.waitForItem(item.id);
  app.spin.stop();
  if (!item) {
    return [item, app.FAILURE];
  }
  if (item.synced) {
    // Item was synced
    app.postSaveNav(item, true);
    return [item, null];
  }
  // Something went wrong
  if (!item.error) {
    // Save failed without server error: probably offline
    // FIXME: waitForItem() probably doesn't resolve until back online.
    app.postSaveNav(item, false);
    return [item, null];
  } else if (typeof item.error === "string") {
    // Save failed and error information is not in JSON format
    // (likely a 500 server failure)
    return [item, app.FAILURE];
  } else {
    // Save failed and error information is in JSON format
    // (likely a 400 bad data error)
    return [item, app.ERROR];
  }
};
function _hasNestedObject(value) {
  return Object.values(value).some(val => typeof val === "object" && (!Array.isArray(val) || typeof val[0] === "object"));
}
function _flattenJson(value, prefix = "") {
  const result = {};
  if (prefix) {
    if (value === null || value === undefined) {
      return {
        [prefix]: ""
      };
    } else if (typeof value !== "object") {
      return {
        [prefix]: value
      };
    }
  }
  Object.entries(value).forEach(([key, val]) => {
    const fullKey = prefix ? `${prefix}[${key}]` : key;
    if (Array.isArray(val)) {
      val.forEach((row, i) => Object.assign(result, _flattenJson(row, `${fullKey}[${i}]`)));
    } else if (typeof val === "object") {
      if (_isFile(val)) {
        result[fullKey] = val;
      } else if (_isGeometry(val)) {
        result[fullKey] = JSON.stringify(val);
      } else {
        Object.assign(result, _flattenJson(val, fullKey));
      }
    } else {
      result[fullKey] = val;
    }
  });
  return result;
}
function _isFile(val) {
  return val && val.type && val.name && (val.body || val.uri);
}
function _isGeometry(val) {
  return val && val.type && val.coordinates;
}
app.getAuthState = function () {
  return this.plugins.auth && this.plugins.auth.getState() || {};
};

// Load configuration based on page id
function _getConf(page, silentFail) {
  var conf = app.config.pages[page];
  if (!conf) {
    if (silentFail) {
      return;
    } else {
      throw new Error('Configuration for "' + page + '" not found!');
    }
  }
  return {
    page: page,
    form: [],
    modes: conf.list ? ["list", "detail", "edit"] : [],
    ...conf
  };
}

// Helper to load configuration based on URL
function _getConfByUrl(url, silentFail) {
  var parts = url.split("/");
  var conf;
  for (var p in app.config.pages) {
    if (app.config.pages[p].url == parts[0]) {
      conf = app.config.pages[p];
    }
  }
  if (!conf) {
    if (silentFail) {
      return;
    } else {
      throw 'Configuration for "/' + url + '" not found!';
    }
  }
  return conf;
}
async function _loadFromServer(url) {
  // options = (ui && ui.options) || {};
  if (app.config.debug) {
    console.log("Loading " + url + " from server");
    if (app.base_url && url.indexOf(app.base_url) !== 0) {
      console.warn(url + " does not include " + app.base_url);
    }
  }
  const response = await fetch(url),
    html = await response.text();
  return router.rawHTML(html);
}
function _serverContext(ctx) {
  const {
      router_info: routeInfo
    } = ctx,
    {
      full_path: url
    } = routeInfo;
  return _loadFromServer(url);
}
function _fetchFail(query, error) {
  /* eslint no-unused-vars: off */
  app.spin.alert("Error Loading Data");
}

var shim = {exports: {}};

var useSyncExternalStoreShim_development = {};

/**
 * @license React
 * use-sync-external-store-shim.development.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 () {

    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function') {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
    }
    var React = reactExports$1;
    var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
    function error(format) {
      {
        {
          for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
            args[_key2 - 1] = arguments[_key2];
          }
          printWarning('error', format, args);
        }
      }
    }
    function printWarning(level, format, args) {
      // When changing this logic, you might want to also
      // update consoleWithStackDev.www.js as well.
      {
        var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
        var stack = ReactDebugCurrentFrame.getStackAddendum();
        if (stack !== '') {
          format += '%s';
          args = args.concat([stack]);
        } // eslint-disable-next-line react-internal/safe-string-coercion

        var argsWithFormat = args.map(function (item) {
          return String(item);
        }); // Careful: RN currently depends on this prefix

        argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
        // breaks IE9: https://github.com/facebook/react/issues/13610
        // eslint-disable-next-line react-internal/no-production-logging

        Function.prototype.apply.call(console[level], console, argsWithFormat);
      }
    }

    /**
     * inlined Object.is polyfill to avoid requiring consumers ship their own
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
     */
    function is(x, y) {
      return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
      ;
    }

    var objectIs = typeof Object.is === 'function' ? Object.is : is;

    // dispatch for CommonJS interop named imports.

    var useState = React.useState,
      useEffect = React.useEffect,
      useLayoutEffect = React.useLayoutEffect,
      useDebugValue = React.useDebugValue;
    var didWarnOld18Alpha = false;
    var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
    // because of a very particular set of implementation details and assumptions
    // -- change any one of them and it will break. The most important assumption
    // is that updates are always synchronous, because concurrent rendering is
    // only available in versions of React that also have a built-in
    // useSyncExternalStore API. And we only use this shim when the built-in API
    // does not exist.
    //
    // Do not assume that the clever hacks used by this hook also work in general.
    // The point of this shim is to replace the need for hacks by other libraries.

    function useSyncExternalStore(subscribe, getSnapshot,
    // Note: The shim does not use getServerSnapshot, because pre-18 versions of
    // React do not expose a way to check if we're hydrating. So users of the shim
    // will need to track that themselves and return the correct value
    // from `getSnapshot`.
    getServerSnapshot) {
      {
        if (!didWarnOld18Alpha) {
          if (React.startTransition !== undefined) {
            didWarnOld18Alpha = true;
            error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');
          }
        }
      } // Read the current snapshot from the store on every render. Again, this
      // breaks the rules of React, and only works here because of specific
      // implementation details, most importantly that updates are
      // always synchronous.

      var value = getSnapshot();
      {
        if (!didWarnUncachedGetSnapshot) {
          var cachedValue = getSnapshot();
          if (!objectIs(value, cachedValue)) {
            error('The result of getSnapshot should be cached to avoid an infinite loop');
            didWarnUncachedGetSnapshot = true;
          }
        }
      } // Because updates are synchronous, we don't queue them. Instead we force a
      // re-render whenever the subscribed state changes by updating an some
      // arbitrary useState hook. Then, during render, we call getSnapshot to read
      // the current value.
      //
      // Because we don't actually use the state returned by the useState hook, we
      // can save a bit of memory by storing other stuff in that slot.
      //
      // To implement the early bailout, we need to track some things on a mutable
      // object. Usually, we would put that in a useRef hook, but we can stash it in
      // our useState hook instead.
      //
      // To force a re-render, we call forceUpdate({inst}). That works because the
      // new object always fails an equality check.

      var _useState = useState({
          inst: {
            value: value,
            getSnapshot: getSnapshot
          }
        }),
        inst = _useState[0].inst,
        forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
      // in the layout phase so we can access it during the tearing check that
      // happens on subscribe.

      useLayoutEffect(function () {
        inst.value = value;
        inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
        // commit phase if there was an interleaved mutation. In concurrent mode
        // this can happen all the time, but even in synchronous mode, an earlier
        // effect may have mutated the store.

        if (checkIfSnapshotChanged(inst)) {
          // Force a re-render.
          forceUpdate({
            inst: inst
          });
        }
      }, [subscribe, value, getSnapshot]);
      useEffect(function () {
        // Check for changes right before subscribing. Subsequent changes will be
        // detected in the subscription handler.
        if (checkIfSnapshotChanged(inst)) {
          // Force a re-render.
          forceUpdate({
            inst: inst
          });
        }
        var handleStoreChange = function () {
          // TODO: Because there is no cross-renderer API for batching updates, it's
          // up to the consumer of this library to wrap their subscription event
          // with unstable_batchedUpdates. Should we try to detect when this isn't
          // the case and print a warning in development?
          // The store changed. Check if the snapshot changed since the last time we
          // read from the store.
          if (checkIfSnapshotChanged(inst)) {
            // Force a re-render.
            forceUpdate({
              inst: inst
            });
          }
        }; // Subscribe to the store and return a clean-up function.

        return subscribe(handleStoreChange);
      }, [subscribe]);
      useDebugValue(value);
      return value;
    }
    function checkIfSnapshotChanged(inst) {
      var latestGetSnapshot = inst.getSnapshot;
      var prevValue = inst.value;
      try {
        var nextValue = latestGetSnapshot();
        return !objectIs(prevValue, nextValue);
      } catch (error) {
        return true;
      }
    }
    function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
      // Note: The shim does not use getServerSnapshot, because pre-18 versions of
      // React do not expose a way to check if we're hydrating. So users of the shim
      // will need to track that themselves and return the correct value
      // from `getSnapshot`.
      return getSnapshot();
    }
    var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
    var isServerEnvironment = !canUseDOM;
    var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
    var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
    useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function') {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
    }
  })();
}

{
  shim.exports = useSyncExternalStoreShim_development;
}

var shimExports = shim.exports;

var withSelector = {exports: {}};

var withSelector_development = {};

/**
 * @license React
 * use-sync-external-store-shim/with-selector.development.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 () {

    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function') {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
    }
    var React = reactExports$1;
    var shim = shimExports;

    /**
     * inlined Object.is polyfill to avoid requiring consumers ship their own
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
     */
    function is(x, y) {
      return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
      ;
    }

    var objectIs = typeof Object.is === 'function' ? Object.is : is;
    var useSyncExternalStore = shim.useSyncExternalStore;

    // for CommonJS interop.

    var useRef = React.useRef,
      useEffect = React.useEffect,
      useMemo = React.useMemo,
      useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.

    function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
      // Use this to track the rendered snapshot.
      var instRef = useRef(null);
      var inst;
      if (instRef.current === null) {
        inst = {
          hasValue: false,
          value: null
        };
        instRef.current = inst;
      } else {
        inst = instRef.current;
      }
      var _useMemo = useMemo(function () {
          // Track the memoized state using closure variables that are local to this
          // memoized instance of a getSnapshot function. Intentionally not using a
          // useRef hook, because that state would be shared across all concurrent
          // copies of the hook/component.
          var hasMemo = false;
          var memoizedSnapshot;
          var memoizedSelection;
          var memoizedSelector = function (nextSnapshot) {
            if (!hasMemo) {
              // The first time the hook is called, there is no memoized result.
              hasMemo = true;
              memoizedSnapshot = nextSnapshot;
              var _nextSelection = selector(nextSnapshot);
              if (isEqual !== undefined) {
                // Even if the selector has changed, the currently rendered selection
                // may be equal to the new selection. We should attempt to reuse the
                // current value if possible, to preserve downstream memoizations.
                if (inst.hasValue) {
                  var currentSelection = inst.value;
                  if (isEqual(currentSelection, _nextSelection)) {
                    memoizedSelection = currentSelection;
                    return currentSelection;
                  }
                }
              }
              memoizedSelection = _nextSelection;
              return _nextSelection;
            } // We may be able to reuse the previous invocation's result.

            // We may be able to reuse the previous invocation's result.
            var prevSnapshot = memoizedSnapshot;
            var prevSelection = memoizedSelection;
            if (objectIs(prevSnapshot, nextSnapshot)) {
              // The snapshot is the same as last time. Reuse the previous selection.
              return prevSelection;
            } // The snapshot has changed, so we need to compute a new selection.

            // The snapshot has changed, so we need to compute a new selection.
            var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data
            // has changed. If it hasn't, return the previous selection. That signals
            // to React that the selections are conceptually equal, and we can bail
            // out of rendering.

            // If a custom isEqual function is provided, use that to check if the data
            // has changed. If it hasn't, return the previous selection. That signals
            // to React that the selections are conceptually equal, and we can bail
            // out of rendering.
            if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
              return prevSelection;
            }
            memoizedSnapshot = nextSnapshot;
            memoizedSelection = nextSelection;
            return nextSelection;
          }; // Assigning this to a constant so that Flow knows it can't change.

          // Assigning this to a constant so that Flow knows it can't change.
          var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
          var getSnapshotWithSelector = function () {
            return memoizedSelector(getSnapshot());
          };
          var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
            return memoizedSelector(maybeGetServerSnapshot());
          };
          return [getSnapshotWithSelector, getServerSnapshotWithSelector];
        }, [getSnapshot, getServerSnapshot, selector, isEqual]),
        getSelection = _useMemo[0],
        getServerSelection = _useMemo[1];
      var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
      useEffect(function () {
        inst.hasValue = true;
        inst.value = value;
      }, [value]);
      useDebugValue(value);
      return value;
    }
    withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function') {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
    }
  })();
}

{
  withSelector.exports = withSelector_development;
}

var withSelectorExports = withSelector.exports;

var reactDom = {exports: {}};

var reactDom_development = {};

var scheduler = {exports: {}};

var scheduler_development = {};

/**
 * @license React
 * scheduler.development.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 () {

	    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
	    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function') {
	      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
	    }
	    var enableSchedulerDebugging = false;
	    var enableProfiling = false;
	    var frameYieldMs = 5;
	    function push(heap, node) {
	      var index = heap.length;
	      heap.push(node);
	      siftUp(heap, node, index);
	    }
	    function peek(heap) {
	      return heap.length === 0 ? null : heap[0];
	    }
	    function pop(heap) {
	      if (heap.length === 0) {
	        return null;
	      }
	      var first = heap[0];
	      var last = heap.pop();
	      if (last !== first) {
	        heap[0] = last;
	        siftDown(heap, last, 0);
	      }
	      return first;
	    }
	    function siftUp(heap, node, i) {
	      var index = i;
	      while (index > 0) {
	        var parentIndex = index - 1 >>> 1;
	        var parent = heap[parentIndex];
	        if (compare(parent, node) > 0) {
	          // The parent is larger. Swap positions.
	          heap[parentIndex] = node;
	          heap[index] = parent;
	          index = parentIndex;
	        } else {
	          // The parent is smaller. Exit.
	          return;
	        }
	      }
	    }
	    function siftDown(heap, node, i) {
	      var index = i;
	      var length = heap.length;
	      var halfLength = length >>> 1;
	      while (index < halfLength) {
	        var leftIndex = (index + 1) * 2 - 1;
	        var left = heap[leftIndex];
	        var rightIndex = leftIndex + 1;
	        var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.

	        if (compare(left, node) < 0) {
	          if (rightIndex < length && compare(right, left) < 0) {
	            heap[index] = right;
	            heap[rightIndex] = node;
	            index = rightIndex;
	          } else {
	            heap[index] = left;
	            heap[leftIndex] = node;
	            index = leftIndex;
	          }
	        } else if (rightIndex < length && compare(right, node) < 0) {
	          heap[index] = right;
	          heap[rightIndex] = node;
	          index = rightIndex;
	        } else {
	          // Neither child is smaller. Exit.
	          return;
	        }
	      }
	    }
	    function compare(a, b) {
	      // Compare sort index first, then task id.
	      var diff = a.sortIndex - b.sortIndex;
	      return diff !== 0 ? diff : a.id - b.id;
	    }

	    // TODO: Use symbols?
	    var ImmediatePriority = 1;
	    var UserBlockingPriority = 2;
	    var NormalPriority = 3;
	    var LowPriority = 4;
	    var IdlePriority = 5;
	    function markTaskErrored(task, ms) {}

	    /* eslint-disable no-var */

	    var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
	    if (hasPerformanceNow) {
	      var localPerformance = performance;
	      exports.unstable_now = function () {
	        return localPerformance.now();
	      };
	    } else {
	      var localDate = Date;
	      var initialTime = localDate.now();
	      exports.unstable_now = function () {
	        return localDate.now() - initialTime;
	      };
	    } // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
	    // Math.pow(2, 30) - 1
	    // 0b111111111111111111111111111111

	    var maxSigned31BitInt = 1073741823; // Times out immediately

	    var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out

	    var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
	    var NORMAL_PRIORITY_TIMEOUT = 5000;
	    var LOW_PRIORITY_TIMEOUT = 10000; // Never times out

	    var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap

	    var taskQueue = [];
	    var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.

	    var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
	    var currentTask = null;
	    var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.

	    var isPerformingWork = false;
	    var isHostCallbackScheduled = false;
	    var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.

	    var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
	    var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
	    var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom

	    typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
	    function advanceTimers(currentTime) {
	      // Check for tasks that are no longer delayed and add them to the queue.
	      var timer = peek(timerQueue);
	      while (timer !== null) {
	        if (timer.callback === null) {
	          // Timer was cancelled.
	          pop(timerQueue);
	        } else if (timer.startTime <= currentTime) {
	          // Timer fired. Transfer to the task queue.
	          pop(timerQueue);
	          timer.sortIndex = timer.expirationTime;
	          push(taskQueue, timer);
	        } else {
	          // Remaining timers are pending.
	          return;
	        }
	        timer = peek(timerQueue);
	      }
	    }
	    function handleTimeout(currentTime) {
	      isHostTimeoutScheduled = false;
	      advanceTimers(currentTime);
	      if (!isHostCallbackScheduled) {
	        if (peek(taskQueue) !== null) {
	          isHostCallbackScheduled = true;
	          requestHostCallback(flushWork);
	        } else {
	          var firstTimer = peek(timerQueue);
	          if (firstTimer !== null) {
	            requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
	          }
	        }
	      }
	    }
	    function flushWork(hasTimeRemaining, initialTime) {
	      isHostCallbackScheduled = false;
	      if (isHostTimeoutScheduled) {
	        // We scheduled a timeout but it's no longer needed. Cancel it.
	        isHostTimeoutScheduled = false;
	        cancelHostTimeout();
	      }
	      isPerformingWork = true;
	      var previousPriorityLevel = currentPriorityLevel;
	      try {
	        var currentTime; if (enableProfiling) ; else {
	          // No catch in prod code path.
	          return workLoop(hasTimeRemaining, initialTime);
	        }
	      } finally {
	        currentTask = null;
	        currentPriorityLevel = previousPriorityLevel;
	        isPerformingWork = false;
	      }
	    }
	    function workLoop(hasTimeRemaining, initialTime) {
	      var currentTime = initialTime;
	      advanceTimers(currentTime);
	      currentTask = peek(taskQueue);
	      while (currentTask !== null && !enableSchedulerDebugging) {
	        if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
	          // This currentTask hasn't expired, and we've reached the deadline.
	          break;
	        }
	        var callback = currentTask.callback;
	        if (typeof callback === 'function') {
	          currentTask.callback = null;
	          currentPriorityLevel = currentTask.priorityLevel;
	          var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
	          var continuationCallback = callback(didUserCallbackTimeout);
	          currentTime = exports.unstable_now();
	          if (typeof continuationCallback === 'function') {
	            currentTask.callback = continuationCallback;
	          } else {
	            if (currentTask === peek(taskQueue)) {
	              pop(taskQueue);
	            }
	          }
	          advanceTimers(currentTime);
	        } else {
	          pop(taskQueue);
	        }
	        currentTask = peek(taskQueue);
	      } // Return whether there's additional work

	      if (currentTask !== null) {
	        return true;
	      } else {
	        var firstTimer = peek(timerQueue);
	        if (firstTimer !== null) {
	          requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
	        }
	        return false;
	      }
	    }
	    function unstable_runWithPriority(priorityLevel, eventHandler) {
	      switch (priorityLevel) {
	        case ImmediatePriority:
	        case UserBlockingPriority:
	        case NormalPriority:
	        case LowPriority:
	        case IdlePriority:
	          break;
	        default:
	          priorityLevel = NormalPriority;
	      }
	      var previousPriorityLevel = currentPriorityLevel;
	      currentPriorityLevel = priorityLevel;
	      try {
	        return eventHandler();
	      } finally {
	        currentPriorityLevel = previousPriorityLevel;
	      }
	    }
	    function unstable_next(eventHandler) {
	      var priorityLevel;
	      switch (currentPriorityLevel) {
	        case ImmediatePriority:
	        case UserBlockingPriority:
	        case NormalPriority:
	          // Shift down to normal priority
	          priorityLevel = NormalPriority;
	          break;
	        default:
	          // Anything lower than normal priority should remain at the current level.
	          priorityLevel = currentPriorityLevel;
	          break;
	      }
	      var previousPriorityLevel = currentPriorityLevel;
	      currentPriorityLevel = priorityLevel;
	      try {
	        return eventHandler();
	      } finally {
	        currentPriorityLevel = previousPriorityLevel;
	      }
	    }
	    function unstable_wrapCallback(callback) {
	      var parentPriorityLevel = currentPriorityLevel;
	      return function () {
	        // This is a fork of runWithPriority, inlined for performance.
	        var previousPriorityLevel = currentPriorityLevel;
	        currentPriorityLevel = parentPriorityLevel;
	        try {
	          return callback.apply(this, arguments);
	        } finally {
	          currentPriorityLevel = previousPriorityLevel;
	        }
	      };
	    }
	    function unstable_scheduleCallback(priorityLevel, callback, options) {
	      var currentTime = exports.unstable_now();
	      var startTime;
	      if (typeof options === 'object' && options !== null) {
	        var delay = options.delay;
	        if (typeof delay === 'number' && delay > 0) {
	          startTime = currentTime + delay;
	        } else {
	          startTime = currentTime;
	        }
	      } else {
	        startTime = currentTime;
	      }
	      var timeout;
	      switch (priorityLevel) {
	        case ImmediatePriority:
	          timeout = IMMEDIATE_PRIORITY_TIMEOUT;
	          break;
	        case UserBlockingPriority:
	          timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
	          break;
	        case IdlePriority:
	          timeout = IDLE_PRIORITY_TIMEOUT;
	          break;
	        case LowPriority:
	          timeout = LOW_PRIORITY_TIMEOUT;
	          break;
	        case NormalPriority:
	        default:
	          timeout = NORMAL_PRIORITY_TIMEOUT;
	          break;
	      }
	      var expirationTime = startTime + timeout;
	      var newTask = {
	        id: taskIdCounter++,
	        callback: callback,
	        priorityLevel: priorityLevel,
	        startTime: startTime,
	        expirationTime: expirationTime,
	        sortIndex: -1
	      };
	      if (startTime > currentTime) {
	        // This is a delayed task.
	        newTask.sortIndex = startTime;
	        push(timerQueue, newTask);
	        if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
	          // All tasks are delayed, and this is the task with the earliest delay.
	          if (isHostTimeoutScheduled) {
	            // Cancel an existing timeout.
	            cancelHostTimeout();
	          } else {
	            isHostTimeoutScheduled = true;
	          } // Schedule a timeout.

	          requestHostTimeout(handleTimeout, startTime - currentTime);
	        }
	      } else {
	        newTask.sortIndex = expirationTime;
	        push(taskQueue, newTask);
	        // wait until the next time we yield.

	        if (!isHostCallbackScheduled && !isPerformingWork) {
	          isHostCallbackScheduled = true;
	          requestHostCallback(flushWork);
	        }
	      }
	      return newTask;
	    }
	    function unstable_pauseExecution() {}
	    function unstable_continueExecution() {
	      if (!isHostCallbackScheduled && !isPerformingWork) {
	        isHostCallbackScheduled = true;
	        requestHostCallback(flushWork);
	      }
	    }
	    function unstable_getFirstCallbackNode() {
	      return peek(taskQueue);
	    }
	    function unstable_cancelCallback(task) {
	      // remove from the queue because you can't remove arbitrary nodes from an
	      // array based heap, only the first one.)

	      task.callback = null;
	    }
	    function unstable_getCurrentPriorityLevel() {
	      return currentPriorityLevel;
	    }
	    var isMessageLoopRunning = false;
	    var scheduledHostCallback = null;
	    var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
	    // thread, like user events. By default, it yields multiple times per frame.
	    // It does not attempt to align with frame boundaries, since most tasks don't
	    // need to be frame aligned; for those that do, use requestAnimationFrame.

	    var frameInterval = frameYieldMs;
	    var startTime = -1;
	    function shouldYieldToHost() {
	      var timeElapsed = exports.unstable_now() - startTime;
	      if (timeElapsed < frameInterval) {
	        // The main thread has only been blocked for a really short amount of time;
	        // smaller than a single frame. Don't yield yet.
	        return false;
	      } // The main thread has been blocked for a non-negligible amount of time. We

	      return true;
	    }
	    function requestPaint() {}
	    function forceFrameRate(fps) {
	      if (fps < 0 || fps > 125) {
	        // Using console['error'] to evade Babel and ESLint
	        console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
	        return;
	      }
	      if (fps > 0) {
	        frameInterval = Math.floor(1000 / fps);
	      } else {
	        // reset the framerate
	        frameInterval = frameYieldMs;
	      }
	    }
	    var performWorkUntilDeadline = function () {
	      if (scheduledHostCallback !== null) {
	        var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread
	        // has been blocked.

	        startTime = currentTime;
	        var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
	        // error can be observed.
	        //
	        // Intentionally not using a try-catch, since that makes some debugging
	        // techniques harder. Instead, if `scheduledHostCallback` errors, then
	        // `hasMoreWork` will remain true, and we'll continue the work loop.

	        var hasMoreWork = true;
	        try {
	          hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
	        } finally {
	          if (hasMoreWork) {
	            // If there's more work, schedule the next message event at the end
	            // of the preceding one.
	            schedulePerformWorkUntilDeadline();
	          } else {
	            isMessageLoopRunning = false;
	            scheduledHostCallback = null;
	          }
	        }
	      } else {
	        isMessageLoopRunning = false;
	      } // Yielding to the browser will give it a chance to paint, so we can
	    };

	    var schedulePerformWorkUntilDeadline;
	    if (typeof localSetImmediate === 'function') {
	      // Node.js and old IE.
	      // There's a few reasons for why we prefer setImmediate.
	      //
	      // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
	      // (Even though this is a DOM fork of the Scheduler, you could get here
	      // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
	      // https://github.com/facebook/react/issues/20756
	      //
	      // But also, it runs earlier which is the semantic we want.
	      // If other browsers ever implement it, it's better to use it.
	      // Although both of these would be inferior to native scheduling.
	      schedulePerformWorkUntilDeadline = function () {
	        localSetImmediate(performWorkUntilDeadline);
	      };
	    } else if (typeof MessageChannel !== 'undefined') {
	      // DOM and Worker environments.
	      // We prefer MessageChannel because of the 4ms setTimeout clamping.
	      var channel = new MessageChannel();
	      var port = channel.port2;
	      channel.port1.onmessage = performWorkUntilDeadline;
	      schedulePerformWorkUntilDeadline = function () {
	        port.postMessage(null);
	      };
	    } else {
	      // We should only fallback here in non-browser environments.
	      schedulePerformWorkUntilDeadline = function () {
	        localSetTimeout(performWorkUntilDeadline, 0);
	      };
	    }
	    function requestHostCallback(callback) {
	      scheduledHostCallback = callback;
	      if (!isMessageLoopRunning) {
	        isMessageLoopRunning = true;
	        schedulePerformWorkUntilDeadline();
	      }
	    }
	    function requestHostTimeout(callback, ms) {
	      taskTimeoutID = localSetTimeout(function () {
	        callback(exports.unstable_now());
	      }, ms);
	    }
	    function cancelHostTimeout() {
	      localClearTimeout(taskTimeoutID);
	      taskTimeoutID = -1;
	    }
	    var unstable_requestPaint = requestPaint;
	    var unstable_Profiling = null;
	    exports.unstable_IdlePriority = IdlePriority;
	    exports.unstable_ImmediatePriority = ImmediatePriority;
	    exports.unstable_LowPriority = LowPriority;
	    exports.unstable_NormalPriority = NormalPriority;
	    exports.unstable_Profiling = unstable_Profiling;
	    exports.unstable_UserBlockingPriority = UserBlockingPriority;
	    exports.unstable_cancelCallback = unstable_cancelCallback;
	    exports.unstable_continueExecution = unstable_continueExecution;
	    exports.unstable_forceFrameRate = forceFrameRate;
	    exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
	    exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
	    exports.unstable_next = unstable_next;
	    exports.unstable_pauseExecution = unstable_pauseExecution;
	    exports.unstable_requestPaint = unstable_requestPaint;
	    exports.unstable_runWithPriority = unstable_runWithPriority;
	    exports.unstable_scheduleCallback = unstable_scheduleCallback;
	    exports.unstable_shouldYield = shouldYieldToHost;
	    exports.unstable_wrapCallback = unstable_wrapCallback;
	    /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
	    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function') {
	      __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
	    }
	  })();
	} 
} (scheduler_development));

{
  scheduler.exports = scheduler_development;
}

var schedulerExports = scheduler.exports;

/**
 * @license React
 * react-dom.development.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(){/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!=='undefined'&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart==='function'){__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());}var React=reactExports$1;var Scheduler=schedulerExports;var ReactSharedInternals=React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;var suppressWarning=false;function setSuppressWarning(newSuppressWarning){{suppressWarning=newSuppressWarning;}}// In DEV, calls to console.warn and console.error get replaced
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format){{if(!suppressWarning){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}printWarning('warn',format,args);}}}function error(format){{if(!suppressWarning){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}printWarning('error',format,args);}}}function printWarning(level,format,args){// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;var stack=ReactDebugCurrentFrame.getStackAddendum();if(stack!==''){format+='%s';args=args.concat([stack]);}// eslint-disable-next-line react-internal/safe-string-coercion
var argsWithFormat=args.map(function(item){return String(item);});// Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: '+format);// We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level],console,argsWithFormat);}}var FunctionComponent=0;var ClassComponent=1;var IndeterminateComponent=2;// Before we know whether it is function or class
var HostRoot=3;// Root of a host tree. Could be nested inside another node.
var HostPortal=4;// A subtree. Could be an entry point to a different renderer.
var HostComponent=5;var HostText=6;var Fragment=7;var Mode=8;var ContextConsumer=9;var ContextProvider=10;var ForwardRef=11;var Profiler=12;var SuspenseComponent=13;var MemoComponent=14;var SimpleMemoComponent=15;var LazyComponent=16;var IncompleteClassComponent=17;var DehydratedFragment=18;var SuspenseListComponent=19;var ScopeComponent=21;var OffscreenComponent=22;var LegacyHiddenComponent=23;var CacheComponent=24;var TracingMarkerComponent=25;// -----------------------------------------------------------------------------
var enableClientRenderFallbackOnTextMismatch=true;// TODO: Need to review this code one more time before landing
// the react-reconciler package.
var enableNewReconciler=false;// Support legacy Primer support on internal FB www
var enableLazyContextPropagation=false;// FB-only usage. The new API has different semantics.
var enableLegacyHidden=false;// Enables unstable_avoidThisFallback feature in Fiber
var enableSuspenseAvoidThisFallback=false;// Enables unstable_avoidThisFallback feature in Fizz
// React DOM Chopping Block
//
// Similar to main Chopping Block but only flags related to React DOM. These are
// grouped because we will likely batch all of them into a single major release.
// -----------------------------------------------------------------------------
// Disable support for comment nodes as React DOM containers. Already disabled
// in open source, but www codebase still relies on it. Need to remove.
var disableCommentsAsDOMContainers=true;// Disable javascript: URL strings in href for XSS protection.
// and client rendering, mostly to allow JSX attributes to apply to the custom
// element's object properties instead of only HTML attributes.
// https://github.com/facebook/react/issues/11347
var enableCustomElementPropertySupport=false;// Disables children for <textarea> elements
var warnAboutStringRefs=false;// -----------------------------------------------------------------------------
// Debugging and DevTools
// -----------------------------------------------------------------------------
// Adds user timing marks for e.g. state updates, suspense, and work loop stuff,
// for an experimental timeline tool.
var enableSchedulingProfiler=true;// Helps identify side effects in render-phase lifecycle hooks and setState
var enableProfilerTimer=true;// Record durations for commit and passive effects phases.
var enableProfilerCommitHooks=true;// Phase param passed to onRender callback differentiates between an "update" and a "cascading-update".
var allNativeEvents=new Set();/**
 * Mapping from registration name to event name
 */var registrationNameDependencies={};/**
 * Mapping from lowercase registration names to the properly cased version,
 * used to warn in the case of missing event handlers. Available
 * only in true.
 * @type {Object}
 */var possibleRegistrationNames={};// Trust the developer to only use possibleRegistrationNames in true
function registerTwoPhaseEvent(registrationName,dependencies){registerDirectEvent(registrationName,dependencies);registerDirectEvent(registrationName+'Capture',dependencies);}function registerDirectEvent(registrationName,dependencies){{if(registrationNameDependencies[registrationName]){error('EventRegistry: More than one plugin attempted to publish the same '+'registration name, `%s`.',registrationName);}}registrationNameDependencies[registrationName]=dependencies;{var lowerCasedName=registrationName.toLowerCase();possibleRegistrationNames[lowerCasedName]=registrationName;if(registrationName==='onDoubleClick'){possibleRegistrationNames.ondblclick=registrationName;}}for(var i=0;i<dependencies.length;i++){allNativeEvents.add(dependencies[i]);}}var canUseDOM=!!(typeof window!=='undefined'&&typeof window.document!=='undefined'&&typeof window.document.createElement!=='undefined');var hasOwnProperty=Object.prototype.hasOwnProperty;/*
 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
 *
 * The functions in this module will throw an easier-to-understand,
 * easier-to-debug exception with a clear errors message message explaining the
 * problem. (Instead of a confusing exception thrown inside the implementation
 * of the `value` object).
 */ // $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value){{// toStringTag is needed for namespaced types like Temporal.Instant
var hasToStringTag=typeof Symbol==='function'&&Symbol.toStringTag;var type=hasToStringTag&&value[Symbol.toStringTag]||value.constructor.name||'Object';return type;}}// $FlowFixMe only called in DEV, so void return is not possible.
function willCoercionThrow(value){{try{testStringCoercion(value);return false;}catch(e){return true;}}}function testStringCoercion(value){// If you ended up here by following an exception call stack, here's what's
// happened: you supplied an object or symbol value to React (as a prop, key,
// DOM attribute, CSS property, string ref, etc.) and when React tried to
// coerce it to a string using `'' + value`, an exception was thrown.
//
// The most common types that will cause this exception are `Symbol` instances
// and Temporal objects like `Temporal.Instant`. But any object that has a
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
// exception. (Library authors do this to prevent users from using built-in
// numeric operators like `+` or comparison operators like `>=` because custom
// methods are needed to perform accurate arithmetic or comparison.)
//
// To fix the problem, coerce this object or symbol value to a string before
// passing it to React. The most reliable way is usually `String(value)`.
//
// To find which value is throwing, check the browser or debugger console.
// Before this exception was thrown, there should be `console.error` output
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
// problem and how that type was used: key, atrribute, input value prop, etc.
// In most cases, this console output also shows the component and its
// ancestor components where the exception happened.
//
// eslint-disable-next-line react-internal/safe-string-coercion
return ''+value;}function checkAttributeStringCoercion(value,attributeName){{if(willCoercionThrow(value)){error('The provided `%s` attribute is an unsupported type %s.'+' This value must be coerced to a string before before using it here.',attributeName,typeName(value));return testStringCoercion(value);// throw (to help callers find troubleshooting comments)
}}}function checkKeyStringCoercion(value){{if(willCoercionThrow(value)){error('The provided key is an unsupported type %s.'+' This value must be coerced to a string before before using it here.',typeName(value));return testStringCoercion(value);// throw (to help callers find troubleshooting comments)
}}}function checkPropStringCoercion(value,propName){{if(willCoercionThrow(value)){error('The provided `%s` prop is an unsupported type %s.'+' This value must be coerced to a string before before using it here.',propName,typeName(value));return testStringCoercion(value);// throw (to help callers find troubleshooting comments)
}}}function checkCSSPropertyStringCoercion(value,propName){{if(willCoercionThrow(value)){error('The provided `%s` CSS property is an unsupported type %s.'+' This value must be coerced to a string before before using it here.',propName,typeName(value));return testStringCoercion(value);// throw (to help callers find troubleshooting comments)
}}}function checkHtmlStringCoercion(value){{if(willCoercionThrow(value)){error('The provided HTML markup uses a value of unsupported type %s.'+' This value must be coerced to a string before before using it here.',typeName(value));return testStringCoercion(value);// throw (to help callers find troubleshooting comments)
}}}function checkFormFieldValueStringCoercion(value){{if(willCoercionThrow(value)){error('Form field values (value, checked, defaultValue, or defaultChecked props)'+' must be strings, not %s.'+' This value must be coerced to a string before before using it here.',typeName(value));return testStringCoercion(value);// throw (to help callers find troubleshooting comments)
}}}// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED=0;// A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.
var STRING=1;// A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.
var BOOLEANISH_STRING=2;// A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
var BOOLEAN=3;// An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.
var OVERLOADED_BOOLEAN=4;// An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.
var NUMERIC=5;// An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.
var POSITIVE_NUMERIC=6;/* eslint-disable max-len */var ATTRIBUTE_NAME_START_CHAR=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";/* eslint-enable max-len */var ATTRIBUTE_NAME_CHAR=ATTRIBUTE_NAME_START_CHAR+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";var VALID_ATTRIBUTE_NAME_REGEX=new RegExp('^['+ATTRIBUTE_NAME_START_CHAR+']['+ATTRIBUTE_NAME_CHAR+']*$');var illegalAttributeNameCache={};var validatedAttributeNameCache={};function isAttributeNameSafe(attributeName){if(hasOwnProperty.call(validatedAttributeNameCache,attributeName)){return true;}if(hasOwnProperty.call(illegalAttributeNameCache,attributeName)){return false;}if(VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)){validatedAttributeNameCache[attributeName]=true;return true;}illegalAttributeNameCache[attributeName]=true;{error('Invalid attribute name: `%s`',attributeName);}return false;}function shouldIgnoreAttribute(name,propertyInfo,isCustomComponentTag){if(propertyInfo!==null){return propertyInfo.type===RESERVED;}if(isCustomComponentTag){return false;}if(name.length>2&&(name[0]==='o'||name[0]==='O')&&(name[1]==='n'||name[1]==='N')){return true;}return false;}function shouldRemoveAttributeWithWarning(name,value,propertyInfo,isCustomComponentTag){if(propertyInfo!==null&&propertyInfo.type===RESERVED){return false;}switch(typeof value){case'function':// $FlowIssue symbol is perfectly valid here
case'symbol':// eslint-disable-line
return true;case'boolean':{if(isCustomComponentTag){return false;}if(propertyInfo!==null){return !propertyInfo.acceptsBooleans;}else {var prefix=name.toLowerCase().slice(0,5);return prefix!=='data-'&&prefix!=='aria-';}}default:return false;}}function shouldRemoveAttribute(name,value,propertyInfo,isCustomComponentTag){if(value===null||typeof value==='undefined'){return true;}if(shouldRemoveAttributeWithWarning(name,value,propertyInfo,isCustomComponentTag)){return true;}if(isCustomComponentTag){return false;}if(propertyInfo!==null){switch(propertyInfo.type){case BOOLEAN:return !value;case OVERLOADED_BOOLEAN:return value===false;case NUMERIC:return isNaN(value);case POSITIVE_NUMERIC:return isNaN(value)||value<1;}}return false;}function getPropertyInfo(name){return properties.hasOwnProperty(name)?properties[name]:null;}function PropertyInfoRecord(name,type,mustUseProperty,attributeName,attributeNamespace,sanitizeURL,removeEmptyString){this.acceptsBooleans=type===BOOLEANISH_STRING||type===BOOLEAN||type===OVERLOADED_BOOLEAN;this.attributeName=attributeName;this.attributeNamespace=attributeNamespace;this.mustUseProperty=mustUseProperty;this.propertyName=name;this.type=type;this.sanitizeURL=sanitizeURL;this.removeEmptyString=removeEmptyString;}// When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.
var properties={};// These props are reserved by React. They shouldn't be written to the DOM.
var reservedProps=['children','dangerouslySetInnerHTML',// TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue','defaultChecked','innerHTML','suppressContentEditableWarning','suppressHydrationWarning','style'];reservedProps.forEach(function(name){properties[name]=new PropertyInfoRecord(name,RESERVED,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.
[['acceptCharset','accept-charset'],['className','class'],['htmlFor','for'],['httpEquiv','http-equiv']].forEach(function(_ref){var name=_ref[0],attributeName=_ref[1];properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
['contentEditable','draggable','spellCheck','value'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEANISH_STRING,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.
['autoReverse','externalResourcesRequired','focusable','preserveAlpha'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEANISH_STRING,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML boolean attributes.
['allowFullScreen','async',// Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus','autoPlay','controls','default','defer','disabled','disablePictureInPicture','disableRemotePlayback','formNoValidate','hidden','loop','noModule','noValidate','open','playsInline','readOnly','required','reversed','scoped','seamless',// Microdata
'itemScope'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEAN,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.
['checked',// Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple','muted','selected'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,BOOLEAN,true,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.
['capture','download'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,OVERLOADED_BOOLEAN,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that must be positive numbers.
['cols','rows','size','span'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(name){properties[name]=new PropertyInfoRecord(name,POSITIVE_NUMERIC,false,// mustUseProperty
name,// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These are HTML attributes that must be numbers.
['rowSpan','start'].forEach(function(name){properties[name]=new PropertyInfoRecord(name,NUMERIC,false,// mustUseProperty
name.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});var CAMELIZE=/[\-\:]([a-z])/g;var capitalize=function(token){return token[1].toUpperCase();};// This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.
['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'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,null,// attributeNamespace
false,// sanitizeURL
false);});// String SVG attributes with the xlink namespace.
['xlink:actuate','xlink:arcrole','xlink:role','xlink:show','xlink:title','xlink:type'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,'http://www.w3.org/1999/xlink',false,// sanitizeURL
false);});// String SVG attributes with the xml namespace.
['xml:base','xml:lang','xml:space'// NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function(attributeName){var name=attributeName.replace(CAMELIZE,capitalize);properties[name]=new PropertyInfoRecord(name,STRING,false,// mustUseProperty
attributeName,'http://www.w3.org/XML/1998/namespace',false,// sanitizeURL
false);});// These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.
['tabIndex','crossOrigin'].forEach(function(attributeName){properties[attributeName]=new PropertyInfoRecord(attributeName,STRING,false,// mustUseProperty
attributeName.toLowerCase(),// attributeName
null,// attributeNamespace
false,// sanitizeURL
false);});// These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.
var xlinkHref='xlinkHref';properties[xlinkHref]=new PropertyInfoRecord('xlinkHref',STRING,false,// mustUseProperty
'xlink:href','http://www.w3.org/1999/xlink',true,// sanitizeURL
false);['src','href','action','formAction'].forEach(function(attributeName){properties[attributeName]=new PropertyInfoRecord(attributeName,STRING,false,// mustUseProperty
attributeName.toLowerCase(),// attributeName
null,// attributeNamespace
true,// sanitizeURL
true);});// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space
/* eslint-disable max-len */var isJavaScriptProtocol=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;var didWarn=false;function sanitizeURL(url){{if(!didWarn&&isJavaScriptProtocol.test(url)){didWarn=true;error('A future version of React will block javascript: URLs as a security precaution. '+'Use event handlers instead if you can. If you need to generate unsafe HTML try '+'using dangerouslySetInnerHTML instead. React was passed %s.',JSON.stringify(url));}}}/**
 * Get the value for a property on a node. Only used in DEV for SSR validation.
 * The "expected" argument is used as a hint of what the expected value is.
 * Some properties have multiple equivalent values.
 */function getValueForProperty(node,name,expected,propertyInfo){{if(propertyInfo.mustUseProperty){var propertyName=propertyInfo.propertyName;return node[propertyName];}else {// This check protects multiple uses of `expected`, which is why the
// react-internal/safe-string-coercion rule is disabled in several spots
// below.
{checkAttributeStringCoercion(expected,name);}if(propertyInfo.sanitizeURL){// If we haven't fully disabled javascript: URLs, and if
// the hydration is successful of a javascript: URL, we
// still want to warn on the client.
// eslint-disable-next-line react-internal/safe-string-coercion
sanitizeURL(''+expected);}var attributeName=propertyInfo.attributeName;var stringValue=null;if(propertyInfo.type===OVERLOADED_BOOLEAN){if(node.hasAttribute(attributeName)){var value=node.getAttribute(attributeName);if(value===''){return true;}if(shouldRemoveAttribute(name,expected,propertyInfo,false)){return value;}// eslint-disable-next-line react-internal/safe-string-coercion
if(value===''+expected){return expected;}return value;}}else if(node.hasAttribute(attributeName)){if(shouldRemoveAttribute(name,expected,propertyInfo,false)){// We had an attribute but shouldn't have had one, so read it
// for the error message.
return node.getAttribute(attributeName);}if(propertyInfo.type===BOOLEAN){// If this was a boolean, it doesn't matter what the value is
// the fact that we have it is the same as the expected.
return expected;}// Even if this property uses a namespace we use getAttribute
// because we assume its namespaced name is the same as our config.
// To use getAttributeNS we need the local name which we don't have
// in our config atm.
stringValue=node.getAttribute(attributeName);}if(shouldRemoveAttribute(name,expected,propertyInfo,false)){return stringValue===null?expected:stringValue;// eslint-disable-next-line react-internal/safe-string-coercion
}else if(stringValue===''+expected){return expected;}else {return stringValue;}}}}/**
 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
 * The third argument is used as a hint of what the expected value is. Some
 * attributes have multiple equivalent values.
 */function getValueForAttribute(node,name,expected,isCustomComponentTag){{if(!isAttributeNameSafe(name)){return;}if(!node.hasAttribute(name)){return expected===undefined?undefined:null;}var value=node.getAttribute(name);{checkAttributeStringCoercion(expected,name);}if(value===''+expected){return expected;}return value;}}/**
 * Sets the value for a property on a node.
 *
 * @param {DOMElement} node
 * @param {string} name
 * @param {*} value
 */function setValueForProperty(node,name,value,isCustomComponentTag){var propertyInfo=getPropertyInfo(name);if(shouldIgnoreAttribute(name,propertyInfo,isCustomComponentTag)){return;}if(shouldRemoveAttribute(name,value,propertyInfo,isCustomComponentTag)){value=null;}if(isCustomComponentTag||propertyInfo===null){if(isAttributeNameSafe(name)){var _attributeName=name;if(value===null){node.removeAttribute(_attributeName);}else {{checkAttributeStringCoercion(value,name);}node.setAttribute(_attributeName,''+value);}}return;}var mustUseProperty=propertyInfo.mustUseProperty;if(mustUseProperty){var propertyName=propertyInfo.propertyName;if(value===null){var type=propertyInfo.type;node[propertyName]=type===BOOLEAN?false:'';}else {// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyName]=value;}return;}// The rest are treated as attributes with special cases.
var attributeName=propertyInfo.attributeName,attributeNamespace=propertyInfo.attributeNamespace;if(value===null){node.removeAttribute(attributeName);}else {var _type=propertyInfo.type;var attributeValue;if(_type===BOOLEAN||_type===OVERLOADED_BOOLEAN&&value===true){// If attribute type is boolean, we know for sure it won't be an execution sink
// and we won't require Trusted Type here.
attributeValue='';}else {// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
{{checkAttributeStringCoercion(value,attributeName);}attributeValue=''+value;}if(propertyInfo.sanitizeURL){sanitizeURL(attributeValue.toString());}}if(attributeNamespace){node.setAttributeNS(attributeNamespace,attributeName,attributeValue);}else {node.setAttribute(attributeName,attributeValue);}}}// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE=Symbol.for('react.element');var REACT_PORTAL_TYPE=Symbol.for('react.portal');var REACT_FRAGMENT_TYPE=Symbol.for('react.fragment');var REACT_STRICT_MODE_TYPE=Symbol.for('react.strict_mode');var REACT_PROFILER_TYPE=Symbol.for('react.profiler');var REACT_PROVIDER_TYPE=Symbol.for('react.provider');var REACT_CONTEXT_TYPE=Symbol.for('react.context');var REACT_FORWARD_REF_TYPE=Symbol.for('react.forward_ref');var REACT_SUSPENSE_TYPE=Symbol.for('react.suspense');var REACT_SUSPENSE_LIST_TYPE=Symbol.for('react.suspense_list');var REACT_MEMO_TYPE=Symbol.for('react.memo');var REACT_LAZY_TYPE=Symbol.for('react.lazy');var REACT_SCOPE_TYPE=Symbol.for('react.scope');var REACT_DEBUG_TRACING_MODE_TYPE=Symbol.for('react.debug_trace_mode');var REACT_OFFSCREEN_TYPE=Symbol.for('react.offscreen');var REACT_LEGACY_HIDDEN_TYPE=Symbol.for('react.legacy_hidden');var REACT_CACHE_TYPE=Symbol.for('react.cache');var REACT_TRACING_MARKER_TYPE=Symbol.for('react.tracing_marker');var MAYBE_ITERATOR_SYMBOL=Symbol.iterator;var FAUX_ITERATOR_SYMBOL='@@iterator';function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=='object'){return null;}var maybeIterator=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL];if(typeof maybeIterator==='function'){return maybeIterator;}return null;}var assign=Object.assign;// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth=0;var prevLog;var prevInfo;var prevWarn;var prevError;var prevGroup;var prevGroupCollapsed;var prevGroupEnd;function disabledLog(){}disabledLog.__reactDisabledLog=true;function disableLogs(){{if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */prevLog=console.log;prevInfo=console.info;prevWarn=console.warn;prevError=console.error;prevGroup=console.group;prevGroupCollapsed=console.groupCollapsed;prevGroupEnd=console.groupEnd;// https://github.com/facebook/react/issues/19099
var props={configurable:true,enumerable:true,value:disabledLog,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{info:props,log:props,warn:props,error:props,group:props,groupCollapsed:props,groupEnd:props});/* eslint-enable react-internal/no-production-logging */}disabledDepth++;}}function reenableLogs(){{disabledDepth--;if(disabledDepth===0){/* eslint-disable react-internal/no-production-logging */var props={configurable:true,enumerable:true,writable:true};// $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console,{log:assign({},props,{value:prevLog}),info:assign({},props,{value:prevInfo}),warn:assign({},props,{value:prevWarn}),error:assign({},props,{value:prevError}),group:assign({},props,{value:prevGroup}),groupCollapsed:assign({},props,{value:prevGroupCollapsed}),groupEnd:assign({},props,{value:prevGroupEnd})});/* eslint-enable react-internal/no-production-logging */}if(disabledDepth<0){error('disabledDepth fell below zero. '+'This is a bug in React. Please file an issue.');}}}var ReactCurrentDispatcher=ReactSharedInternals.ReactCurrentDispatcher;var prefix;function describeBuiltInComponentFrame(name,source,ownerFn){{if(prefix===undefined){// Extract the VM specific prefix used by each line.
try{throw Error();}catch(x){var match=x.stack.trim().match(/\n( *(at )?)/);prefix=match&&match[1]||'';}}// We use the prefix to ensure our stacks line up with native stack frames.
return '\n'+prefix+name;}}var reentry=false;var componentFrameCache;{var PossiblyWeakMap=typeof WeakMap==='function'?WeakMap:Map;componentFrameCache=new PossiblyWeakMap();}function describeNativeComponentFrame(fn,construct){// If something asked for a stack inside a fake render, it should get ignored.
if(!fn||reentry){return '';}{var frame=componentFrameCache.get(fn);if(frame!==undefined){return frame;}}var control;reentry=true;var previousPrepareStackTrace=Error.prepareStackTrace;// $FlowFixMe It does accept undefined.
Error.prepareStackTrace=undefined;var previousDispatcher;{previousDispatcher=ReactCurrentDispatcher.current;// Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher.current=null;disableLogs();}try{// This should throw.
if(construct){// Something should be setting the props in the constructor.
var Fake=function(){throw Error();};// $FlowFixMe
Object.defineProperty(Fake.prototype,'props',{set:function(){// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();}});if(typeof Reflect==='object'&&Reflect.construct){// We construct a different control for this case to include any extra
// frames added by the construct call.
try{Reflect.construct(Fake,[]);}catch(x){control=x;}Reflect.construct(fn,[],Fake);}else {try{Fake.call();}catch(x){control=x;}fn.call(Fake.prototype);}}else {try{throw Error();}catch(x){control=x;}fn();}}catch(sample){// This is inlined manually because closure doesn't do it for us.
if(sample&&control&&typeof sample.stack==='string'){// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines=sample.stack.split('\n');var controlLines=control.stack.split('\n');var s=sampleLines.length-1;var c=controlLines.length-1;while(s>=1&&c>=0&&sampleLines[s]!==controlLines[c]){// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;}for(;s>=1&&c>=0;s--,c--){// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if(sampleLines[s]!==controlLines[c]){// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if(s!==1||c!==1){do{s--;c--;// We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if(c<0||sampleLines[s]!==controlLines[c]){// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame='\n'+sampleLines[s].replace(' at new ',' at ');// If our component frame is labeled "<anonymous>"
// but we have a user-provided "displayName"
// splice it in to make the stack more readable.
if(fn.displayName&&_frame.includes('<anonymous>')){_frame=_frame.replace('<anonymous>',fn.displayName);}{if(typeof fn==='function'){componentFrameCache.set(fn,_frame);}}// Return the line we found.
return _frame;}}while(s>=1&&c>=0);}break;}}}}finally{reentry=false;{ReactCurrentDispatcher.current=previousDispatcher;reenableLogs();}Error.prepareStackTrace=previousPrepareStackTrace;}// Fallback to just using the name if we couldn't make it throw.
var name=fn?fn.displayName||fn.name:'';var syntheticFrame=name?describeBuiltInComponentFrame(name):'';{if(typeof fn==='function'){componentFrameCache.set(fn,syntheticFrame);}}return syntheticFrame;}function describeClassComponentFrame(ctor,source,ownerFn){{return describeNativeComponentFrame(ctor,true);}}function describeFunctionComponentFrame(fn,source,ownerFn){{return describeNativeComponentFrame(fn,false);}}function shouldConstruct(Component){var prototype=Component.prototype;return !!(prototype&&prototype.isReactComponent);}function describeUnknownElementTypeFrameInDEV(type,source,ownerFn){if(type==null){return '';}if(typeof type==='function'){{return describeNativeComponentFrame(type,shouldConstruct(type));}}if(typeof type==='string'){return describeBuiltInComponentFrame(type);}switch(type){case REACT_SUSPENSE_TYPE:return describeBuiltInComponentFrame('Suspense');case REACT_SUSPENSE_LIST_TYPE:return describeBuiltInComponentFrame('SuspenseList');}if(typeof type==='object'){switch(type.$$typeof){case REACT_FORWARD_REF_TYPE:return describeFunctionComponentFrame(type.render);case REACT_MEMO_TYPE:// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type,source,ownerFn);case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload),source,ownerFn);}catch(x){}}}}return '';}function describeFiber(fiber){fiber._debugOwner?fiber._debugOwner.type:null;fiber._debugSource;switch(fiber.tag){case HostComponent:return describeBuiltInComponentFrame(fiber.type);case LazyComponent:return describeBuiltInComponentFrame('Lazy');case SuspenseComponent:return describeBuiltInComponentFrame('Suspense');case SuspenseListComponent:return describeBuiltInComponentFrame('SuspenseList');case FunctionComponent:case IndeterminateComponent:case SimpleMemoComponent:return describeFunctionComponentFrame(fiber.type);case ForwardRef:return describeFunctionComponentFrame(fiber.type.render);case ClassComponent:return describeClassComponentFrame(fiber.type);default:return '';}}function getStackByFiberInDevAndProd(workInProgress){try{var info='';var node=workInProgress;do{info+=describeFiber(node);node=node.return;}while(node);return info;}catch(x){return '\nError generating stack: '+x.message+'\n'+x.stack;}}function getWrappedName(outerType,innerType,wrapperName){var displayName=outerType.displayName;if(displayName){return displayName;}var functionName=innerType.displayName||innerType.name||'';return functionName!==''?wrapperName+"("+functionName+")":wrapperName;}// Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type){return type.displayName||'Context';}// Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type){if(type==null){// Host root, text node or just invalid type.
return null;}{if(typeof type.tag==='number'){error('Received an unexpected object in getComponentNameFromType(). '+'This is likely a bug in React. Please file an issue.');}}if(typeof type==='function'){return type.displayName||type.name||null;}if(typeof type==='string'){return type;}switch(type){case REACT_FRAGMENT_TYPE:return 'Fragment';case REACT_PORTAL_TYPE:return 'Portal';case REACT_PROFILER_TYPE:return 'Profiler';case REACT_STRICT_MODE_TYPE:return 'StrictMode';case REACT_SUSPENSE_TYPE:return 'Suspense';case REACT_SUSPENSE_LIST_TYPE:return 'SuspenseList';}if(typeof type==='object'){switch(type.$$typeof){case REACT_CONTEXT_TYPE:var context=type;return getContextName(context)+'.Consumer';case REACT_PROVIDER_TYPE:var provider=type;return getContextName(provider._context)+'.Provider';case REACT_FORWARD_REF_TYPE:return getWrappedName(type,type.render,'ForwardRef');case REACT_MEMO_TYPE:var outerName=type.displayName||null;if(outerName!==null){return outerName;}return getComponentNameFromType(type.type)||'Memo';case REACT_LAZY_TYPE:{var lazyComponent=type;var payload=lazyComponent._payload;var init=lazyComponent._init;try{return getComponentNameFromType(init(payload));}catch(x){return null;}}// eslint-disable-next-line no-fallthrough
}}return null;}function getWrappedName$1(outerType,innerType,wrapperName){var functionName=innerType.displayName||innerType.name||'';return outerType.displayName||(functionName!==''?wrapperName+"("+functionName+")":wrapperName);}// Keep in sync with shared/getComponentNameFromType
function getContextName$1(type){return type.displayName||'Context';}function getComponentNameFromFiber(fiber){var tag=fiber.tag,type=fiber.type;switch(tag){case CacheComponent:return 'Cache';case ContextConsumer:var context=type;return getContextName$1(context)+'.Consumer';case ContextProvider:var provider=type;return getContextName$1(provider._context)+'.Provider';case DehydratedFragment:return 'DehydratedFragment';case ForwardRef:return getWrappedName$1(type,type.render,'ForwardRef');case Fragment:return 'Fragment';case HostComponent:// Host component type is the display name (e.g. "div", "View")
return type;case HostPortal:return 'Portal';case HostRoot:return 'Root';case HostText:return 'Text';case LazyComponent:// Name comes from the type in this case; we don't have a tag.
return getComponentNameFromType(type);case Mode:if(type===REACT_STRICT_MODE_TYPE){// Don't be less specific than shared/getComponentNameFromType
return 'StrictMode';}return 'Mode';case OffscreenComponent:return 'Offscreen';case Profiler:return 'Profiler';case ScopeComponent:return 'Scope';case SuspenseComponent:return 'Suspense';case SuspenseListComponent:return 'SuspenseList';case TracingMarkerComponent:return 'TracingMarker';// The display name for this tags come from the user-provided type:
case ClassComponent:case FunctionComponent:case IncompleteClassComponent:case IndeterminateComponent:case MemoComponent:case SimpleMemoComponent:if(typeof type==='function'){return type.displayName||type.name||null;}if(typeof type==='string'){return type;}break;}return null;}var ReactDebugCurrentFrame=ReactSharedInternals.ReactDebugCurrentFrame;var current=null;var isRendering=false;function getCurrentFiberOwnerNameInDevOrNull(){{if(current===null){return null;}var owner=current._debugOwner;if(owner!==null&&typeof owner!=='undefined'){return getComponentNameFromFiber(owner);}}return null;}function getCurrentFiberStackInDev(){{if(current===null){return '';}// Safe because if current fiber exists, we are reconciling,
// and it is guaranteed to be the work-in-progress version.
return getStackByFiberInDevAndProd(current);}}function resetCurrentFiber(){{ReactDebugCurrentFrame.getCurrentStack=null;current=null;isRendering=false;}}function setCurrentFiber(fiber){{ReactDebugCurrentFrame.getCurrentStack=fiber===null?null:getCurrentFiberStackInDev;current=fiber;isRendering=false;}}function getCurrentFiber(){{return current;}}function setIsRendering(rendering){{isRendering=rendering;}}// Flow does not allow string concatenation of most non-string types. To work
// around this limitation, we use an opaque type that can only be obtained by
// passing the value through getToStringValue first.
function toString(value){// The coercion safety check is performed in getToStringValue().
// eslint-disable-next-line react-internal/safe-string-coercion
return ''+value;}function getToStringValue(value){switch(typeof value){case'boolean':case'number':case'string':case'undefined':return value;case'object':{checkFormFieldValueStringCoercion(value);}return value;default:// function, symbol are assigned as empty strings
return '';}}var hasReadOnlyValue={button:true,checkbox:true,image:true,hidden:true,radio:true,reset:true,submit:true};function checkControlledValueProps(tagName,props){{if(!(hasReadOnlyValue[props.type]||props.onChange||props.onInput||props.readOnly||props.disabled||props.value==null)){error('You provided a `value` prop to a form field without an '+'`onChange` handler. This will render a read-only field. If '+'the field should be mutable use `defaultValue`. Otherwise, '+'set either `onChange` or `readOnly`.');}if(!(props.onChange||props.readOnly||props.disabled||props.checked==null)){error('You provided a `checked` prop to a form field without an '+'`onChange` handler. This will render a read-only field. If '+'the field should be mutable use `defaultChecked`. Otherwise, '+'set either `onChange` or `readOnly`.');}}}function isCheckable(elem){var type=elem.type;var nodeName=elem.nodeName;return nodeName&&nodeName.toLowerCase()==='input'&&(type==='checkbox'||type==='radio');}function getTracker(node){return node._valueTracker;}function detachTracker(node){node._valueTracker=null;}function getValueFromNode(node){var value='';if(!node){return value;}if(isCheckable(node)){value=node.checked?'true':'false';}else {value=node.value;}return value;}function trackValueOnNode(node){var valueField=isCheckable(node)?'checked':'value';var descriptor=Object.getOwnPropertyDescriptor(node.constructor.prototype,valueField);{checkFormFieldValueStringCoercion(node[valueField]);}var currentValue=''+node[valueField];// if someone has already defined a value or Safari, then bail
// and don't track value will cause over reporting of changes,
// but it's better then a hard failure
// (needed for certain tests that spyOn input values and Safari)
if(node.hasOwnProperty(valueField)||typeof descriptor==='undefined'||typeof descriptor.get!=='function'||typeof descriptor.set!=='function'){return;}var get=descriptor.get,set=descriptor.set;Object.defineProperty(node,valueField,{configurable:true,get:function(){return get.call(this);},set:function(value){{checkFormFieldValueStringCoercion(value);}currentValue=''+value;set.call(this,value);}});// We could've passed this the first time
// but it triggers a bug in IE11 and Edge 14/15.
// Calling defineProperty() again should be equivalent.
// https://github.com/facebook/react/issues/11768
Object.defineProperty(node,valueField,{enumerable:descriptor.enumerable});var tracker={getValue:function(){return currentValue;},setValue:function(value){{checkFormFieldValueStringCoercion(value);}currentValue=''+value;},stopTracking:function(){detachTracker(node);delete node[valueField];}};return tracker;}function track(node){if(getTracker(node)){return;}// TODO: Once it's just Fiber we can move this to node._wrapperState
node._valueTracker=trackValueOnNode(node);}function updateValueIfChanged(node){if(!node){return false;}var tracker=getTracker(node);// if there is no tracker at this point it's unlikely
// that trying again will succeed
if(!tracker){return true;}var lastValue=tracker.getValue();var nextValue=getValueFromNode(node);if(nextValue!==lastValue){tracker.setValue(nextValue);return true;}return false;}function getActiveElement(doc){doc=doc||(typeof document!=='undefined'?document:undefined);if(typeof doc==='undefined'){return null;}try{return doc.activeElement||doc.body;}catch(e){return doc.body;}}var didWarnValueDefaultValue=false;var didWarnCheckedDefaultChecked=false;var didWarnControlledToUncontrolled=false;var didWarnUncontrolledToControlled=false;function isControlled(props){var usesChecked=props.type==='checkbox'||props.type==='radio';return usesChecked?props.checked!=null:props.value!=null;}/**
 * Implements an <input> host component that allows setting these optional
 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
 *
 * If `checked` or `value` are not supplied (or null/undefined), user actions
 * that affect the checked state or value will trigger updates to the element.
 *
 * If they are supplied (and not null/undefined), the rendered element will not
 * trigger updates to the element. Instead, the props must change in order for
 * the rendered element to be updated.
 *
 * The rendered element will be initialized as unchecked (or `defaultChecked`)
 * with an empty value (or `defaultValue`).
 *
 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
 */function getHostProps(element,props){var node=element;var checked=props.checked;var hostProps=assign({},props,{defaultChecked:undefined,defaultValue:undefined,value:undefined,checked:checked!=null?checked:node._wrapperState.initialChecked});return hostProps;}function initWrapperState(element,props){{checkControlledValueProps('input',props);if(props.checked!==undefined&&props.defaultChecked!==undefined&&!didWarnCheckedDefaultChecked){error('%s contains an input of type %s with both checked and defaultChecked props. '+'Input elements must be either controlled or uncontrolled '+'(specify either the checked prop, or the defaultChecked prop, but not '+'both). Decide between using a controlled or uncontrolled input '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components',getCurrentFiberOwnerNameInDevOrNull()||'A component',props.type);didWarnCheckedDefaultChecked=true;}if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnValueDefaultValue){error('%s contains an input of type %s with both value and defaultValue props. '+'Input elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled input '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components',getCurrentFiberOwnerNameInDevOrNull()||'A component',props.type);didWarnValueDefaultValue=true;}}var node=element;var defaultValue=props.defaultValue==null?'':props.defaultValue;node._wrapperState={initialChecked:props.checked!=null?props.checked:props.defaultChecked,initialValue:getToStringValue(props.value!=null?props.value:defaultValue),controlled:isControlled(props)};}function updateChecked(element,props){var node=element;var checked=props.checked;if(checked!=null){setValueForProperty(node,'checked',checked,false);}}function updateWrapper(element,props){var node=element;{var controlled=isControlled(props);if(!node._wrapperState.controlled&&controlled&&!didWarnUncontrolledToControlled){error('A component is changing an uncontrolled input to be controlled. '+'This is likely caused by the value changing from undefined to '+'a defined value, which should not happen. '+'Decide between using a controlled or uncontrolled input '+'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');didWarnUncontrolledToControlled=true;}if(node._wrapperState.controlled&&!controlled&&!didWarnControlledToUncontrolled){error('A component is changing a controlled input to be uncontrolled. '+'This is likely caused by the value changing from a defined to '+'undefined, which should not happen. '+'Decide between using a controlled or uncontrolled input '+'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');didWarnControlledToUncontrolled=true;}}updateChecked(element,props);var value=getToStringValue(props.value);var type=props.type;if(value!=null){if(type==='number'){if(value===0&&node.value===''||// We explicitly want to coerce to number here if possible.
// eslint-disable-next-line
node.value!=value){node.value=toString(value);}}else if(node.value!==toString(value)){node.value=toString(value);}}else if(type==='submit'||type==='reset'){// Submit/reset inputs need the attribute removed completely to avoid
// blank-text buttons.
node.removeAttribute('value');return;}{// When syncing the value attribute, the value comes from a cascade of
// properties:
//  1. The value React property
//  2. The defaultValue React property
//  3. Otherwise there should be no change
if(props.hasOwnProperty('value')){setDefaultValue(node,props.type,value);}else if(props.hasOwnProperty('defaultValue')){setDefaultValue(node,props.type,getToStringValue(props.defaultValue));}}{// When syncing the checked attribute, it only changes when it needs
// to be removed, such as transitioning from a checkbox into a text input
if(props.checked==null&&props.defaultChecked!=null){node.defaultChecked=!!props.defaultChecked;}}}function postMountWrapper(element,props,isHydrating){var node=element;// Do not assign value if it is already set. This prevents user text input
// from being lost during SSR hydration.
if(props.hasOwnProperty('value')||props.hasOwnProperty('defaultValue')){var type=props.type;var isButton=type==='submit'||type==='reset';// Avoid setting value attribute on submit/reset inputs as it overrides the
// default value provided by the browser. See: #12872
if(isButton&&(props.value===undefined||props.value===null)){return;}var initialValue=toString(node._wrapperState.initialValue);// Do not assign value if it is already set. This prevents user text input
// from being lost during SSR hydration.
if(!isHydrating){{// When syncing the value attribute, the value property should use
// the wrapperState._initialValue property. This uses:
//
//   1. The value React property when present
//   2. The defaultValue React property when present
//   3. An empty string
if(initialValue!==node.value){node.value=initialValue;}}}{// Otherwise, the value attribute is synchronized to the property,
// so we assign defaultValue to the same thing as the value property
// assignment step above.
node.defaultValue=initialValue;}}// Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
// this is needed to work around a chrome bug where setting defaultChecked
// will sometimes influence the value of checked (even after detachment).
// Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
// We need to temporarily unset name to avoid disrupting radio button groups.
var name=node.name;if(name!==''){node.name='';}{// When syncing the checked attribute, both the checked property and
// attribute are assigned at the same time using defaultChecked. This uses:
//
//   1. The checked React property when present
//   2. The defaultChecked React property when present
//   3. Otherwise, false
node.defaultChecked=!node.defaultChecked;node.defaultChecked=!!node._wrapperState.initialChecked;}if(name!==''){node.name=name;}}function restoreControlledState(element,props){var node=element;updateWrapper(node,props);updateNamedCousins(node,props);}function updateNamedCousins(rootNode,props){var name=props.name;if(props.type==='radio'&&name!=null){var queryRoot=rootNode;while(queryRoot.parentNode){queryRoot=queryRoot.parentNode;}// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form. It might not even be in the
// document. Let's just use the local `querySelectorAll` to ensure we don't
// miss anything.
{checkAttributeStringCoercion(name,'name');}var group=queryRoot.querySelectorAll('input[name='+JSON.stringify(''+name)+'][type="radio"]');for(var i=0;i<group.length;i++){var otherNode=group[i];if(otherNode===rootNode||otherNode.form!==rootNode.form){continue;}// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherProps=getFiberCurrentPropsFromNode(otherNode);if(!otherProps){throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the '+'same `name` is not supported.');}// We need update the tracked value on the named cousin since the value
// was changed but the input saw no event or value set
updateValueIfChanged(otherNode);// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
updateWrapper(otherNode,otherProps);}}}// In Chrome, assigning defaultValue to certain input types triggers input validation.
// For number inputs, the display value loses trailing decimal points. For email inputs,
// Chrome raises "The specified value <x> is not a valid email address".
//
// Here we check to see if the defaultValue has actually changed, avoiding these problems
// when the user is inputting text
//
// https://github.com/facebook/react/issues/7253
function setDefaultValue(node,type,value){if(// Focused number inputs synchronize on blur. See ChangeEventPlugin.js
type!=='number'||getActiveElement(node.ownerDocument)!==node){if(value==null){node.defaultValue=toString(node._wrapperState.initialValue);}else if(node.defaultValue!==toString(value)){node.defaultValue=toString(value);}}}var didWarnSelectedSetOnOption=false;var didWarnInvalidChild=false;var didWarnInvalidInnerHTML=false;/**
 * Implements an <option> host component that warns when `selected` is set.
 */function validateProps(element,props){{// If a value is not provided, then the children must be simple.
if(props.value==null){if(typeof props.children==='object'&&props.children!==null){React.Children.forEach(props.children,function(child){if(child==null){return;}if(typeof child==='string'||typeof child==='number'){return;}if(!didWarnInvalidChild){didWarnInvalidChild=true;error('Cannot infer the option value of complex children. '+'Pass a `value` prop or use a plain string as children to <option>.');}});}else if(props.dangerouslySetInnerHTML!=null){if(!didWarnInvalidInnerHTML){didWarnInvalidInnerHTML=true;error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows '+'which value should be selected.');}}}// TODO: Remove support for `selected` in <option>.
if(props.selected!=null&&!didWarnSelectedSetOnOption){error('Use the `defaultValue` or `value` props on <select> instead of '+'setting `selected` on <option>.');didWarnSelectedSetOnOption=true;}}}function postMountWrapper$1(element,props){// value="" should make a value attribute (#6219)
if(props.value!=null){element.setAttribute('value',toString(getToStringValue(props.value)));}}var isArrayImpl=Array.isArray;// eslint-disable-next-line no-redeclare
function isArray(a){return isArrayImpl(a);}var didWarnValueDefaultValue$1;{didWarnValueDefaultValue$1=false;}function getDeclarationErrorAddendum(){var ownerName=getCurrentFiberOwnerNameInDevOrNull();if(ownerName){return '\n\nCheck the render method of `'+ownerName+'`.';}return '';}var valuePropNames=['value','defaultValue'];/**
 * Validation function for `value` and `defaultValue`.
 */function checkSelectPropTypes(props){{checkControlledValueProps('select',props);for(var i=0;i<valuePropNames.length;i++){var propName=valuePropNames[i];if(props[propName]==null){continue;}var propNameIsArray=isArray(props[propName]);if(props.multiple&&!propNameIsArray){error('The `%s` prop supplied to <select> must be an array if '+'`multiple` is true.%s',propName,getDeclarationErrorAddendum());}else if(!props.multiple&&propNameIsArray){error('The `%s` prop supplied to <select> must be a scalar '+'value if `multiple` is false.%s',propName,getDeclarationErrorAddendum());}}}}function updateOptions(node,multiple,propValue,setDefaultSelected){var options=node.options;if(multiple){var selectedValues=propValue;var selectedValue={};for(var i=0;i<selectedValues.length;i++){// Prefix to avoid chaos with special keys.
selectedValue['$'+selectedValues[i]]=true;}for(var _i=0;_i<options.length;_i++){var selected=selectedValue.hasOwnProperty('$'+options[_i].value);if(options[_i].selected!==selected){options[_i].selected=selected;}if(selected&&setDefaultSelected){options[_i].defaultSelected=true;}}}else {// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
var _selectedValue=toString(getToStringValue(propValue));var defaultSelected=null;for(var _i2=0;_i2<options.length;_i2++){if(options[_i2].value===_selectedValue){options[_i2].selected=true;if(setDefaultSelected){options[_i2].defaultSelected=true;}return;}if(defaultSelected===null&&!options[_i2].disabled){defaultSelected=options[_i2];}}if(defaultSelected!==null){defaultSelected.selected=true;}}}/**
 * Implements a <select> host component that allows optionally setting the
 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
 * stringable. If `multiple` is true, the prop must be an array of stringables.
 *
 * If `value` is not supplied (or null/undefined), user actions that change the
 * selected option will trigger updates to the rendered options.
 *
 * If it is supplied (and not null/undefined), the rendered options will not
 * update in response to user actions. Instead, the `value` prop must change in
 * order for the rendered options to update.
 *
 * If `defaultValue` is provided, any options with the supplied values will be
 * selected.
 */function getHostProps$1(element,props){return assign({},props,{value:undefined});}function initWrapperState$1(element,props){var node=element;{checkSelectPropTypes(props);}node._wrapperState={wasMultiple:!!props.multiple};{if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnValueDefaultValue$1){error('Select elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled select '+'element and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components');didWarnValueDefaultValue$1=true;}}}function postMountWrapper$2(element,props){var node=element;node.multiple=!!props.multiple;var value=props.value;if(value!=null){updateOptions(node,!!props.multiple,value,false);}else if(props.defaultValue!=null){updateOptions(node,!!props.multiple,props.defaultValue,true);}}function postUpdateWrapper(element,props){var node=element;var wasMultiple=node._wrapperState.wasMultiple;node._wrapperState.wasMultiple=!!props.multiple;var value=props.value;if(value!=null){updateOptions(node,!!props.multiple,value,false);}else if(wasMultiple!==!!props.multiple){// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if(props.defaultValue!=null){updateOptions(node,!!props.multiple,props.defaultValue,true);}else {// Revert the select back to its default unselected state.
updateOptions(node,!!props.multiple,props.multiple?[]:'',false);}}}function restoreControlledState$1(element,props){var node=element;var value=props.value;if(value!=null){updateOptions(node,!!props.multiple,value,false);}}var didWarnValDefaultVal=false;/**
 * Implements a <textarea> host component that allows setting `value`, and
 * `defaultValue`. This differs from the traditional DOM API because value is
 * usually set as PCDATA children.
 *
 * If `value` is not supplied (or null/undefined), user actions that affect the
 * value will trigger updates to the element.
 *
 * If `value` is supplied (and not null/undefined), the rendered element will
 * not trigger updates to the element. Instead, the `value` prop must change in
 * order for the rendered element to be updated.
 *
 * The rendered element will be initialized with an empty value, the prop
 * `defaultValue` if specified, or the children content (deprecated).
 */function getHostProps$2(element,props){var node=element;if(props.dangerouslySetInnerHTML!=null){throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');}// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.  We could add a check in setTextContent
// to only set the value if/when the value differs from the node value (which would
// completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
// solution. The value can be a boolean or object so that's why it's forced
// to be a string.
var hostProps=assign({},props,{value:undefined,defaultValue:undefined,children:toString(node._wrapperState.initialValue)});return hostProps;}function initWrapperState$2(element,props){var node=element;{checkControlledValueProps('textarea',props);if(props.value!==undefined&&props.defaultValue!==undefined&&!didWarnValDefaultVal){error('%s contains a textarea with both value and defaultValue props. '+'Textarea elements must be either controlled or uncontrolled '+'(specify either the value prop, or the defaultValue prop, but not '+'both). Decide between using a controlled or uncontrolled textarea '+'and remove one of these props. More info: '+'https://reactjs.org/link/controlled-components',getCurrentFiberOwnerNameInDevOrNull()||'A component');didWarnValDefaultVal=true;}}var initialValue=props.value;// Only bother fetching default value if we're going to use it
if(initialValue==null){var children=props.children,defaultValue=props.defaultValue;if(children!=null){{error('Use the `defaultValue` or `value` props instead of setting '+'children on <textarea>.');}{if(defaultValue!=null){throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');}if(isArray(children)){if(children.length>1){throw new Error('<textarea> can only have at most one child.');}children=children[0];}defaultValue=children;}}if(defaultValue==null){defaultValue='';}initialValue=defaultValue;}node._wrapperState={initialValue:getToStringValue(initialValue)};}function updateWrapper$1(element,props){var node=element;var value=getToStringValue(props.value);var defaultValue=getToStringValue(props.defaultValue);if(value!=null){// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
var newValue=toString(value);// To avoid side effects (such as losing text selection), only set value if changed
if(newValue!==node.value){node.value=newValue;}if(props.defaultValue==null&&node.defaultValue!==newValue){node.defaultValue=newValue;}}if(defaultValue!=null){node.defaultValue=toString(defaultValue);}}function postMountWrapper$3(element,props){var node=element;// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var textContent=node.textContent;// Only set node.value if textContent is equal to the expected
// initial value. In IE10/IE11 there is a bug where the placeholder attribute
// will populate textContent as well.
// https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
if(textContent===node._wrapperState.initialValue){if(textContent!==''&&textContent!==null){node.value=textContent;}}}function restoreControlledState$2(element,props){// DOM component is still mounted; update
updateWrapper$1(element,props);}var HTML_NAMESPACE='http://www.w3.org/1999/xhtml';var MATH_NAMESPACE='http://www.w3.org/1998/Math/MathML';var SVG_NAMESPACE='http://www.w3.org/2000/svg';// Assumes there is no parent namespace.
function getIntrinsicNamespace(type){switch(type){case'svg':return SVG_NAMESPACE;case'math':return MATH_NAMESPACE;default:return HTML_NAMESPACE;}}function getChildNamespace(parentNamespace,type){if(parentNamespace==null||parentNamespace===HTML_NAMESPACE){// No (or default) parent namespace: potential entry point.
return getIntrinsicNamespace(type);}if(parentNamespace===SVG_NAMESPACE&&type==='foreignObject'){// We're leaving SVG.
return HTML_NAMESPACE;}// By default, pass namespace below.
return parentNamespace;}/* globals MSApp */ /**
 * Create a function which has 'unsafe' privileges (required by windows8 apps)
 */var createMicrosoftUnsafeLocalFunction=function(func){if(typeof MSApp!=='undefined'&&MSApp.execUnsafeLocalFunction){return function(arg0,arg1,arg2,arg3){MSApp.execUnsafeLocalFunction(function(){return func(arg0,arg1,arg2,arg3);});};}else {return func;}};var reusableSVGContainer;/**
 * Set the innerHTML property of a node
 *
 * @param {DOMElement} node
 * @param {string} html
 * @internal
 */var setInnerHTML=createMicrosoftUnsafeLocalFunction(function(node,html){if(node.namespaceURI===SVG_NAMESPACE){if(!('innerHTML'in node)){// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
reusableSVGContainer=reusableSVGContainer||document.createElement('div');reusableSVGContainer.innerHTML='<svg>'+html.valueOf().toString()+'</svg>';var svgNode=reusableSVGContainer.firstChild;while(node.firstChild){node.removeChild(node.firstChild);}while(svgNode.firstChild){node.appendChild(svgNode.firstChild);}return;}}node.innerHTML=html;});/**
 * HTML nodeType values that represent the type of the node
 */var ELEMENT_NODE=1;var TEXT_NODE=3;var COMMENT_NODE=8;var DOCUMENT_NODE=9;var DOCUMENT_FRAGMENT_NODE=11;/**
 * Set the textContent property of a node. For text updates, it's faster
 * to set the `nodeValue` of the Text node directly instead of using
 * `.textContent` which will remove the existing node and create a new one.
 *
 * @param {DOMElement} node
 * @param {string} text
 * @internal
 */var setTextContent=function(node,text){if(text){var firstChild=node.firstChild;if(firstChild&&firstChild===node.lastChild&&firstChild.nodeType===TEXT_NODE){firstChild.nodeValue=text;return;}}node.textContent=text;};// List derived from Gecko source code:
// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
var shorthandToLonghand={animation:['animationDelay','animationDirection','animationDuration','animationFillMode','animationIterationCount','animationName','animationPlayState','animationTimingFunction'],background:['backgroundAttachment','backgroundClip','backgroundColor','backgroundImage','backgroundOrigin','backgroundPositionX','backgroundPositionY','backgroundRepeat','backgroundSize'],backgroundPosition:['backgroundPositionX','backgroundPositionY'],border:['borderBottomColor','borderBottomStyle','borderBottomWidth','borderImageOutset','borderImageRepeat','borderImageSlice','borderImageSource','borderImageWidth','borderLeftColor','borderLeftStyle','borderLeftWidth','borderRightColor','borderRightStyle','borderRightWidth','borderTopColor','borderTopStyle','borderTopWidth'],borderBlockEnd:['borderBlockEndColor','borderBlockEndStyle','borderBlockEndWidth'],borderBlockStart:['borderBlockStartColor','borderBlockStartStyle','borderBlockStartWidth'],borderBottom:['borderBottomColor','borderBottomStyle','borderBottomWidth'],borderColor:['borderBottomColor','borderLeftColor','borderRightColor','borderTopColor'],borderImage:['borderImageOutset','borderImageRepeat','borderImageSlice','borderImageSource','borderImageWidth'],borderInlineEnd:['borderInlineEndColor','borderInlineEndStyle','borderInlineEndWidth'],borderInlineStart:['borderInlineStartColor','borderInlineStartStyle','borderInlineStartWidth'],borderLeft:['borderLeftColor','borderLeftStyle','borderLeftWidth'],borderRadius:['borderBottomLeftRadius','borderBottomRightRadius','borderTopLeftRadius','borderTopRightRadius'],borderRight:['borderRightColor','borderRightStyle','borderRightWidth'],borderStyle:['borderBottomStyle','borderLeftStyle','borderRightStyle','borderTopStyle'],borderTop:['borderTopColor','borderTopStyle','borderTopWidth'],borderWidth:['borderBottomWidth','borderLeftWidth','borderRightWidth','borderTopWidth'],columnRule:['columnRuleColor','columnRuleStyle','columnRuleWidth'],columns:['columnCount','columnWidth'],flex:['flexBasis','flexGrow','flexShrink'],flexFlow:['flexDirection','flexWrap'],font:['fontFamily','fontFeatureSettings','fontKerning','fontLanguageOverride','fontSize','fontSizeAdjust','fontStretch','fontStyle','fontVariant','fontVariantAlternates','fontVariantCaps','fontVariantEastAsian','fontVariantLigatures','fontVariantNumeric','fontVariantPosition','fontWeight','lineHeight'],fontVariant:['fontVariantAlternates','fontVariantCaps','fontVariantEastAsian','fontVariantLigatures','fontVariantNumeric','fontVariantPosition'],gap:['columnGap','rowGap'],grid:['gridAutoColumns','gridAutoFlow','gridAutoRows','gridTemplateAreas','gridTemplateColumns','gridTemplateRows'],gridArea:['gridColumnEnd','gridColumnStart','gridRowEnd','gridRowStart'],gridColumn:['gridColumnEnd','gridColumnStart'],gridColumnGap:['columnGap'],gridGap:['columnGap','rowGap'],gridRow:['gridRowEnd','gridRowStart'],gridRowGap:['rowGap'],gridTemplate:['gridTemplateAreas','gridTemplateColumns','gridTemplateRows'],listStyle:['listStyleImage','listStylePosition','listStyleType'],margin:['marginBottom','marginLeft','marginRight','marginTop'],marker:['markerEnd','markerMid','markerStart'],mask:['maskClip','maskComposite','maskImage','maskMode','maskOrigin','maskPositionX','maskPositionY','maskRepeat','maskSize'],maskPosition:['maskPositionX','maskPositionY'],outline:['outlineColor','outlineStyle','outlineWidth'],overflow:['overflowX','overflowY'],padding:['paddingBottom','paddingLeft','paddingRight','paddingTop'],placeContent:['alignContent','justifyContent'],placeItems:['alignItems','justifyItems'],placeSelf:['alignSelf','justifySelf'],textDecoration:['textDecorationColor','textDecorationLine','textDecorationStyle'],textEmphasis:['textEmphasisColor','textEmphasisStyle'],transition:['transitionDelay','transitionDuration','transitionProperty','transitionTimingFunction'],wordWrap:['overflowWrap']};/**
 * CSS properties which accept numbers but are not in units of "px".
 */var isUnitlessNumber={animationIterationCount:true,aspectRatio:true,borderImageOutset:true,borderImageSlice:true,borderImageWidth:true,boxFlex:true,boxFlexGroup:true,boxOrdinalGroup:true,columnCount:true,columns:true,flex:true,flexGrow:true,flexPositive:true,flexShrink:true,flexNegative:true,flexOrder:true,gridArea:true,gridRow:true,gridRowEnd:true,gridRowSpan:true,gridRowStart:true,gridColumn:true,gridColumnEnd:true,gridColumnSpan:true,gridColumnStart:true,fontWeight:true,lineClamp:true,lineHeight:true,opacity:true,order:true,orphans:true,tabSize:true,widows:true,zIndex:true,zoom:true,// SVG-related properties
fillOpacity:true,floodOpacity:true,stopOpacity:true,strokeDasharray:true,strokeDashoffset:true,strokeMiterlimit:true,strokeOpacity:true,strokeWidth:true};/**
 * @param {string} prefix vendor-specific prefix, eg: Webkit
 * @param {string} key style name, eg: transitionDuration
 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
 * WebkitTransitionDuration
 */function prefixKey(prefix,key){return prefix+key.charAt(0).toUpperCase()+key.substring(1);}/**
 * Support style names that may come passed in prefixed by adding permutations
 * of vendor prefixes.
 */var prefixes=['Webkit','ms','Moz','O'];// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function(prop){prefixes.forEach(function(prefix){isUnitlessNumber[prefixKey(prefix,prop)]=isUnitlessNumber[prop];});});/**
 * Convert a value into the proper css writable value. The style name `name`
 * should be logical (no hyphens), as specified
 * in `CSSProperty.isUnitlessNumber`.
 *
 * @param {string} name CSS property name such as `topMargin`.
 * @param {*} value CSS property value such as `10px`.
 * @return {string} Normalized style value with dimensions applied.
 */function dangerousStyleValue(name,value,isCustomProperty){// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty=value==null||typeof value==='boolean'||value==='';if(isEmpty){return '';}if(!isCustomProperty&&typeof value==='number'&&value!==0&&!(isUnitlessNumber.hasOwnProperty(name)&&isUnitlessNumber[name])){return value+'px';// Presumes implicit 'px' suffix for unitless numbers
}{checkCSSPropertyStringCoercion(value,name);}return (''+value).trim();}var uppercasePattern=/([A-Z])/g;var msPattern=/^ms-/;/**
 * Hyphenates a camelcased CSS property name, for example:
 *
 *   > hyphenateStyleName('backgroundColor')
 *   < "background-color"
 *   > hyphenateStyleName('MozTransition')
 *   < "-moz-transition"
 *   > hyphenateStyleName('msTransition')
 *   < "-ms-transition"
 *
 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
 * is converted to `-ms-`.
 */function hyphenateStyleName(name){return name.replace(uppercasePattern,'-$1').toLowerCase().replace(msPattern,'-ms-');}var warnValidStyle=function(){};{// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern=/^(?:webkit|moz|o)[A-Z]/;var msPattern$1=/^-ms-/;var hyphenPattern=/-(.)/g;// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern=/;\s*$/;var warnedStyleNames={};var warnedStyleValues={};var warnedForNaNValue=false;var warnedForInfinityValue=false;var camelize=function(string){return string.replace(hyphenPattern,function(_,character){return character.toUpperCase();});};var warnHyphenatedStyleName=function(name){if(warnedStyleNames.hasOwnProperty(name)&&warnedStyleNames[name]){return;}warnedStyleNames[name]=true;error('Unsupported style property %s. Did you mean %s?',name,// As Andi Smith suggests
// (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
// is converted to lowercase `ms`.
camelize(name.replace(msPattern$1,'ms-')));};var warnBadVendoredStyleName=function(name){if(warnedStyleNames.hasOwnProperty(name)&&warnedStyleNames[name]){return;}warnedStyleNames[name]=true;error('Unsupported vendor-prefixed style property %s. Did you mean %s?',name,name.charAt(0).toUpperCase()+name.slice(1));};var warnStyleValueWithSemicolon=function(name,value){if(warnedStyleValues.hasOwnProperty(value)&&warnedStyleValues[value]){return;}warnedStyleValues[value]=true;error("Style property values shouldn't contain a semicolon. "+'Try "%s: %s" instead.',name,value.replace(badStyleValueWithSemicolonPattern,''));};var warnStyleValueIsNaN=function(name,value){if(warnedForNaNValue){return;}warnedForNaNValue=true;error('`NaN` is an invalid value for the `%s` css style property.',name);};var warnStyleValueIsInfinity=function(name,value){if(warnedForInfinityValue){return;}warnedForInfinityValue=true;error('`Infinity` is an invalid value for the `%s` css style property.',name);};warnValidStyle=function(name,value){if(name.indexOf('-')>-1){warnHyphenatedStyleName(name);}else if(badVendoredStyleNamePattern.test(name)){warnBadVendoredStyleName(name);}else if(badStyleValueWithSemicolonPattern.test(value)){warnStyleValueWithSemicolon(name,value);}if(typeof value==='number'){if(isNaN(value)){warnStyleValueIsNaN(name,value);}else if(!isFinite(value)){warnStyleValueIsInfinity(name,value);}}};}var warnValidStyle$1=warnValidStyle;/**
 * Operations for dealing with CSS properties.
 */ /**
 * This creates a string that is expected to be equivalent to the style
 * attribute generated by server-side rendering. It by-passes warnings and
 * security checks so it's not safe to use this value for anything other than
 * comparison. It is only used in DEV for SSR validation.
 */function createDangerousStringForStyles(styles){{var serialized='';var delimiter='';for(var styleName in styles){if(!styles.hasOwnProperty(styleName)){continue;}var styleValue=styles[styleName];if(styleValue!=null){var isCustomProperty=styleName.indexOf('--')===0;serialized+=delimiter+(isCustomProperty?styleName:hyphenateStyleName(styleName))+':';serialized+=dangerousStyleValue(styleName,styleValue,isCustomProperty);delimiter=';';}}return serialized||null;}}/**
 * Sets the value for multiple styles on a node.  If a value is specified as
 * '' (empty string), the corresponding style property will be unset.
 *
 * @param {DOMElement} node
 * @param {object} styles
 */function setValueForStyles(node,styles){var style=node.style;for(var styleName in styles){if(!styles.hasOwnProperty(styleName)){continue;}var isCustomProperty=styleName.indexOf('--')===0;{if(!isCustomProperty){warnValidStyle$1(styleName,styles[styleName]);}}var styleValue=dangerousStyleValue(styleName,styles[styleName],isCustomProperty);if(styleName==='float'){styleName='cssFloat';}if(isCustomProperty){style.setProperty(styleName,styleValue);}else {style[styleName]=styleValue;}}}function isValueEmpty(value){return value==null||typeof value==='boolean'||value==='';}/**
 * Given {color: 'red', overflow: 'hidden'} returns {
 *   color: 'color',
 *   overflowX: 'overflow',
 *   overflowY: 'overflow',
 * }. This can be read as "the overflowY property was set by the overflow
 * shorthand". That is, the values are the property that each was derived from.
 */function expandShorthandMap(styles){var expanded={};for(var key in styles){var longhands=shorthandToLonghand[key]||[key];for(var i=0;i<longhands.length;i++){expanded[longhands[i]]=key;}}return expanded;}/**
 * When mixing shorthand and longhand property names, we warn during updates if
 * we expect an incorrect result to occur. In particular, we warn for:
 *
 * Updating a shorthand property (longhand gets overwritten):
 *   {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
 *   becomes .style.font = 'baz'
 * Removing a shorthand property (longhand gets lost too):
 *   {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
 *   becomes .style.font = ''
 * Removing a longhand property (should revert to shorthand; doesn't):
 *   {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
 *   becomes .style.fontVariant = ''
 */function validateShorthandPropertyCollisionInDev(styleUpdates,nextStyles){{if(!nextStyles){return;}var expandedUpdates=expandShorthandMap(styleUpdates);var expandedStyles=expandShorthandMap(nextStyles);var warnedAbout={};for(var key in expandedUpdates){var originalKey=expandedUpdates[key];var correctOriginalKey=expandedStyles[key];if(correctOriginalKey&&originalKey!==correctOriginalKey){var warningKey=originalKey+','+correctOriginalKey;if(warnedAbout[warningKey]){continue;}warnedAbout[warningKey]=true;error('%s a style property during rerender (%s) when a '+'conflicting property is set (%s) can lead to styling bugs. To '+"avoid this, don't mix shorthand and non-shorthand properties "+'for the same value; instead, replace the shorthand with '+'separate values.',isValueEmpty(styleUpdates[originalKey])?'Removing':'Updating',originalKey,correctOriginalKey);}}}}// For HTML, certain tags should omit their close tag. We keep a list for
// those special-case tags.
var omittedCloseTags={area:true,base:true,br:true,col:true,embed:true,hr:true,img:true,input:true,keygen:true,link:true,meta:true,param:true,source:true,track:true,wbr:true// NOTE: menuitem's close tag should be omitted, but that causes problems.
};// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags=assign({menuitem:true},omittedCloseTags);var HTML='__html';function assertValidProps(tag,props){if(!props){return;}// Note the use of `==` which checks for null or undefined.
if(voidElementTags[tag]){if(props.children!=null||props.dangerouslySetInnerHTML!=null){throw new Error(tag+" is a void element tag and must neither have `children` nor "+'use `dangerouslySetInnerHTML`.');}}if(props.dangerouslySetInnerHTML!=null){if(props.children!=null){throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');}if(typeof props.dangerouslySetInnerHTML!=='object'||!(HTML in props.dangerouslySetInnerHTML)){throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. '+'Please visit https://reactjs.org/link/dangerously-set-inner-html '+'for more information.');}}{if(!props.suppressContentEditableWarning&&props.contentEditable&&props.children!=null){error('A component is `contentEditable` and contains `children` managed by '+'React. It is now your responsibility to guarantee that none of '+'those nodes are unexpectedly modified or duplicated. This is '+'probably not intentional.');}}if(props.style!=null&&typeof props.style!=='object'){throw new Error('The `style` prop expects a mapping from style properties to values, '+"not a string. For example, style={{marginRight: spacing + 'em'}} when "+'using JSX.');}}function isCustomComponent(tagName,props){if(tagName.indexOf('-')===-1){return typeof props.is==='string';}switch(tagName){// These are reserved SVG and MathML elements.
// We don't mind this list too much because we expect it to never grow.
// The alternative is to track the namespace in a few places which is convoluted.
// https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
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 false;default:return true;}}// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames={// HTML
accept:'accept',acceptcharset:'acceptCharset','accept-charset':'acceptCharset',accesskey:'accessKey',action:'action',allowfullscreen:'allowFullScreen',alt:'alt',as:'as',async:'async',autocapitalize:'autoCapitalize',autocomplete:'autoComplete',autocorrect:'autoCorrect',autofocus:'autoFocus',autoplay:'autoPlay',autosave:'autoSave',capture:'capture',cellpadding:'cellPadding',cellspacing:'cellSpacing',challenge:'challenge',charset:'charSet',checked:'checked',children:'children',cite:'cite',class:'className',classid:'classID',classname:'className',cols:'cols',colspan:'colSpan',content:'content',contenteditable:'contentEditable',contextmenu:'contextMenu',controls:'controls',controlslist:'controlsList',coords:'coords',crossorigin:'crossOrigin',dangerouslysetinnerhtml:'dangerouslySetInnerHTML',data:'data',datetime:'dateTime',default:'default',defaultchecked:'defaultChecked',defaultvalue:'defaultValue',defer:'defer',dir:'dir',disabled:'disabled',disablepictureinpicture:'disablePictureInPicture',disableremoteplayback:'disableRemotePlayback',download:'download',draggable:'draggable',enctype:'encType',enterkeyhint:'enterKeyHint',for:'htmlFor',form:'form',formmethod:'formMethod',formaction:'formAction',formenctype:'formEncType',formnovalidate:'formNoValidate',formtarget:'formTarget',frameborder:'frameBorder',headers:'headers',height:'height',hidden:'hidden',high:'high',href:'href',hreflang:'hrefLang',htmlfor:'htmlFor',httpequiv:'httpEquiv','http-equiv':'httpEquiv',icon:'icon',id:'id',imagesizes:'imageSizes',imagesrcset:'imageSrcSet',innerhtml:'innerHTML',inputmode:'inputMode',integrity:'integrity',is:'is',itemid:'itemID',itemprop:'itemProp',itemref:'itemRef',itemscope:'itemScope',itemtype:'itemType',keyparams:'keyParams',keytype:'keyType',kind:'kind',label:'label',lang:'lang',list:'list',loop:'loop',low:'low',manifest:'manifest',marginwidth:'marginWidth',marginheight:'marginHeight',max:'max',maxlength:'maxLength',media:'media',mediagroup:'mediaGroup',method:'method',min:'min',minlength:'minLength',multiple:'multiple',muted:'muted',name:'name',nomodule:'noModule',nonce:'nonce',novalidate:'noValidate',open:'open',optimum:'optimum',pattern:'pattern',placeholder:'placeholder',playsinline:'playsInline',poster:'poster',preload:'preload',profile:'profile',radiogroup:'radioGroup',readonly:'readOnly',referrerpolicy:'referrerPolicy',rel:'rel',required:'required',reversed:'reversed',role:'role',rows:'rows',rowspan:'rowSpan',sandbox:'sandbox',scope:'scope',scoped:'scoped',scrolling:'scrolling',seamless:'seamless',selected:'selected',shape:'shape',size:'size',sizes:'sizes',span:'span',spellcheck:'spellCheck',src:'src',srcdoc:'srcDoc',srclang:'srcLang',srcset:'srcSet',start:'start',step:'step',style:'style',summary:'summary',tabindex:'tabIndex',target:'target',title:'title',type:'type',usemap:'useMap',value:'value',width:'width',wmode:'wmode',wrap:'wrap',// SVG
about:'about',accentheight:'accentHeight','accent-height':'accentHeight',accumulate:'accumulate',additive:'additive',alignmentbaseline:'alignmentBaseline','alignment-baseline':'alignmentBaseline',allowreorder:'allowReorder',alphabetic:'alphabetic',amplitude:'amplitude',arabicform:'arabicForm','arabic-form':'arabicForm',ascent:'ascent',attributename:'attributeName',attributetype:'attributeType',autoreverse:'autoReverse',azimuth:'azimuth',basefrequency:'baseFrequency',baselineshift:'baselineShift','baseline-shift':'baselineShift',baseprofile:'baseProfile',bbox:'bbox',begin:'begin',bias:'bias',by:'by',calcmode:'calcMode',capheight:'capHeight','cap-height':'capHeight',clip:'clip',clippath:'clipPath','clip-path':'clipPath',clippathunits:'clipPathUnits',cliprule:'clipRule','clip-rule':'clipRule',color:'color',colorinterpolation:'colorInterpolation','color-interpolation':'colorInterpolation',colorinterpolationfilters:'colorInterpolationFilters','color-interpolation-filters':'colorInterpolationFilters',colorprofile:'colorProfile','color-profile':'colorProfile',colorrendering:'colorRendering','color-rendering':'colorRendering',contentscripttype:'contentScriptType',contentstyletype:'contentStyleType',cursor:'cursor',cx:'cx',cy:'cy',d:'d',datatype:'datatype',decelerate:'decelerate',descent:'descent',diffuseconstant:'diffuseConstant',direction:'direction',display:'display',divisor:'divisor',dominantbaseline:'dominantBaseline','dominant-baseline':'dominantBaseline',dur:'dur',dx:'dx',dy:'dy',edgemode:'edgeMode',elevation:'elevation',enablebackground:'enableBackground','enable-background':'enableBackground',end:'end',exponent:'exponent',externalresourcesrequired:'externalResourcesRequired',fill:'fill',fillopacity:'fillOpacity','fill-opacity':'fillOpacity',fillrule:'fillRule','fill-rule':'fillRule',filter:'filter',filterres:'filterRes',filterunits:'filterUnits',floodopacity:'floodOpacity','flood-opacity':'floodOpacity',floodcolor:'floodColor','flood-color':'floodColor',focusable:'focusable',fontfamily:'fontFamily','font-family':'fontFamily',fontsize:'fontSize','font-size':'fontSize',fontsizeadjust:'fontSizeAdjust','font-size-adjust':'fontSizeAdjust',fontstretch:'fontStretch','font-stretch':'fontStretch',fontstyle:'fontStyle','font-style':'fontStyle',fontvariant:'fontVariant','font-variant':'fontVariant',fontweight:'fontWeight','font-weight':'fontWeight',format:'format',from:'from',fx:'fx',fy:'fy',g1:'g1',g2:'g2',glyphname:'glyphName','glyph-name':'glyphName',glyphorientationhorizontal:'glyphOrientationHorizontal','glyph-orientation-horizontal':'glyphOrientationHorizontal',glyphorientationvertical:'glyphOrientationVertical','glyph-orientation-vertical':'glyphOrientationVertical',glyphref:'glyphRef',gradienttransform:'gradientTransform',gradientunits:'gradientUnits',hanging:'hanging',horizadvx:'horizAdvX','horiz-adv-x':'horizAdvX',horizoriginx:'horizOriginX','horiz-origin-x':'horizOriginX',ideographic:'ideographic',imagerendering:'imageRendering','image-rendering':'imageRendering',in2:'in2',in:'in',inlist:'inlist',intercept:'intercept',k1:'k1',k2:'k2',k3:'k3',k4:'k4',k:'k',kernelmatrix:'kernelMatrix',kernelunitlength:'kernelUnitLength',kerning:'kerning',keypoints:'keyPoints',keysplines:'keySplines',keytimes:'keyTimes',lengthadjust:'lengthAdjust',letterspacing:'letterSpacing','letter-spacing':'letterSpacing',lightingcolor:'lightingColor','lighting-color':'lightingColor',limitingconeangle:'limitingConeAngle',local:'local',markerend:'markerEnd','marker-end':'markerEnd',markerheight:'markerHeight',markermid:'markerMid','marker-mid':'markerMid',markerstart:'markerStart','marker-start':'markerStart',markerunits:'markerUnits',markerwidth:'markerWidth',mask:'mask',maskcontentunits:'maskContentUnits',maskunits:'maskUnits',mathematical:'mathematical',mode:'mode',numoctaves:'numOctaves',offset:'offset',opacity:'opacity',operator:'operator',order:'order',orient:'orient',orientation:'orientation',origin:'origin',overflow:'overflow',overlineposition:'overlinePosition','overline-position':'overlinePosition',overlinethickness:'overlineThickness','overline-thickness':'overlineThickness',paintorder:'paintOrder','paint-order':'paintOrder',panose1:'panose1','panose-1':'panose1',pathlength:'pathLength',patterncontentunits:'patternContentUnits',patterntransform:'patternTransform',patternunits:'patternUnits',pointerevents:'pointerEvents','pointer-events':'pointerEvents',points:'points',pointsatx:'pointsAtX',pointsaty:'pointsAtY',pointsatz:'pointsAtZ',prefix:'prefix',preservealpha:'preserveAlpha',preserveaspectratio:'preserveAspectRatio',primitiveunits:'primitiveUnits',property:'property',r:'r',radius:'radius',refx:'refX',refy:'refY',renderingintent:'renderingIntent','rendering-intent':'renderingIntent',repeatcount:'repeatCount',repeatdur:'repeatDur',requiredextensions:'requiredExtensions',requiredfeatures:'requiredFeatures',resource:'resource',restart:'restart',result:'result',results:'results',rotate:'rotate',rx:'rx',ry:'ry',scale:'scale',security:'security',seed:'seed',shaperendering:'shapeRendering','shape-rendering':'shapeRendering',slope:'slope',spacing:'spacing',specularconstant:'specularConstant',specularexponent:'specularExponent',speed:'speed',spreadmethod:'spreadMethod',startoffset:'startOffset',stddeviation:'stdDeviation',stemh:'stemh',stemv:'stemv',stitchtiles:'stitchTiles',stopcolor:'stopColor','stop-color':'stopColor',stopopacity:'stopOpacity','stop-opacity':'stopOpacity',strikethroughposition:'strikethroughPosition','strikethrough-position':'strikethroughPosition',strikethroughthickness:'strikethroughThickness','strikethrough-thickness':'strikethroughThickness',string:'string',stroke:'stroke',strokedasharray:'strokeDasharray','stroke-dasharray':'strokeDasharray',strokedashoffset:'strokeDashoffset','stroke-dashoffset':'strokeDashoffset',strokelinecap:'strokeLinecap','stroke-linecap':'strokeLinecap',strokelinejoin:'strokeLinejoin','stroke-linejoin':'strokeLinejoin',strokemiterlimit:'strokeMiterlimit','stroke-miterlimit':'strokeMiterlimit',strokewidth:'strokeWidth','stroke-width':'strokeWidth',strokeopacity:'strokeOpacity','stroke-opacity':'strokeOpacity',suppresscontenteditablewarning:'suppressContentEditableWarning',suppresshydrationwarning:'suppressHydrationWarning',surfacescale:'surfaceScale',systemlanguage:'systemLanguage',tablevalues:'tableValues',targetx:'targetX',targety:'targetY',textanchor:'textAnchor','text-anchor':'textAnchor',textdecoration:'textDecoration','text-decoration':'textDecoration',textlength:'textLength',textrendering:'textRendering','text-rendering':'textRendering',to:'to',transform:'transform',typeof:'typeof',u1:'u1',u2:'u2',underlineposition:'underlinePosition','underline-position':'underlinePosition',underlinethickness:'underlineThickness','underline-thickness':'underlineThickness',unicode:'unicode',unicodebidi:'unicodeBidi','unicode-bidi':'unicodeBidi',unicoderange:'unicodeRange','unicode-range':'unicodeRange',unitsperem:'unitsPerEm','units-per-em':'unitsPerEm',unselectable:'unselectable',valphabetic:'vAlphabetic','v-alphabetic':'vAlphabetic',values:'values',vectoreffect:'vectorEffect','vector-effect':'vectorEffect',version:'version',vertadvy:'vertAdvY','vert-adv-y':'vertAdvY',vertoriginx:'vertOriginX','vert-origin-x':'vertOriginX',vertoriginy:'vertOriginY','vert-origin-y':'vertOriginY',vhanging:'vHanging','v-hanging':'vHanging',videographic:'vIdeographic','v-ideographic':'vIdeographic',viewbox:'viewBox',viewtarget:'viewTarget',visibility:'visibility',vmathematical:'vMathematical','v-mathematical':'vMathematical',vocab:'vocab',widths:'widths',wordspacing:'wordSpacing','word-spacing':'wordSpacing',writingmode:'writingMode','writing-mode':'writingMode',x1:'x1',x2:'x2',x:'x',xchannelselector:'xChannelSelector',xheight:'xHeight','x-height':'xHeight',xlinkactuate:'xlinkActuate','xlink:actuate':'xlinkActuate',xlinkarcrole:'xlinkArcrole','xlink:arcrole':'xlinkArcrole',xlinkhref:'xlinkHref','xlink:href':'xlinkHref',xlinkrole:'xlinkRole','xlink:role':'xlinkRole',xlinkshow:'xlinkShow','xlink:show':'xlinkShow',xlinktitle:'xlinkTitle','xlink:title':'xlinkTitle',xlinktype:'xlinkType','xlink:type':'xlinkType',xmlbase:'xmlBase','xml:base':'xmlBase',xmllang:'xmlLang','xml:lang':'xmlLang',xmlns:'xmlns','xml:space':'xmlSpace',xmlnsxlink:'xmlnsXlink','xmlns:xlink':'xmlnsXlink',xmlspace:'xmlSpace',y1:'y1',y2:'y2',y:'y',ychannelselector:'yChannelSelector',z:'z',zoomandpan:'zoomAndPan'};var ariaProperties={'aria-current':0,// state
'aria-description':0,'aria-details':0,'aria-disabled':0,// state
'aria-hidden':0,// state
'aria-invalid':0,// state
'aria-keyshortcuts':0,'aria-label':0,'aria-roledescription':0,// Widget Attributes
'aria-autocomplete':0,'aria-checked':0,'aria-expanded':0,'aria-haspopup':0,'aria-level':0,'aria-modal':0,'aria-multiline':0,'aria-multiselectable':0,'aria-orientation':0,'aria-placeholder':0,'aria-pressed':0,'aria-readonly':0,'aria-required':0,'aria-selected':0,'aria-sort':0,'aria-valuemax':0,'aria-valuemin':0,'aria-valuenow':0,'aria-valuetext':0,// Live Region Attributes
'aria-atomic':0,'aria-busy':0,'aria-live':0,'aria-relevant':0,// Drag-and-Drop Attributes
'aria-dropeffect':0,'aria-grabbed':0,// Relationship Attributes
'aria-activedescendant':0,'aria-colcount':0,'aria-colindex':0,'aria-colspan':0,'aria-controls':0,'aria-describedby':0,'aria-errormessage':0,'aria-flowto':0,'aria-labelledby':0,'aria-owns':0,'aria-posinset':0,'aria-rowcount':0,'aria-rowindex':0,'aria-rowspan':0,'aria-setsize':0};var warnedProperties={};var rARIA=new RegExp('^(aria)-['+ATTRIBUTE_NAME_CHAR+']*$');var rARIACamel=new RegExp('^(aria)[A-Z]['+ATTRIBUTE_NAME_CHAR+']*$');function validateProperty(tagName,name){{if(hasOwnProperty.call(warnedProperties,name)&&warnedProperties[name]){return true;}if(rARIACamel.test(name)){var ariaName='aria-'+name.slice(4).toLowerCase();var correctName=ariaProperties.hasOwnProperty(ariaName)?ariaName:null;// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if(correctName==null){error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.',name);warnedProperties[name]=true;return true;}// aria-* attributes should be lowercase; suggest the lowercase version.
if(name!==correctName){error('Invalid ARIA attribute `%s`. Did you mean `%s`?',name,correctName);warnedProperties[name]=true;return true;}}if(rARIA.test(name)){var lowerCasedName=name.toLowerCase();var standardName=ariaProperties.hasOwnProperty(lowerCasedName)?lowerCasedName:null;// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if(standardName==null){warnedProperties[name]=true;return false;}// aria-* attributes should be lowercase; suggest the lowercase version.
if(name!==standardName){error('Unknown ARIA attribute `%s`. Did you mean `%s`?',name,standardName);warnedProperties[name]=true;return true;}}}return true;}function warnInvalidARIAProps(type,props){{var invalidProps=[];for(var key in props){var isValid=validateProperty(type,key);if(!isValid){invalidProps.push(key);}}var unknownPropString=invalidProps.map(function(prop){return '`'+prop+'`';}).join(', ');if(invalidProps.length===1){error('Invalid aria prop %s on <%s> tag. '+'For details, see https://reactjs.org/link/invalid-aria-props',unknownPropString,type);}else if(invalidProps.length>1){error('Invalid aria props %s on <%s> tag. '+'For details, see https://reactjs.org/link/invalid-aria-props',unknownPropString,type);}}}function validateProperties(type,props){if(isCustomComponent(type,props)){return;}warnInvalidARIAProps(type,props);}var didWarnValueNull=false;function validateProperties$1(type,props){{if(type!=='input'&&type!=='textarea'&&type!=='select'){return;}if(props!=null&&props.value===null&&!didWarnValueNull){didWarnValueNull=true;if(type==='select'&&props.multiple){error('`value` prop on `%s` should not be null. '+'Consider using an empty array when `multiple` is set to `true` '+'to clear the component or `undefined` for uncontrolled components.',type);}else {error('`value` prop on `%s` should not be null. '+'Consider using an empty string to clear the component or `undefined` '+'for uncontrolled components.',type);}}}}var validateProperty$1=function(){};{var warnedProperties$1={};var EVENT_NAME_REGEX=/^on./;var INVALID_EVENT_NAME_REGEX=/^on[^A-Z]/;var rARIA$1=new RegExp('^(aria)-['+ATTRIBUTE_NAME_CHAR+']*$');var rARIACamel$1=new RegExp('^(aria)[A-Z]['+ATTRIBUTE_NAME_CHAR+']*$');validateProperty$1=function(tagName,name,value,eventRegistry){if(hasOwnProperty.call(warnedProperties$1,name)&&warnedProperties$1[name]){return true;}var lowerCasedName=name.toLowerCase();if(lowerCasedName==='onfocusin'||lowerCasedName==='onfocusout'){error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. '+'All React events are normalized to bubble, so onFocusIn and onFocusOut '+'are not needed/supported by React.');warnedProperties$1[name]=true;return true;}// We can't rely on the event system being injected on the server.
if(eventRegistry!=null){var registrationNameDependencies=eventRegistry.registrationNameDependencies,possibleRegistrationNames=eventRegistry.possibleRegistrationNames;if(registrationNameDependencies.hasOwnProperty(name)){return true;}var registrationName=possibleRegistrationNames.hasOwnProperty(lowerCasedName)?possibleRegistrationNames[lowerCasedName]:null;if(registrationName!=null){error('Invalid event handler property `%s`. Did you mean `%s`?',name,registrationName);warnedProperties$1[name]=true;return true;}if(EVENT_NAME_REGEX.test(name)){error('Unknown event handler property `%s`. It will be ignored.',name);warnedProperties$1[name]=true;return true;}}else if(EVENT_NAME_REGEX.test(name)){// If no event plugins have been injected, we are in a server environment.
// So we can't tell if the event name is correct for sure, but we can filter
// out known bad ones like `onclick`. We can't suggest a specific replacement though.
if(INVALID_EVENT_NAME_REGEX.test(name)){error('Invalid event handler property `%s`. '+'React events use the camelCase naming convention, for example `onClick`.',name);}warnedProperties$1[name]=true;return true;}// Let the ARIA attribute hook validate ARIA attributes
if(rARIA$1.test(name)||rARIACamel$1.test(name)){return true;}if(lowerCasedName==='innerhtml'){error('Directly setting property `innerHTML` is not permitted. '+'For more information, lookup documentation on `dangerouslySetInnerHTML`.');warnedProperties$1[name]=true;return true;}if(lowerCasedName==='aria'){error('The `aria` attribute is reserved for future use in React. '+'Pass individual `aria-` attributes instead.');warnedProperties$1[name]=true;return true;}if(lowerCasedName==='is'&&value!==null&&value!==undefined&&typeof value!=='string'){error('Received a `%s` for a string attribute `is`. If this is expected, cast '+'the value to a string.',typeof value);warnedProperties$1[name]=true;return true;}if(typeof value==='number'&&isNaN(value)){error('Received NaN for the `%s` attribute. If this is expected, cast '+'the value to a string.',name);warnedProperties$1[name]=true;return true;}var propertyInfo=getPropertyInfo(name);var isReserved=propertyInfo!==null&&propertyInfo.type===RESERVED;// Known attributes should match the casing specified in the property config.
if(possibleStandardNames.hasOwnProperty(lowerCasedName)){var standardName=possibleStandardNames[lowerCasedName];if(standardName!==name){error('Invalid DOM property `%s`. Did you mean `%s`?',name,standardName);warnedProperties$1[name]=true;return true;}}else if(!isReserved&&name!==lowerCasedName){// Unknown attributes should have lowercase casing since that's how they
// will be cased anyway with server rendering.
error('React does not recognize the `%s` prop on a DOM element. If you '+'intentionally want it to appear in the DOM as a custom '+'attribute, spell it as lowercase `%s` instead. '+'If you accidentally passed it from a parent component, remove '+'it from the DOM element.',name,lowerCasedName);warnedProperties$1[name]=true;return true;}if(typeof value==='boolean'&&shouldRemoveAttributeWithWarning(name,value,propertyInfo,false)){if(value){error('Received `%s` for a non-boolean attribute `%s`.\n\n'+'If you want to write it to the DOM, pass a string instead: '+'%s="%s" or %s={value.toString()}.',value,name,name,value,name);}else {error('Received `%s` for a non-boolean attribute `%s`.\n\n'+'If you want to write it to the DOM, pass a string instead: '+'%s="%s" or %s={value.toString()}.\n\n'+'If you used to conditionally omit it with %s={condition && value}, '+'pass %s={condition ? value : undefined} instead.',value,name,name,value,name,name,name);}warnedProperties$1[name]=true;return true;}// Now that we've validated casing, do not validate
// data types for reserved props
if(isReserved){return true;}// Warn when a known attribute is a bad type
if(shouldRemoveAttributeWithWarning(name,value,propertyInfo,false)){warnedProperties$1[name]=true;return false;}// Warn when passing the strings 'false' or 'true' into a boolean prop
if((value==='false'||value==='true')&&propertyInfo!==null&&propertyInfo.type===BOOLEAN){error('Received the string `%s` for the boolean attribute `%s`. '+'%s '+'Did you mean %s={%s}?',value,name,value==='false'?'The browser will interpret it as a truthy value.':'Although this works, it will not work as expected if you pass the string "false".',name,value);warnedProperties$1[name]=true;return true;}return true;};}var warnUnknownProperties=function(type,props,eventRegistry){{var unknownProps=[];for(var key in props){var isValid=validateProperty$1(type,key,props[key],eventRegistry);if(!isValid){unknownProps.push(key);}}var unknownPropString=unknownProps.map(function(prop){return '`'+prop+'`';}).join(', ');if(unknownProps.length===1){error('Invalid value for prop %s on <%s> tag. Either remove it from the element, '+'or pass a string or number value to keep it in the DOM. '+'For details, see https://reactjs.org/link/attribute-behavior ',unknownPropString,type);}else if(unknownProps.length>1){error('Invalid values for props %s on <%s> tag. Either remove them from the element, '+'or pass a string or number value to keep them in the DOM. '+'For details, see https://reactjs.org/link/attribute-behavior ',unknownPropString,type);}}};function validateProperties$2(type,props,eventRegistry){if(isCustomComponent(type,props)){return;}warnUnknownProperties(type,props,eventRegistry);}var IS_EVENT_HANDLE_NON_MANAGED_NODE=1;var IS_NON_DELEGATED=1<<1;var IS_CAPTURE_PHASE=1<<2;// set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
// we call willDeferLaterForLegacyFBSupport, thus not bailing out
// will result in endless cycles like an infinite loop.
// We also don't want to defer during event replaying.
var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS=IS_EVENT_HANDLE_NON_MANAGED_NODE|IS_NON_DELEGATED|IS_CAPTURE_PHASE;// This exists to avoid circular dependency between ReactDOMEventReplaying
// and DOMPluginEventSystem.
var currentReplayingEvent=null;function setReplayingEvent(event){{if(currentReplayingEvent!==null){error('Expected currently replaying event to be null. This error '+'is likely caused by a bug in React. Please file an issue.');}}currentReplayingEvent=event;}function resetReplayingEvent(){{if(currentReplayingEvent===null){error('Expected currently replaying event to not be null. This error '+'is likely caused by a bug in React. Please file an issue.');}}currentReplayingEvent=null;}function isReplayingEvent(event){return event===currentReplayingEvent;}/**
 * Gets the target node from a native browser event by accounting for
 * inconsistencies in browser DOM APIs.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {DOMEventTarget} Target node.
 */function getEventTarget(nativeEvent){// Fallback to nativeEvent.srcElement for IE9
// https://github.com/facebook/react/issues/12506
var target=nativeEvent.target||nativeEvent.srcElement||window;// Normalize SVG <use> element events #4963
if(target.correspondingUseElement){target=target.correspondingUseElement;}// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType===TEXT_NODE?target.parentNode:target;}var restoreImpl=null;var restoreTarget=null;var restoreQueue=null;function restoreStateOfTarget(target){// We perform this translation at the end of the event loop so that we
// always receive the correct fiber here
var internalInstance=getInstanceFromNode(target);if(!internalInstance){// Unmounted
return;}if(typeof restoreImpl!=='function'){throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled '+'events. This error is likely caused by a bug in React. Please file an issue.');}var stateNode=internalInstance.stateNode;// Guard against Fiber being unmounted.
if(stateNode){var _props=getFiberCurrentPropsFromNode(stateNode);restoreImpl(internalInstance.stateNode,internalInstance.type,_props);}}function setRestoreImplementation(impl){restoreImpl=impl;}function enqueueStateRestore(target){if(restoreTarget){if(restoreQueue){restoreQueue.push(target);}else {restoreQueue=[target];}}else {restoreTarget=target;}}function needsStateRestore(){return restoreTarget!==null||restoreQueue!==null;}function restoreStateIfNeeded(){if(!restoreTarget){return;}var target=restoreTarget;var queuedTargets=restoreQueue;restoreTarget=null;restoreQueue=null;restoreStateOfTarget(target);if(queuedTargets){for(var i=0;i<queuedTargets.length;i++){restoreStateOfTarget(queuedTargets[i]);}}}// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.
// Defaults
var batchedUpdatesImpl=function(fn,bookkeeping){return fn(bookkeeping);};var flushSyncImpl=function(){};var isInsideEventHandler=false;function finishEventHandler(){// Here we wait until all updates have propagated, which is important
// when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
// Then we restore state of any controlled component.
var controlledComponentsHavePendingUpdates=needsStateRestore();if(controlledComponentsHavePendingUpdates){// If a controlled event was fired, we may need to restore the state of
// the DOM node back to the controlled value. This is necessary when React
// bails out of the update without touching the DOM.
// TODO: Restore state in the microtask, after the discrete updates flush,
// instead of early flushing them here.
flushSyncImpl();restoreStateIfNeeded();}}function batchedUpdates(fn,a,b){if(isInsideEventHandler){// If we are currently inside another batch, we need to wait until it
// fully completes before restoring state.
return fn(a,b);}isInsideEventHandler=true;try{return batchedUpdatesImpl(fn,a,b);}finally{isInsideEventHandler=false;finishEventHandler();}}// TODO: Replace with flushSync
function setBatchingImplementation(_batchedUpdatesImpl,_discreteUpdatesImpl,_flushSyncImpl){batchedUpdatesImpl=_batchedUpdatesImpl;flushSyncImpl=_flushSyncImpl;}function isInteractive(tag){return tag==='button'||tag==='input'||tag==='select'||tag==='textarea';}function shouldPreventMouseEvent(name,type,props){switch(name){case'onClick':case'onClickCapture':case'onDoubleClick':case'onDoubleClickCapture':case'onMouseDown':case'onMouseDownCapture':case'onMouseMove':case'onMouseMoveCapture':case'onMouseUp':case'onMouseUpCapture':case'onMouseEnter':return !!(props.disabled&&isInteractive(type));default:return false;}}/**
 * @param {object} inst The instance, which is the source of events.
 * @param {string} registrationName Name of listener (e.g. `onClick`).
 * @return {?function} The stored callback.
 */function getListener(inst,registrationName){var stateNode=inst.stateNode;if(stateNode===null){// Work in progress (ex: onload events in incremental mode).
return null;}var props=getFiberCurrentPropsFromNode(stateNode);if(props===null){// Work in progress.
return null;}var listener=props[registrationName];if(shouldPreventMouseEvent(registrationName,inst.type,props)){return null;}if(listener&&typeof listener!=='function'){throw new Error("Expected `"+registrationName+"` listener to be a function, instead got a value of `"+typeof listener+"` type.");}return listener;}var passiveBrowserEventsSupported=false;// Check if browser support events with passive listeners
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
if(canUseDOM){try{var options={};// $FlowFixMe: Ignore Flow complaining about needing a value
Object.defineProperty(options,'passive',{get:function(){passiveBrowserEventsSupported=true;}});window.addEventListener('test',options,options);window.removeEventListener('test',options,options);}catch(e){passiveBrowserEventsSupported=false;}}function invokeGuardedCallbackProd(name,func,context,a,b,c,d,e,f){var funcArgs=Array.prototype.slice.call(arguments,3);try{func.apply(context,funcArgs);}catch(error){this.onError(error);}}var invokeGuardedCallbackImpl=invokeGuardedCallbackProd;{// In DEV mode, we swap out invokeGuardedCallback for a special version
// that plays more nicely with the browser's DevTools. The idea is to preserve
// "Pause on exceptions" behavior. Because React wraps all user-provided
// functions in invokeGuardedCallback, and the production version of
// invokeGuardedCallback uses a try-catch, all user exceptions are treated
// like caught exceptions, and the DevTools won't pause unless the developer
// takes the extra step of enabling pause on caught exceptions. This is
// unintuitive, though, because even though React has caught the error, from
// the developer's perspective, the error is uncaught.
//
// To preserve the expected "Pause on exceptions" behavior, we don't use a
// try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
// DOM node, and call the user-provided callback from inside an event handler
// for that fake event. If the callback throws, the error is "captured" using
// a global event handler. But because the error happens in a different
// event loop context, it does not interrupt the normal program flow.
// Effectively, this gives us try-catch behavior without actually using
// try-catch. Neat!
// Check that the browser supports the APIs we need to implement our special
// DEV version of invokeGuardedCallback
if(typeof window!=='undefined'&&typeof window.dispatchEvent==='function'&&typeof document!=='undefined'&&typeof document.createEvent==='function'){var fakeNode=document.createElement('react');invokeGuardedCallbackImpl=function invokeGuardedCallbackDev(name,func,context,a,b,c,d,e,f){// If document doesn't exist we know for sure we will crash in this method
// when we call document.createEvent(). However this can cause confusing
// errors: https://github.com/facebook/create-react-app/issues/3482
// So we preemptively throw with a better message instead.
if(typeof document==='undefined'||document===null){throw new Error('The `document` global was defined when React was initialized, but is not '+'defined anymore. This can happen in a test environment if a component '+'schedules an update from an asynchronous callback, but the test has already '+'finished running. To solve this, you can either unmount the component at '+'the end of your test (and ensure that any asynchronous operations get '+'canceled in `componentWillUnmount`), or you can change the test itself '+'to be asynchronous.');}var evt=document.createEvent('Event');var didCall=false;// Keeps track of whether the user-provided callback threw an error. We
// set this to true at the beginning, then set it to false right after
// calling the function. If the function errors, `didError` will never be
// set to false. This strategy works even if the browser is flaky and
// fails to call our global error handler, because it doesn't rely on
// the error event at all.
var didError=true;// Keeps track of the value of window.event so that we can reset it
// during the callback to let user code access window.event in the
// browsers that support it.
var windowEvent=window.event;// Keeps track of the descriptor of window.event to restore it after event
// dispatching: https://github.com/facebook/react/issues/13688
var windowEventDescriptor=Object.getOwnPropertyDescriptor(window,'event');function restoreAfterDispatch(){// We immediately remove the callback from event listeners so that
// nested `invokeGuardedCallback` calls do not clash. Otherwise, a
// nested call would trigger the fake event handlers of any call higher
// in the stack.
fakeNode.removeEventListener(evtType,callCallback,false);// We check for window.hasOwnProperty('event') to prevent the
// window.event assignment in both IE <= 10 as they throw an error
// "Member not found" in strict mode, and in Firefox which does not
// support window.event.
if(typeof window.event!=='undefined'&&window.hasOwnProperty('event')){window.event=windowEvent;}}// Create an event handler for our fake event. We will synchronously
// dispatch our fake event using `dispatchEvent`. Inside the handler, we
// call the user-provided callback.
var funcArgs=Array.prototype.slice.call(arguments,3);function callCallback(){didCall=true;restoreAfterDispatch();func.apply(context,funcArgs);didError=false;}// Create a global error event handler. We use this to capture the value
// that was thrown. It's possible that this error handler will fire more
// than once; for example, if non-React code also calls `dispatchEvent`
// and a handler for that event throws. We should be resilient to most of
// those cases. Even if our error event handler fires more than once, the
// last error event is always used. If the callback actually does error,
// we know that the last error event is the correct one, because it's not
// possible for anything else to have happened in between our callback
// erroring and the code that follows the `dispatchEvent` call below. If
// the callback doesn't error, but the error event was fired, we know to
// ignore it because `didError` will be false, as described above.
var error;// Use this to track whether the error event is ever called.
var didSetError=false;var isCrossOriginError=false;function handleWindowError(event){error=event.error;didSetError=true;if(error===null&&event.colno===0&&event.lineno===0){isCrossOriginError=true;}if(event.defaultPrevented){// Some other error handler has prevented default.
// Browsers silence the error report if this happens.
// We'll remember this to later decide whether to log it or not.
if(error!=null&&typeof error==='object'){try{error._suppressLogging=true;}catch(inner){// Ignore.
}}}}// Create a fake event type.
var evtType="react-"+(name?name:'invokeguardedcallback');// Attach our event handlers
window.addEventListener('error',handleWindowError);fakeNode.addEventListener(evtType,callCallback,false);// Synchronously dispatch our fake event. If the user-provided function
// errors, it will trigger our global error handler.
evt.initEvent(evtType,false,false);fakeNode.dispatchEvent(evt);if(windowEventDescriptor){Object.defineProperty(window,'event',windowEventDescriptor);}if(didCall&&didError){if(!didSetError){// The callback errored, but the error event never fired.
// eslint-disable-next-line react-internal/prod-error-codes
error=new Error('An error was thrown inside one of your components, but React '+"doesn't know what it was. This is likely due to browser "+'flakiness. React does its best to preserve the "Pause on '+'exceptions" behavior of the DevTools, which requires some '+"DEV-mode only tricks. It's possible that these don't work in "+'your browser. Try triggering the error in production mode, '+'or switching to a modern browser. If you suspect that this is '+'actually an issue with React, please file an issue.');}else if(isCrossOriginError){// eslint-disable-next-line react-internal/prod-error-codes
error=new Error("A cross-origin error was thrown. React doesn't have access to "+'the actual error object in development. '+'See https://reactjs.org/link/crossorigin-error for more information.');}this.onError(error);}// Remove our event listeners
window.removeEventListener('error',handleWindowError);if(!didCall){// Something went really wrong, and our event was not dispatched.
// https://github.com/facebook/react/issues/16734
// https://github.com/facebook/react/issues/16585
// Fall back to the production implementation.
restoreAfterDispatch();return invokeGuardedCallbackProd.apply(this,arguments);}};}}var invokeGuardedCallbackImpl$1=invokeGuardedCallbackImpl;var hasError=false;var caughtError=null;// Used by event system to capture/rethrow the first error.
var hasRethrowError=false;var rethrowError=null;var reporter={onError:function(error){hasError=true;caughtError=error;}};/**
 * Call a function while guarding against errors that happens within it.
 * Returns an error if it throws, otherwise null.
 *
 * In production, this is implemented using a try-catch. The reason we don't
 * use a try-catch directly is so that we can swap out a different
 * implementation in DEV mode.
 *
 * @param {String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} context The context to use when calling the function
 * @param {...*} args Arguments for function
 */function invokeGuardedCallback(name,func,context,a,b,c,d,e,f){hasError=false;caughtError=null;invokeGuardedCallbackImpl$1.apply(reporter,arguments);}/**
 * Same as invokeGuardedCallback, but instead of returning an error, it stores
 * it in a global so it can be rethrown by `rethrowCaughtError` later.
 * TODO: See if caughtError and rethrowError can be unified.
 *
 * @param {String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} context The context to use when calling the function
 * @param {...*} args Arguments for function
 */function invokeGuardedCallbackAndCatchFirstError(name,func,context,a,b,c,d,e,f){invokeGuardedCallback.apply(this,arguments);if(hasError){var error=clearCaughtError();if(!hasRethrowError){hasRethrowError=true;rethrowError=error;}}}/**
 * During execution of guarded functions we will capture the first error which
 * we will rethrow to be handled by the top level error handler.
 */function rethrowCaughtError(){if(hasRethrowError){var error=rethrowError;hasRethrowError=false;rethrowError=null;throw error;}}function hasCaughtError(){return hasError;}function clearCaughtError(){if(hasError){var error=caughtError;hasError=false;caughtError=null;return error;}else {throw new Error('clearCaughtError was called but no error was captured. This error '+'is likely caused by a bug in React. Please file an issue.');}}/**
 * `ReactInstanceMap` maintains a mapping from a public facing stateful
 * instance (key) and the internal representation (value). This allows public
 * methods to accept the user facing instance as an argument and map them back
 * to internal methods.
 *
 * Note that this module is currently shared and assumed to be stateless.
 * If this becomes an actual Map, that will break.
 */function get(key){return key._reactInternals;}function has(key){return key._reactInternals!==undefined;}function set(key,value){key._reactInternals=value;}// Don't change these two values. They're used by React Dev Tools.
var NoFlags=/*                      */0;var PerformedWork=/*                */1;// You can change the rest (and add more).
var Placement=/*                    */2;var Update=/*                       */4;var ChildDeletion=/*                */16;var ContentReset=/*                 */32;var Callback=/*                     */64;var DidCapture=/*                   */128;var ForceClientRender=/*            */256;var Ref=/*                          */512;var Snapshot=/*                     */1024;var Passive=/*                      */2048;var Hydrating=/*                    */4096;var Visibility=/*                   */8192;var StoreConsistency=/*             */16384;var LifecycleEffectMask=Passive|Update|Callback|Ref|Snapshot|StoreConsistency;// Union of all commit flags (flags with the lifetime of a particular commit)
var HostEffectMask=/*               */32767;// These are not really side effects, but we still reuse this field.
var Incomplete=/*                   */32768;var ShouldCapture=/*                */65536;var ForceUpdateForLegacySuspense=/* */131072;var Forked=/*                       */1048576;// Static tags describe aspects of a fiber that are not specific to a render,
// e.g. a fiber uses a passive effect (even if there are no updates on this particular render).
// This enables us to defer more work in the unmount case,
// since we can defer traversing the tree during layout to look for Passive effects,
// and instead rely on the static flag as a signal that there may be cleanup work.
var RefStatic=/*                    */2097152;var LayoutStatic=/*                 */4194304;var PassiveStatic=/*                */8388608;// These flags allow us to traverse to fibers that have effects on mount
// without traversing the entire tree after every commit for
// double invoking
var MountLayoutDev=/*               */16777216;var MountPassiveDev=/*              */33554432;// Groups of flags that are used in the commit phase to skip over trees that
// don't contain effects, by checking subtreeFlags.
var BeforeMutationMask=// TODO: Remove Update flag from before mutation phase by re-landing Visibility
// flag logic (see #20043)
Update|Snapshot|0;var MutationMask=Placement|Update|ChildDeletion|ContentReset|Ref|Hydrating|Visibility;var LayoutMask=Update|Callback|Ref|Visibility;// TODO: Split into PassiveMountMask and PassiveUnmountMask
var PassiveMask=Passive|ChildDeletion;// Union of tags that don't get reset on clones.
// This allows certain concepts to persist without recalculating them,
// e.g. whether a subtree contains passive effects or portals.
var StaticMask=LayoutStatic|PassiveStatic|RefStatic;var ReactCurrentOwner=ReactSharedInternals.ReactCurrentOwner;function getNearestMountedFiber(fiber){var node=fiber;var nearestMounted=fiber;if(!fiber.alternate){// If there is no alternate, this might be a new tree that isn't inserted
// yet. If it is, then it will have a pending insertion effect on it.
var nextNode=node;do{node=nextNode;if((node.flags&(Placement|Hydrating))!==NoFlags){// This is an insertion or in-progress hydration. The nearest possible
// mounted fiber is the parent but we need to continue to figure out
// if that one is still mounted.
nearestMounted=node.return;}nextNode=node.return;}while(nextNode);}else {while(node.return){node=node.return;}}if(node.tag===HostRoot){// TODO: Check if this was a nested HostRoot when used with
// renderContainerIntoSubtree.
return nearestMounted;}// If we didn't hit the root, that means that we're in an disconnected tree
// that has been unmounted.
return null;}function getSuspenseInstanceFromFiber(fiber){if(fiber.tag===SuspenseComponent){var suspenseState=fiber.memoizedState;if(suspenseState===null){var current=fiber.alternate;if(current!==null){suspenseState=current.memoizedState;}}if(suspenseState!==null){return suspenseState.dehydrated;}}return null;}function getContainerFromFiber(fiber){return fiber.tag===HostRoot?fiber.stateNode.containerInfo:null;}function isFiberMounted(fiber){return getNearestMountedFiber(fiber)===fiber;}function isMounted(component){{var owner=ReactCurrentOwner.current;if(owner!==null&&owner.tag===ClassComponent){var ownerFiber=owner;var instance=ownerFiber.stateNode;if(!instance._warnedAboutRefsInRender){error('%s is accessing isMounted inside its render() function. '+'render() should be a pure function of props and state. It should '+'never access something that requires stale data from the previous '+'render, such as refs. Move this logic to componentDidMount and '+'componentDidUpdate instead.',getComponentNameFromFiber(ownerFiber)||'A component');}instance._warnedAboutRefsInRender=true;}}var fiber=get(component);if(!fiber){return false;}return getNearestMountedFiber(fiber)===fiber;}function assertIsMounted(fiber){if(getNearestMountedFiber(fiber)!==fiber){throw new Error('Unable to find node on an unmounted component.');}}function findCurrentFiberUsingSlowPath(fiber){var alternate=fiber.alternate;if(!alternate){// If there is no alternate, then we only need to check if it is mounted.
var nearestMounted=getNearestMountedFiber(fiber);if(nearestMounted===null){throw new Error('Unable to find node on an unmounted component.');}if(nearestMounted!==fiber){return null;}return fiber;}// If we have two possible branches, we'll walk backwards up to the root
// to see what path the root points to. On the way we may hit one of the
// special cases and we'll deal with them.
var a=fiber;var b=alternate;while(true){var parentA=a.return;if(parentA===null){// We're at the root.
break;}var parentB=parentA.alternate;if(parentB===null){// There is no alternate. This is an unusual case. Currently, it only
// happens when a Suspense component is hidden. An extra fragment fiber
// is inserted in between the Suspense fiber and its children. Skip
// over this extra fragment fiber and proceed to the next parent.
var nextParent=parentA.return;if(nextParent!==null){a=b=nextParent;continue;}// If there's no parent, we're at the root.
break;}// If both copies of the parent fiber point to the same child, we can
// assume that the child is current. This happens when we bailout on low
// priority: the bailed out fiber's child reuses the current child.
if(parentA.child===parentB.child){var child=parentA.child;while(child){if(child===a){// We've determined that A is the current branch.
assertIsMounted(parentA);return fiber;}if(child===b){// We've determined that B is the current branch.
assertIsMounted(parentA);return alternate;}child=child.sibling;}// We should never have an alternate for any mounting node. So the only
// way this could possibly happen is if this was unmounted, if at all.
throw new Error('Unable to find node on an unmounted component.');}if(a.return!==b.return){// The return pointer of A and the return pointer of B point to different
// fibers. We assume that return pointers never criss-cross, so A must
// belong to the child set of A.return, and B must belong to the child
// set of B.return.
a=parentA;b=parentB;}else {// The return pointers point to the same fiber. We'll have to use the
// default, slow path: scan the child sets of each parent alternate to see
// which child belongs to which set.
//
// Search parent A's child set
var didFindChild=false;var _child=parentA.child;while(_child){if(_child===a){didFindChild=true;a=parentA;b=parentB;break;}if(_child===b){didFindChild=true;b=parentA;a=parentB;break;}_child=_child.sibling;}if(!didFindChild){// Search parent B's child set
_child=parentB.child;while(_child){if(_child===a){didFindChild=true;a=parentB;b=parentA;break;}if(_child===b){didFindChild=true;b=parentB;a=parentA;break;}_child=_child.sibling;}if(!didFindChild){throw new Error('Child was not found in either parent set. This indicates a bug '+'in React related to the return pointer. Please file an issue.');}}}if(a.alternate!==b){throw new Error("Return fibers should always be each others' alternates. "+'This error is likely caused by a bug in React. Please file an issue.');}}// If the root is not a host container, we're in a disconnected tree. I.e.
// unmounted.
if(a.tag!==HostRoot){throw new Error('Unable to find node on an unmounted component.');}if(a.stateNode.current===a){// We've determined that A is the current branch.
return fiber;}// Otherwise B has to be current branch.
return alternate;}function findCurrentHostFiber(parent){var currentParent=findCurrentFiberUsingSlowPath(parent);return currentParent!==null?findCurrentHostFiberImpl(currentParent):null;}function findCurrentHostFiberImpl(node){// Next we'll drill down this component to find the first HostComponent/Text.
if(node.tag===HostComponent||node.tag===HostText){return node;}var child=node.child;while(child!==null){var match=findCurrentHostFiberImpl(child);if(match!==null){return match;}child=child.sibling;}return null;}function findCurrentHostFiberWithNoPortals(parent){var currentParent=findCurrentFiberUsingSlowPath(parent);return currentParent!==null?findCurrentHostFiberWithNoPortalsImpl(currentParent):null;}function findCurrentHostFiberWithNoPortalsImpl(node){// Next we'll drill down this component to find the first HostComponent/Text.
if(node.tag===HostComponent||node.tag===HostText){return node;}var child=node.child;while(child!==null){if(child.tag!==HostPortal){var match=findCurrentHostFiberWithNoPortalsImpl(child);if(match!==null){return match;}}child=child.sibling;}return null;}// This module only exists as an ESM wrapper around the external CommonJS
var scheduleCallback=Scheduler.unstable_scheduleCallback;var cancelCallback=Scheduler.unstable_cancelCallback;var shouldYield=Scheduler.unstable_shouldYield;var requestPaint=Scheduler.unstable_requestPaint;var now=Scheduler.unstable_now;var getCurrentPriorityLevel=Scheduler.unstable_getCurrentPriorityLevel;var ImmediatePriority=Scheduler.unstable_ImmediatePriority;var UserBlockingPriority=Scheduler.unstable_UserBlockingPriority;var NormalPriority=Scheduler.unstable_NormalPriority;var LowPriority=Scheduler.unstable_LowPriority;var IdlePriority=Scheduler.unstable_IdlePriority;// this doesn't actually exist on the scheduler, but it *does*
// on scheduler/unstable_mock, which we'll need for internal testing
var unstable_yieldValue=Scheduler.unstable_yieldValue;var unstable_setDisableYieldValue=Scheduler.unstable_setDisableYieldValue;var rendererID=null;var injectedHook=null;var injectedProfilingHooks=null;var hasLoggedError=false;var isDevToolsPresent=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!=='undefined';function injectInternals(internals){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__==='undefined'){// No DevTools
return false;}var hook=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(hook.isDisabled){// This isn't a real property on the hook, but it can be set to opt out
// of DevTools integration and associated warnings and logs.
// https://github.com/facebook/react/issues/3877
return true;}if(!hook.supportsFiber){{error('The installed version of React DevTools is too old and will not work '+'with the current version of React. Please update React DevTools. '+'https://reactjs.org/link/react-devtools');}// DevTools exists, even though it doesn't support Fiber.
return true;}try{if(enableSchedulingProfiler){// Conditionally inject these hooks only if Timeline profiler is supported by this build.
// This gives DevTools a way to feature detect that isn't tied to version number
// (since profiling and timeline are controlled by different feature flags).
internals=assign({},internals,{getLaneLabelMap:getLaneLabelMap,injectProfilingHooks:injectProfilingHooks});}rendererID=hook.inject(internals);// We have successfully injected, so now it is safe to set up hooks.
injectedHook=hook;}catch(err){// Catch all errors because it is unsafe to throw during initialization.
{error('React instrumentation encountered an error: %s.',err);}}if(hook.checkDCE){// This is the real DevTools.
return true;}else {// This is likely a hook installed by Fast Refresh runtime.
return false;}}function onScheduleRoot(root,children){{if(injectedHook&&typeof injectedHook.onScheduleFiberRoot==='function'){try{injectedHook.onScheduleFiberRoot(rendererID,root,children);}catch(err){if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}function onCommitRoot(root,eventPriority){if(injectedHook&&typeof injectedHook.onCommitFiberRoot==='function'){try{var didError=(root.current.flags&DidCapture)===DidCapture;if(enableProfilerTimer){var schedulerPriority;switch(eventPriority){case DiscreteEventPriority:schedulerPriority=ImmediatePriority;break;case ContinuousEventPriority:schedulerPriority=UserBlockingPriority;break;case DefaultEventPriority:schedulerPriority=NormalPriority;break;case IdleEventPriority:schedulerPriority=IdlePriority;break;default:schedulerPriority=NormalPriority;break;}injectedHook.onCommitFiberRoot(rendererID,root,schedulerPriority,didError);}}catch(err){{if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}function onPostCommitRoot(root){if(injectedHook&&typeof injectedHook.onPostCommitFiberRoot==='function'){try{injectedHook.onPostCommitFiberRoot(rendererID,root);}catch(err){{if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}function onCommitUnmount(fiber){if(injectedHook&&typeof injectedHook.onCommitFiberUnmount==='function'){try{injectedHook.onCommitFiberUnmount(rendererID,fiber);}catch(err){{if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}function setIsStrictModeForDevtools(newIsStrictMode){{if(typeof unstable_yieldValue==='function'){// We're in a test because Scheduler.unstable_yieldValue only exists
// in SchedulerMock. To reduce the noise in strict mode tests,
// suppress warnings and disable scheduler yielding during the double render
unstable_setDisableYieldValue(newIsStrictMode);setSuppressWarning(newIsStrictMode);}if(injectedHook&&typeof injectedHook.setStrictMode==='function'){try{injectedHook.setStrictMode(rendererID,newIsStrictMode);}catch(err){{if(!hasLoggedError){hasLoggedError=true;error('React instrumentation encountered an error: %s',err);}}}}}}// Profiler API hooks
function injectProfilingHooks(profilingHooks){injectedProfilingHooks=profilingHooks;}function getLaneLabelMap(){{var map=new Map();var lane=1;for(var index=0;index<TotalLanes;index++){var label=getLabelForLane(lane);map.set(lane,label);lane*=2;}return map;}}function markCommitStarted(lanes){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markCommitStarted==='function'){injectedProfilingHooks.markCommitStarted(lanes);}}}function markCommitStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markCommitStopped==='function'){injectedProfilingHooks.markCommitStopped();}}}function markComponentRenderStarted(fiber){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentRenderStarted==='function'){injectedProfilingHooks.markComponentRenderStarted(fiber);}}}function markComponentRenderStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentRenderStopped==='function'){injectedProfilingHooks.markComponentRenderStopped();}}}function markComponentPassiveEffectMountStarted(fiber){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted==='function'){injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);}}}function markComponentPassiveEffectMountStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped==='function'){injectedProfilingHooks.markComponentPassiveEffectMountStopped();}}}function markComponentPassiveEffectUnmountStarted(fiber){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted==='function'){injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);}}}function markComponentPassiveEffectUnmountStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped==='function'){injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();}}}function markComponentLayoutEffectMountStarted(fiber){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted==='function'){injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);}}}function markComponentLayoutEffectMountStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped==='function'){injectedProfilingHooks.markComponentLayoutEffectMountStopped();}}}function markComponentLayoutEffectUnmountStarted(fiber){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted==='function'){injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);}}}function markComponentLayoutEffectUnmountStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped==='function'){injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();}}}function markComponentErrored(fiber,thrownValue,lanes){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentErrored==='function'){injectedProfilingHooks.markComponentErrored(fiber,thrownValue,lanes);}}}function markComponentSuspended(fiber,wakeable,lanes){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markComponentSuspended==='function'){injectedProfilingHooks.markComponentSuspended(fiber,wakeable,lanes);}}}function markLayoutEffectsStarted(lanes){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markLayoutEffectsStarted==='function'){injectedProfilingHooks.markLayoutEffectsStarted(lanes);}}}function markLayoutEffectsStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markLayoutEffectsStopped==='function'){injectedProfilingHooks.markLayoutEffectsStopped();}}}function markPassiveEffectsStarted(lanes){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markPassiveEffectsStarted==='function'){injectedProfilingHooks.markPassiveEffectsStarted(lanes);}}}function markPassiveEffectsStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markPassiveEffectsStopped==='function'){injectedProfilingHooks.markPassiveEffectsStopped();}}}function markRenderStarted(lanes){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markRenderStarted==='function'){injectedProfilingHooks.markRenderStarted(lanes);}}}function markRenderYielded(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markRenderYielded==='function'){injectedProfilingHooks.markRenderYielded();}}}function markRenderStopped(){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markRenderStopped==='function'){injectedProfilingHooks.markRenderStopped();}}}function markRenderScheduled(lane){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markRenderScheduled==='function'){injectedProfilingHooks.markRenderScheduled(lane);}}}function markForceUpdateScheduled(fiber,lane){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markForceUpdateScheduled==='function'){injectedProfilingHooks.markForceUpdateScheduled(fiber,lane);}}}function markStateUpdateScheduled(fiber,lane){{if(injectedProfilingHooks!==null&&typeof injectedProfilingHooks.markStateUpdateScheduled==='function'){injectedProfilingHooks.markStateUpdateScheduled(fiber,lane);}}}var NoMode=/*                         */0;// TODO: Remove ConcurrentMode by reading from the root tag instead
var ConcurrentMode=/*                 */1;var ProfileMode=/*                    */2;var StrictLegacyMode=/*               */8;var StrictEffectsMode=/*              */16;// TODO: This is pretty well supported by browsers. Maybe we can drop it.
var clz32=Math.clz32?Math.clz32:clz32Fallback;// Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
var log=Math.log;var LN2=Math.LN2;function clz32Fallback(x){var asUint=x>>>0;if(asUint===0){return 32;}return 31-(log(asUint)/LN2|0)|0;}// If those values are changed that package should be rebuilt and redeployed.
var TotalLanes=31;var NoLanes=/*                        */0;var NoLane=/*                          */0;var SyncLane=/*                        */1;var InputContinuousHydrationLane=/*    */2;var InputContinuousLane=/*             */4;var DefaultHydrationLane=/*            */8;var DefaultLane=/*                     */16;var TransitionHydrationLane=/*                */32;var TransitionLanes=/*                       */4194240;var TransitionLane1=/*                        */64;var TransitionLane2=/*                        */128;var TransitionLane3=/*                        */256;var TransitionLane4=/*                        */512;var TransitionLane5=/*                        */1024;var TransitionLane6=/*                        */2048;var TransitionLane7=/*                        */4096;var TransitionLane8=/*                        */8192;var TransitionLane9=/*                        */16384;var TransitionLane10=/*                       */32768;var TransitionLane11=/*                       */65536;var TransitionLane12=/*                       */131072;var TransitionLane13=/*                       */262144;var TransitionLane14=/*                       */524288;var TransitionLane15=/*                       */1048576;var TransitionLane16=/*                       */2097152;var RetryLanes=/*                            */130023424;var RetryLane1=/*                             */4194304;var RetryLane2=/*                             */8388608;var RetryLane3=/*                             */16777216;var RetryLane4=/*                             */33554432;var RetryLane5=/*                             */67108864;var SomeRetryLane=RetryLane1;var SelectiveHydrationLane=/*          */134217728;var NonIdleLanes=/*                          */268435455;var IdleHydrationLane=/*               */268435456;var IdleLane=/*                        */536870912;var OffscreenLane=/*                   */1073741824;// This function is used for the experimental timeline (react-devtools-timeline)
// It should be kept in sync with the Lanes values above.
function getLabelForLane(lane){{if(lane&SyncLane){return 'Sync';}if(lane&InputContinuousHydrationLane){return 'InputContinuousHydration';}if(lane&InputContinuousLane){return 'InputContinuous';}if(lane&DefaultHydrationLane){return 'DefaultHydration';}if(lane&DefaultLane){return 'Default';}if(lane&TransitionHydrationLane){return 'TransitionHydration';}if(lane&TransitionLanes){return 'Transition';}if(lane&RetryLanes){return 'Retry';}if(lane&SelectiveHydrationLane){return 'SelectiveHydration';}if(lane&IdleHydrationLane){return 'IdleHydration';}if(lane&IdleLane){return 'Idle';}if(lane&OffscreenLane){return 'Offscreen';}}}var NoTimestamp=-1;var nextTransitionLane=TransitionLane1;var nextRetryLane=RetryLane1;function getHighestPriorityLanes(lanes){switch(getHighestPriorityLane(lanes)){case SyncLane:return SyncLane;case InputContinuousHydrationLane:return InputContinuousHydrationLane;case InputContinuousLane:return InputContinuousLane;case DefaultHydrationLane:return DefaultHydrationLane;case DefaultLane:return DefaultLane;case TransitionHydrationLane:return TransitionHydrationLane;case TransitionLane1:case TransitionLane2:case TransitionLane3:case TransitionLane4:case TransitionLane5:case TransitionLane6:case TransitionLane7:case TransitionLane8:case TransitionLane9:case TransitionLane10:case TransitionLane11:case TransitionLane12:case TransitionLane13:case TransitionLane14:case TransitionLane15:case TransitionLane16:return lanes&TransitionLanes;case RetryLane1:case RetryLane2:case RetryLane3:case RetryLane4:case RetryLane5:return lanes&RetryLanes;case SelectiveHydrationLane:return SelectiveHydrationLane;case IdleHydrationLane:return IdleHydrationLane;case IdleLane:return IdleLane;case OffscreenLane:return OffscreenLane;default:{error('Should have found matching lanes. This is a bug in React.');}// This shouldn't be reachable, but as a fallback, return the entire bitmask.
return lanes;}}function getNextLanes(root,wipLanes){// Early bailout if there's no pending work left.
var pendingLanes=root.pendingLanes;if(pendingLanes===NoLanes){return NoLanes;}var nextLanes=NoLanes;var suspendedLanes=root.suspendedLanes;var pingedLanes=root.pingedLanes;// Do not work on any idle work until all the non-idle work has finished,
// even if the work is suspended.
var nonIdlePendingLanes=pendingLanes&NonIdleLanes;if(nonIdlePendingLanes!==NoLanes){var nonIdleUnblockedLanes=nonIdlePendingLanes&~suspendedLanes;if(nonIdleUnblockedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(nonIdleUnblockedLanes);}else {var nonIdlePingedLanes=nonIdlePendingLanes&pingedLanes;if(nonIdlePingedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(nonIdlePingedLanes);}}}else {// The only remaining work is Idle.
var unblockedLanes=pendingLanes&~suspendedLanes;if(unblockedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(unblockedLanes);}else {if(pingedLanes!==NoLanes){nextLanes=getHighestPriorityLanes(pingedLanes);}}}if(nextLanes===NoLanes){// This should only be reachable if we're suspended
// TODO: Consider warning in this path if a fallback timer is not scheduled.
return NoLanes;}// If we're already in the middle of a render, switching lanes will interrupt
// it and we'll lose our progress. We should only do this if the new lanes are
// higher priority.
if(wipLanes!==NoLanes&&wipLanes!==nextLanes&&// If we already suspended with a delay, then interrupting is fine. Don't
// bother waiting until the root is complete.
(wipLanes&suspendedLanes)===NoLanes){var nextLane=getHighestPriorityLane(nextLanes);var wipLane=getHighestPriorityLane(wipLanes);if(// Tests whether the next lane is equal or lower priority than the wip
// one. This works because the bits decrease in priority as you go left.
nextLane>=wipLane||// Default priority updates should not interrupt transition updates. The
// only difference between default updates and transition updates is that
// default updates do not support refresh transitions.
nextLane===DefaultLane&&(wipLane&TransitionLanes)!==NoLanes){// Keep working on the existing in-progress tree. Do not interrupt.
return wipLanes;}}if((nextLanes&InputContinuousLane)!==NoLanes){// When updates are sync by default, we entangle continuous priority updates
// and default updates, so they render in the same batch. The only reason
// they use separate lanes is because continuous updates should interrupt
// transitions, but default updates should not.
nextLanes|=pendingLanes&DefaultLane;}// Check for entangled lanes and add them to the batch.
//
// A lane is said to be entangled with another when it's not allowed to render
// in a batch that does not also include the other lane. Typically we do this
// when multiple updates have the same source, and we only want to respond to
// the most recent event from that source.
//
// Note that we apply entanglements *after* checking for partial work above.
// This means that if a lane is entangled during an interleaved event while
// it's already rendering, we won't interrupt it. This is intentional, since
// entanglement is usually "best effort": we'll try our best to render the
// lanes in the same batch, but it's not worth throwing out partially
// completed work in order to do it.
// TODO: Reconsider this. The counter-argument is that the partial work
// represents an intermediate state, which we don't want to show to the user.
// And by spending extra time finishing it, we're increasing the amount of
// time it takes to show the final state, which is what they are actually
// waiting for.
//
// For those exceptions where entanglement is semantically important, like
// useMutableSource, we should ensure that there is no partial work at the
// time we apply the entanglement.
var entangledLanes=root.entangledLanes;if(entangledLanes!==NoLanes){var entanglements=root.entanglements;var lanes=nextLanes&entangledLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;nextLanes|=entanglements[index];lanes&=~lane;}}return nextLanes;}function getMostRecentEventTime(root,lanes){var eventTimes=root.eventTimes;var mostRecentEventTime=NoTimestamp;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;var eventTime=eventTimes[index];if(eventTime>mostRecentEventTime){mostRecentEventTime=eventTime;}lanes&=~lane;}return mostRecentEventTime;}function computeExpirationTime(lane,currentTime){switch(lane){case SyncLane:case InputContinuousHydrationLane:case InputContinuousLane:// User interactions should expire slightly more quickly.
//
// NOTE: This is set to the corresponding constant as in Scheduler.js.
// When we made it larger, a product metric in www regressed, suggesting
// there's a user interaction that's being starved by a series of
// synchronous updates. If that theory is correct, the proper solution is
// to fix the starvation. However, this scenario supports the idea that
// expiration times are an important safeguard when starvation
// does happen.
return currentTime+250;case DefaultHydrationLane:case DefaultLane:case TransitionHydrationLane:case TransitionLane1:case TransitionLane2:case TransitionLane3:case TransitionLane4:case TransitionLane5:case TransitionLane6:case TransitionLane7:case TransitionLane8:case TransitionLane9:case TransitionLane10:case TransitionLane11:case TransitionLane12:case TransitionLane13:case TransitionLane14:case TransitionLane15:case TransitionLane16:return currentTime+5000;case RetryLane1:case RetryLane2:case RetryLane3:case RetryLane4:case RetryLane5:// TODO: Retries should be allowed to expire if they are CPU bound for
// too long, but when I made this change it caused a spike in browser
// crashes. There must be some other underlying bug; not super urgent but
// ideally should figure out why and fix it. Unfortunately we don't have
// a repro for the crashes, only detected via production metrics.
return NoTimestamp;case SelectiveHydrationLane:case IdleHydrationLane:case IdleLane:case OffscreenLane:// Anything idle priority or lower should never expire.
return NoTimestamp;default:{error('Should have found matching lanes. This is a bug in React.');}return NoTimestamp;}}function markStarvedLanesAsExpired(root,currentTime){// TODO: This gets called every time we yield. We can optimize by storing
// the earliest expiration time on the root. Then use that to quickly bail out
// of this function.
var pendingLanes=root.pendingLanes;var suspendedLanes=root.suspendedLanes;var pingedLanes=root.pingedLanes;var expirationTimes=root.expirationTimes;// Iterate through the pending lanes and check if we've reached their
// expiration time. If so, we'll assume the update is being starved and mark
// it as expired to force it to finish.
var lanes=pendingLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;var expirationTime=expirationTimes[index];if(expirationTime===NoTimestamp){// Found a pending lane with no expiration time. If it's not suspended, or
// if it's pinged, assume it's CPU-bound. Compute a new expiration time
// using the current time.
if((lane&suspendedLanes)===NoLanes||(lane&pingedLanes)!==NoLanes){// Assumes timestamps are monotonically increasing.
expirationTimes[index]=computeExpirationTime(lane,currentTime);}}else if(expirationTime<=currentTime){// This lane expired
root.expiredLanes|=lane;}lanes&=~lane;}}// This returns the highest priority pending lanes regardless of whether they
// are suspended.
function getHighestPriorityPendingLanes(root){return getHighestPriorityLanes(root.pendingLanes);}function getLanesToRetrySynchronouslyOnError(root){var everythingButOffscreen=root.pendingLanes&~OffscreenLane;if(everythingButOffscreen!==NoLanes){return everythingButOffscreen;}if(everythingButOffscreen&OffscreenLane){return OffscreenLane;}return NoLanes;}function includesSyncLane(lanes){return (lanes&SyncLane)!==NoLanes;}function includesNonIdleWork(lanes){return (lanes&NonIdleLanes)!==NoLanes;}function includesOnlyRetries(lanes){return (lanes&RetryLanes)===lanes;}function includesOnlyNonUrgentLanes(lanes){var UrgentLanes=SyncLane|InputContinuousLane|DefaultLane;return (lanes&UrgentLanes)===NoLanes;}function includesOnlyTransitions(lanes){return (lanes&TransitionLanes)===lanes;}function includesBlockingLane(root,lanes){var SyncDefaultLanes=InputContinuousHydrationLane|InputContinuousLane|DefaultHydrationLane|DefaultLane;return (lanes&SyncDefaultLanes)!==NoLanes;}function includesExpiredLane(root,lanes){// This is a separate check from includesBlockingLane because a lane can
// expire after a render has already started.
return (lanes&root.expiredLanes)!==NoLanes;}function isTransitionLane(lane){return (lane&TransitionLanes)!==NoLanes;}function claimNextTransitionLane(){// Cycle through the lanes, assigning each new transition to the next lane.
// In most cases, this means every transition gets its own lane, until we
// run out of lanes and cycle back to the beginning.
var lane=nextTransitionLane;nextTransitionLane<<=1;if((nextTransitionLane&TransitionLanes)===NoLanes){nextTransitionLane=TransitionLane1;}return lane;}function claimNextRetryLane(){var lane=nextRetryLane;nextRetryLane<<=1;if((nextRetryLane&RetryLanes)===NoLanes){nextRetryLane=RetryLane1;}return lane;}function getHighestPriorityLane(lanes){return lanes&-lanes;}function pickArbitraryLane(lanes){// This wrapper function gets inlined. Only exists so to communicate that it
// doesn't matter which bit is selected; you can pick any bit without
// affecting the algorithms where its used. Here I'm using
// getHighestPriorityLane because it requires the fewest operations.
return getHighestPriorityLane(lanes);}function pickArbitraryLaneIndex(lanes){return 31-clz32(lanes);}function laneToIndex(lane){return pickArbitraryLaneIndex(lane);}function includesSomeLane(a,b){return (a&b)!==NoLanes;}function isSubsetOfLanes(set,subset){return (set&subset)===subset;}function mergeLanes(a,b){return a|b;}function removeLanes(set,subset){return set&~subset;}function intersectLanes(a,b){return a&b;}// Seems redundant, but it changes the type from a single lane (used for
// updates) to a group of lanes (used for flushing work).
function laneToLanes(lane){return lane;}function higherPriorityLane(a,b){// This works because the bit ranges decrease in priority as you go left.
return a!==NoLane&&a<b?a:b;}function createLaneMap(initial){// Intentionally pushing one by one.
// https://v8.dev/blog/elements-kinds#avoid-creating-holes
var laneMap=[];for(var i=0;i<TotalLanes;i++){laneMap.push(initial);}return laneMap;}function markRootUpdated(root,updateLane,eventTime){root.pendingLanes|=updateLane;// If there are any suspended transitions, it's possible this new update
// could unblock them. Clear the suspended lanes so that we can try rendering
// them again.
//
// TODO: We really only need to unsuspend only lanes that are in the
// `subtreeLanes` of the updated fiber, or the update lanes of the return
// path. This would exclude suspended updates in an unrelated sibling tree,
// since there's no way for this update to unblock it.
//
// We don't do this if the incoming update is idle, because we never process
// idle updates until after all the regular updates have finished; there's no
// way it could unblock a transition.
if(updateLane!==IdleLane){root.suspendedLanes=NoLanes;root.pingedLanes=NoLanes;}var eventTimes=root.eventTimes;var index=laneToIndex(updateLane);// We can always overwrite an existing timestamp because we prefer the most
// recent event, and we assume time is monotonically increasing.
eventTimes[index]=eventTime;}function markRootSuspended(root,suspendedLanes){root.suspendedLanes|=suspendedLanes;root.pingedLanes&=~suspendedLanes;// The suspended lanes are no longer CPU-bound. Clear their expiration times.
var expirationTimes=root.expirationTimes;var lanes=suspendedLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;expirationTimes[index]=NoTimestamp;lanes&=~lane;}}function markRootPinged(root,pingedLanes,eventTime){root.pingedLanes|=root.suspendedLanes&pingedLanes;}function markRootFinished(root,remainingLanes){var noLongerPendingLanes=root.pendingLanes&~remainingLanes;root.pendingLanes=remainingLanes;// Let's try everything again
root.suspendedLanes=NoLanes;root.pingedLanes=NoLanes;root.expiredLanes&=remainingLanes;root.mutableReadLanes&=remainingLanes;root.entangledLanes&=remainingLanes;var entanglements=root.entanglements;var eventTimes=root.eventTimes;var expirationTimes=root.expirationTimes;// Clear the lanes that no longer have pending work
var lanes=noLongerPendingLanes;while(lanes>0){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;entanglements[index]=NoLanes;eventTimes[index]=NoTimestamp;expirationTimes[index]=NoTimestamp;lanes&=~lane;}}function markRootEntangled(root,entangledLanes){// In addition to entangling each of the given lanes with each other, we also
// have to consider _transitive_ entanglements. For each lane that is already
// entangled with *any* of the given lanes, that lane is now transitively
// entangled with *all* the given lanes.
//
// Translated: If C is entangled with A, then entangling A with B also
// entangles C with B.
//
// If this is hard to grasp, it might help to intentionally break this
// function and look at the tests that fail in ReactTransition-test.js. Try
// commenting out one of the conditions below.
var rootEntangledLanes=root.entangledLanes|=entangledLanes;var entanglements=root.entanglements;var lanes=rootEntangledLanes;while(lanes){var index=pickArbitraryLaneIndex(lanes);var lane=1<<index;if(// Is this one of the newly entangled lanes?
lane&entangledLanes|// Is this lane transitively entangled with the newly entangled lanes?
entanglements[index]&entangledLanes){entanglements[index]|=entangledLanes;}lanes&=~lane;}}function getBumpedLaneForHydration(root,renderLanes){var renderLane=getHighestPriorityLane(renderLanes);var lane;switch(renderLane){case InputContinuousLane:lane=InputContinuousHydrationLane;break;case DefaultLane:lane=DefaultHydrationLane;break;case TransitionLane1:case TransitionLane2:case TransitionLane3:case TransitionLane4:case TransitionLane5:case TransitionLane6:case TransitionLane7:case TransitionLane8:case TransitionLane9:case TransitionLane10:case TransitionLane11:case TransitionLane12:case TransitionLane13:case TransitionLane14:case TransitionLane15:case TransitionLane16:case RetryLane1:case RetryLane2:case RetryLane3:case RetryLane4:case RetryLane5:lane=TransitionHydrationLane;break;case IdleLane:lane=IdleHydrationLane;break;default:// Everything else is already either a hydration lane, or shouldn't
// be retried at a hydration lane.
lane=NoLane;break;}// Check if the lane we chose is suspended. If so, that indicates that we
// already attempted and failed to hydrate at that level. Also check if we're
// already rendering that lane, which is rare but could happen.
if((lane&(root.suspendedLanes|renderLanes))!==NoLane){// Give up trying to hydrate and fall back to client render.
return NoLane;}return lane;}function addFiberToLanesMap(root,fiber,lanes){if(!isDevToolsPresent){return;}var pendingUpdatersLaneMap=root.pendingUpdatersLaneMap;while(lanes>0){var index=laneToIndex(lanes);var lane=1<<index;var updaters=pendingUpdatersLaneMap[index];updaters.add(fiber);lanes&=~lane;}}function movePendingFibersToMemoized(root,lanes){if(!isDevToolsPresent){return;}var pendingUpdatersLaneMap=root.pendingUpdatersLaneMap;var memoizedUpdaters=root.memoizedUpdaters;while(lanes>0){var index=laneToIndex(lanes);var lane=1<<index;var updaters=pendingUpdatersLaneMap[index];if(updaters.size>0){updaters.forEach(function(fiber){var alternate=fiber.alternate;if(alternate===null||!memoizedUpdaters.has(alternate)){memoizedUpdaters.add(fiber);}});updaters.clear();}lanes&=~lane;}}function getTransitionsForLanes(root,lanes){{return null;}}var DiscreteEventPriority=SyncLane;var ContinuousEventPriority=InputContinuousLane;var DefaultEventPriority=DefaultLane;var IdleEventPriority=IdleLane;var currentUpdatePriority=NoLane;function getCurrentUpdatePriority(){return currentUpdatePriority;}function setCurrentUpdatePriority(newPriority){currentUpdatePriority=newPriority;}function runWithPriority(priority,fn){var previousPriority=currentUpdatePriority;try{currentUpdatePriority=priority;return fn();}finally{currentUpdatePriority=previousPriority;}}function higherEventPriority(a,b){return a!==0&&a<b?a:b;}function lowerEventPriority(a,b){return a===0||a>b?a:b;}function isHigherEventPriority(a,b){return a!==0&&a<b;}function lanesToEventPriority(lanes){var lane=getHighestPriorityLane(lanes);if(!isHigherEventPriority(DiscreteEventPriority,lane)){return DiscreteEventPriority;}if(!isHigherEventPriority(ContinuousEventPriority,lane)){return ContinuousEventPriority;}if(includesNonIdleWork(lane)){return DefaultEventPriority;}return IdleEventPriority;}// This is imported by the event replaying implementation in React DOM. It's
// in a separate file to break a circular dependency between the renderer and
// the reconciler.
function isRootDehydrated(root){var currentState=root.current.memoizedState;return currentState.isDehydrated;}var _attemptSynchronousHydration;function setAttemptSynchronousHydration(fn){_attemptSynchronousHydration=fn;}function attemptSynchronousHydration(fiber){_attemptSynchronousHydration(fiber);}var attemptContinuousHydration;function setAttemptContinuousHydration(fn){attemptContinuousHydration=fn;}var attemptHydrationAtCurrentPriority;function setAttemptHydrationAtCurrentPriority(fn){attemptHydrationAtCurrentPriority=fn;}var getCurrentUpdatePriority$1;function setGetCurrentUpdatePriority(fn){getCurrentUpdatePriority$1=fn;}var attemptHydrationAtPriority;function setAttemptHydrationAtPriority(fn){attemptHydrationAtPriority=fn;}// TODO: Upgrade this definition once we're on a newer version of Flow that
// has this definition built-in.
var hasScheduledReplayAttempt=false;// The queue of discrete events to be replayed.
var queuedDiscreteEvents=[];// Indicates if any continuous event targets are non-null for early bailout.
// if the last target was dehydrated.
var queuedFocus=null;var queuedDrag=null;var queuedMouse=null;// For pointer events there can be one latest event per pointerId.
var queuedPointers=new Map();var queuedPointerCaptures=new Map();// We could consider replaying selectionchange and touchmoves too.
var queuedExplicitHydrationTargets=[];var discreteReplayableEvents=['mousedown','mouseup','touchcancel','touchend','touchstart','auxclick','dblclick','pointercancel','pointerdown','pointerup','dragend','dragstart','drop','compositionend','compositionstart','keydown','keypress','keyup','input','textInput',// Intentionally camelCase
'copy','cut','paste','click','change','contextmenu','reset','submit'];function isDiscreteEventThatRequiresHydration(eventType){return discreteReplayableEvents.indexOf(eventType)>-1;}function createQueuedReplayableEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){return {blockedOn:blockedOn,domEventName:domEventName,eventSystemFlags:eventSystemFlags,nativeEvent:nativeEvent,targetContainers:[targetContainer]};}function clearIfContinuousEvent(domEventName,nativeEvent){switch(domEventName){case'focusin':case'focusout':queuedFocus=null;break;case'dragenter':case'dragleave':queuedDrag=null;break;case'mouseover':case'mouseout':queuedMouse=null;break;case'pointerover':case'pointerout':{var pointerId=nativeEvent.pointerId;queuedPointers.delete(pointerId);break;}case'gotpointercapture':case'lostpointercapture':{var _pointerId=nativeEvent.pointerId;queuedPointerCaptures.delete(_pointerId);break;}}}function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent,blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){if(existingQueuedEvent===null||existingQueuedEvent.nativeEvent!==nativeEvent){var queuedEvent=createQueuedReplayableEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent);if(blockedOn!==null){var _fiber2=getInstanceFromNode(blockedOn);if(_fiber2!==null){// Attempt to increase the priority of this target.
attemptContinuousHydration(_fiber2);}}return queuedEvent;}// If we have already queued this exact event, then it's because
// the different event systems have different DOM event listeners.
// We can accumulate the flags, and the targetContainers, and
// store a single event to be replayed.
existingQueuedEvent.eventSystemFlags|=eventSystemFlags;var targetContainers=existingQueuedEvent.targetContainers;if(targetContainer!==null&&targetContainers.indexOf(targetContainer)===-1){targetContainers.push(targetContainer);}return existingQueuedEvent;}function queueIfContinuousEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent){// These set relatedTarget to null because the replayed event will be treated as if we
// moved from outside the window (no target) onto the target once it hydrates.
// Instead of mutating we could clone the event.
switch(domEventName){case'focusin':{var focusEvent=nativeEvent;queuedFocus=accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus,blockedOn,domEventName,eventSystemFlags,targetContainer,focusEvent);return true;}case'dragenter':{var dragEvent=nativeEvent;queuedDrag=accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag,blockedOn,domEventName,eventSystemFlags,targetContainer,dragEvent);return true;}case'mouseover':{var mouseEvent=nativeEvent;queuedMouse=accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse,blockedOn,domEventName,eventSystemFlags,targetContainer,mouseEvent);return true;}case'pointerover':{var pointerEvent=nativeEvent;var pointerId=pointerEvent.pointerId;queuedPointers.set(pointerId,accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId)||null,blockedOn,domEventName,eventSystemFlags,targetContainer,pointerEvent));return true;}case'gotpointercapture':{var _pointerEvent=nativeEvent;var _pointerId2=_pointerEvent.pointerId;queuedPointerCaptures.set(_pointerId2,accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2)||null,blockedOn,domEventName,eventSystemFlags,targetContainer,_pointerEvent));return true;}}return false;}// Check if this target is unblocked. Returns true if it's unblocked.
function attemptExplicitHydrationTarget(queuedTarget){// TODO: This function shares a lot of logic with findInstanceBlockingEvent.
// Try to unify them. It's a bit tricky since it would require two return
// values.
var targetInst=getClosestInstanceFromNode(queuedTarget.target);if(targetInst!==null){var nearestMounted=getNearestMountedFiber(targetInst);if(nearestMounted!==null){var tag=nearestMounted.tag;if(tag===SuspenseComponent){var instance=getSuspenseInstanceFromFiber(nearestMounted);if(instance!==null){// We're blocked on hydrating this boundary.
// Increase its priority.
queuedTarget.blockedOn=instance;attemptHydrationAtPriority(queuedTarget.priority,function(){attemptHydrationAtCurrentPriority(nearestMounted);});return;}}else if(tag===HostRoot){var root=nearestMounted.stateNode;if(isRootDehydrated(root)){queuedTarget.blockedOn=getContainerFromFiber(nearestMounted);// We don't currently have a way to increase the priority of
// a root other than sync.
return;}}}}queuedTarget.blockedOn=null;}function queueExplicitHydrationTarget(target){// TODO: This will read the priority if it's dispatched by the React
// event system but not native events. Should read window.event.type, like
// we do for updates (getCurrentEventPriority).
var updatePriority=getCurrentUpdatePriority$1();var queuedTarget={blockedOn:null,target:target,priority:updatePriority};var i=0;for(;i<queuedExplicitHydrationTargets.length;i++){// Stop once we hit the first target with lower priority than
if(!isHigherEventPriority(updatePriority,queuedExplicitHydrationTargets[i].priority)){break;}}queuedExplicitHydrationTargets.splice(i,0,queuedTarget);if(i===0){attemptExplicitHydrationTarget(queuedTarget);}}function attemptReplayContinuousQueuedEvent(queuedEvent){if(queuedEvent.blockedOn!==null){return false;}var targetContainers=queuedEvent.targetContainers;while(targetContainers.length>0){var targetContainer=targetContainers[0];var nextBlockedOn=findInstanceBlockingEvent(queuedEvent.domEventName,queuedEvent.eventSystemFlags,targetContainer,queuedEvent.nativeEvent);if(nextBlockedOn===null){{var nativeEvent=queuedEvent.nativeEvent;var nativeEventClone=new nativeEvent.constructor(nativeEvent.type,nativeEvent);setReplayingEvent(nativeEventClone);nativeEvent.target.dispatchEvent(nativeEventClone);resetReplayingEvent();}}else {// We're still blocked. Try again later.
var _fiber3=getInstanceFromNode(nextBlockedOn);if(_fiber3!==null){attemptContinuousHydration(_fiber3);}queuedEvent.blockedOn=nextBlockedOn;return false;}// This target container was successfully dispatched. Try the next.
targetContainers.shift();}return true;}function attemptReplayContinuousQueuedEventInMap(queuedEvent,key,map){if(attemptReplayContinuousQueuedEvent(queuedEvent)){map.delete(key);}}function replayUnblockedEvents(){hasScheduledReplayAttempt=false;if(queuedFocus!==null&&attemptReplayContinuousQueuedEvent(queuedFocus)){queuedFocus=null;}if(queuedDrag!==null&&attemptReplayContinuousQueuedEvent(queuedDrag)){queuedDrag=null;}if(queuedMouse!==null&&attemptReplayContinuousQueuedEvent(queuedMouse)){queuedMouse=null;}queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);}function scheduleCallbackIfUnblocked(queuedEvent,unblocked){if(queuedEvent.blockedOn===unblocked){queuedEvent.blockedOn=null;if(!hasScheduledReplayAttempt){hasScheduledReplayAttempt=true;// Schedule a callback to attempt replaying as many events as are
// now unblocked. This first might not actually be unblocked yet.
// We could check it early to avoid scheduling an unnecessary callback.
Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority,replayUnblockedEvents);}}}function retryIfBlockedOn(unblocked){// Mark anything that was blocked on this as no longer blocked
// and eligible for a replay.
if(queuedDiscreteEvents.length>0){scheduleCallbackIfUnblocked(queuedDiscreteEvents[0],unblocked);// This is a exponential search for each boundary that commits. I think it's
// worth it because we expect very few discrete events to queue up and once
// we are actually fully unblocked it will be fast to replay them.
for(var i=1;i<queuedDiscreteEvents.length;i++){var queuedEvent=queuedDiscreteEvents[i];if(queuedEvent.blockedOn===unblocked){queuedEvent.blockedOn=null;}}}if(queuedFocus!==null){scheduleCallbackIfUnblocked(queuedFocus,unblocked);}if(queuedDrag!==null){scheduleCallbackIfUnblocked(queuedDrag,unblocked);}if(queuedMouse!==null){scheduleCallbackIfUnblocked(queuedMouse,unblocked);}var unblock=function(queuedEvent){return scheduleCallbackIfUnblocked(queuedEvent,unblocked);};queuedPointers.forEach(unblock);queuedPointerCaptures.forEach(unblock);for(var _i=0;_i<queuedExplicitHydrationTargets.length;_i++){var queuedTarget=queuedExplicitHydrationTargets[_i];if(queuedTarget.blockedOn===unblocked){queuedTarget.blockedOn=null;}}while(queuedExplicitHydrationTargets.length>0){var nextExplicitTarget=queuedExplicitHydrationTargets[0];if(nextExplicitTarget.blockedOn!==null){// We're still blocked.
break;}else {attemptExplicitHydrationTarget(nextExplicitTarget);if(nextExplicitTarget.blockedOn===null){// We're unblocked.
queuedExplicitHydrationTargets.shift();}}}}var ReactCurrentBatchConfig=ReactSharedInternals.ReactCurrentBatchConfig;// TODO: can we stop exporting these?
var _enabled=true;// This is exported in FB builds for use by legacy FB layer infra.
// We'd like to remove this but it's not clear if this is safe.
function setEnabled(enabled){_enabled=!!enabled;}function isEnabled(){return _enabled;}function createEventListenerWrapperWithPriority(targetContainer,domEventName,eventSystemFlags){var eventPriority=getEventPriority(domEventName);var listenerWrapper;switch(eventPriority){case DiscreteEventPriority:listenerWrapper=dispatchDiscreteEvent;break;case ContinuousEventPriority:listenerWrapper=dispatchContinuousEvent;break;case DefaultEventPriority:default:listenerWrapper=dispatchEvent;break;}return listenerWrapper.bind(null,domEventName,eventSystemFlags,targetContainer);}function dispatchDiscreteEvent(domEventName,eventSystemFlags,container,nativeEvent){var previousPriority=getCurrentUpdatePriority();var prevTransition=ReactCurrentBatchConfig.transition;ReactCurrentBatchConfig.transition=null;try{setCurrentUpdatePriority(DiscreteEventPriority);dispatchEvent(domEventName,eventSystemFlags,container,nativeEvent);}finally{setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig.transition=prevTransition;}}function dispatchContinuousEvent(domEventName,eventSystemFlags,container,nativeEvent){var previousPriority=getCurrentUpdatePriority();var prevTransition=ReactCurrentBatchConfig.transition;ReactCurrentBatchConfig.transition=null;try{setCurrentUpdatePriority(ContinuousEventPriority);dispatchEvent(domEventName,eventSystemFlags,container,nativeEvent);}finally{setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig.transition=prevTransition;}}function dispatchEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent){if(!_enabled){return;}{dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName,eventSystemFlags,targetContainer,nativeEvent);}}function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName,eventSystemFlags,targetContainer,nativeEvent){var blockedOn=findInstanceBlockingEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent);if(blockedOn===null){dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,return_targetInst,targetContainer);clearIfContinuousEvent(domEventName,nativeEvent);return;}if(queueIfContinuousEvent(blockedOn,domEventName,eventSystemFlags,targetContainer,nativeEvent)){nativeEvent.stopPropagation();return;}// We need to clear only if we didn't queue because
// queueing is accumulative.
clearIfContinuousEvent(domEventName,nativeEvent);if(eventSystemFlags&IS_CAPTURE_PHASE&&isDiscreteEventThatRequiresHydration(domEventName)){while(blockedOn!==null){var fiber=getInstanceFromNode(blockedOn);if(fiber!==null){attemptSynchronousHydration(fiber);}var nextBlockedOn=findInstanceBlockingEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent);if(nextBlockedOn===null){dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,return_targetInst,targetContainer);}if(nextBlockedOn===blockedOn){break;}blockedOn=nextBlockedOn;}if(blockedOn!==null){nativeEvent.stopPropagation();}return;}// This is not replayable so we'll invoke it but without a target,
// in case the event system needs to trace it.
dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,null,targetContainer);}var return_targetInst=null;// Returns a SuspenseInstance or Container if it's blocked.
// The return_targetInst field above is conceptually part of the return value.
function findInstanceBlockingEvent(domEventName,eventSystemFlags,targetContainer,nativeEvent){// TODO: Warn if _enabled is false.
return_targetInst=null;var nativeEventTarget=getEventTarget(nativeEvent);var targetInst=getClosestInstanceFromNode(nativeEventTarget);if(targetInst!==null){var nearestMounted=getNearestMountedFiber(targetInst);if(nearestMounted===null){// This tree has been unmounted already. Dispatch without a target.
targetInst=null;}else {var tag=nearestMounted.tag;if(tag===SuspenseComponent){var instance=getSuspenseInstanceFromFiber(nearestMounted);if(instance!==null){// Queue the event to be replayed later. Abort dispatching since we
// don't want this event dispatched twice through the event system.
// TODO: If this is the first discrete event in the queue. Schedule an increased
// priority for this boundary.
return instance;}// This shouldn't happen, something went wrong but to avoid blocking
// the whole system, dispatch the event without a target.
// TODO: Warn.
targetInst=null;}else if(tag===HostRoot){var root=nearestMounted.stateNode;if(isRootDehydrated(root)){// If this happens during a replay something went wrong and it might block
// the whole system.
return getContainerFromFiber(nearestMounted);}targetInst=null;}else if(nearestMounted!==targetInst){// If we get an event (ex: img onload) before committing that
// component's mount, ignore it for now (that is, treat it as if it was an
// event on a non-React tree). We might also consider queueing events and
// dispatching them after the mount.
targetInst=null;}}}return_targetInst=targetInst;// We're not blocked on anything.
return null;}function getEventPriority(domEventName){switch(domEventName){// Used by SimpleEventPlugin:
case'cancel':case'click':case'close':case'contextmenu':case'copy':case'cut':case'auxclick':case'dblclick':case'dragend':case'dragstart':case'drop':case'focusin':case'focusout':case'input':case'invalid':case'keydown':case'keypress':case'keyup':case'mousedown':case'mouseup':case'paste':case'pause':case'play':case'pointercancel':case'pointerdown':case'pointerup':case'ratechange':case'reset':case'resize':case'seeked':case'submit':case'touchcancel':case'touchend':case'touchstart':case'volumechange':// Used by polyfills:
// eslint-disable-next-line no-fallthrough
case'change':case'selectionchange':case'textInput':case'compositionstart':case'compositionend':case'compositionupdate':// Only enableCreateEventHandleAPI:
// eslint-disable-next-line no-fallthrough
case'beforeblur':case'afterblur':// Not used by React but could be by user code:
// eslint-disable-next-line no-fallthrough
case'beforeinput':case'blur':case'fullscreenchange':case'focus':case'hashchange':case'popstate':case'select':case'selectstart':return DiscreteEventPriority;case'drag':case'dragenter':case'dragexit':case'dragleave':case'dragover':case'mousemove':case'mouseout':case'mouseover':case'pointermove':case'pointerout':case'pointerover':case'scroll':case'toggle':case'touchmove':case'wheel':// Not used by React but could be by user code:
// eslint-disable-next-line no-fallthrough
case'mouseenter':case'mouseleave':case'pointerenter':case'pointerleave':return ContinuousEventPriority;case'message':{// We might be in the Scheduler callback.
// Eventually this mechanism will be replaced by a check
// of the current priority on the native scheduler.
var schedulerPriority=getCurrentPriorityLevel();switch(schedulerPriority){case ImmediatePriority:return DiscreteEventPriority;case UserBlockingPriority:return ContinuousEventPriority;case NormalPriority:case LowPriority:// TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
return DefaultEventPriority;case IdlePriority:return IdleEventPriority;default:return DefaultEventPriority;}}default:return DefaultEventPriority;}}function addEventBubbleListener(target,eventType,listener){target.addEventListener(eventType,listener,false);return listener;}function addEventCaptureListener(target,eventType,listener){target.addEventListener(eventType,listener,true);return listener;}function addEventCaptureListenerWithPassiveFlag(target,eventType,listener,passive){target.addEventListener(eventType,listener,{capture:true,passive:passive});return listener;}function addEventBubbleListenerWithPassiveFlag(target,eventType,listener,passive){target.addEventListener(eventType,listener,{passive:passive});return listener;}/**
 * These variables store information about text content of a target node,
 * allowing comparison of content before and after a given event.
 *
 * Identify the node where selection currently begins, then observe
 * both its text content and its current position in the DOM. Since the
 * browser may natively replace the target node during composition, we can
 * use its position to find its replacement.
 *
 *
 */var root=null;var startText=null;var fallbackText=null;function initialize(nativeEventTarget){root=nativeEventTarget;startText=getText();return true;}function reset(){root=null;startText=null;fallbackText=null;}function getData(){if(fallbackText){return fallbackText;}var start;var startValue=startText;var startLength=startValue.length;var end;var endValue=getText();var endLength=endValue.length;for(start=0;start<startLength;start++){if(startValue[start]!==endValue[start]){break;}}var minEnd=startLength-start;for(end=1;end<=minEnd;end++){if(startValue[startLength-end]!==endValue[endLength-end]){break;}}var sliceTail=end>1?1-end:undefined;fallbackText=endValue.slice(start,sliceTail);return fallbackText;}function getText(){if('value'in root){return root.value;}return root.textContent;}/**
 * `charCode` represents the actual "character code" and is safe to use with
 * `String.fromCharCode`. As such, only keys that correspond to printable
 * characters produce a valid `charCode`, the only exception to this is Enter.
 * The Tab-key is considered non-printable and does not have a `charCode`,
 * presumably because it does not produce a tab-character in browsers.
 *
 * @param {object} nativeEvent Native browser event.
 * @return {number} Normalized `charCode` property.
 */function getEventCharCode(nativeEvent){var charCode;var keyCode=nativeEvent.keyCode;if('charCode'in nativeEvent){charCode=nativeEvent.charCode;// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if(charCode===0&&keyCode===13){charCode=13;}}else {// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode=keyCode;}// IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
// report Enter as charCode 10 when ctrl is pressed.
if(charCode===10){charCode=13;}// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if(charCode>=32||charCode===13){return charCode;}return 0;}function functionThatReturnsTrue(){return true;}function functionThatReturnsFalse(){return false;}// This is intentionally a factory so that we have different returned constructors.
// If we had a single constructor, it would be megamorphic and engines would deopt.
function createSyntheticEvent(Interface){/**
   * Synthetic events are dispatched by event plugins, typically in response to a
   * top-level event delegation handler.
   *
   * These systems should generally use pooling to reduce the frequency of garbage
   * collection. The system should check `isPersistent` to determine whether the
   * event should be released into the pool after being dispatched. Users that
   * need a persisted event should invoke `persist`.
   *
   * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
   * normalizing browser quirks. Subclasses do not necessarily have to implement a
   * DOM interface; custom application-specific events can also subclass this.
   */function SyntheticBaseEvent(reactName,reactEventType,targetInst,nativeEvent,nativeEventTarget){this._reactName=reactName;this._targetInst=targetInst;this.type=reactEventType;this.nativeEvent=nativeEvent;this.target=nativeEventTarget;this.currentTarget=null;for(var _propName in Interface){if(!Interface.hasOwnProperty(_propName)){continue;}var normalize=Interface[_propName];if(normalize){this[_propName]=normalize(nativeEvent);}else {this[_propName]=nativeEvent[_propName];}}var defaultPrevented=nativeEvent.defaultPrevented!=null?nativeEvent.defaultPrevented:nativeEvent.returnValue===false;if(defaultPrevented){this.isDefaultPrevented=functionThatReturnsTrue;}else {this.isDefaultPrevented=functionThatReturnsFalse;}this.isPropagationStopped=functionThatReturnsFalse;return this;}assign(SyntheticBaseEvent.prototype,{preventDefault:function(){this.defaultPrevented=true;var event=this.nativeEvent;if(!event){return;}if(event.preventDefault){event.preventDefault();// $FlowFixMe - flow is not aware of `unknown` in IE
}else if(typeof event.returnValue!=='unknown'){event.returnValue=false;}this.isDefaultPrevented=functionThatReturnsTrue;},stopPropagation:function(){var event=this.nativeEvent;if(!event){return;}if(event.stopPropagation){event.stopPropagation();// $FlowFixMe - flow is not aware of `unknown` in IE
}else if(typeof event.cancelBubble!=='unknown'){// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found".  A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble=true;}this.isPropagationStopped=functionThatReturnsTrue;},/**
     * We release all dispatched `SyntheticEvent`s after each event loop, adding
     * them back into the pool. This allows a way to hold onto a reference that
     * won't be added back into the pool.
     */persist:function(){// Modern event system doesn't use pooling.
},/**
     * Checks if this event should be released back into the pool.
     *
     * @return {boolean} True if this should not be released, false otherwise.
     */isPersistent:functionThatReturnsTrue});return SyntheticBaseEvent;}/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */var EventInterface={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(event){return event.timeStamp||Date.now();},defaultPrevented:0,isTrusted:0};var SyntheticEvent=createSyntheticEvent(EventInterface);var UIEventInterface=assign({},EventInterface,{view:0,detail:0});var SyntheticUIEvent=createSyntheticEvent(UIEventInterface);var lastMovementX;var lastMovementY;var lastMouseEvent;function updateMouseMovementPolyfillState(event){if(event!==lastMouseEvent){if(lastMouseEvent&&event.type==='mousemove'){lastMovementX=event.screenX-lastMouseEvent.screenX;lastMovementY=event.screenY-lastMouseEvent.screenY;}else {lastMovementX=0;lastMovementY=0;}lastMouseEvent=event;}}/**
 * @interface MouseEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */var MouseEventInterface=assign({},UIEventInterface,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:getEventModifierState,button:0,buttons:0,relatedTarget:function(event){if(event.relatedTarget===undefined)return event.fromElement===event.srcElement?event.toElement:event.fromElement;return event.relatedTarget;},movementX:function(event){if('movementX'in event){return event.movementX;}updateMouseMovementPolyfillState(event);return lastMovementX;},movementY:function(event){if('movementY'in event){return event.movementY;}// Don't need to call updateMouseMovementPolyfillState() here
// because it's guaranteed to have already run when movementX
// was copied.
return lastMovementY;}});var SyntheticMouseEvent=createSyntheticEvent(MouseEventInterface);/**
 * @interface DragEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */var DragEventInterface=assign({},MouseEventInterface,{dataTransfer:0});var SyntheticDragEvent=createSyntheticEvent(DragEventInterface);/**
 * @interface FocusEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */var FocusEventInterface=assign({},UIEventInterface,{relatedTarget:0});var SyntheticFocusEvent=createSyntheticEvent(FocusEventInterface);/**
 * @interface Event
 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
 */var AnimationEventInterface=assign({},EventInterface,{animationName:0,elapsedTime:0,pseudoElement:0});var SyntheticAnimationEvent=createSyntheticEvent(AnimationEventInterface);/**
 * @interface Event
 * @see http://www.w3.org/TR/clipboard-apis/
 */var ClipboardEventInterface=assign({},EventInterface,{clipboardData:function(event){return 'clipboardData'in event?event.clipboardData:window.clipboardData;}});var SyntheticClipboardEvent=createSyntheticEvent(ClipboardEventInterface);/**
 * @interface Event
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
 */var CompositionEventInterface=assign({},EventInterface,{data:0});var SyntheticCompositionEvent=createSyntheticEvent(CompositionEventInterface);/**
 * @interface Event
 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
 *      /#events-inputevents
 */ // Happens to share the same list for now.
var SyntheticInputEvent=SyntheticCompositionEvent;/**
 * Normalization of deprecated HTML5 `key` values
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */var normalizeKey={Esc:'Escape',Spacebar:' ',Left:'ArrowLeft',Up:'ArrowUp',Right:'ArrowRight',Down:'ArrowDown',Del:'Delete',Win:'OS',Menu:'ContextMenu',Apps:'ContextMenu',Scroll:'ScrollLock',MozPrintableKey:'Unidentified'};/**
 * Translation from legacy `keyCode` to HTML5 `key`
 * Only special keys supported, all others depend on keyboard layout or browser
 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
 */var translateToKey={'8':'Backspace','9':'Tab','12':'Clear','13':'Enter','16':'Shift','17':'Control','18':'Alt','19':'Pause','20':'CapsLock','27':'Escape','32':' ','33':'PageUp','34':'PageDown','35':'End','36':'Home','37':'ArrowLeft','38':'ArrowUp','39':'ArrowRight','40':'ArrowDown','45':'Insert','46':'Delete','112':'F1','113':'F2','114':'F3','115':'F4','116':'F5','117':'F6','118':'F7','119':'F8','120':'F9','121':'F10','122':'F11','123':'F12','144':'NumLock','145':'ScrollLock','224':'Meta'};/**
 * @param {object} nativeEvent Native browser event.
 * @return {string} Normalized `key` property.
 */function getEventKey(nativeEvent){if(nativeEvent.key){// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key=normalizeKey[nativeEvent.key]||nativeEvent.key;if(key!=='Unidentified'){return key;}}// Browser does not implement `key`, polyfill as much of it as we can.
if(nativeEvent.type==='keypress'){var charCode=getEventCharCode(nativeEvent);// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode===13?'Enter':String.fromCharCode(charCode);}if(nativeEvent.type==='keydown'||nativeEvent.type==='keyup'){// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode]||'Unidentified';}return '';}/**
 * Translation from modifier key to the associated property in the event.
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
 */var modifierKeyToProp={Alt:'altKey',Control:'ctrlKey',Meta:'metaKey',Shift:'shiftKey'};// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
// getModifierState. If getModifierState is not supported, we map it to a set of
// modifier keys exposed by the event. In this case, Lock-keys are not supported.
function modifierStateGetter(keyArg){var syntheticEvent=this;var nativeEvent=syntheticEvent.nativeEvent;if(nativeEvent.getModifierState){return nativeEvent.getModifierState(keyArg);}var keyProp=modifierKeyToProp[keyArg];return keyProp?!!nativeEvent[keyProp]:false;}function getEventModifierState(nativeEvent){return modifierStateGetter;}/**
 * @interface KeyboardEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */var KeyboardEventInterface=assign({},UIEventInterface,{key:getEventKey,code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:getEventModifierState,// Legacy Interface
charCode:function(event){// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if(event.type==='keypress'){return getEventCharCode(event);}return 0;},keyCode:function(event){// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if(event.type==='keydown'||event.type==='keyup'){return event.keyCode;}return 0;},which:function(event){// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if(event.type==='keypress'){return getEventCharCode(event);}if(event.type==='keydown'||event.type==='keyup'){return event.keyCode;}return 0;}});var SyntheticKeyboardEvent=createSyntheticEvent(KeyboardEventInterface);/**
 * @interface PointerEvent
 * @see http://www.w3.org/TR/pointerevents/
 */var PointerEventInterface=assign({},MouseEventInterface,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0});var SyntheticPointerEvent=createSyntheticEvent(PointerEventInterface);/**
 * @interface TouchEvent
 * @see http://www.w3.org/TR/touch-events/
 */var TouchEventInterface=assign({},UIEventInterface,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:getEventModifierState});var SyntheticTouchEvent=createSyntheticEvent(TouchEventInterface);/**
 * @interface Event
 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
 */var TransitionEventInterface=assign({},EventInterface,{propertyName:0,elapsedTime:0,pseudoElement:0});var SyntheticTransitionEvent=createSyntheticEvent(TransitionEventInterface);/**
 * @interface WheelEvent
 * @see http://www.w3.org/TR/DOM-Level-3-Events/
 */var WheelEventInterface=assign({},MouseEventInterface,{deltaX:function(event){return 'deltaX'in event?event.deltaX:// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX'in event?-event.wheelDeltaX:0;},deltaY:function(event){return 'deltaY'in event?event.deltaY:// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY'in event?-event.wheelDeltaY:// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta'in event?-event.wheelDelta:0;},deltaZ:0,// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode:0});var SyntheticWheelEvent=createSyntheticEvent(WheelEventInterface);var END_KEYCODES=[9,13,27,32];// Tab, Return, Esc, Space
var START_KEYCODE=229;var canUseCompositionEvent=canUseDOM&&'CompositionEvent'in window;var documentMode=null;if(canUseDOM&&'documentMode'in document){documentMode=document.documentMode;}// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent=canUseDOM&&'TextEvent'in window&&!documentMode;// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData=canUseDOM&&(!canUseCompositionEvent||documentMode&&documentMode>8&&documentMode<=11);var SPACEBAR_CODE=32;var SPACEBAR_CHAR=String.fromCharCode(SPACEBAR_CODE);function registerEvents(){registerTwoPhaseEvent('onBeforeInput',['compositionend','keypress','textInput','paste']);registerTwoPhaseEvent('onCompositionEnd',['compositionend','focusout','keydown','keypress','keyup','mousedown']);registerTwoPhaseEvent('onCompositionStart',['compositionstart','focusout','keydown','keypress','keyup','mousedown']);registerTwoPhaseEvent('onCompositionUpdate',['compositionupdate','focusout','keydown','keypress','keyup','mousedown']);}// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress=false;/**
 * Return whether a native keypress event is assumed to be a command.
 * This is required because Firefox fires `keypress` events for key commands
 * (cut, copy, select-all, etc.) even though no character is inserted.
 */function isKeypressCommand(nativeEvent){return (nativeEvent.ctrlKey||nativeEvent.altKey||nativeEvent.metaKey)&&// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey&&nativeEvent.altKey);}/**
 * Translate native top level events into event types.
 */function getCompositionEventType(domEventName){switch(domEventName){case'compositionstart':return 'onCompositionStart';case'compositionend':return 'onCompositionEnd';case'compositionupdate':return 'onCompositionUpdate';}}/**
 * Does our fallback best-guess model think this event signifies that
 * composition has begun?
 */function isFallbackCompositionStart(domEventName,nativeEvent){return domEventName==='keydown'&&nativeEvent.keyCode===START_KEYCODE;}/**
 * Does our fallback mode think that this event is the end of composition?
 */function isFallbackCompositionEnd(domEventName,nativeEvent){switch(domEventName){case'keyup':// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode)!==-1;case'keydown':// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode!==START_KEYCODE;case'keypress':case'mousedown':case'focusout':// Events are not possible without cancelling IME.
return true;default:return false;}}/**
 * Google Input Tools provides composition data via a CustomEvent,
 * with the `data` property populated in the `detail` object. If this
 * is available on the event object, use it. If not, this is a plain
 * composition event and we have nothing special to extract.
 *
 * @param {object} nativeEvent
 * @return {?string}
 */function getDataFromCustomEvent(nativeEvent){var detail=nativeEvent.detail;if(typeof detail==='object'&&'data'in detail){return detail.data;}return null;}/**
 * Check if a composition event was triggered by Korean IME.
 * Our fallback mode does not work well with IE's Korean IME,
 * so just use native composition events when Korean IME is used.
 * Although CompositionEvent.locale property is deprecated,
 * it is available in IE, where our fallback mode is enabled.
 *
 * @param {object} nativeEvent
 * @return {boolean}
 */function isUsingKoreanIME(nativeEvent){return nativeEvent.locale==='ko';}// Track the current IME composition status, if any.
var isComposing=false;/**
 * @return {?object} A SyntheticCompositionEvent.
 */function extractCompositionEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget){var eventType;var fallbackData;if(canUseCompositionEvent){eventType=getCompositionEventType(domEventName);}else if(!isComposing){if(isFallbackCompositionStart(domEventName,nativeEvent)){eventType='onCompositionStart';}}else if(isFallbackCompositionEnd(domEventName,nativeEvent)){eventType='onCompositionEnd';}if(!eventType){return null;}if(useFallbackCompositionData&&!isUsingKoreanIME(nativeEvent)){// The current composition is stored statically and must not be
// overwritten while composition continues.
if(!isComposing&&eventType==='onCompositionStart'){isComposing=initialize(nativeEventTarget);}else if(eventType==='onCompositionEnd'){if(isComposing){fallbackData=getData();}}}var listeners=accumulateTwoPhaseListeners(targetInst,eventType);if(listeners.length>0){var event=new SyntheticCompositionEvent(eventType,domEventName,null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:event,listeners:listeners});if(fallbackData){// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data=fallbackData;}else {var customData=getDataFromCustomEvent(nativeEvent);if(customData!==null){event.data=customData;}}}}function getNativeBeforeInputChars(domEventName,nativeEvent){switch(domEventName){case'compositionend':return getDataFromCustomEvent(nativeEvent);case'keypress':/**
       * If native `textInput` events are available, our goal is to make
       * use of them. However, there is a special case: the spacebar key.
       * In Webkit, preventing default on a spacebar `textInput` event
       * cancels character insertion, but it *also* causes the browser
       * to fall back to its default spacebar behavior of scrolling the
       * page.
       *
       * Tracking at:
       * https://code.google.com/p/chromium/issues/detail?id=355103
       *
       * To avoid this issue, use the keypress event as if no `textInput`
       * event is available.
       */var which=nativeEvent.which;if(which!==SPACEBAR_CODE){return null;}hasSpaceKeypress=true;return SPACEBAR_CHAR;case'textInput':// Record the characters to be added to the DOM.
var chars=nativeEvent.data;// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to ignore it.
if(chars===SPACEBAR_CHAR&&hasSpaceKeypress){return null;}return chars;default:// For other native event types, do nothing.
return null;}}/**
 * For browsers that do not provide the `textInput` event, extract the
 * appropriate string to use for SyntheticInputEvent.
 */function getFallbackBeforeInputChars(domEventName,nativeEvent){// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if(isComposing){if(domEventName==='compositionend'||!canUseCompositionEvent&&isFallbackCompositionEnd(domEventName,nativeEvent)){var chars=getData();reset();isComposing=false;return chars;}return null;}switch(domEventName){case'paste':// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;case'keypress':/**
       * As of v27, Firefox may fire keypress events even when no character
       * will be inserted. A few possibilities:
       *
       * - `which` is `0`. Arrow keys, Esc key, etc.
       *
       * - `which` is the pressed key code, but no char is available.
       *   Ex: 'AltGr + d` in Polish. There is no modified character for
       *   this key combination and no character is inserted into the
       *   document, but FF fires the keypress for char code `100` anyway.
       *   No `input` event will occur.
       *
       * - `which` is the pressed key code, but a command combination is
       *   being used. Ex: `Cmd+C`. No character is inserted, and no
       *   `input` event will occur.
       */if(!isKeypressCommand(nativeEvent)){// IE fires the `keypress` event when a user types an emoji via
// Touch keyboard of Windows.  In such a case, the `char` property
// holds an emoji character like `\uD83D\uDE0A`.  Because its length
// is 2, the property `which` does not represent an emoji correctly.
// In such a case, we directly return the `char` property instead of
// using `which`.
if(nativeEvent.char&&nativeEvent.char.length>1){return nativeEvent.char;}else if(nativeEvent.which){return String.fromCharCode(nativeEvent.which);}}return null;case'compositionend':return useFallbackCompositionData&&!isUsingKoreanIME(nativeEvent)?null:nativeEvent.data;default:return null;}}/**
 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
 * `textInput` or fallback behavior.
 *
 * @return {?object} A SyntheticInputEvent.
 */function extractBeforeInputEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget){var chars;if(canUseTextInputEvent){chars=getNativeBeforeInputChars(domEventName,nativeEvent);}else {chars=getFallbackBeforeInputChars(domEventName,nativeEvent);}// If no characters are being inserted, no BeforeInput event should
// be fired.
if(!chars){return null;}var listeners=accumulateTwoPhaseListeners(targetInst,'onBeforeInput');if(listeners.length>0){var event=new SyntheticInputEvent('onBeforeInput','beforeinput',null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:event,listeners:listeners});event.data=chars;}}/**
 * Create an `onBeforeInput` event to match
 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
 *
 * This event plugin is based on the native `textInput` event
 * available in Chrome, Safari, Opera, and IE. This event fires after
 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
 *
 * `beforeInput` is spec'd but not implemented in any browsers, and
 * the `input` event does not provide any useful information about what has
 * actually been added, contrary to the spec. Thus, `textInput` is the best
 * available event to identify the characters that have actually been inserted
 * into the target node.
 *
 * This plugin is also responsible for emitting `composition` events, thus
 * allowing us to share composition fallback code for both `beforeInput` and
 * `composition` event types.
 */function extractEvents(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){extractCompositionEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractBeforeInputEvent(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);}/**
 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
 */var supportedInputTypes={color:true,date:true,datetime:true,'datetime-local':true,email:true,month:true,number:true,password:true,range:true,search:true,tel:true,text:true,time:true,url:true,week:true};function isTextInputElement(elem){var nodeName=elem&&elem.nodeName&&elem.nodeName.toLowerCase();if(nodeName==='input'){return !!supportedInputTypes[elem.type];}if(nodeName==='textarea'){return true;}return false;}/**
 * Checks if an event is supported in the current execution environment.
 *
 * NOTE: This will not work correctly for non-generic events such as `change`,
 * `reset`, `load`, `error`, and `select`.
 *
 * Borrows from Modernizr.
 *
 * @param {string} eventNameSuffix Event name, e.g. "click".
 * @return {boolean} True if the event is supported.
 * @internal
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
 */function isEventSupported(eventNameSuffix){if(!canUseDOM){return false;}var eventName='on'+eventNameSuffix;var isSupported=(eventName in document);if(!isSupported){var element=document.createElement('div');element.setAttribute(eventName,'return;');isSupported=typeof element[eventName]==='function';}return isSupported;}function registerEvents$1(){registerTwoPhaseEvent('onChange',['change','click','focusin','focusout','input','keydown','keyup','selectionchange']);}function createAndAccumulateChangeEvent(dispatchQueue,inst,nativeEvent,target){// Flag this event loop as needing state restore.
enqueueStateRestore(target);var listeners=accumulateTwoPhaseListeners(inst,'onChange');if(listeners.length>0){var event=new SyntheticEvent('onChange','change',null,nativeEvent,target);dispatchQueue.push({event:event,listeners:listeners});}}/**
 * For IE shims
 */var activeElement=null;var activeElementInst=null;/**
 * SECTION: handle `change` event
 */function shouldUseChangeEvent(elem){var nodeName=elem.nodeName&&elem.nodeName.toLowerCase();return nodeName==='select'||nodeName==='input'&&elem.type==='file';}function manualDispatchChangeEvent(nativeEvent){var dispatchQueue=[];createAndAccumulateChangeEvent(dispatchQueue,activeElementInst,nativeEvent,getEventTarget(nativeEvent));// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
batchedUpdates(runEventInBatch,dispatchQueue);}function runEventInBatch(dispatchQueue){processDispatchQueue(dispatchQueue,0);}function getInstIfValueChanged(targetInst){var targetNode=getNodeFromInstance(targetInst);if(updateValueIfChanged(targetNode)){return targetInst;}}function getTargetInstForChangeEvent(domEventName,targetInst){if(domEventName==='change'){return targetInst;}}/**
 * SECTION: handle `input` event
 */var isInputEventSupported=false;if(canUseDOM){// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
isInputEventSupported=isEventSupported('input')&&(!document.documentMode||document.documentMode>9);}/**
 * (For IE <=9) Starts tracking propertychange events on the passed-in element
 * and override the value property so that we can distinguish user events from
 * value changes in JS.
 */function startWatchingForValueChange(target,targetInst){activeElement=target;activeElementInst=targetInst;activeElement.attachEvent('onpropertychange',handlePropertyChange);}/**
 * (For IE <=9) Removes the event listeners from the currently-tracked element,
 * if any exists.
 */function stopWatchingForValueChange(){if(!activeElement){return;}activeElement.detachEvent('onpropertychange',handlePropertyChange);activeElement=null;activeElementInst=null;}/**
 * (For IE <=9) Handles a propertychange event, sending a `change` event if
 * the value of the active element has changed.
 */function handlePropertyChange(nativeEvent){if(nativeEvent.propertyName!=='value'){return;}if(getInstIfValueChanged(activeElementInst)){manualDispatchChangeEvent(nativeEvent);}}function handleEventsForInputEventPolyfill(domEventName,target,targetInst){if(domEventName==='focusin'){// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();startWatchingForValueChange(target,targetInst);}else if(domEventName==='focusout'){stopWatchingForValueChange();}}// For IE8 and IE9.
function getTargetInstForInputEventPolyfill(domEventName,targetInst){if(domEventName==='selectionchange'||domEventName==='keyup'||domEventName==='keydown'){// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
return getInstIfValueChanged(activeElementInst);}}/**
 * SECTION: handle `click` event
 */function shouldUseClickEvent(elem){// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
var nodeName=elem.nodeName;return nodeName&&nodeName.toLowerCase()==='input'&&(elem.type==='checkbox'||elem.type==='radio');}function getTargetInstForClickEvent(domEventName,targetInst){if(domEventName==='click'){return getInstIfValueChanged(targetInst);}}function getTargetInstForInputOrChangeEvent(domEventName,targetInst){if(domEventName==='input'||domEventName==='change'){return getInstIfValueChanged(targetInst);}}function handleControlledInputBlur(node){var state=node._wrapperState;if(!state||!state.controlled||node.type!=='number'){return;}{// If controlled, assign the value attribute to the current value on blur
setDefaultValue(node,'number',node.value);}}/**
 * This plugin creates an `onChange` event that normalizes change events
 * across form elements. This event fires at a time when it's possible to
 * change the element's value without seeing a flicker.
 *
 * Supported elements are:
 * - input (see `isTextInputElement`)
 * - textarea
 * - select
 */function extractEvents$1(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var targetNode=targetInst?getNodeFromInstance(targetInst):window;var getTargetInstFunc,handleEventFunc;if(shouldUseChangeEvent(targetNode)){getTargetInstFunc=getTargetInstForChangeEvent;}else if(isTextInputElement(targetNode)){if(isInputEventSupported){getTargetInstFunc=getTargetInstForInputOrChangeEvent;}else {getTargetInstFunc=getTargetInstForInputEventPolyfill;handleEventFunc=handleEventsForInputEventPolyfill;}}else if(shouldUseClickEvent(targetNode)){getTargetInstFunc=getTargetInstForClickEvent;}if(getTargetInstFunc){var inst=getTargetInstFunc(domEventName,targetInst);if(inst){createAndAccumulateChangeEvent(dispatchQueue,inst,nativeEvent,nativeEventTarget);return;}}if(handleEventFunc){handleEventFunc(domEventName,targetNode,targetInst);}// When blurring, set the value attribute for number inputs
if(domEventName==='focusout'){handleControlledInputBlur(targetNode);}}function registerEvents$2(){registerDirectEvent('onMouseEnter',['mouseout','mouseover']);registerDirectEvent('onMouseLeave',['mouseout','mouseover']);registerDirectEvent('onPointerEnter',['pointerout','pointerover']);registerDirectEvent('onPointerLeave',['pointerout','pointerover']);}/**
 * For almost every interaction we care about, there will be both a top-level
 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
 * we do not extract duplicate events. However, moving the mouse into the
 * browser from outside will not fire a `mouseout` event. In this case, we use
 * the `mouseover` top-level event.
 */function extractEvents$2(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var isOverEvent=domEventName==='mouseover'||domEventName==='pointerover';var isOutEvent=domEventName==='mouseout'||domEventName==='pointerout';if(isOverEvent&&!isReplayingEvent(nativeEvent)){// If this is an over event with a target, we might have already dispatched
// the event in the out event of the other target. If this is replayed,
// then it's because we couldn't dispatch against this target previously
// so we have to do it now instead.
var related=nativeEvent.relatedTarget||nativeEvent.fromElement;if(related){// If the related node is managed by React, we can assume that we have
// already dispatched the corresponding events during its mouseout.
if(getClosestInstanceFromNode(related)||isContainerMarkedAsRoot(related)){return;}}}if(!isOutEvent&&!isOverEvent){// Must not be a mouse or pointer in or out - ignoring.
return;}var win;// TODO: why is this nullable in the types but we read from it?
if(nativeEventTarget.window===nativeEventTarget){// `nativeEventTarget` is probably a window object.
win=nativeEventTarget;}else {// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc=nativeEventTarget.ownerDocument;if(doc){win=doc.defaultView||doc.parentWindow;}else {win=window;}}var from;var to;if(isOutEvent){var _related=nativeEvent.relatedTarget||nativeEvent.toElement;from=targetInst;to=_related?getClosestInstanceFromNode(_related):null;if(to!==null){var nearestMounted=getNearestMountedFiber(to);if(to!==nearestMounted||to.tag!==HostComponent&&to.tag!==HostText){to=null;}}}else {// Moving to a node from outside the window.
from=null;to=targetInst;}if(from===to){// Nothing pertains to our managed components.
return;}var SyntheticEventCtor=SyntheticMouseEvent;var leaveEventType='onMouseLeave';var enterEventType='onMouseEnter';var eventTypePrefix='mouse';if(domEventName==='pointerout'||domEventName==='pointerover'){SyntheticEventCtor=SyntheticPointerEvent;leaveEventType='onPointerLeave';enterEventType='onPointerEnter';eventTypePrefix='pointer';}var fromNode=from==null?win:getNodeFromInstance(from);var toNode=to==null?win:getNodeFromInstance(to);var leave=new SyntheticEventCtor(leaveEventType,eventTypePrefix+'leave',from,nativeEvent,nativeEventTarget);leave.target=fromNode;leave.relatedTarget=toNode;var enter=null;// We should only process this nativeEvent if we are processing
// the first ancestor. Next time, we will ignore the event.
var nativeTargetInst=getClosestInstanceFromNode(nativeEventTarget);if(nativeTargetInst===targetInst){var enterEvent=new SyntheticEventCtor(enterEventType,eventTypePrefix+'enter',to,nativeEvent,nativeEventTarget);enterEvent.target=toNode;enterEvent.relatedTarget=fromNode;enter=enterEvent;}accumulateEnterLeaveTwoPhaseListeners(dispatchQueue,leave,enter,from,to);}/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y// eslint-disable-line no-self-compare
;}var objectIs=typeof Object.is==='function'?Object.is:is;/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */function shallowEqual(objA,objB){if(objectIs(objA,objB)){return true;}if(typeof objA!=='object'||objA===null||typeof objB!=='object'||objB===null){return false;}var keysA=Object.keys(objA);var keysB=Object.keys(objB);if(keysA.length!==keysB.length){return false;}// Test for A's keys different from B.
for(var i=0;i<keysA.length;i++){var currentKey=keysA[i];if(!hasOwnProperty.call(objB,currentKey)||!objectIs(objA[currentKey],objB[currentKey])){return false;}}return true;}/**
 * Given any node return the first leaf node without children.
 *
 * @param {DOMElement|DOMTextNode} node
 * @return {DOMElement|DOMTextNode}
 */function getLeafNode(node){while(node&&node.firstChild){node=node.firstChild;}return node;}/**
 * Get the next sibling within a container. This will walk up the
 * DOM if a node's siblings have been exhausted.
 *
 * @param {DOMElement|DOMTextNode} node
 * @return {?DOMElement|DOMTextNode}
 */function getSiblingNode(node){while(node){if(node.nextSibling){return node.nextSibling;}node=node.parentNode;}}/**
 * Get object describing the nodes which contain characters at offset.
 *
 * @param {DOMElement|DOMTextNode} root
 * @param {number} offset
 * @return {?object}
 */function getNodeForCharacterOffset(root,offset){var node=getLeafNode(root);var nodeStart=0;var nodeEnd=0;while(node){if(node.nodeType===TEXT_NODE){nodeEnd=nodeStart+node.textContent.length;if(nodeStart<=offset&&nodeEnd>=offset){return {node:node,offset:offset-nodeStart};}nodeStart=nodeEnd;}node=getLeafNode(getSiblingNode(node));}}/**
 * @param {DOMElement} outerNode
 * @return {?object}
 */function getOffsets(outerNode){var ownerDocument=outerNode.ownerDocument;var win=ownerDocument&&ownerDocument.defaultView||window;var selection=win.getSelection&&win.getSelection();if(!selection||selection.rangeCount===0){return null;}var anchorNode=selection.anchorNode,anchorOffset=selection.anchorOffset,focusNode=selection.focusNode,focusOffset=selection.focusOffset;// In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
// up/down buttons on an <input type="number">. Anonymous divs do not seem to
// expose properties, triggering a "Permission denied error" if any of its
// properties are accessed. The only seemingly possible way to avoid erroring
// is to access a property that typically works for non-anonymous divs and
// catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try{/* eslint-disable no-unused-expressions */anchorNode.nodeType;focusNode.nodeType;/* eslint-enable no-unused-expressions */}catch(e){return null;}return getModernOffsetsFromPoints(outerNode,anchorNode,anchorOffset,focusNode,focusOffset);}/**
 * Returns {start, end} where `start` is the character/codepoint index of
 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
 * `end` is the index of (focusNode, focusOffset).
 *
 * Returns null if you pass in garbage input but we should probably just crash.
 *
 * Exported only for testing.
 */function getModernOffsetsFromPoints(outerNode,anchorNode,anchorOffset,focusNode,focusOffset){var length=0;var start=-1;var end=-1;var indexWithinAnchor=0;var indexWithinFocus=0;var node=outerNode;var parentNode=null;outer:while(true){var next=null;while(true){if(node===anchorNode&&(anchorOffset===0||node.nodeType===TEXT_NODE)){start=length+anchorOffset;}if(node===focusNode&&(focusOffset===0||node.nodeType===TEXT_NODE)){end=length+focusOffset;}if(node.nodeType===TEXT_NODE){length+=node.nodeValue.length;}if((next=node.firstChild)===null){break;}// Moving from `node` to its first child `next`.
parentNode=node;node=next;}while(true){if(node===outerNode){// If `outerNode` has children, this is always the second time visiting
// it. If it has no children, this is still the first loop, and the only
// valid selection is anchorNode and focusNode both equal to this node
// and both offsets 0, in which case we will have handled above.
break outer;}if(parentNode===anchorNode&&++indexWithinAnchor===anchorOffset){start=length;}if(parentNode===focusNode&&++indexWithinFocus===focusOffset){end=length;}if((next=node.nextSibling)!==null){break;}node=parentNode;parentNode=node.parentNode;}// Moving from `node` to its next sibling `next`.
node=next;}if(start===-1||end===-1){// This should never happen. (Would happen if the anchor/focus nodes aren't
// actually inside the passed-in node.)
return null;}return {start:start,end:end};}/**
 * In modern non-IE browsers, we can support both forward and backward
 * selections.
 *
 * Note: IE10+ supports the Selection object, but it does not support
 * the `extend` method, which means that even in modern IE, it's not possible
 * to programmatically create a backward selection. Thus, for all IE
 * versions, we use the old IE API to create our selections.
 *
 * @param {DOMElement|DOMTextNode} node
 * @param {object} offsets
 */function setOffsets(node,offsets){var doc=node.ownerDocument||document;var win=doc&&doc.defaultView||window;// Edge fails with "Object expected" in some scenarios.
// (For instance: TinyMCE editor used in a list component that supports pasting to add more,
// fails when pasting 100+ items)
if(!win.getSelection){return;}var selection=win.getSelection();var length=node.textContent.length;var start=Math.min(offsets.start,length);var end=offsets.end===undefined?start:Math.min(offsets.end,length);// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if(!selection.extend&&start>end){var temp=end;end=start;start=temp;}var startMarker=getNodeForCharacterOffset(node,start);var endMarker=getNodeForCharacterOffset(node,end);if(startMarker&&endMarker){if(selection.rangeCount===1&&selection.anchorNode===startMarker.node&&selection.anchorOffset===startMarker.offset&&selection.focusNode===endMarker.node&&selection.focusOffset===endMarker.offset){return;}var range=doc.createRange();range.setStart(startMarker.node,startMarker.offset);selection.removeAllRanges();if(start>end){selection.addRange(range);selection.extend(endMarker.node,endMarker.offset);}else {range.setEnd(endMarker.node,endMarker.offset);selection.addRange(range);}}}function isTextNode(node){return node&&node.nodeType===TEXT_NODE;}function containsNode(outerNode,innerNode){if(!outerNode||!innerNode){return false;}else if(outerNode===innerNode){return true;}else if(isTextNode(outerNode)){return false;}else if(isTextNode(innerNode)){return containsNode(outerNode,innerNode.parentNode);}else if('contains'in outerNode){return outerNode.contains(innerNode);}else if(outerNode.compareDocumentPosition){return !!(outerNode.compareDocumentPosition(innerNode)&16);}else {return false;}}function isInDocument(node){return node&&node.ownerDocument&&containsNode(node.ownerDocument.documentElement,node);}function isSameOriginFrame(iframe){try{// Accessing the contentDocument of a HTMLIframeElement can cause the browser
// to throw, e.g. if it has a cross-origin src attribute.
// Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
// iframe.contentDocument.defaultView;
// A safety way is to access one of the cross origin properties: Window or Location
// Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
// https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
return typeof iframe.contentWindow.location.href==='string';}catch(err){return false;}}function getActiveElementDeep(){var win=window;var element=getActiveElement();while(element instanceof win.HTMLIFrameElement){if(isSameOriginFrame(element)){win=element.contentWindow;}else {return element;}element=getActiveElement(win.document);}return element;}/**
 * @ReactInputSelection: React input selection module. Based on Selection.js,
 * but modified to be suitable for react and has a couple of bug fixes (doesn't
 * assume buttons have range selections allowed).
 * Input selection module for React.
 */ /**
 * @hasSelectionCapabilities: we get the element types that support selection
 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
 * and `selectionEnd` rows.
 */function hasSelectionCapabilities(elem){var nodeName=elem&&elem.nodeName&&elem.nodeName.toLowerCase();return nodeName&&(nodeName==='input'&&(elem.type==='text'||elem.type==='search'||elem.type==='tel'||elem.type==='url'||elem.type==='password')||nodeName==='textarea'||elem.contentEditable==='true');}function getSelectionInformation(){var focusedElem=getActiveElementDeep();return {focusedElem:focusedElem,selectionRange:hasSelectionCapabilities(focusedElem)?getSelection(focusedElem):null};}/**
 * @restoreSelection: If any selection information was potentially lost,
 * restore it. This is useful when performing operations that could remove dom
 * nodes and place them back in, resulting in focus being lost.
 */function restoreSelection(priorSelectionInformation){var curFocusedElem=getActiveElementDeep();var priorFocusedElem=priorSelectionInformation.focusedElem;var priorSelectionRange=priorSelectionInformation.selectionRange;if(curFocusedElem!==priorFocusedElem&&isInDocument(priorFocusedElem)){if(priorSelectionRange!==null&&hasSelectionCapabilities(priorFocusedElem)){setSelection(priorFocusedElem,priorSelectionRange);}// Focusing a node can change the scroll position, which is undesirable
var ancestors=[];var ancestor=priorFocusedElem;while(ancestor=ancestor.parentNode){if(ancestor.nodeType===ELEMENT_NODE){ancestors.push({element:ancestor,left:ancestor.scrollLeft,top:ancestor.scrollTop});}}if(typeof priorFocusedElem.focus==='function'){priorFocusedElem.focus();}for(var i=0;i<ancestors.length;i++){var info=ancestors[i];info.element.scrollLeft=info.left;info.element.scrollTop=info.top;}}}/**
 * @getSelection: Gets the selection bounds of a focused textarea, input or
 * contentEditable node.
 * -@input: Look up selection bounds of this input
 * -@return {start: selectionStart, end: selectionEnd}
 */function getSelection(input){var selection;if('selectionStart'in input){// Modern browser with input or textarea.
selection={start:input.selectionStart,end:input.selectionEnd};}else {// Content editable or old IE textarea.
selection=getOffsets(input);}return selection||{start:0,end:0};}/**
 * @setSelection: Sets the selection bounds of a textarea or input and focuses
 * the input.
 * -@input     Set selection bounds of this input or textarea
 * -@offsets   Object of same form that is returned from get*
 */function setSelection(input,offsets){var start=offsets.start;var end=offsets.end;if(end===undefined){end=start;}if('selectionStart'in input){input.selectionStart=start;input.selectionEnd=Math.min(end,input.value.length);}else {setOffsets(input,offsets);}}var skipSelectionChangeEvent=canUseDOM&&'documentMode'in document&&document.documentMode<=11;function registerEvents$3(){registerTwoPhaseEvent('onSelect',['focusout','contextmenu','dragend','focusin','keydown','keyup','mousedown','mouseup','selectionchange']);}var activeElement$1=null;var activeElementInst$1=null;var lastSelection=null;var mouseDown=false;/**
 * Get an object which is a unique representation of the current selection.
 *
 * The return value will not be consistent across nodes or browsers, but
 * two identical selections on the same node will return identical objects.
 */function getSelection$1(node){if('selectionStart'in node&&hasSelectionCapabilities(node)){return {start:node.selectionStart,end:node.selectionEnd};}else {var win=node.ownerDocument&&node.ownerDocument.defaultView||window;var selection=win.getSelection();return {anchorNode:selection.anchorNode,anchorOffset:selection.anchorOffset,focusNode:selection.focusNode,focusOffset:selection.focusOffset};}}/**
 * Get document associated with the event target.
 */function getEventTargetDocument(eventTarget){return eventTarget.window===eventTarget?eventTarget.document:eventTarget.nodeType===DOCUMENT_NODE?eventTarget:eventTarget.ownerDocument;}/**
 * Poll selection to see whether it's changed.
 *
 * @param {object} nativeEvent
 * @param {object} nativeEventTarget
 * @return {?SyntheticEvent}
 */function constructSelectEvent(dispatchQueue,nativeEvent,nativeEventTarget){// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
var doc=getEventTargetDocument(nativeEventTarget);if(mouseDown||activeElement$1==null||activeElement$1!==getActiveElement(doc)){return;}// Only fire when selection has actually changed.
var currentSelection=getSelection$1(activeElement$1);if(!lastSelection||!shallowEqual(lastSelection,currentSelection)){lastSelection=currentSelection;var listeners=accumulateTwoPhaseListeners(activeElementInst$1,'onSelect');if(listeners.length>0){var event=new SyntheticEvent('onSelect','select',null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:event,listeners:listeners});event.target=activeElement$1;}}}/**
 * This plugin creates an `onSelect` event that normalizes select events
 * across form elements.
 *
 * Supported elements are:
 * - input (see `isTextInputElement`)
 * - textarea
 * - contentEditable
 *
 * This differs from native browser implementations in the following ways:
 * - Fires on contentEditable fields as well as inputs.
 * - Fires for collapsed selection.
 * - Fires after user input.
 */function extractEvents$3(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var targetNode=targetInst?getNodeFromInstance(targetInst):window;switch(domEventName){// Track the input node that has focus.
case'focusin':if(isTextInputElement(targetNode)||targetNode.contentEditable==='true'){activeElement$1=targetNode;activeElementInst$1=targetInst;lastSelection=null;}break;case'focusout':activeElement$1=null;activeElementInst$1=null;lastSelection=null;break;// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case'mousedown':mouseDown=true;break;case'contextmenu':case'mouseup':case'dragend':mouseDown=false;constructSelectEvent(dispatchQueue,nativeEvent,nativeEventTarget);break;// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case'selectionchange':if(skipSelectionChangeEvent){break;}// falls through
case'keydown':case'keyup':constructSelectEvent(dispatchQueue,nativeEvent,nativeEventTarget);}}/**
 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
 *
 * @param {string} styleProp
 * @param {string} eventName
 * @returns {object}
 */function makePrefixMap(styleProp,eventName){var prefixes={};prefixes[styleProp.toLowerCase()]=eventName.toLowerCase();prefixes['Webkit'+styleProp]='webkit'+eventName;prefixes['Moz'+styleProp]='moz'+eventName;return prefixes;}/**
 * A list of event names to a configurable list of vendor prefixes.
 */var vendorPrefixes={animationend:makePrefixMap('Animation','AnimationEnd'),animationiteration:makePrefixMap('Animation','AnimationIteration'),animationstart:makePrefixMap('Animation','AnimationStart'),transitionend:makePrefixMap('Transition','TransitionEnd')};/**
 * Event names that have already been detected and prefixed (if applicable).
 */var prefixedEventNames={};/**
 * Element to check for prefixes on.
 */var style={};/**
 * Bootstrap if a DOM exists.
 */if(canUseDOM){style=document.createElement('div').style;// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if(!('AnimationEvent'in window)){delete vendorPrefixes.animationend.animation;delete vendorPrefixes.animationiteration.animation;delete vendorPrefixes.animationstart.animation;}// Same as above
if(!('TransitionEvent'in window)){delete vendorPrefixes.transitionend.transition;}}/**
 * Attempts to determine the correct vendor prefixed event name.
 *
 * @param {string} eventName
 * @returns {string}
 */function getVendorPrefixedEventName(eventName){if(prefixedEventNames[eventName]){return prefixedEventNames[eventName];}else if(!vendorPrefixes[eventName]){return eventName;}var prefixMap=vendorPrefixes[eventName];for(var styleProp in prefixMap){if(prefixMap.hasOwnProperty(styleProp)&&styleProp in style){return prefixedEventNames[eventName]=prefixMap[styleProp];}}return eventName;}var ANIMATION_END=getVendorPrefixedEventName('animationend');var ANIMATION_ITERATION=getVendorPrefixedEventName('animationiteration');var ANIMATION_START=getVendorPrefixedEventName('animationstart');var TRANSITION_END=getVendorPrefixedEventName('transitionend');var topLevelEventsToReactNames=new Map();// NOTE: Capitalization is important in this list!
//
// E.g. it needs "pointerDown", not "pointerdown".
// This is because we derive both React name ("onPointerDown")
// and DOM name ("pointerdown") from the same list.
//
// Exceptions that don't match this convention are listed separately.
//
// prettier-ignore
var simpleEventPluginEvents=['abort','auxClick','cancel','canPlay','canPlayThrough','click','close','contextMenu','copy','cut','drag','dragEnd','dragEnter','dragExit','dragLeave','dragOver','dragStart','drop','durationChange','emptied','encrypted','ended','error','gotPointerCapture','input','invalid','keyDown','keyPress','keyUp','load','loadedData','loadedMetadata','loadStart','lostPointerCapture','mouseDown','mouseMove','mouseOut','mouseOver','mouseUp','paste','pause','play','playing','pointerCancel','pointerDown','pointerMove','pointerOut','pointerOver','pointerUp','progress','rateChange','reset','resize','seeked','seeking','stalled','submit','suspend','timeUpdate','touchCancel','touchEnd','touchStart','volumeChange','scroll','toggle','touchMove','waiting','wheel'];function registerSimpleEvent(domEventName,reactName){topLevelEventsToReactNames.set(domEventName,reactName);registerTwoPhaseEvent(reactName,[domEventName]);}function registerSimpleEvents(){for(var i=0;i<simpleEventPluginEvents.length;i++){var eventName=simpleEventPluginEvents[i];var domEventName=eventName.toLowerCase();var capitalizedEvent=eventName[0].toUpperCase()+eventName.slice(1);registerSimpleEvent(domEventName,'on'+capitalizedEvent);}// Special cases where event names don't match.
registerSimpleEvent(ANIMATION_END,'onAnimationEnd');registerSimpleEvent(ANIMATION_ITERATION,'onAnimationIteration');registerSimpleEvent(ANIMATION_START,'onAnimationStart');registerSimpleEvent('dblclick','onDoubleClick');registerSimpleEvent('focusin','onFocus');registerSimpleEvent('focusout','onBlur');registerSimpleEvent(TRANSITION_END,'onTransitionEnd');}function extractEvents$4(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){var reactName=topLevelEventsToReactNames.get(domEventName);if(reactName===undefined){return;}var SyntheticEventCtor=SyntheticEvent;var reactEventType=domEventName;switch(domEventName){case'keypress':// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if(getEventCharCode(nativeEvent)===0){return;}/* falls through */case'keydown':case'keyup':SyntheticEventCtor=SyntheticKeyboardEvent;break;case'focusin':reactEventType='focus';SyntheticEventCtor=SyntheticFocusEvent;break;case'focusout':reactEventType='blur';SyntheticEventCtor=SyntheticFocusEvent;break;case'beforeblur':case'afterblur':SyntheticEventCtor=SyntheticFocusEvent;break;case'click':// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if(nativeEvent.button===2){return;}/* falls through */case'auxclick':case'dblclick':case'mousedown':case'mousemove':case'mouseup':// TODO: Disabled elements should not respond to mouse events
/* falls through */case'mouseout':case'mouseover':case'contextmenu':SyntheticEventCtor=SyntheticMouseEvent;break;case'drag':case'dragend':case'dragenter':case'dragexit':case'dragleave':case'dragover':case'dragstart':case'drop':SyntheticEventCtor=SyntheticDragEvent;break;case'touchcancel':case'touchend':case'touchmove':case'touchstart':SyntheticEventCtor=SyntheticTouchEvent;break;case ANIMATION_END:case ANIMATION_ITERATION:case ANIMATION_START:SyntheticEventCtor=SyntheticAnimationEvent;break;case TRANSITION_END:SyntheticEventCtor=SyntheticTransitionEvent;break;case'scroll':SyntheticEventCtor=SyntheticUIEvent;break;case'wheel':SyntheticEventCtor=SyntheticWheelEvent;break;case'copy':case'cut':case'paste':SyntheticEventCtor=SyntheticClipboardEvent;break;case'gotpointercapture':case'lostpointercapture':case'pointercancel':case'pointerdown':case'pointermove':case'pointerout':case'pointerover':case'pointerup':SyntheticEventCtor=SyntheticPointerEvent;break;}var inCapturePhase=(eventSystemFlags&IS_CAPTURE_PHASE)!==0;{// Some events don't bubble in the browser.
// In the past, React has always bubbled them, but this can be surprising.
// We're going to try aligning closer to the browser behavior by not bubbling
// them in React either. We'll start by not bubbling onScroll, and then expand.
var accumulateTargetOnly=!inCapturePhase&&// TODO: ideally, we'd eventually add all events from
// nonDelegatedEvents list in DOMPluginEventSystem.
// Then we can remove this special list.
// This is a breaking change that can wait until React 18.
domEventName==='scroll';var _listeners=accumulateSinglePhaseListeners(targetInst,reactName,nativeEvent.type,inCapturePhase,accumulateTargetOnly);if(_listeners.length>0){// Intentionally create event lazily.
var _event=new SyntheticEventCtor(reactName,reactEventType,null,nativeEvent,nativeEventTarget);dispatchQueue.push({event:_event,listeners:_listeners});}}}// TODO: remove top-level side effect.
registerSimpleEvents();registerEvents$2();registerEvents$1();registerEvents$3();registerEvents();function extractEvents$5(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags,targetContainer){// TODO: we should remove the concept of a "SimpleEventPlugin".
// This is the basic functionality of the event system. All
// the other plugins are essentially polyfills. So the plugin
// should probably be inlined somewhere and have its logic
// be core the to event system. This would potentially allow
// us to ship builds of React without the polyfilled plugins below.
extractEvents$4(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags);var shouldProcessPolyfillPlugins=(eventSystemFlags&SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS)===0;// We don't process these events unless we are in the
// event's native "bubble" phase, which means that we're
// not in the capture phase. That's because we emulate
// the capture phase here still. This is a trade-off,
// because in an ideal world we would not emulate and use
// the phases properly, like we do with the SimpleEvent
// plugin. However, the plugins below either expect
// emulation (EnterLeave) or use state localized to that
// plugin (BeforeInput, Change, Select). The state in
// these modules complicates things, as you'll essentially
// get the case where the capture phase event might change
// state, only for the following bubble event to come in
// later and not trigger anything as the state now
// invalidates the heuristics of the event plugin. We
// could alter all these plugins to work in such ways, but
// that might cause other unknown side-effects that we
// can't foresee right now.
if(shouldProcessPolyfillPlugins){extractEvents$2(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractEvents$1(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractEvents$3(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);extractEvents(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget);}}// List of events that need to be individually attached to media elements.
var mediaEventTypes=['abort','canplay','canplaythrough','durationchange','emptied','encrypted','ended','error','loadeddata','loadedmetadata','loadstart','pause','play','playing','progress','ratechange','resize','seeked','seeking','stalled','suspend','timeupdate','volumechange','waiting'];// We should not delegate these events to the container, but rather
// set them on the actual target element itself. This is primarily
// because these events do not consistently bubble in the DOM.
var nonDelegatedEvents=new Set(['cancel','close','invalid','load','scroll','toggle'].concat(mediaEventTypes));function executeDispatch(event,listener,currentTarget){var type=event.type||'unknown-event';event.currentTarget=currentTarget;invokeGuardedCallbackAndCatchFirstError(type,listener,undefined,event);event.currentTarget=null;}function processDispatchQueueItemsInOrder(event,dispatchListeners,inCapturePhase){var previousInstance;if(inCapturePhase){for(var i=dispatchListeners.length-1;i>=0;i--){var _dispatchListeners$i=dispatchListeners[i],instance=_dispatchListeners$i.instance,currentTarget=_dispatchListeners$i.currentTarget,listener=_dispatchListeners$i.listener;if(instance!==previousInstance&&event.isPropagationStopped()){return;}executeDispatch(event,listener,currentTarget);previousInstance=instance;}}else {for(var _i=0;_i<dispatchListeners.length;_i++){var _dispatchListeners$_i=dispatchListeners[_i],_instance=_dispatchListeners$_i.instance,_currentTarget=_dispatchListeners$_i.currentTarget,_listener=_dispatchListeners$_i.listener;if(_instance!==previousInstance&&event.isPropagationStopped()){return;}executeDispatch(event,_listener,_currentTarget);previousInstance=_instance;}}}function processDispatchQueue(dispatchQueue,eventSystemFlags){var inCapturePhase=(eventSystemFlags&IS_CAPTURE_PHASE)!==0;for(var i=0;i<dispatchQueue.length;i++){var _dispatchQueue$i=dispatchQueue[i],event=_dispatchQueue$i.event,listeners=_dispatchQueue$i.listeners;processDispatchQueueItemsInOrder(event,listeners,inCapturePhase);//  event system doesn't use pooling.
}// This would be a good time to rethrow if any of the event handlers threw.
rethrowCaughtError();}function dispatchEventsForPlugins(domEventName,eventSystemFlags,nativeEvent,targetInst,targetContainer){var nativeEventTarget=getEventTarget(nativeEvent);var dispatchQueue=[];extractEvents$5(dispatchQueue,domEventName,targetInst,nativeEvent,nativeEventTarget,eventSystemFlags);processDispatchQueue(dispatchQueue,eventSystemFlags);}function listenToNonDelegatedEvent(domEventName,targetElement){{if(!nonDelegatedEvents.has(domEventName)){error('Did not expect a listenToNonDelegatedEvent() call for "%s". '+'This is a bug in React. Please file an issue.',domEventName);}}var isCapturePhaseListener=false;var listenerSet=getEventListenerSet(targetElement);var listenerSetKey=getListenerSetKey(domEventName,isCapturePhaseListener);if(!listenerSet.has(listenerSetKey)){addTrappedEventListener(targetElement,domEventName,IS_NON_DELEGATED,isCapturePhaseListener);listenerSet.add(listenerSetKey);}}function listenToNativeEvent(domEventName,isCapturePhaseListener,target){{if(nonDelegatedEvents.has(domEventName)&&!isCapturePhaseListener){error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. '+'This is a bug in React. Please file an issue.',domEventName);}}var eventSystemFlags=0;if(isCapturePhaseListener){eventSystemFlags|=IS_CAPTURE_PHASE;}addTrappedEventListener(target,domEventName,eventSystemFlags,isCapturePhaseListener);}// This is only used by createEventHandle when the
var listeningMarker='_reactListening'+Math.random().toString(36).slice(2);function listenToAllSupportedEvents(rootContainerElement){if(!rootContainerElement[listeningMarker]){rootContainerElement[listeningMarker]=true;allNativeEvents.forEach(function(domEventName){// We handle selectionchange separately because it
// doesn't bubble and needs to be on the document.
if(domEventName!=='selectionchange'){if(!nonDelegatedEvents.has(domEventName)){listenToNativeEvent(domEventName,false,rootContainerElement);}listenToNativeEvent(domEventName,true,rootContainerElement);}});var ownerDocument=rootContainerElement.nodeType===DOCUMENT_NODE?rootContainerElement:rootContainerElement.ownerDocument;if(ownerDocument!==null){// The selectionchange event also needs deduplication
// but it is attached to the document.
if(!ownerDocument[listeningMarker]){ownerDocument[listeningMarker]=true;listenToNativeEvent('selectionchange',false,ownerDocument);}}}}function addTrappedEventListener(targetContainer,domEventName,eventSystemFlags,isCapturePhaseListener,isDeferredListenerForLegacyFBSupport){var listener=createEventListenerWrapperWithPriority(targetContainer,domEventName,eventSystemFlags);// If passive option is not supported, then the event will be
// active and not passive.
var isPassiveListener=undefined;if(passiveBrowserEventsSupported){// Browsers introduced an intervention, making these events
// passive by default on document. React doesn't bind them
// to document anymore, but changing this now would undo
// the performance wins from the change. So we emulate
// the existing behavior manually on the roots now.
// https://github.com/facebook/react/issues/19651
if(domEventName==='touchstart'||domEventName==='touchmove'||domEventName==='wheel'){isPassiveListener=true;}}targetContainer=targetContainer;if(isCapturePhaseListener){if(isPassiveListener!==undefined){addEventCaptureListenerWithPassiveFlag(targetContainer,domEventName,listener,isPassiveListener);}else {addEventCaptureListener(targetContainer,domEventName,listener);}}else {if(isPassiveListener!==undefined){addEventBubbleListenerWithPassiveFlag(targetContainer,domEventName,listener,isPassiveListener);}else {addEventBubbleListener(targetContainer,domEventName,listener);}}}function isMatchingRootContainer(grandContainer,targetContainer){return grandContainer===targetContainer||grandContainer.nodeType===COMMENT_NODE&&grandContainer.parentNode===targetContainer;}function dispatchEventForPluginEventSystem(domEventName,eventSystemFlags,nativeEvent,targetInst,targetContainer){var ancestorInst=targetInst;if((eventSystemFlags&IS_EVENT_HANDLE_NON_MANAGED_NODE)===0&&(eventSystemFlags&IS_NON_DELEGATED)===0){var targetContainerNode=targetContainer;// If we are using the legacy FB support flag, we
if(targetInst!==null){// The below logic attempts to work out if we need to change
// the target fiber to a different ancestor. We had similar logic
// in the legacy event system, except the big difference between
// systems is that the modern event system now has an event listener
// attached to each React Root and React Portal Root. Together,
// the DOM nodes representing these roots are the "rootContainer".
// To figure out which ancestor instance we should use, we traverse
// up the fiber tree from the target instance and attempt to find
// root boundaries that match that of our current "rootContainer".
// If we find that "rootContainer", we find the parent fiber
// sub-tree for that root and make that our ancestor instance.
var node=targetInst;mainLoop:while(true){if(node===null){return;}var nodeTag=node.tag;if(nodeTag===HostRoot||nodeTag===HostPortal){var container=node.stateNode.containerInfo;if(isMatchingRootContainer(container,targetContainerNode)){break;}if(nodeTag===HostPortal){// The target is a portal, but it's not the rootContainer we're looking for.
// Normally portals handle their own events all the way down to the root.
// So we should be able to stop now. However, we don't know if this portal
// was part of *our* root.
var grandNode=node.return;while(grandNode!==null){var grandTag=grandNode.tag;if(grandTag===HostRoot||grandTag===HostPortal){var grandContainer=grandNode.stateNode.containerInfo;if(isMatchingRootContainer(grandContainer,targetContainerNode)){// This is the rootContainer we're looking for and we found it as
// a parent of the Portal. That means we can ignore it because the
// Portal will bubble through to us.
return;}}grandNode=grandNode.return;}}// Now we need to find it's corresponding host fiber in the other
// tree. To do this we can use getClosestInstanceFromNode, but we
// need to validate that the fiber is a host instance, otherwise
// we need to traverse up through the DOM till we find the correct
// node that is from the other tree.
while(container!==null){var parentNode=getClosestInstanceFromNode(container);if(parentNode===null){return;}var parentTag=parentNode.tag;if(parentTag===HostComponent||parentTag===HostText){node=ancestorInst=parentNode;continue mainLoop;}container=container.parentNode;}}node=node.return;}}}batchedUpdates(function(){return dispatchEventsForPlugins(domEventName,eventSystemFlags,nativeEvent,ancestorInst);});}function createDispatchListener(instance,listener,currentTarget){return {instance:instance,listener:listener,currentTarget:currentTarget};}function accumulateSinglePhaseListeners(targetFiber,reactName,nativeEventType,inCapturePhase,accumulateTargetOnly,nativeEvent){var captureName=reactName!==null?reactName+'Capture':null;var reactEventName=inCapturePhase?captureName:reactName;var listeners=[];var instance=targetFiber;var lastHostComponent=null;// Accumulate all instances and listeners via the target -> root path.
while(instance!==null){var _instance2=instance,stateNode=_instance2.stateNode,tag=_instance2.tag;// Handle listeners that are on HostComponents (i.e. <div>)
if(tag===HostComponent&&stateNode!==null){lastHostComponent=stateNode;// createEventHandle listeners
if(reactEventName!==null){var listener=getListener(instance,reactEventName);if(listener!=null){listeners.push(createDispatchListener(instance,listener,lastHostComponent));}}}// If we are only accumulating events for the target, then we don't
// continue to propagate through the React fiber tree to find other
// listeners.
if(accumulateTargetOnly){break;}// If we are processing the onBeforeBlur event, then we need to take
instance=instance.return;}return listeners;}// We should only use this function for:
// - BeforeInputEventPlugin
// - ChangeEventPlugin
// - SelectEventPlugin
// This is because we only process these plugins
// in the bubble phase, so we need to accumulate two
// phase event listeners (via emulation).
function accumulateTwoPhaseListeners(targetFiber,reactName){var captureName=reactName+'Capture';var listeners=[];var instance=targetFiber;// Accumulate all instances and listeners via the target -> root path.
while(instance!==null){var _instance3=instance,stateNode=_instance3.stateNode,tag=_instance3.tag;// Handle listeners that are on HostComponents (i.e. <div>)
if(tag===HostComponent&&stateNode!==null){var currentTarget=stateNode;var captureListener=getListener(instance,captureName);if(captureListener!=null){listeners.unshift(createDispatchListener(instance,captureListener,currentTarget));}var bubbleListener=getListener(instance,reactName);if(bubbleListener!=null){listeners.push(createDispatchListener(instance,bubbleListener,currentTarget));}}instance=instance.return;}return listeners;}function getParent(inst){if(inst===null){return null;}do{inst=inst.return;// TODO: If this is a HostRoot we might want to bail out.
// That is depending on if we want nested subtrees (layers) to bubble
// events to their parent. We could also go through parentNode on the
// host node but that wouldn't work for React Native and doesn't let us
// do the portal feature.
}while(inst&&inst.tag!==HostComponent);if(inst){return inst;}return null;}/**
 * Return the lowest common ancestor of A and B, or null if they are in
 * different trees.
 */function getLowestCommonAncestor(instA,instB){var nodeA=instA;var nodeB=instB;var depthA=0;for(var tempA=nodeA;tempA;tempA=getParent(tempA)){depthA++;}var depthB=0;for(var tempB=nodeB;tempB;tempB=getParent(tempB)){depthB++;}// If A is deeper, crawl up.
while(depthA-depthB>0){nodeA=getParent(nodeA);depthA--;}// If B is deeper, crawl up.
while(depthB-depthA>0){nodeB=getParent(nodeB);depthB--;}// Walk in lockstep until we find a match.
var depth=depthA;while(depth--){if(nodeA===nodeB||nodeB!==null&&nodeA===nodeB.alternate){return nodeA;}nodeA=getParent(nodeA);nodeB=getParent(nodeB);}return null;}function accumulateEnterLeaveListenersForEvent(dispatchQueue,event,target,common,inCapturePhase){var registrationName=event._reactName;var listeners=[];var instance=target;while(instance!==null){if(instance===common){break;}var _instance4=instance,alternate=_instance4.alternate,stateNode=_instance4.stateNode,tag=_instance4.tag;if(alternate!==null&&alternate===common){break;}if(tag===HostComponent&&stateNode!==null){var currentTarget=stateNode;if(inCapturePhase){var captureListener=getListener(instance,registrationName);if(captureListener!=null){listeners.unshift(createDispatchListener(instance,captureListener,currentTarget));}}else if(!inCapturePhase){var bubbleListener=getListener(instance,registrationName);if(bubbleListener!=null){listeners.push(createDispatchListener(instance,bubbleListener,currentTarget));}}}instance=instance.return;}if(listeners.length!==0){dispatchQueue.push({event:event,listeners:listeners});}}// We should only use this function for:
// - EnterLeaveEventPlugin
// This is because we only process this plugin
// in the bubble phase, so we need to accumulate two
// phase event listeners.
function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue,leaveEvent,enterEvent,from,to){var common=from&&to?getLowestCommonAncestor(from,to):null;if(from!==null){accumulateEnterLeaveListenersForEvent(dispatchQueue,leaveEvent,from,common,false);}if(to!==null&&enterEvent!==null){accumulateEnterLeaveListenersForEvent(dispatchQueue,enterEvent,to,common,true);}}function getListenerSetKey(domEventName,capture){return domEventName+"__"+(capture?'capture':'bubble');}var didWarnInvalidHydration=false;var DANGEROUSLY_SET_INNER_HTML='dangerouslySetInnerHTML';var SUPPRESS_CONTENT_EDITABLE_WARNING='suppressContentEditableWarning';var SUPPRESS_HYDRATION_WARNING='suppressHydrationWarning';var AUTOFOCUS='autoFocus';var CHILDREN='children';var STYLE='style';var HTML$1='__html';var warnedUnknownTags;var validatePropertiesInDevelopment;var warnForPropDifference;var warnForExtraAttributes;var warnForInvalidEventListener;var canDiffStyleForHydrationWarning;var normalizeHTML;{warnedUnknownTags={// There are working polyfills for <dialog>. Let people use it.
dialog:true,// Electron ships a custom <webview> tag to display external web content in
// an isolated frame and process.
// This tag is not present in non Electron environments such as JSDom which
// is often used for testing purposes.
// @see https://electronjs.org/docs/api/webview-tag
webview:true};validatePropertiesInDevelopment=function(type,props){validateProperties(type,props);validateProperties$1(type,props);validateProperties$2(type,props,{registrationNameDependencies:registrationNameDependencies,possibleRegistrationNames:possibleRegistrationNames});};// IE 11 parses & normalizes the style attribute as opposed to other
// browsers. It adds spaces and sorts the properties in some
// non-alphabetical order. Handling that would require sorting CSS
// properties in the client & server versions or applying
// `expectedStyle` to a temporary DOM node to read its `style` attribute
// normalized. Since it only affects IE, we're skipping style warnings
// in that browser completely in favor of doing all that work.
// See https://github.com/facebook/react/issues/11807
canDiffStyleForHydrationWarning=canUseDOM&&!document.documentMode;warnForPropDifference=function(propName,serverValue,clientValue){if(didWarnInvalidHydration){return;}var normalizedClientValue=normalizeMarkupForTextOrAttribute(clientValue);var normalizedServerValue=normalizeMarkupForTextOrAttribute(serverValue);if(normalizedServerValue===normalizedClientValue){return;}didWarnInvalidHydration=true;error('Prop `%s` did not match. Server: %s Client: %s',propName,JSON.stringify(normalizedServerValue),JSON.stringify(normalizedClientValue));};warnForExtraAttributes=function(attributeNames){if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;var names=[];attributeNames.forEach(function(name){names.push(name);});error('Extra attributes from the server: %s',names);};warnForInvalidEventListener=function(registrationName,listener){if(listener===false){error('Expected `%s` listener to be a function, instead got `false`.\n\n'+'If you used to conditionally omit it with %s={condition && value}, '+'pass %s={condition ? value : undefined} instead.',registrationName,registrationName,registrationName);}else {error('Expected `%s` listener to be a function, instead got a value of `%s` type.',registrationName,typeof listener);}};// Parse the HTML and read it back to normalize the HTML string so that it
// can be used for comparison.
normalizeHTML=function(parent,html){// We could have created a separate document here to avoid
// re-initializing custom elements if they exist. But this breaks
// how <noscript> is being handled. So we use the same document.
// See the discussion in https://github.com/facebook/react/pull/11157.
var testElement=parent.namespaceURI===HTML_NAMESPACE?parent.ownerDocument.createElement(parent.tagName):parent.ownerDocument.createElementNS(parent.namespaceURI,parent.tagName);testElement.innerHTML=html;return testElement.innerHTML;};}// HTML parsing normalizes CR and CRLF to LF.
// It also can turn \u0000 into \uFFFD inside attributes.
// https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
// If we have a mismatch, it might be caused by that.
// We will still patch up in this case but not fire the warning.
var NORMALIZE_NEWLINES_REGEX=/\r\n?/g;var NORMALIZE_NULL_AND_REPLACEMENT_REGEX=/\u0000|\uFFFD/g;function normalizeMarkupForTextOrAttribute(markup){{checkHtmlStringCoercion(markup);}var markupString=typeof markup==='string'?markup:''+markup;return markupString.replace(NORMALIZE_NEWLINES_REGEX,'\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX,'');}function checkForUnmatchedText(serverText,clientText,isConcurrentMode,shouldWarnDev){var normalizedClientText=normalizeMarkupForTextOrAttribute(clientText);var normalizedServerText=normalizeMarkupForTextOrAttribute(serverText);if(normalizedServerText===normalizedClientText){return;}if(shouldWarnDev){{if(!didWarnInvalidHydration){didWarnInvalidHydration=true;error('Text content did not match. Server: "%s" Client: "%s"',normalizedServerText,normalizedClientText);}}}if(isConcurrentMode&&enableClientRenderFallbackOnTextMismatch){// In concurrent roots, we throw when there's a text mismatch and revert to
// client rendering, up to the nearest Suspense boundary.
throw new Error('Text content does not match server-rendered HTML.');}}function getOwnerDocumentFromRootContainer(rootContainerElement){return rootContainerElement.nodeType===DOCUMENT_NODE?rootContainerElement:rootContainerElement.ownerDocument;}function noop(){}function trapClickOnNonInteractiveElement(node){// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
// https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
// Just set it using the onclick property so that we don't have to manage any
// bookkeeping for it. Not sure if we need to clear it when the listener is
// removed.
// TODO: Only do this for the relevant Safaris maybe?
node.onclick=noop;}function setInitialDOMProperties(tag,domElement,rootContainerElement,nextProps,isCustomComponentTag){for(var propKey in nextProps){if(!nextProps.hasOwnProperty(propKey)){continue;}var nextProp=nextProps[propKey];if(propKey===STYLE){{if(nextProp){// Freeze the next style object so that we can assume it won't be
// mutated. We have already warned for this in the past.
Object.freeze(nextProp);}}// Relies on `updateStylesByID` not mutating `styleUpdates`.
setValueForStyles(domElement,nextProp);}else if(propKey===DANGEROUSLY_SET_INNER_HTML){var nextHtml=nextProp?nextProp[HTML$1]:undefined;if(nextHtml!=null){setInnerHTML(domElement,nextHtml);}}else if(propKey===CHILDREN){if(typeof nextProp==='string'){// Avoid setting initial textContent when the text is empty. In IE11 setting
// textContent on a <textarea> will cause the placeholder to not
// show within the <textarea> until it has been focused and blurred again.
// https://github.com/facebook/react/issues/6731#issuecomment-254874553
var canSetTextContent=tag!=='textarea'||nextProp!=='';if(canSetTextContent){setTextContent(domElement,nextProp);}}else if(typeof nextProp==='number'){setTextContent(domElement,''+nextProp);}}else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING);else if(propKey===AUTOFOCUS);else if(registrationNameDependencies.hasOwnProperty(propKey)){if(nextProp!=null){if(typeof nextProp!=='function'){warnForInvalidEventListener(propKey,nextProp);}if(propKey==='onScroll'){listenToNonDelegatedEvent('scroll',domElement);}}}else if(nextProp!=null){setValueForProperty(domElement,propKey,nextProp,isCustomComponentTag);}}}function updateDOMProperties(domElement,updatePayload,wasCustomComponentTag,isCustomComponentTag){// TODO: Handle wasCustomComponentTag
for(var i=0;i<updatePayload.length;i+=2){var propKey=updatePayload[i];var propValue=updatePayload[i+1];if(propKey===STYLE){setValueForStyles(domElement,propValue);}else if(propKey===DANGEROUSLY_SET_INNER_HTML){setInnerHTML(domElement,propValue);}else if(propKey===CHILDREN){setTextContent(domElement,propValue);}else {setValueForProperty(domElement,propKey,propValue,isCustomComponentTag);}}}function createElement(type,props,rootContainerElement,parentNamespace){var isCustomComponentTag;// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var ownerDocument=getOwnerDocumentFromRootContainer(rootContainerElement);var domElement;var namespaceURI=parentNamespace;if(namespaceURI===HTML_NAMESPACE){namespaceURI=getIntrinsicNamespace(type);}if(namespaceURI===HTML_NAMESPACE){{isCustomComponentTag=isCustomComponent(type,props);// Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
if(!isCustomComponentTag&&type!==type.toLowerCase()){error('<%s /> is using incorrect casing. '+'Use PascalCase for React components, '+'or lowercase for HTML elements.',type);}}if(type==='script'){// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div=ownerDocument.createElement('div');div.innerHTML='<script><'+'/script>';// eslint-disable-line
// This is guaranteed to yield a script element.
var firstChild=div.firstChild;domElement=div.removeChild(firstChild);}else if(typeof props.is==='string'){// $FlowIssue `createElement` should be updated for Web Components
domElement=ownerDocument.createElement(type,{is:props.is});}else {// Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
domElement=ownerDocument.createElement(type);// Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
// attributes on `select`s needs to be added before `option`s are inserted.
// This prevents:
// - a bug where the `select` does not scroll to the correct option because singular
//  `select` elements automatically pick the first item #13222
// - a bug where the `select` set the first item as selected despite the `size` attribute #14239
// See https://github.com/facebook/react/issues/13222
// and https://github.com/facebook/react/issues/14239
if(type==='select'){var node=domElement;if(props.multiple){node.multiple=true;}else if(props.size){// Setting a size greater than 1 causes a select to behave like `multiple=true`, where
// it is possible that no option is selected.
//
// This is only necessary when a select in "single selection mode".
node.size=props.size;}}}}else {domElement=ownerDocument.createElementNS(namespaceURI,type);}{if(namespaceURI===HTML_NAMESPACE){if(!isCustomComponentTag&&Object.prototype.toString.call(domElement)==='[object HTMLUnknownElement]'&&!hasOwnProperty.call(warnedUnknownTags,type)){warnedUnknownTags[type]=true;error('The tag <%s> is unrecognized in this browser. '+'If you meant to render a React component, start its name with '+'an uppercase letter.',type);}}}return domElement;}function createTextNode(text,rootContainerElement){return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);}function setInitialProperties(domElement,tag,rawProps,rootContainerElement){var isCustomComponentTag=isCustomComponent(tag,rawProps);{validatePropertiesInDevelopment(tag,rawProps);}// TODO: Make sure that we check isMounted before firing any of these events.
var props;switch(tag){case'dialog':listenToNonDelegatedEvent('cancel',domElement);listenToNonDelegatedEvent('close',domElement);props=rawProps;break;case'iframe':case'object':case'embed':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load',domElement);props=rawProps;break;case'video':case'audio':// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for(var i=0;i<mediaEventTypes.length;i++){listenToNonDelegatedEvent(mediaEventTypes[i],domElement);}props=rawProps;break;case'source':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error',domElement);props=rawProps;break;case'img':case'image':case'link':// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error',domElement);listenToNonDelegatedEvent('load',domElement);props=rawProps;break;case'details':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle',domElement);props=rawProps;break;case'input':initWrapperState(domElement,rawProps);props=getHostProps(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'option':validateProps(domElement,rawProps);props=rawProps;break;case'select':initWrapperState$1(domElement,rawProps);props=getHostProps$1(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'textarea':initWrapperState$2(domElement,rawProps);props=getHostProps$2(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;default:props=rawProps;}assertValidProps(tag,props);setInitialDOMProperties(tag,domElement,rootContainerElement,props,isCustomComponentTag);switch(tag){case'input':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper(domElement,rawProps,false);break;case'textarea':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper$3(domElement);break;case'option':postMountWrapper$1(domElement,rawProps);break;case'select':postMountWrapper$2(domElement,rawProps);break;default:if(typeof props.onClick==='function'){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);}break;}}// Calculate the diff between the two objects.
function diffProperties(domElement,tag,lastRawProps,nextRawProps,rootContainerElement){{validatePropertiesInDevelopment(tag,nextRawProps);}var updatePayload=null;var lastProps;var nextProps;switch(tag){case'input':lastProps=getHostProps(domElement,lastRawProps);nextProps=getHostProps(domElement,nextRawProps);updatePayload=[];break;case'select':lastProps=getHostProps$1(domElement,lastRawProps);nextProps=getHostProps$1(domElement,nextRawProps);updatePayload=[];break;case'textarea':lastProps=getHostProps$2(domElement,lastRawProps);nextProps=getHostProps$2(domElement,nextRawProps);updatePayload=[];break;default:lastProps=lastRawProps;nextProps=nextRawProps;if(typeof lastProps.onClick!=='function'&&typeof nextProps.onClick==='function'){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);}break;}assertValidProps(tag,nextProps);var propKey;var styleName;var styleUpdates=null;for(propKey in lastProps){if(nextProps.hasOwnProperty(propKey)||!lastProps.hasOwnProperty(propKey)||lastProps[propKey]==null){continue;}if(propKey===STYLE){var lastStyle=lastProps[propKey];for(styleName in lastStyle){if(lastStyle.hasOwnProperty(styleName)){if(!styleUpdates){styleUpdates={};}styleUpdates[styleName]='';}}}else if(propKey===DANGEROUSLY_SET_INNER_HTML||propKey===CHILDREN);else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING);else if(propKey===AUTOFOCUS);else if(registrationNameDependencies.hasOwnProperty(propKey)){// This is a special case. If any listener updates we need to ensure
// that the "current" fiber pointer gets updated so we need a commit
// to update this element.
if(!updatePayload){updatePayload=[];}}else {// For all other deleted properties we add it to the queue. We use
// the allowed property list in the commit phase instead.
(updatePayload=updatePayload||[]).push(propKey,null);}}for(propKey in nextProps){var nextProp=nextProps[propKey];var lastProp=lastProps!=null?lastProps[propKey]:undefined;if(!nextProps.hasOwnProperty(propKey)||nextProp===lastProp||nextProp==null&&lastProp==null){continue;}if(propKey===STYLE){{if(nextProp){// Freeze the next style object so that we can assume it won't be
// mutated. We have already warned for this in the past.
Object.freeze(nextProp);}}if(lastProp){// Unset styles on `lastProp` but not on `nextProp`.
for(styleName in lastProp){if(lastProp.hasOwnProperty(styleName)&&(!nextProp||!nextProp.hasOwnProperty(styleName))){if(!styleUpdates){styleUpdates={};}styleUpdates[styleName]='';}}// Update styles that changed since `lastProp`.
for(styleName in nextProp){if(nextProp.hasOwnProperty(styleName)&&lastProp[styleName]!==nextProp[styleName]){if(!styleUpdates){styleUpdates={};}styleUpdates[styleName]=nextProp[styleName];}}}else {// Relies on `updateStylesByID` not mutating `styleUpdates`.
if(!styleUpdates){if(!updatePayload){updatePayload=[];}updatePayload.push(propKey,styleUpdates);}styleUpdates=nextProp;}}else if(propKey===DANGEROUSLY_SET_INNER_HTML){var nextHtml=nextProp?nextProp[HTML$1]:undefined;var lastHtml=lastProp?lastProp[HTML$1]:undefined;if(nextHtml!=null){if(lastHtml!==nextHtml){(updatePayload=updatePayload||[]).push(propKey,nextHtml);}}}else if(propKey===CHILDREN){if(typeof nextProp==='string'||typeof nextProp==='number'){(updatePayload=updatePayload||[]).push(propKey,''+nextProp);}}else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING);else if(registrationNameDependencies.hasOwnProperty(propKey)){if(nextProp!=null){// We eagerly listen to this even though we haven't committed yet.
if(typeof nextProp!=='function'){warnForInvalidEventListener(propKey,nextProp);}if(propKey==='onScroll'){listenToNonDelegatedEvent('scroll',domElement);}}if(!updatePayload&&lastProp!==nextProp){// This is a special case. If any listener updates we need to ensure
// that the "current" props pointer gets updated so we need a commit
// to update this element.
updatePayload=[];}}else {// For any other property we always add it to the queue and then we
// filter it out using the allowed property list during the commit.
(updatePayload=updatePayload||[]).push(propKey,nextProp);}}if(styleUpdates){{validateShorthandPropertyCollisionInDev(styleUpdates,nextProps[STYLE]);}(updatePayload=updatePayload||[]).push(STYLE,styleUpdates);}return updatePayload;}// Apply the diff.
function updateProperties(domElement,updatePayload,tag,lastRawProps,nextRawProps){// Update checked *before* name.
// In the middle of an update, it is possible to have multiple checked.
// When a checked radio tries to change name, browser makes another radio's checked false.
if(tag==='input'&&nextRawProps.type==='radio'&&nextRawProps.name!=null){updateChecked(domElement,nextRawProps);}var wasCustomComponentTag=isCustomComponent(tag,lastRawProps);var isCustomComponentTag=isCustomComponent(tag,nextRawProps);// Apply the diff.
updateDOMProperties(domElement,updatePayload,wasCustomComponentTag,isCustomComponentTag);// TODO: Ensure that an update gets scheduled if any of the special props
// changed.
switch(tag){case'input':// Update the wrapper around inputs *after* updating props. This has to
// happen after `updateDOMProperties`. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
updateWrapper(domElement,nextRawProps);break;case'textarea':updateWrapper$1(domElement,nextRawProps);break;case'select':// <select> value update needs to occur after <option> children
// reconciliation
postUpdateWrapper(domElement,nextRawProps);break;}}function getPossibleStandardName(propName){{var lowerCasedName=propName.toLowerCase();if(!possibleStandardNames.hasOwnProperty(lowerCasedName)){return null;}return possibleStandardNames[lowerCasedName]||null;}}function diffHydratedProperties(domElement,tag,rawProps,parentNamespace,rootContainerElement,isConcurrentMode,shouldWarnDev){var isCustomComponentTag;var extraAttributeNames;{isCustomComponentTag=isCustomComponent(tag,rawProps);validatePropertiesInDevelopment(tag,rawProps);}// TODO: Make sure that we check isMounted before firing any of these events.
switch(tag){case'dialog':listenToNonDelegatedEvent('cancel',domElement);listenToNonDelegatedEvent('close',domElement);break;case'iframe':case'object':case'embed':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load',domElement);break;case'video':case'audio':// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for(var i=0;i<mediaEventTypes.length;i++){listenToNonDelegatedEvent(mediaEventTypes[i],domElement);}break;case'source':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error',domElement);break;case'img':case'image':case'link':// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error',domElement);listenToNonDelegatedEvent('load',domElement);break;case'details':// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle',domElement);break;case'input':initWrapperState(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'option':validateProps(domElement,rawProps);break;case'select':initWrapperState$1(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;case'textarea':initWrapperState$2(domElement,rawProps);// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid',domElement);break;}assertValidProps(tag,rawProps);{extraAttributeNames=new Set();var attributes=domElement.attributes;for(var _i=0;_i<attributes.length;_i++){var name=attributes[_i].name.toLowerCase();switch(name){// Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
case'value':break;case'checked':break;case'selected':break;default:// Intentionally use the original name.
// See discussion in https://github.com/facebook/react/pull/10676.
extraAttributeNames.add(attributes[_i].name);}}}var updatePayload=null;for(var propKey in rawProps){if(!rawProps.hasOwnProperty(propKey)){continue;}var nextProp=rawProps[propKey];if(propKey===CHILDREN){// For text content children we compare against textContent. This
// might match additional HTML that is hidden when we read it using
// textContent. E.g. "foo" will match "f<span>oo</span>" but that still
// satisfies our requirement. Our requirement is not to produce perfect
// HTML and attributes. Ideally we should preserve structure but it's
// ok not to if the visible content is still enough to indicate what
// even listeners these nodes might be wired up to.
// TODO: Warn if there is more than a single textNode as a child.
// TODO: Should we use domElement.firstChild.nodeValue to compare?
if(typeof nextProp==='string'){if(domElement.textContent!==nextProp){if(rawProps[SUPPRESS_HYDRATION_WARNING]!==true){checkForUnmatchedText(domElement.textContent,nextProp,isConcurrentMode,shouldWarnDev);}updatePayload=[CHILDREN,nextProp];}}else if(typeof nextProp==='number'){if(domElement.textContent!==''+nextProp){if(rawProps[SUPPRESS_HYDRATION_WARNING]!==true){checkForUnmatchedText(domElement.textContent,nextProp,isConcurrentMode,shouldWarnDev);}updatePayload=[CHILDREN,''+nextProp];}}}else if(registrationNameDependencies.hasOwnProperty(propKey)){if(nextProp!=null){if(typeof nextProp!=='function'){warnForInvalidEventListener(propKey,nextProp);}if(propKey==='onScroll'){listenToNonDelegatedEvent('scroll',domElement);}}}else if(shouldWarnDev&&true&&// Convince Flow we've calculated it (it's DEV-only in this method.)
typeof isCustomComponentTag==='boolean'){// Validate that the properties correspond to their expected values.
var serverValue=void 0;var propertyInfo=isCustomComponentTag&&enableCustomElementPropertySupport?null:getPropertyInfo(propKey);if(rawProps[SUPPRESS_HYDRATION_WARNING]===true);else if(propKey===SUPPRESS_CONTENT_EDITABLE_WARNING||propKey===SUPPRESS_HYDRATION_WARNING||// Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
propKey==='value'||propKey==='checked'||propKey==='selected');else if(propKey===DANGEROUSLY_SET_INNER_HTML){var serverHTML=domElement.innerHTML;var nextHtml=nextProp?nextProp[HTML$1]:undefined;if(nextHtml!=null){var expectedHTML=normalizeHTML(domElement,nextHtml);if(expectedHTML!==serverHTML){warnForPropDifference(propKey,serverHTML,expectedHTML);}}}else if(propKey===STYLE){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey);if(canDiffStyleForHydrationWarning){var expectedStyle=createDangerousStringForStyles(nextProp);serverValue=domElement.getAttribute('style');if(expectedStyle!==serverValue){warnForPropDifference(propKey,serverValue,expectedStyle);}}}else if(isCustomComponentTag&&!enableCustomElementPropertySupport){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey.toLowerCase());serverValue=getValueForAttribute(domElement,propKey,nextProp);if(nextProp!==serverValue){warnForPropDifference(propKey,serverValue,nextProp);}}else if(!shouldIgnoreAttribute(propKey,propertyInfo,isCustomComponentTag)&&!shouldRemoveAttribute(propKey,nextProp,propertyInfo,isCustomComponentTag)){var isMismatchDueToBadCasing=false;if(propertyInfo!==null){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propertyInfo.attributeName);serverValue=getValueForProperty(domElement,propKey,nextProp,propertyInfo);}else {var ownNamespace=parentNamespace;if(ownNamespace===HTML_NAMESPACE){ownNamespace=getIntrinsicNamespace(tag);}if(ownNamespace===HTML_NAMESPACE){// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey.toLowerCase());}else {var standardName=getPossibleStandardName(propKey);if(standardName!==null&&standardName!==propKey){// If an SVG prop is supplied with bad casing, it will
// be successfully parsed from HTML, but will produce a mismatch
// (and would be incorrectly rendered on the client).
// However, we already warn about bad casing elsewhere.
// So we'll skip the misleading extra mismatch warning in this case.
isMismatchDueToBadCasing=true;// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(standardName);}// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey);}serverValue=getValueForAttribute(domElement,propKey,nextProp);}var dontWarnCustomElement=enableCustomElementPropertySupport;if(!dontWarnCustomElement&&nextProp!==serverValue&&!isMismatchDueToBadCasing){warnForPropDifference(propKey,serverValue,nextProp);}}}}{if(shouldWarnDev){if(// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.size>0&&rawProps[SUPPRESS_HYDRATION_WARNING]!==true){// $FlowFixMe - Should be inferred as not undefined.
warnForExtraAttributes(extraAttributeNames);}}}switch(tag){case'input':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper(domElement,rawProps,true);break;case'textarea':// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);postMountWrapper$3(domElement);break;case'select':case'option':// For input and textarea we current always set the value property at
// post mount to force it to diverge from attributes. However, for
// option and select we don't quite do the same thing and select
// is not resilient to the DOM state changing so we don't do that here.
// TODO: Consider not doing this for input and textarea.
break;default:if(typeof rawProps.onClick==='function'){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);}break;}return updatePayload;}function diffHydratedText(textNode,text,isConcurrentMode){var isDifferent=textNode.nodeValue!==text;return isDifferent;}function warnForDeletedHydratableElement(parentNode,child){{if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Did not expect server HTML to contain a <%s> in <%s>.',child.nodeName.toLowerCase(),parentNode.nodeName.toLowerCase());}}function warnForDeletedHydratableText(parentNode,child){{if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Did not expect server HTML to contain the text node "%s" in <%s>.',child.nodeValue,parentNode.nodeName.toLowerCase());}}function warnForInsertedHydratedElement(parentNode,tag,props){{if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Expected server HTML to contain a matching <%s> in <%s>.',tag,parentNode.nodeName.toLowerCase());}}function warnForInsertedHydratedText(parentNode,text){{if(text===''){// We expect to insert empty text nodes since they're not represented in
// the HTML.
// TODO: Remove this special case if we can just avoid inserting empty
// text nodes.
return;}if(didWarnInvalidHydration){return;}didWarnInvalidHydration=true;error('Expected server HTML to contain a matching text node for "%s" in <%s>.',text,parentNode.nodeName.toLowerCase());}}function restoreControlledState$3(domElement,tag,props){switch(tag){case'input':restoreControlledState(domElement,props);return;case'textarea':restoreControlledState$2(domElement,props);return;case'select':restoreControlledState$1(domElement,props);return;}}var validateDOMNesting=function(){};var updatedAncestorInfo=function(){};{// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags=['address','applet','area','article','aside','base','basefont','bgsound','blockquote','body','br','button','caption','center','col','colgroup','dd','details','dir','div','dl','dt','embed','fieldset','figcaption','figure','footer','form','frame','frameset','h1','h2','h3','h4','h5','h6','head','header','hgroup','hr','html','iframe','img','input','isindex','li','link','listing','main','marquee','menu','menuitem','meta','nav','noembed','noframes','noscript','object','ol','p','param','plaintext','pre','script','section','select','source','style','summary','table','tbody','td','template','textarea','tfoot','th','thead','title','tr','track','ul','wbr','xmp'];// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags=['applet','caption','html','table','td','th','marquee','object','template',// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject','desc','title'];// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags=inScopeTags.concat(['button']);// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags=['dd','dt','li','option','optgroup','p','rp','rt'];var emptyAncestorInfo={current:null,formTag:null,aTagInScope:null,buttonTagInScope:null,nobrTagInScope:null,pTagInButtonScope:null,listItemTagAutoclosing:null,dlItemTagAutoclosing:null};updatedAncestorInfo=function(oldInfo,tag){var ancestorInfo=assign({},oldInfo||emptyAncestorInfo);var info={tag:tag};if(inScopeTags.indexOf(tag)!==-1){ancestorInfo.aTagInScope=null;ancestorInfo.buttonTagInScope=null;ancestorInfo.nobrTagInScope=null;}if(buttonScopeTags.indexOf(tag)!==-1){ancestorInfo.pTagInButtonScope=null;}// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if(specialTags.indexOf(tag)!==-1&&tag!=='address'&&tag!=='div'&&tag!=='p'){ancestorInfo.listItemTagAutoclosing=null;ancestorInfo.dlItemTagAutoclosing=null;}ancestorInfo.current=info;if(tag==='form'){ancestorInfo.formTag=info;}if(tag==='a'){ancestorInfo.aTagInScope=info;}if(tag==='button'){ancestorInfo.buttonTagInScope=info;}if(tag==='nobr'){ancestorInfo.nobrTagInScope=info;}if(tag==='p'){ancestorInfo.pTagInButtonScope=info;}if(tag==='li'){ancestorInfo.listItemTagAutoclosing=info;}if(tag==='dd'||tag==='dt'){ancestorInfo.dlItemTagAutoclosing=info;}return ancestorInfo;};/**
   * Returns whether
   */var isTagValidWithParent=function(tag,parentTag){// First, let's check if we're in an unusual parsing mode...
switch(parentTag){// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case'select':return tag==='option'||tag==='optgroup'||tag==='#text';case'optgroup':return tag==='option'||tag==='#text';// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case'option':return tag==='#text';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case'tr':return tag==='th'||tag==='td'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case'tbody':case'thead':case'tfoot':return tag==='tr'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case'colgroup':return tag==='col'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case'table':return tag==='caption'||tag==='colgroup'||tag==='tbody'||tag==='tfoot'||tag==='thead'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case'head':return tag==='base'||tag==='basefont'||tag==='bgsound'||tag==='link'||tag==='meta'||tag==='title'||tag==='noscript'||tag==='noframes'||tag==='style'||tag==='script'||tag==='template';// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case'html':return tag==='head'||tag==='body'||tag==='frameset';case'frameset':return tag==='frame';case'#document':return tag==='html';}// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch(tag){case'h1':case'h2':case'h3':case'h4':case'h5':case'h6':return parentTag!=='h1'&&parentTag!=='h2'&&parentTag!=='h3'&&parentTag!=='h4'&&parentTag!=='h5'&&parentTag!=='h6';case'rp':case'rt':return impliedEndTags.indexOf(parentTag)===-1;case'body':case'caption':case'col':case'colgroup':case'frameset':case'frame':case'head':case'html':case'tbody':case'td':case'tfoot':case'th':case'thead':case'tr':// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag==null;}return true;};/**
   * Returns whether
   */var findInvalidAncestorForTag=function(tag,ancestorInfo){switch(tag){case'address':case'article':case'aside':case'blockquote':case'center':case'details':case'dialog':case'dir':case'div':case'dl':case'fieldset':case'figcaption':case'figure':case'footer':case'header':case'hgroup':case'main':case'menu':case'nav':case'ol':case'p':case'section':case'summary':case'ul':case'pre':case'listing':case'table':case'hr':case'xmp':case'h1':case'h2':case'h3':case'h4':case'h5':case'h6':return ancestorInfo.pTagInButtonScope;case'form':return ancestorInfo.formTag||ancestorInfo.pTagInButtonScope;case'li':return ancestorInfo.listItemTagAutoclosing;case'dd':case'dt':return ancestorInfo.dlItemTagAutoclosing;case'button':return ancestorInfo.buttonTagInScope;case'a':// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;case'nobr':return ancestorInfo.nobrTagInScope;}return null;};var didWarn$1={};validateDOMNesting=function(childTag,childText,ancestorInfo){ancestorInfo=ancestorInfo||emptyAncestorInfo;var parentInfo=ancestorInfo.current;var parentTag=parentInfo&&parentInfo.tag;if(childText!=null){if(childTag!=null){error('validateDOMNesting: when childText is passed, childTag should be null');}childTag='#text';}var invalidParent=isTagValidWithParent(childTag,parentTag)?null:parentInfo;var invalidAncestor=invalidParent?null:findInvalidAncestorForTag(childTag,ancestorInfo);var invalidParentOrAncestor=invalidParent||invalidAncestor;if(!invalidParentOrAncestor){return;}var ancestorTag=invalidParentOrAncestor.tag;var warnKey=!!invalidParent+'|'+childTag+'|'+ancestorTag;if(didWarn$1[warnKey]){return;}didWarn$1[warnKey]=true;var tagDisplayName=childTag;var whitespaceInfo='';if(childTag==='#text'){if(/\S/.test(childText)){tagDisplayName='Text nodes';}else {tagDisplayName='Whitespace text nodes';whitespaceInfo=" Make sure you don't have any extra whitespace between tags on "+'each line of your source code.';}}else {tagDisplayName='<'+childTag+'>';}if(invalidParent){var info='';if(ancestorTag==='table'&&childTag==='tr'){info+=' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by '+'the browser.';}error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s',tagDisplayName,ancestorTag,whitespaceInfo,info);}else {error('validateDOMNesting(...): %s cannot appear as a descendant of '+'<%s>.',tagDisplayName,ancestorTag);}};}var SUPPRESS_HYDRATION_WARNING$1='suppressHydrationWarning';var SUSPENSE_START_DATA='$';var SUSPENSE_END_DATA='/$';var SUSPENSE_PENDING_START_DATA='$?';var SUSPENSE_FALLBACK_START_DATA='$!';var STYLE$1='style';var eventsEnabled=null;var selectionInformation=null;function getRootHostContext(rootContainerInstance){var type;var namespace;var nodeType=rootContainerInstance.nodeType;switch(nodeType){case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:{type=nodeType===DOCUMENT_NODE?'#document':'#fragment';var root=rootContainerInstance.documentElement;namespace=root?root.namespaceURI:getChildNamespace(null,'');break;}default:{var container=nodeType===COMMENT_NODE?rootContainerInstance.parentNode:rootContainerInstance;var ownNamespace=container.namespaceURI||null;type=container.tagName;namespace=getChildNamespace(ownNamespace,type);break;}}{var validatedTag=type.toLowerCase();var ancestorInfo=updatedAncestorInfo(null,validatedTag);return {namespace:namespace,ancestorInfo:ancestorInfo};}}function getChildHostContext(parentHostContext,type,rootContainerInstance){{var parentHostContextDev=parentHostContext;var namespace=getChildNamespace(parentHostContextDev.namespace,type);var ancestorInfo=updatedAncestorInfo(parentHostContextDev.ancestorInfo,type);return {namespace:namespace,ancestorInfo:ancestorInfo};}}function getPublicInstance(instance){return instance;}function prepareForCommit(containerInfo){eventsEnabled=isEnabled();selectionInformation=getSelectionInformation();var activeInstance=null;setEnabled(false);return activeInstance;}function resetAfterCommit(containerInfo){restoreSelection(selectionInformation);setEnabled(eventsEnabled);eventsEnabled=null;selectionInformation=null;}function createInstance(type,props,rootContainerInstance,hostContext,internalInstanceHandle){var parentNamespace;{// TODO: take namespace into account when validating.
var hostContextDev=hostContext;validateDOMNesting(type,null,hostContextDev.ancestorInfo);if(typeof props.children==='string'||typeof props.children==='number'){var string=''+props.children;var ownAncestorInfo=updatedAncestorInfo(hostContextDev.ancestorInfo,type);validateDOMNesting(null,string,ownAncestorInfo);}parentNamespace=hostContextDev.namespace;}var domElement=createElement(type,props,rootContainerInstance,parentNamespace);precacheFiberNode(internalInstanceHandle,domElement);updateFiberProps(domElement,props);return domElement;}function appendInitialChild(parentInstance,child){parentInstance.appendChild(child);}function finalizeInitialChildren(domElement,type,props,rootContainerInstance,hostContext){setInitialProperties(domElement,type,props,rootContainerInstance);switch(type){case'button':case'input':case'select':case'textarea':return !!props.autoFocus;case'img':return true;default:return false;}}function prepareUpdate(domElement,type,oldProps,newProps,rootContainerInstance,hostContext){{var hostContextDev=hostContext;if(typeof newProps.children!==typeof oldProps.children&&(typeof newProps.children==='string'||typeof newProps.children==='number')){var string=''+newProps.children;var ownAncestorInfo=updatedAncestorInfo(hostContextDev.ancestorInfo,type);validateDOMNesting(null,string,ownAncestorInfo);}}return diffProperties(domElement,type,oldProps,newProps);}function shouldSetTextContent(type,props){return type==='textarea'||type==='noscript'||typeof props.children==='string'||typeof props.children==='number'||typeof props.dangerouslySetInnerHTML==='object'&&props.dangerouslySetInnerHTML!==null&&props.dangerouslySetInnerHTML.__html!=null;}function createTextInstance(text,rootContainerInstance,hostContext,internalInstanceHandle){{var hostContextDev=hostContext;validateDOMNesting(null,text,hostContextDev.ancestorInfo);}var textNode=createTextNode(text,rootContainerInstance);precacheFiberNode(internalInstanceHandle,textNode);return textNode;}function getCurrentEventPriority(){var currentEvent=window.event;if(currentEvent===undefined){return DefaultEventPriority;}return getEventPriority(currentEvent.type);}// if a component just imports ReactDOM (e.g. for findDOMNode).
// Some environments might not have setTimeout or clearTimeout.
var scheduleTimeout=typeof setTimeout==='function'?setTimeout:undefined;var cancelTimeout=typeof clearTimeout==='function'?clearTimeout:undefined;var noTimeout=-1;var localPromise=typeof Promise==='function'?Promise:undefined;// -------------------
var scheduleMicrotask=typeof queueMicrotask==='function'?queueMicrotask:typeof localPromise!=='undefined'?function(callback){return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);}:scheduleTimeout;// TODO: Determine the best fallback here.
function handleErrorInNextTick(error){setTimeout(function(){throw error;});}// -------------------
function commitMount(domElement,type,newProps,internalInstanceHandle){// Despite the naming that might imply otherwise, this method only
// fires if there is an `Update` effect scheduled during mounting.
// This happens if `finalizeInitialChildren` returns `true` (which it
// does to implement the `autoFocus` attribute on the client). But
// there are also other cases when this might happen (such as patching
// up text content during hydration mismatch). So we'll check this again.
switch(type){case'button':case'input':case'select':case'textarea':if(newProps.autoFocus){domElement.focus();}return;case'img':{if(newProps.src){domElement.src=newProps.src;}return;}}}function commitUpdate(domElement,updatePayload,type,oldProps,newProps,internalInstanceHandle){// Apply the diff to the DOM node.
updateProperties(domElement,updatePayload,type,oldProps,newProps);// Update the props handle so that we know which props are the ones with
// with current event handlers.
updateFiberProps(domElement,newProps);}function resetTextContent(domElement){setTextContent(domElement,'');}function commitTextUpdate(textInstance,oldText,newText){textInstance.nodeValue=newText;}function appendChild(parentInstance,child){parentInstance.appendChild(child);}function appendChildToContainer(container,child){var parentNode;if(container.nodeType===COMMENT_NODE){parentNode=container.parentNode;parentNode.insertBefore(child,container);}else {parentNode=container;parentNode.appendChild(child);}// This container might be used for a portal.
// If something inside a portal is clicked, that click should bubble
// through the React tree. However, on Mobile Safari the click would
// never bubble through the *DOM* tree unless an ancestor with onclick
// event exists. So we wouldn't see it and dispatch it.
// This is why we ensure that non React root containers have inline onclick
// defined.
// https://github.com/facebook/react/issues/11918
var reactRootContainer=container._reactRootContainer;if((reactRootContainer===null||reactRootContainer===undefined)&&parentNode.onclick===null){// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(parentNode);}}function insertBefore(parentInstance,child,beforeChild){parentInstance.insertBefore(child,beforeChild);}function insertInContainerBefore(container,child,beforeChild){if(container.nodeType===COMMENT_NODE){container.parentNode.insertBefore(child,beforeChild);}else {container.insertBefore(child,beforeChild);}}function removeChild(parentInstance,child){parentInstance.removeChild(child);}function removeChildFromContainer(container,child){if(container.nodeType===COMMENT_NODE){container.parentNode.removeChild(child);}else {container.removeChild(child);}}function clearSuspenseBoundary(parentInstance,suspenseInstance){var node=suspenseInstance;// Delete all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth=0;do{var nextNode=node.nextSibling;parentInstance.removeChild(node);if(nextNode&&nextNode.nodeType===COMMENT_NODE){var data=nextNode.data;if(data===SUSPENSE_END_DATA){if(depth===0){parentInstance.removeChild(nextNode);// Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);return;}else {depth--;}}else if(data===SUSPENSE_START_DATA||data===SUSPENSE_PENDING_START_DATA||data===SUSPENSE_FALLBACK_START_DATA){depth++;}}node=nextNode;}while(node);// TODO: Warn, we didn't find the end comment boundary.
// Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);}function clearSuspenseBoundaryFromContainer(container,suspenseInstance){if(container.nodeType===COMMENT_NODE){clearSuspenseBoundary(container.parentNode,suspenseInstance);}else if(container.nodeType===ELEMENT_NODE){clearSuspenseBoundary(container,suspenseInstance);}// Retry if any event replaying was blocked on this.
retryIfBlockedOn(container);}function hideInstance(instance){// TODO: Does this work for all element types? What about MathML? Should we
// pass host context to this method?
instance=instance;var style=instance.style;if(typeof style.setProperty==='function'){style.setProperty('display','none','important');}else {style.display='none';}}function hideTextInstance(textInstance){textInstance.nodeValue='';}function unhideInstance(instance,props){instance=instance;var styleProp=props[STYLE$1];var display=styleProp!==undefined&&styleProp!==null&&styleProp.hasOwnProperty('display')?styleProp.display:null;instance.style.display=dangerousStyleValue('display',display);}function unhideTextInstance(textInstance,text){textInstance.nodeValue=text;}function clearContainer(container){if(container.nodeType===ELEMENT_NODE){container.textContent='';}else if(container.nodeType===DOCUMENT_NODE){if(container.documentElement){container.removeChild(container.documentElement);}}}// -------------------
function canHydrateInstance(instance,type,props){if(instance.nodeType!==ELEMENT_NODE||type.toLowerCase()!==instance.nodeName.toLowerCase()){return null;}// This has now been refined to an element node.
return instance;}function canHydrateTextInstance(instance,text){if(text===''||instance.nodeType!==TEXT_NODE){// Empty strings are not parsed by HTML so there won't be a correct match here.
return null;}// This has now been refined to a text node.
return instance;}function canHydrateSuspenseInstance(instance){if(instance.nodeType!==COMMENT_NODE){// Empty strings are not parsed by HTML so there won't be a correct match here.
return null;}// This has now been refined to a suspense node.
return instance;}function isSuspenseInstancePending(instance){return instance.data===SUSPENSE_PENDING_START_DATA;}function isSuspenseInstanceFallback(instance){return instance.data===SUSPENSE_FALLBACK_START_DATA;}function getSuspenseInstanceFallbackErrorDetails(instance){var dataset=instance.nextSibling&&instance.nextSibling.dataset;var digest,message,stack;if(dataset){digest=dataset.dgst;{message=dataset.msg;stack=dataset.stck;}}{return {message:message,digest:digest,stack:stack};}// let value = {message: undefined, hash: undefined};
// const nextSibling = instance.nextSibling;
// if (nextSibling) {
//   const dataset = ((nextSibling: any): HTMLTemplateElement).dataset;
//   value.message = dataset.msg;
//   value.hash = dataset.hash;
//   if (true) {
//     value.stack = dataset.stack;
//   }
// }
// return value;
}function registerSuspenseInstanceRetry(instance,callback){instance._reactRetry=callback;}function getNextHydratable(node){// Skip non-hydratable nodes.
for(;node!=null;node=node.nextSibling){var nodeType=node.nodeType;if(nodeType===ELEMENT_NODE||nodeType===TEXT_NODE){break;}if(nodeType===COMMENT_NODE){var nodeData=node.data;if(nodeData===SUSPENSE_START_DATA||nodeData===SUSPENSE_FALLBACK_START_DATA||nodeData===SUSPENSE_PENDING_START_DATA){break;}if(nodeData===SUSPENSE_END_DATA){return null;}}}return node;}function getNextHydratableSibling(instance){return getNextHydratable(instance.nextSibling);}function getFirstHydratableChild(parentInstance){return getNextHydratable(parentInstance.firstChild);}function getFirstHydratableChildWithinContainer(parentContainer){return getNextHydratable(parentContainer.firstChild);}function getFirstHydratableChildWithinSuspenseInstance(parentInstance){return getNextHydratable(parentInstance.nextSibling);}function hydrateInstance(instance,type,props,rootContainerInstance,hostContext,internalInstanceHandle,shouldWarnDev){precacheFiberNode(internalInstanceHandle,instance);// TODO: Possibly defer this until the commit phase where all the events
// get attached.
updateFiberProps(instance,props);var parentNamespace;{var hostContextDev=hostContext;parentNamespace=hostContextDev.namespace;}// TODO: Temporary hack to check if we're in a concurrent root. We can delete
// when the legacy root API is removed.
var isConcurrentMode=(internalInstanceHandle.mode&ConcurrentMode)!==NoMode;return diffHydratedProperties(instance,type,props,parentNamespace,rootContainerInstance,isConcurrentMode,shouldWarnDev);}function hydrateTextInstance(textInstance,text,internalInstanceHandle,shouldWarnDev){precacheFiberNode(internalInstanceHandle,textInstance);// TODO: Temporary hack to check if we're in a concurrent root. We can delete
// when the legacy root API is removed.
(internalInstanceHandle.mode&ConcurrentMode)!==NoMode;return diffHydratedText(textInstance,text);}function hydrateSuspenseInstance(suspenseInstance,internalInstanceHandle){precacheFiberNode(internalInstanceHandle,suspenseInstance);}function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance){var node=suspenseInstance.nextSibling;// Skip past all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth=0;while(node){if(node.nodeType===COMMENT_NODE){var data=node.data;if(data===SUSPENSE_END_DATA){if(depth===0){return getNextHydratableSibling(node);}else {depth--;}}else if(data===SUSPENSE_START_DATA||data===SUSPENSE_FALLBACK_START_DATA||data===SUSPENSE_PENDING_START_DATA){depth++;}}node=node.nextSibling;}// TODO: Warn, we didn't find the end comment boundary.
return null;}// Returns the SuspenseInstance if this node is a direct child of a
// SuspenseInstance. I.e. if its previous sibling is a Comment with
// SUSPENSE_x_START_DATA. Otherwise, null.
function getParentSuspenseInstance(targetInstance){var node=targetInstance.previousSibling;// Skip past all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth=0;while(node){if(node.nodeType===COMMENT_NODE){var data=node.data;if(data===SUSPENSE_START_DATA||data===SUSPENSE_FALLBACK_START_DATA||data===SUSPENSE_PENDING_START_DATA){if(depth===0){return node;}else {depth--;}}else if(data===SUSPENSE_END_DATA){depth++;}}node=node.previousSibling;}return null;}function commitHydratedContainer(container){// Retry if any event replaying was blocked on this.
retryIfBlockedOn(container);}function commitHydratedSuspenseInstance(suspenseInstance){// Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);}function shouldDeleteUnhydratedTailInstances(parentType){return parentType!=='head'&&parentType!=='body';}function didNotMatchHydratedContainerTextInstance(parentContainer,textInstance,text,isConcurrentMode){var shouldWarnDev=true;checkForUnmatchedText(textInstance.nodeValue,text,isConcurrentMode,shouldWarnDev);}function didNotMatchHydratedTextInstance(parentType,parentProps,parentInstance,textInstance,text,isConcurrentMode){if(parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){var shouldWarnDev=true;checkForUnmatchedText(textInstance.nodeValue,text,isConcurrentMode,shouldWarnDev);}}function didNotHydrateInstanceWithinContainer(parentContainer,instance){{if(instance.nodeType===ELEMENT_NODE){warnForDeletedHydratableElement(parentContainer,instance);}else if(instance.nodeType===COMMENT_NODE);else {warnForDeletedHydratableText(parentContainer,instance);}}}function didNotHydrateInstanceWithinSuspenseInstance(parentInstance,instance){{// $FlowFixMe: Only Element or Document can be parent nodes.
var parentNode=parentInstance.parentNode;if(parentNode!==null){if(instance.nodeType===ELEMENT_NODE){warnForDeletedHydratableElement(parentNode,instance);}else if(instance.nodeType===COMMENT_NODE);else {warnForDeletedHydratableText(parentNode,instance);}}}}function didNotHydrateInstance(parentType,parentProps,parentInstance,instance,isConcurrentMode){{if(isConcurrentMode||parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){if(instance.nodeType===ELEMENT_NODE){warnForDeletedHydratableElement(parentInstance,instance);}else if(instance.nodeType===COMMENT_NODE);else {warnForDeletedHydratableText(parentInstance,instance);}}}}function didNotFindHydratableInstanceWithinContainer(parentContainer,type,props){{warnForInsertedHydratedElement(parentContainer,type);}}function didNotFindHydratableTextInstanceWithinContainer(parentContainer,text){{warnForInsertedHydratedText(parentContainer,text);}}function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance,type,props){{// $FlowFixMe: Only Element or Document can be parent nodes.
var parentNode=parentInstance.parentNode;if(parentNode!==null)warnForInsertedHydratedElement(parentNode,type);}}function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance,text){{// $FlowFixMe: Only Element or Document can be parent nodes.
var parentNode=parentInstance.parentNode;if(parentNode!==null)warnForInsertedHydratedText(parentNode,text);}}function didNotFindHydratableInstance(parentType,parentProps,parentInstance,type,props,isConcurrentMode){{if(isConcurrentMode||parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){warnForInsertedHydratedElement(parentInstance,type);}}}function didNotFindHydratableTextInstance(parentType,parentProps,parentInstance,text,isConcurrentMode){{if(isConcurrentMode||parentProps[SUPPRESS_HYDRATION_WARNING$1]!==true){warnForInsertedHydratedText(parentInstance,text);}}}function errorHydratingContainer(parentContainer){{// TODO: This gets logged by onRecoverableError, too, so we should be
// able to remove it.
error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.',parentContainer.nodeName.toLowerCase());}}function preparePortalMount(portalInstance){listenToAllSupportedEvents(portalInstance);}var randomKey=Math.random().toString(36).slice(2);var internalInstanceKey='__reactFiber$'+randomKey;var internalPropsKey='__reactProps$'+randomKey;var internalContainerInstanceKey='__reactContainer$'+randomKey;var internalEventHandlersKey='__reactEvents$'+randomKey;var internalEventHandlerListenersKey='__reactListeners$'+randomKey;var internalEventHandlesSetKey='__reactHandles$'+randomKey;function detachDeletedInstance(node){// TODO: This function is only called on host components. I don't think all of
// these fields are relevant.
delete node[internalInstanceKey];delete node[internalPropsKey];delete node[internalEventHandlersKey];delete node[internalEventHandlerListenersKey];delete node[internalEventHandlesSetKey];}function precacheFiberNode(hostInst,node){node[internalInstanceKey]=hostInst;}function markContainerAsRoot(hostRoot,node){node[internalContainerInstanceKey]=hostRoot;}function unmarkContainerAsRoot(node){node[internalContainerInstanceKey]=null;}function isContainerMarkedAsRoot(node){return !!node[internalContainerInstanceKey];}// Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
// If the target node is part of a hydrated or not yet rendered subtree, then
// this may also return a SuspenseComponent or HostRoot to indicate that.
// Conceptually the HostRoot fiber is a child of the Container node. So if you
// pass the Container node as the targetNode, you will not actually get the
// HostRoot back. To get to the HostRoot, you need to pass a child of it.
// The same thing applies to Suspense boundaries.
function getClosestInstanceFromNode(targetNode){var targetInst=targetNode[internalInstanceKey];if(targetInst){// Don't return HostRoot or SuspenseComponent here.
return targetInst;}// If the direct event target isn't a React owned DOM node, we need to look
// to see if one of its parents is a React owned DOM node.
var parentNode=targetNode.parentNode;while(parentNode){// We'll check if this is a container root that could include
// React nodes in the future. We need to check this first because
// if we're a child of a dehydrated container, we need to first
// find that inner container before moving on to finding the parent
// instance. Note that we don't check this field on  the targetNode
// itself because the fibers are conceptually between the container
// node and the first child. It isn't surrounding the container node.
// If it's not a container, we check if it's an instance.
targetInst=parentNode[internalContainerInstanceKey]||parentNode[internalInstanceKey];if(targetInst){// Since this wasn't the direct target of the event, we might have
// stepped past dehydrated DOM nodes to get here. However they could
// also have been non-React nodes. We need to answer which one.
// If we the instance doesn't have any children, then there can't be
// a nested suspense boundary within it. So we can use this as a fast
// bailout. Most of the time, when people add non-React children to
// the tree, it is using a ref to a child-less DOM node.
// Normally we'd only need to check one of the fibers because if it
// has ever gone from having children to deleting them or vice versa
// it would have deleted the dehydrated boundary nested inside already.
// However, since the HostRoot starts out with an alternate it might
// have one on the alternate so we need to check in case this was a
// root.
var alternate=targetInst.alternate;if(targetInst.child!==null||alternate!==null&&alternate.child!==null){// Next we need to figure out if the node that skipped past is
// nested within a dehydrated boundary and if so, which one.
var suspenseInstance=getParentSuspenseInstance(targetNode);while(suspenseInstance!==null){// We found a suspense instance. That means that we haven't
// hydrated it yet. Even though we leave the comments in the
// DOM after hydrating, and there are boundaries in the DOM
// that could already be hydrated, we wouldn't have found them
// through this pass since if the target is hydrated it would
// have had an internalInstanceKey on it.
// Let's get the fiber associated with the SuspenseComponent
// as the deepest instance.
var targetSuspenseInst=suspenseInstance[internalInstanceKey];if(targetSuspenseInst){return targetSuspenseInst;}// If we don't find a Fiber on the comment, it might be because
// we haven't gotten to hydrate it yet. There might still be a
// parent boundary that hasn't above this one so we need to find
// the outer most that is known.
suspenseInstance=getParentSuspenseInstance(suspenseInstance);// If we don't find one, then that should mean that the parent
// host component also hasn't hydrated yet. We can return it
// below since it will bail out on the isMounted check later.
}}return targetInst;}targetNode=parentNode;parentNode=targetNode.parentNode;}return null;}/**
 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
 * instance, or null if the node was not rendered by this React.
 */function getInstanceFromNode(node){var inst=node[internalInstanceKey]||node[internalContainerInstanceKey];if(inst){if(inst.tag===HostComponent||inst.tag===HostText||inst.tag===SuspenseComponent||inst.tag===HostRoot){return inst;}else {return null;}}return null;}/**
 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
 * DOM node.
 */function getNodeFromInstance(inst){if(inst.tag===HostComponent||inst.tag===HostText){// In Fiber this, is just the state node right now. We assume it will be
// a host component or host text.
return inst.stateNode;}// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
throw new Error('getNodeFromInstance: Invalid argument.');}function getFiberCurrentPropsFromNode(node){return node[internalPropsKey]||null;}function updateFiberProps(node,props){node[internalPropsKey]=props;}function getEventListenerSet(node){var elementListenerSet=node[internalEventHandlersKey];if(elementListenerSet===undefined){elementListenerSet=node[internalEventHandlersKey]=new Set();}return elementListenerSet;}var loggedTypeFailures={};var ReactDebugCurrentFrame$1=ReactSharedInternals.ReactDebugCurrentFrame;function setCurrentlyValidatingElement(element){{if(element){var owner=element._owner;var stack=describeUnknownElementTypeFrameInDEV(element.type,element._source,owner?owner.type:null);ReactDebugCurrentFrame$1.setExtraStackFrame(stack);}else {ReactDebugCurrentFrame$1.setExtraStackFrame(null);}}}function checkPropTypes(typeSpecs,values,location,componentName,element){{// $FlowFixMe This is okay but Flow doesn't know it.
var has=Function.call.bind(hasOwnProperty);for(var typeSpecName in typeSpecs){if(has(typeSpecs,typeSpecName)){var error$1=void 0;// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try{// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if(typeof typeSpecs[typeSpecName]!=='function'){// eslint-disable-next-line react-internal/prod-error-codes
var err=Error((componentName||'React class')+': '+location+' type `'+typeSpecName+'` is invalid; '+'it must be a function, usually from the `prop-types` package, but received `'+typeof typeSpecs[typeSpecName]+'`.'+'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');err.name='Invariant Violation';throw err;}error$1=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');}catch(ex){error$1=ex;}if(error$1&&!(error$1 instanceof Error)){setCurrentlyValidatingElement(element);error('%s: type specification of %s'+' `%s` is invalid; the type checker '+'function must return `null` or an `Error` but returned a %s. '+'You may have forgotten to pass an argument to the type checker '+'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and '+'shape all require an argument).',componentName||'React class',location,typeSpecName,typeof error$1);setCurrentlyValidatingElement(null);}if(error$1 instanceof Error&&!(error$1.message in loggedTypeFailures)){// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message]=true;setCurrentlyValidatingElement(element);error('Failed %s type: %s',location,error$1.message);setCurrentlyValidatingElement(null);}}}}}var valueStack=[];var fiberStack;{fiberStack=[];}var index=-1;function createCursor(defaultValue){return {current:defaultValue};}function pop(cursor,fiber){if(index<0){{error('Unexpected pop.');}return;}{if(fiber!==fiberStack[index]){error('Unexpected Fiber popped.');}}cursor.current=valueStack[index];valueStack[index]=null;{fiberStack[index]=null;}index--;}function push(cursor,value,fiber){index++;valueStack[index]=cursor.current;{fiberStack[index]=fiber;}cursor.current=value;}var warnedAboutMissingGetChildContext;{warnedAboutMissingGetChildContext={};}var emptyContextObject={};{Object.freeze(emptyContextObject);}// A cursor to the current merged context object on the stack.
var contextStackCursor=createCursor(emptyContextObject);// A cursor to a boolean indicating whether the context has changed.
var didPerformWorkStackCursor=createCursor(false);// Keep track of the previous context object that was on the stack.
// We use this to get access to the parent context after we have already
// pushed the next context provider, and now need to merge their contexts.
var previousContext=emptyContextObject;function getUnmaskedContext(workInProgress,Component,didPushOwnContextIfProvider){{if(didPushOwnContextIfProvider&&isContextProvider(Component)){// If the fiber is a context provider itself, when we read its context
// we may have already pushed its own child context on the stack. A context
// provider should not "see" its own child context. Therefore we read the
// previous (parent) context instead for a context provider.
return previousContext;}return contextStackCursor.current;}}function cacheContext(workInProgress,unmaskedContext,maskedContext){{var instance=workInProgress.stateNode;instance.__reactInternalMemoizedUnmaskedChildContext=unmaskedContext;instance.__reactInternalMemoizedMaskedChildContext=maskedContext;}}function getMaskedContext(workInProgress,unmaskedContext){{var type=workInProgress.type;var contextTypes=type.contextTypes;if(!contextTypes){return emptyContextObject;}// Avoid recreating masked context unless unmasked context has changed.
// Failing to do this will result in unnecessary calls to componentWillReceiveProps.
// This may trigger infinite loops if componentWillReceiveProps calls setState.
var instance=workInProgress.stateNode;if(instance&&instance.__reactInternalMemoizedUnmaskedChildContext===unmaskedContext){return instance.__reactInternalMemoizedMaskedChildContext;}var context={};for(var key in contextTypes){context[key]=unmaskedContext[key];}{var name=getComponentNameFromFiber(workInProgress)||'Unknown';checkPropTypes(contextTypes,context,'context',name);}// Cache unmasked context so we can avoid recreating masked context unless necessary.
// Context is created before the class component is instantiated so check for instance.
if(instance){cacheContext(workInProgress,unmaskedContext,context);}return context;}}function hasContextChanged(){{return didPerformWorkStackCursor.current;}}function isContextProvider(type){{var childContextTypes=type.childContextTypes;return childContextTypes!==null&&childContextTypes!==undefined;}}function popContext(fiber){{pop(didPerformWorkStackCursor,fiber);pop(contextStackCursor,fiber);}}function popTopLevelContextObject(fiber){{pop(didPerformWorkStackCursor,fiber);pop(contextStackCursor,fiber);}}function pushTopLevelContextObject(fiber,context,didChange){{if(contextStackCursor.current!==emptyContextObject){throw new Error('Unexpected context found on stack. '+'This error is likely caused by a bug in React. Please file an issue.');}push(contextStackCursor,context,fiber);push(didPerformWorkStackCursor,didChange,fiber);}}function processChildContext(fiber,type,parentContext){{var instance=fiber.stateNode;var childContextTypes=type.childContextTypes;// TODO (bvaughn) Replace this behavior with an invariant() in the future.
// It has only been added in Fiber to match the (unintentional) behavior in Stack.
if(typeof instance.getChildContext!=='function'){{var componentName=getComponentNameFromFiber(fiber)||'Unknown';if(!warnedAboutMissingGetChildContext[componentName]){warnedAboutMissingGetChildContext[componentName]=true;error('%s.childContextTypes is specified but there is no getChildContext() method '+'on the instance. You can either define getChildContext() on %s or remove '+'childContextTypes from it.',componentName,componentName);}}return parentContext;}var childContext=instance.getChildContext();for(var contextKey in childContext){if(!(contextKey in childContextTypes)){throw new Error((getComponentNameFromFiber(fiber)||'Unknown')+".getChildContext(): key \""+contextKey+"\" is not defined in childContextTypes.");}}{var name=getComponentNameFromFiber(fiber)||'Unknown';checkPropTypes(childContextTypes,childContext,'child context',name);}return assign({},parentContext,childContext);}}function pushContextProvider(workInProgress){{var instance=workInProgress.stateNode;// We push the context as early as possible to ensure stack integrity.
// If the instance does not exist yet, we will push null at first,
// and replace it on the stack later when invalidating the context.
var memoizedMergedChildContext=instance&&instance.__reactInternalMemoizedMergedChildContext||emptyContextObject;// Remember the parent context so we can merge with it later.
// Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
previousContext=contextStackCursor.current;push(contextStackCursor,memoizedMergedChildContext,workInProgress);push(didPerformWorkStackCursor,didPerformWorkStackCursor.current,workInProgress);return true;}}function invalidateContextProvider(workInProgress,type,didChange){{var instance=workInProgress.stateNode;if(!instance){throw new Error('Expected to have an instance by this point. '+'This error is likely caused by a bug in React. Please file an issue.');}if(didChange){// Merge parent and own context.
// Skip this if we're not updating due to sCU.
// This avoids unnecessarily recomputing memoized values.
var mergedContext=processChildContext(workInProgress,type,previousContext);instance.__reactInternalMemoizedMergedChildContext=mergedContext;// Replace the old (or empty) context with the new one.
// It is important to unwind the context in the reverse order.
pop(didPerformWorkStackCursor,workInProgress);pop(contextStackCursor,workInProgress);// Now push the new context and mark that it has changed.
push(contextStackCursor,mergedContext,workInProgress);push(didPerformWorkStackCursor,didChange,workInProgress);}else {pop(didPerformWorkStackCursor,workInProgress);push(didPerformWorkStackCursor,didChange,workInProgress);}}}function findCurrentUnmaskedContext(fiber){{// Currently this is only used with renderSubtreeIntoContainer; not sure if it
// makes sense elsewhere
if(!isFiberMounted(fiber)||fiber.tag!==ClassComponent){throw new Error('Expected subtree parent to be a mounted class component. '+'This error is likely caused by a bug in React. Please file an issue.');}var node=fiber;do{switch(node.tag){case HostRoot:return node.stateNode.context;case ClassComponent:{var Component=node.type;if(isContextProvider(Component)){return node.stateNode.__reactInternalMemoizedMergedChildContext;}break;}}node=node.return;}while(node!==null);throw new Error('Found unexpected detached subtree parent. '+'This error is likely caused by a bug in React. Please file an issue.');}}var LegacyRoot=0;var ConcurrentRoot=1;var syncQueue=null;var includesLegacySyncCallbacks=false;var isFlushingSyncQueue=false;function scheduleSyncCallback(callback){// Push this callback into an internal queue. We'll flush these either in
// the next tick, or earlier if something calls `flushSyncCallbackQueue`.
if(syncQueue===null){syncQueue=[callback];}else {// Push onto existing queue. Don't need to schedule a callback because
// we already scheduled one when we created the queue.
syncQueue.push(callback);}}function scheduleLegacySyncCallback(callback){includesLegacySyncCallbacks=true;scheduleSyncCallback(callback);}function flushSyncCallbacksOnlyInLegacyMode(){// Only flushes the queue if there's a legacy sync callback scheduled.
// TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So
// it might make more sense for the queue to be a list of roots instead of a
// list of generic callbacks. Then we can have two: one for legacy roots, one
// for concurrent roots. And this method would only flush the legacy ones.
if(includesLegacySyncCallbacks){flushSyncCallbacks();}}function flushSyncCallbacks(){if(!isFlushingSyncQueue&&syncQueue!==null){// Prevent re-entrance.
isFlushingSyncQueue=true;var i=0;var previousUpdatePriority=getCurrentUpdatePriority();try{var isSync=true;var queue=syncQueue;// TODO: Is this necessary anymore? The only user code that runs in this
// queue is in the render or commit phases.
setCurrentUpdatePriority(DiscreteEventPriority);for(;i<queue.length;i++){var callback=queue[i];do{callback=callback(isSync);}while(callback!==null);}syncQueue=null;includesLegacySyncCallbacks=false;}catch(error){// If something throws, leave the remaining callbacks on the queue.
if(syncQueue!==null){syncQueue=syncQueue.slice(i+1);}// Resume flushing in the next tick
scheduleCallback(ImmediatePriority,flushSyncCallbacks);throw error;}finally{setCurrentUpdatePriority(previousUpdatePriority);isFlushingSyncQueue=false;}}return null;}// TODO: Use the unified fiber stack module instead of this local one?
// Intentionally not using it yet to derisk the initial implementation, because
// the way we push/pop these values is a bit unusual. If there's a mistake, I'd
// rather the ids be wrong than crash the whole reconciler.
var forkStack=[];var forkStackIndex=0;var treeForkProvider=null;var treeForkCount=0;var idStack=[];var idStackIndex=0;var treeContextProvider=null;var treeContextId=1;var treeContextOverflow='';function isForkedChild(workInProgress){warnIfNotHydrating();return (workInProgress.flags&Forked)!==NoFlags;}function getForksAtLevel(workInProgress){warnIfNotHydrating();return treeForkCount;}function getTreeId(){var overflow=treeContextOverflow;var idWithLeadingBit=treeContextId;var id=idWithLeadingBit&~getLeadingBit(idWithLeadingBit);return id.toString(32)+overflow;}function pushTreeFork(workInProgress,totalChildren){// This is called right after we reconcile an array (or iterator) of child
// fibers, because that's the only place where we know how many children in
// the whole set without doing extra work later, or storing addtional
// information on the fiber.
//
// That's why this function is separate from pushTreeId — it's called during
// the render phase of the fork parent, not the child, which is where we push
// the other context values.
//
// In the Fizz implementation this is much simpler because the child is
// rendered in the same callstack as the parent.
//
// It might be better to just add a `forks` field to the Fiber type. It would
// make this module simpler.
warnIfNotHydrating();forkStack[forkStackIndex++]=treeForkCount;forkStack[forkStackIndex++]=treeForkProvider;treeForkProvider=workInProgress;treeForkCount=totalChildren;}function pushTreeId(workInProgress,totalChildren,index){warnIfNotHydrating();idStack[idStackIndex++]=treeContextId;idStack[idStackIndex++]=treeContextOverflow;idStack[idStackIndex++]=treeContextProvider;treeContextProvider=workInProgress;var baseIdWithLeadingBit=treeContextId;var baseOverflow=treeContextOverflow;// The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
// of the id; we use it to account for leading 0s.
var baseLength=getBitLength(baseIdWithLeadingBit)-1;var baseId=baseIdWithLeadingBit&~(1<<baseLength);var slot=index+1;var length=getBitLength(totalChildren)+baseLength;// 30 is the max length we can store without overflowing, taking into
// consideration the leading 1 we use to mark the end of the sequence.
if(length>30){// We overflowed the bitwise-safe range. Fall back to slower algorithm.
// This branch assumes the length of the base id is greater than 5; it won't
// work for smaller ids, because you need 5 bits per character.
//
// We encode the id in multiple steps: first the base id, then the
// remaining digits.
//
// Each 5 bit sequence corresponds to a single base 32 character. So for
// example, if the current id is 23 bits long, we can convert 20 of those
// bits into a string of 4 characters, with 3 bits left over.
//
// First calculate how many bits in the base id represent a complete
// sequence of characters.
var numberOfOverflowBits=baseLength-baseLength%5;// Then create a bitmask that selects only those bits.
var newOverflowBits=(1<<numberOfOverflowBits)-1;// Select the bits, and convert them to a base 32 string.
var newOverflow=(baseId&newOverflowBits).toString(32);// Now we can remove those bits from the base id.
var restOfBaseId=baseId>>numberOfOverflowBits;var restOfBaseLength=baseLength-numberOfOverflowBits;// Finally, encode the rest of the bits using the normal algorithm. Because
// we made more room, this time it won't overflow.
var restOfLength=getBitLength(totalChildren)+restOfBaseLength;var restOfNewBits=slot<<restOfBaseLength;var id=restOfNewBits|restOfBaseId;var overflow=newOverflow+baseOverflow;treeContextId=1<<restOfLength|id;treeContextOverflow=overflow;}else {// Normal path
var newBits=slot<<baseLength;var _id=newBits|baseId;var _overflow=baseOverflow;treeContextId=1<<length|_id;treeContextOverflow=_overflow;}}function pushMaterializedTreeId(workInProgress){warnIfNotHydrating();// This component materialized an id. This will affect any ids that appear
// in its children.
var returnFiber=workInProgress.return;if(returnFiber!==null){var numberOfForks=1;var slotIndex=0;pushTreeFork(workInProgress,numberOfForks);pushTreeId(workInProgress,numberOfForks,slotIndex);}}function getBitLength(number){return 32-clz32(number);}function getLeadingBit(id){return 1<<getBitLength(id)-1;}function popTreeContext(workInProgress){// Restore the previous values.
// This is a bit more complicated than other context-like modules in Fiber
// because the same Fiber may appear on the stack multiple times and for
// different reasons. We have to keep popping until the work-in-progress is
// no longer at the top of the stack.
while(workInProgress===treeForkProvider){treeForkProvider=forkStack[--forkStackIndex];forkStack[forkStackIndex]=null;treeForkCount=forkStack[--forkStackIndex];forkStack[forkStackIndex]=null;}while(workInProgress===treeContextProvider){treeContextProvider=idStack[--idStackIndex];idStack[idStackIndex]=null;treeContextOverflow=idStack[--idStackIndex];idStack[idStackIndex]=null;treeContextId=idStack[--idStackIndex];idStack[idStackIndex]=null;}}function getSuspendedTreeContext(){warnIfNotHydrating();if(treeContextProvider!==null){return {id:treeContextId,overflow:treeContextOverflow};}else {return null;}}function restoreSuspendedTreeContext(workInProgress,suspendedContext){warnIfNotHydrating();idStack[idStackIndex++]=treeContextId;idStack[idStackIndex++]=treeContextOverflow;idStack[idStackIndex++]=treeContextProvider;treeContextId=suspendedContext.id;treeContextOverflow=suspendedContext.overflow;treeContextProvider=workInProgress;}function warnIfNotHydrating(){{if(!getIsHydrating()){error('Expected to be hydrating. This is a bug in React. Please file '+'an issue.');}}}// This may have been an insertion or a hydration.
var hydrationParentFiber=null;var nextHydratableInstance=null;var isHydrating=false;// This flag allows for warning supression when we expect there to be mismatches
// due to earlier mismatches or a suspended fiber.
var didSuspendOrErrorDEV=false;// Hydration errors that were thrown inside this boundary
var hydrationErrors=null;function warnIfHydrating(){{if(isHydrating){error('We should not be hydrating here. This is a bug in React. Please file a bug.');}}}function markDidThrowWhileHydratingDEV(){{didSuspendOrErrorDEV=true;}}function didSuspendOrErrorWhileHydratingDEV(){{return didSuspendOrErrorDEV;}}function enterHydrationState(fiber){var parentInstance=fiber.stateNode.containerInfo;nextHydratableInstance=getFirstHydratableChildWithinContainer(parentInstance);hydrationParentFiber=fiber;isHydrating=true;hydrationErrors=null;didSuspendOrErrorDEV=false;return true;}function reenterHydrationStateFromDehydratedSuspenseInstance(fiber,suspenseInstance,treeContext){nextHydratableInstance=getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);hydrationParentFiber=fiber;isHydrating=true;hydrationErrors=null;didSuspendOrErrorDEV=false;if(treeContext!==null){restoreSuspendedTreeContext(fiber,treeContext);}return true;}function warnUnhydratedInstance(returnFiber,instance){{switch(returnFiber.tag){case HostRoot:{didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo,instance);break;}case HostComponent:{var isConcurrentMode=(returnFiber.mode&ConcurrentMode)!==NoMode;didNotHydrateInstance(returnFiber.type,returnFiber.memoizedProps,returnFiber.stateNode,instance,// TODO: Delete this argument when we remove the legacy root API.
isConcurrentMode);break;}case SuspenseComponent:{var suspenseState=returnFiber.memoizedState;if(suspenseState.dehydrated!==null)didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated,instance);break;}}}}function deleteHydratableInstance(returnFiber,instance){warnUnhydratedInstance(returnFiber,instance);var childToDelete=createFiberFromHostInstanceForDeletion();childToDelete.stateNode=instance;childToDelete.return=returnFiber;var deletions=returnFiber.deletions;if(deletions===null){returnFiber.deletions=[childToDelete];returnFiber.flags|=ChildDeletion;}else {deletions.push(childToDelete);}}function warnNonhydratedInstance(returnFiber,fiber){{if(didSuspendOrErrorDEV){// Inside a boundary that already suspended. We're currently rendering the
// siblings of a suspended node. The mismatch may be due to the missing
// data, so it's probably a false positive.
return;}switch(returnFiber.tag){case HostRoot:{var parentContainer=returnFiber.stateNode.containerInfo;switch(fiber.tag){case HostComponent:var type=fiber.type;fiber.pendingProps;didNotFindHydratableInstanceWithinContainer(parentContainer,type);break;case HostText:var text=fiber.pendingProps;didNotFindHydratableTextInstanceWithinContainer(parentContainer,text);break;}break;}case HostComponent:{var parentType=returnFiber.type;var parentProps=returnFiber.memoizedProps;var parentInstance=returnFiber.stateNode;switch(fiber.tag){case HostComponent:{var _type=fiber.type;var _props=fiber.pendingProps;var isConcurrentMode=(returnFiber.mode&ConcurrentMode)!==NoMode;didNotFindHydratableInstance(parentType,parentProps,parentInstance,_type,_props,// TODO: Delete this argument when we remove the legacy root API.
isConcurrentMode);break;}case HostText:{var _text=fiber.pendingProps;var _isConcurrentMode=(returnFiber.mode&ConcurrentMode)!==NoMode;didNotFindHydratableTextInstance(parentType,parentProps,parentInstance,_text,// TODO: Delete this argument when we remove the legacy root API.
_isConcurrentMode);break;}}break;}case SuspenseComponent:{var suspenseState=returnFiber.memoizedState;var _parentInstance=suspenseState.dehydrated;if(_parentInstance!==null)switch(fiber.tag){case HostComponent:var _type2=fiber.type;fiber.pendingProps;didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance,_type2);break;case HostText:var _text2=fiber.pendingProps;didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance,_text2);break;}break;}default:return;}}}function insertNonHydratedInstance(returnFiber,fiber){fiber.flags=fiber.flags&~Hydrating|Placement;warnNonhydratedInstance(returnFiber,fiber);}function tryHydrate(fiber,nextInstance){switch(fiber.tag){case HostComponent:{var type=fiber.type;fiber.pendingProps;var instance=canHydrateInstance(nextInstance,type);if(instance!==null){fiber.stateNode=instance;hydrationParentFiber=fiber;nextHydratableInstance=getFirstHydratableChild(instance);return true;}return false;}case HostText:{var text=fiber.pendingProps;var textInstance=canHydrateTextInstance(nextInstance,text);if(textInstance!==null){fiber.stateNode=textInstance;hydrationParentFiber=fiber;// Text Instances don't have children so there's nothing to hydrate.
nextHydratableInstance=null;return true;}return false;}case SuspenseComponent:{var suspenseInstance=canHydrateSuspenseInstance(nextInstance);if(suspenseInstance!==null){var suspenseState={dehydrated:suspenseInstance,treeContext:getSuspendedTreeContext(),retryLane:OffscreenLane};fiber.memoizedState=suspenseState;// Store the dehydrated fragment as a child fiber.
// This simplifies the code for getHostSibling and deleting nodes,
// since it doesn't have to consider all Suspense boundaries and
// check if they're dehydrated ones or not.
var dehydratedFragment=createFiberFromDehydratedFragment(suspenseInstance);dehydratedFragment.return=fiber;fiber.child=dehydratedFragment;hydrationParentFiber=fiber;// While a Suspense Instance does have children, we won't step into
// it during the first pass. Instead, we'll reenter it later.
nextHydratableInstance=null;return true;}return false;}default:return false;}}function shouldClientRenderOnMismatch(fiber){return (fiber.mode&ConcurrentMode)!==NoMode&&(fiber.flags&DidCapture)===NoFlags;}function throwOnHydrationMismatch(fiber){throw new Error('Hydration failed because the initial UI does not match what was '+'rendered on the server.');}function tryToClaimNextHydratableInstance(fiber){if(!isHydrating){return;}var nextInstance=nextHydratableInstance;if(!nextInstance){if(shouldClientRenderOnMismatch(fiber)){warnNonhydratedInstance(hydrationParentFiber,fiber);throwOnHydrationMismatch();}// Nothing to hydrate. Make it an insertion.
insertNonHydratedInstance(hydrationParentFiber,fiber);isHydrating=false;hydrationParentFiber=fiber;return;}var firstAttemptedInstance=nextInstance;if(!tryHydrate(fiber,nextInstance)){if(shouldClientRenderOnMismatch(fiber)){warnNonhydratedInstance(hydrationParentFiber,fiber);throwOnHydrationMismatch();}// If we can't hydrate this instance let's try the next one.
// We use this as a heuristic. It's based on intuition and not data so it
// might be flawed or unnecessary.
nextInstance=getNextHydratableSibling(firstAttemptedInstance);var prevHydrationParentFiber=hydrationParentFiber;if(!nextInstance||!tryHydrate(fiber,nextInstance)){// Nothing to hydrate. Make it an insertion.
insertNonHydratedInstance(hydrationParentFiber,fiber);isHydrating=false;hydrationParentFiber=fiber;return;}// We matched the next one, we'll now assume that the first one was
// superfluous and we'll delete it. Since we can't eagerly delete it
// we'll have to schedule a deletion. To do that, this node needs a dummy
// fiber associated with it.
deleteHydratableInstance(prevHydrationParentFiber,firstAttemptedInstance);}}function prepareToHydrateHostInstance(fiber,rootContainerInstance,hostContext){var instance=fiber.stateNode;var shouldWarnIfMismatchDev=!didSuspendOrErrorDEV;var updatePayload=hydrateInstance(instance,fiber.type,fiber.memoizedProps,rootContainerInstance,hostContext,fiber,shouldWarnIfMismatchDev);// TODO: Type this specific to this type of component.
fiber.updateQueue=updatePayload;// If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update.
if(updatePayload!==null){return true;}return false;}function prepareToHydrateHostTextInstance(fiber){var textInstance=fiber.stateNode;var textContent=fiber.memoizedProps;var shouldUpdate=hydrateTextInstance(textInstance,textContent,fiber);if(shouldUpdate){// We assume that prepareToHydrateHostTextInstance is called in a context where the
// hydration parent is the parent host component of this host text.
var returnFiber=hydrationParentFiber;if(returnFiber!==null){switch(returnFiber.tag){case HostRoot:{var parentContainer=returnFiber.stateNode.containerInfo;var isConcurrentMode=(returnFiber.mode&ConcurrentMode)!==NoMode;didNotMatchHydratedContainerTextInstance(parentContainer,textInstance,textContent,// TODO: Delete this argument when we remove the legacy root API.
isConcurrentMode);break;}case HostComponent:{var parentType=returnFiber.type;var parentProps=returnFiber.memoizedProps;var parentInstance=returnFiber.stateNode;var _isConcurrentMode2=(returnFiber.mode&ConcurrentMode)!==NoMode;didNotMatchHydratedTextInstance(parentType,parentProps,parentInstance,textInstance,textContent,// TODO: Delete this argument when we remove the legacy root API.
_isConcurrentMode2);break;}}}}return shouldUpdate;}function prepareToHydrateHostSuspenseInstance(fiber){var suspenseState=fiber.memoizedState;var suspenseInstance=suspenseState!==null?suspenseState.dehydrated:null;if(!suspenseInstance){throw new Error('Expected to have a hydrated suspense instance. '+'This error is likely caused by a bug in React. Please file an issue.');}hydrateSuspenseInstance(suspenseInstance,fiber);}function skipPastDehydratedSuspenseInstance(fiber){var suspenseState=fiber.memoizedState;var suspenseInstance=suspenseState!==null?suspenseState.dehydrated:null;if(!suspenseInstance){throw new Error('Expected to have a hydrated suspense instance. '+'This error is likely caused by a bug in React. Please file an issue.');}return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);}function popToNextHostParent(fiber){var parent=fiber.return;while(parent!==null&&parent.tag!==HostComponent&&parent.tag!==HostRoot&&parent.tag!==SuspenseComponent){parent=parent.return;}hydrationParentFiber=parent;}function popHydrationState(fiber){if(fiber!==hydrationParentFiber){// We're deeper than the current hydration context, inside an inserted
// tree.
return false;}if(!isHydrating){// If we're not currently hydrating but we're in a hydration context, then
// we were an insertion and now need to pop up reenter hydration of our
// siblings.
popToNextHostParent(fiber);isHydrating=true;return false;}// If we have any remaining hydratable nodes, we need to delete them now.
// We only do this deeper than head and body since they tend to have random
// other nodes in them. We also ignore components with pure text content in
// side of them. We also don't delete anything inside the root container.
if(fiber.tag!==HostRoot&&(fiber.tag!==HostComponent||shouldDeleteUnhydratedTailInstances(fiber.type)&&!shouldSetTextContent(fiber.type,fiber.memoizedProps))){var nextInstance=nextHydratableInstance;if(nextInstance){if(shouldClientRenderOnMismatch(fiber)){warnIfUnhydratedTailNodes(fiber);throwOnHydrationMismatch();}else {while(nextInstance){deleteHydratableInstance(fiber,nextInstance);nextInstance=getNextHydratableSibling(nextInstance);}}}}popToNextHostParent(fiber);if(fiber.tag===SuspenseComponent){nextHydratableInstance=skipPastDehydratedSuspenseInstance(fiber);}else {nextHydratableInstance=hydrationParentFiber?getNextHydratableSibling(fiber.stateNode):null;}return true;}function hasUnhydratedTailNodes(){return isHydrating&&nextHydratableInstance!==null;}function warnIfUnhydratedTailNodes(fiber){var nextInstance=nextHydratableInstance;while(nextInstance){warnUnhydratedInstance(fiber,nextInstance);nextInstance=getNextHydratableSibling(nextInstance);}}function resetHydrationState(){hydrationParentFiber=null;nextHydratableInstance=null;isHydrating=false;didSuspendOrErrorDEV=false;}function upgradeHydrationErrorsToRecoverable(){if(hydrationErrors!==null){// Successfully completed a forced client render. The errors that occurred
// during the hydration attempt are now recovered. We will log them in
// commit phase, once the entire tree has finished.
queueRecoverableErrors(hydrationErrors);hydrationErrors=null;}}function getIsHydrating(){return isHydrating;}function queueHydrationError(error){if(hydrationErrors===null){hydrationErrors=[error];}else {hydrationErrors.push(error);}}var ReactCurrentBatchConfig$1=ReactSharedInternals.ReactCurrentBatchConfig;var NoTransition=null;function requestCurrentTransition(){return ReactCurrentBatchConfig$1.transition;}var ReactStrictModeWarnings={recordUnsafeLifecycleWarnings:function(fiber,instance){},flushPendingUnsafeLifecycleWarnings:function(){},recordLegacyContextWarning:function(fiber,instance){},flushLegacyContextWarning:function(){},discardPendingWarnings:function(){}};{var findStrictRoot=function(fiber){var maybeStrictRoot=null;var node=fiber;while(node!==null){if(node.mode&StrictLegacyMode){maybeStrictRoot=node;}node=node.return;}return maybeStrictRoot;};var setToSortedString=function(set){var array=[];set.forEach(function(value){array.push(value);});return array.sort().join(', ');};var pendingComponentWillMountWarnings=[];var pendingUNSAFE_ComponentWillMountWarnings=[];var pendingComponentWillReceivePropsWarnings=[];var pendingUNSAFE_ComponentWillReceivePropsWarnings=[];var pendingComponentWillUpdateWarnings=[];var pendingUNSAFE_ComponentWillUpdateWarnings=[];// Tracks components we have already warned about.
var didWarnAboutUnsafeLifecycles=new Set();ReactStrictModeWarnings.recordUnsafeLifecycleWarnings=function(fiber,instance){// Dedupe strategy: Warn once per component.
if(didWarnAboutUnsafeLifecycles.has(fiber.type)){return;}if(typeof instance.componentWillMount==='function'&&// Don't warn about react-lifecycles-compat polyfilled components.
instance.componentWillMount.__suppressDeprecationWarning!==true){pendingComponentWillMountWarnings.push(fiber);}if(fiber.mode&StrictLegacyMode&&typeof instance.UNSAFE_componentWillMount==='function'){pendingUNSAFE_ComponentWillMountWarnings.push(fiber);}if(typeof instance.componentWillReceiveProps==='function'&&instance.componentWillReceiveProps.__suppressDeprecationWarning!==true){pendingComponentWillReceivePropsWarnings.push(fiber);}if(fiber.mode&StrictLegacyMode&&typeof instance.UNSAFE_componentWillReceiveProps==='function'){pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);}if(typeof instance.componentWillUpdate==='function'&&instance.componentWillUpdate.__suppressDeprecationWarning!==true){pendingComponentWillUpdateWarnings.push(fiber);}if(fiber.mode&StrictLegacyMode&&typeof instance.UNSAFE_componentWillUpdate==='function'){pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);}};ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings=function(){// We do an initial pass to gather component names
var componentWillMountUniqueNames=new Set();if(pendingComponentWillMountWarnings.length>0){pendingComponentWillMountWarnings.forEach(function(fiber){componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingComponentWillMountWarnings=[];}var UNSAFE_componentWillMountUniqueNames=new Set();if(pendingUNSAFE_ComponentWillMountWarnings.length>0){pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber){UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingUNSAFE_ComponentWillMountWarnings=[];}var componentWillReceivePropsUniqueNames=new Set();if(pendingComponentWillReceivePropsWarnings.length>0){pendingComponentWillReceivePropsWarnings.forEach(function(fiber){componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingComponentWillReceivePropsWarnings=[];}var UNSAFE_componentWillReceivePropsUniqueNames=new Set();if(pendingUNSAFE_ComponentWillReceivePropsWarnings.length>0){pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber){UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingUNSAFE_ComponentWillReceivePropsWarnings=[];}var componentWillUpdateUniqueNames=new Set();if(pendingComponentWillUpdateWarnings.length>0){pendingComponentWillUpdateWarnings.forEach(function(fiber){componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingComponentWillUpdateWarnings=[];}var UNSAFE_componentWillUpdateUniqueNames=new Set();if(pendingUNSAFE_ComponentWillUpdateWarnings.length>0){pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber){UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutUnsafeLifecycles.add(fiber.type);});pendingUNSAFE_ComponentWillUpdateWarnings=[];}// Finally, we flush all the warnings
// UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
if(UNSAFE_componentWillMountUniqueNames.size>0){var sortedNames=setToSortedString(UNSAFE_componentWillMountUniqueNames);error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move code with side effects to componentDidMount, and set initial state in the constructor.\n'+'\nPlease update the following components: %s',sortedNames);}if(UNSAFE_componentWillReceivePropsUniqueNames.size>0){var _sortedNames=setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended '+'and may indicate bugs in your code. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+"* If you're updating state whenever props change, "+'refactor your code to use memoization techniques or move it to '+'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n'+'\nPlease update the following components: %s',_sortedNames);}if(UNSAFE_componentWillUpdateUniqueNames.size>0){var _sortedNames2=setToSortedString(UNSAFE_componentWillUpdateUniqueNames);error('Using UNSAFE_componentWillUpdate in strict mode is not recommended '+'and may indicate bugs in your code. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+'\nPlease update the following components: %s',_sortedNames2);}if(componentWillMountUniqueNames.size>0){var _sortedNames3=setToSortedString(componentWillMountUniqueNames);warn('componentWillMount has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move code with side effects to componentDidMount, and set initial state in the constructor.\n'+'* Rename componentWillMount to UNSAFE_componentWillMount to suppress '+'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. '+'To rename all deprecated lifecycles to their new names, you can run '+'`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n'+'\nPlease update the following components: %s',_sortedNames3);}if(componentWillReceivePropsUniqueNames.size>0){var _sortedNames4=setToSortedString(componentWillReceivePropsUniqueNames);warn('componentWillReceiveProps has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+"* If you're updating state whenever props change, refactor your "+'code to use memoization techniques or move it to '+'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n'+'* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress '+'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. '+'To rename all deprecated lifecycles to their new names, you can run '+'`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n'+'\nPlease update the following components: %s',_sortedNames4);}if(componentWillUpdateUniqueNames.size>0){var _sortedNames5=setToSortedString(componentWillUpdateUniqueNames);warn('componentWillUpdate has been renamed, and is not recommended for use. '+'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n'+'* Move data fetching code or side effects to componentDidUpdate.\n'+'* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress '+'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. '+'To rename all deprecated lifecycles to their new names, you can run '+'`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n'+'\nPlease update the following components: %s',_sortedNames5);}};var pendingLegacyContextWarning=new Map();// Tracks components we have already warned about.
var didWarnAboutLegacyContext=new Set();ReactStrictModeWarnings.recordLegacyContextWarning=function(fiber,instance){var strictRoot=findStrictRoot(fiber);if(strictRoot===null){error('Expected to find a StrictMode component in a strict mode tree. '+'This error is likely caused by a bug in React. Please file an issue.');return;}// Dedup strategy: Warn once per component.
if(didWarnAboutLegacyContext.has(fiber.type)){return;}var warningsForRoot=pendingLegacyContextWarning.get(strictRoot);if(fiber.type.contextTypes!=null||fiber.type.childContextTypes!=null||instance!==null&&typeof instance.getChildContext==='function'){if(warningsForRoot===undefined){warningsForRoot=[];pendingLegacyContextWarning.set(strictRoot,warningsForRoot);}warningsForRoot.push(fiber);}};ReactStrictModeWarnings.flushLegacyContextWarning=function(){pendingLegacyContextWarning.forEach(function(fiberArray,strictRoot){if(fiberArray.length===0){return;}var firstFiber=fiberArray[0];var uniqueNames=new Set();fiberArray.forEach(function(fiber){uniqueNames.add(getComponentNameFromFiber(fiber)||'Component');didWarnAboutLegacyContext.add(fiber.type);});var sortedNames=setToSortedString(uniqueNames);try{setCurrentFiber(firstFiber);error('Legacy context API has been detected within a strict-mode tree.'+'\n\nThe old API will be supported in all 16.x releases, but applications '+'using it should migrate to the new version.'+'\n\nPlease update the following components: %s'+'\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context',sortedNames);}finally{resetCurrentFiber();}});};ReactStrictModeWarnings.discardPendingWarnings=function(){pendingComponentWillMountWarnings=[];pendingUNSAFE_ComponentWillMountWarnings=[];pendingComponentWillReceivePropsWarnings=[];pendingUNSAFE_ComponentWillReceivePropsWarnings=[];pendingComponentWillUpdateWarnings=[];pendingUNSAFE_ComponentWillUpdateWarnings=[];pendingLegacyContextWarning=new Map();};}function resolveDefaultProps(Component,baseProps){if(Component&&Component.defaultProps){// Resolve default props. Taken from ReactElement
var props=assign({},baseProps);var defaultProps=Component.defaultProps;for(var propName in defaultProps){if(props[propName]===undefined){props[propName]=defaultProps[propName];}}return props;}return baseProps;}var valueCursor=createCursor(null);var rendererSigil;{// Use this to detect multiple renderers using the same context
rendererSigil={};}var currentlyRenderingFiber=null;var lastContextDependency=null;var lastFullyObservedContext=null;var isDisallowedContextReadInDEV=false;function resetContextDependencies(){// This is called right before React yields execution, to ensure `readContext`
// cannot be called outside the render phase.
currentlyRenderingFiber=null;lastContextDependency=null;lastFullyObservedContext=null;{isDisallowedContextReadInDEV=false;}}function enterDisallowedContextReadInDEV(){{isDisallowedContextReadInDEV=true;}}function exitDisallowedContextReadInDEV(){{isDisallowedContextReadInDEV=false;}}function pushProvider(providerFiber,context,nextValue){{push(valueCursor,context._currentValue,providerFiber);context._currentValue=nextValue;{if(context._currentRenderer!==undefined&&context._currentRenderer!==null&&context._currentRenderer!==rendererSigil){error('Detected multiple renderers concurrently rendering the '+'same context provider. This is currently unsupported.');}context._currentRenderer=rendererSigil;}}}function popProvider(context,providerFiber){var currentValue=valueCursor.current;pop(valueCursor,providerFiber);{{context._currentValue=currentValue;}}}function scheduleContextWorkOnParentPath(parent,renderLanes,propagationRoot){// Update the child lanes of all the ancestors, including the alternates.
var node=parent;while(node!==null){var alternate=node.alternate;if(!isSubsetOfLanes(node.childLanes,renderLanes)){node.childLanes=mergeLanes(node.childLanes,renderLanes);if(alternate!==null){alternate.childLanes=mergeLanes(alternate.childLanes,renderLanes);}}else if(alternate!==null&&!isSubsetOfLanes(alternate.childLanes,renderLanes)){alternate.childLanes=mergeLanes(alternate.childLanes,renderLanes);}if(node===propagationRoot){break;}node=node.return;}{if(node!==propagationRoot){error('Expected to find the propagation root when scheduling context work. '+'This error is likely caused by a bug in React. Please file an issue.');}}}function propagateContextChange(workInProgress,context,renderLanes){{propagateContextChange_eager(workInProgress,context,renderLanes);}}function propagateContextChange_eager(workInProgress,context,renderLanes){var fiber=workInProgress.child;if(fiber!==null){// Set the return pointer of the child to the work-in-progress fiber.
fiber.return=workInProgress;}while(fiber!==null){var nextFiber=void 0;// Visit this fiber.
var list=fiber.dependencies;if(list!==null){nextFiber=fiber.child;var dependency=list.firstContext;while(dependency!==null){// Check if the context matches.
if(dependency.context===context){// Match! Schedule an update on this fiber.
if(fiber.tag===ClassComponent){// Schedule a force update on the work-in-progress.
var lane=pickArbitraryLane(renderLanes);var update=createUpdate(NoTimestamp,lane);update.tag=ForceUpdate;// TODO: Because we don't have a work-in-progress, this will add the
// update to the current fiber, too, which means it will persist even if
// this render is thrown away. Since it's a race condition, not sure it's
// worth fixing.
// Inlined `enqueueUpdate` to remove interleaved update check
var updateQueue=fiber.updateQueue;if(updateQueue===null);else {var sharedQueue=updateQueue.shared;var pending=sharedQueue.pending;if(pending===null){// This is the first update. Create a circular list.
update.next=update;}else {update.next=pending.next;pending.next=update;}sharedQueue.pending=update;}}fiber.lanes=mergeLanes(fiber.lanes,renderLanes);var alternate=fiber.alternate;if(alternate!==null){alternate.lanes=mergeLanes(alternate.lanes,renderLanes);}scheduleContextWorkOnParentPath(fiber.return,renderLanes,workInProgress);// Mark the updated lanes on the list, too.
list.lanes=mergeLanes(list.lanes,renderLanes);// Since we already found a match, we can stop traversing the
// dependency list.
break;}dependency=dependency.next;}}else if(fiber.tag===ContextProvider){// Don't scan deeper if this is a matching provider
nextFiber=fiber.type===workInProgress.type?null:fiber.child;}else if(fiber.tag===DehydratedFragment){// If a dehydrated suspense boundary is in this subtree, we don't know
// if it will have any context consumers in it. The best we can do is
// mark it as having updates.
var parentSuspense=fiber.return;if(parentSuspense===null){throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.');}parentSuspense.lanes=mergeLanes(parentSuspense.lanes,renderLanes);var _alternate=parentSuspense.alternate;if(_alternate!==null){_alternate.lanes=mergeLanes(_alternate.lanes,renderLanes);}// This is intentionally passing this fiber as the parent
// because we want to schedule this fiber as having work
// on its children. We'll use the childLanes on
// this fiber to indicate that a context has changed.
scheduleContextWorkOnParentPath(parentSuspense,renderLanes,workInProgress);nextFiber=fiber.sibling;}else {// Traverse down.
nextFiber=fiber.child;}if(nextFiber!==null){// Set the return pointer of the child to the work-in-progress fiber.
nextFiber.return=fiber;}else {// No child. Traverse to next sibling.
nextFiber=fiber;while(nextFiber!==null){if(nextFiber===workInProgress){// We're back to the root of this subtree. Exit.
nextFiber=null;break;}var sibling=nextFiber.sibling;if(sibling!==null){// Set the return pointer of the sibling to the work-in-progress fiber.
sibling.return=nextFiber.return;nextFiber=sibling;break;}// No more siblings. Traverse up.
nextFiber=nextFiber.return;}}fiber=nextFiber;}}function prepareToReadContext(workInProgress,renderLanes){currentlyRenderingFiber=workInProgress;lastContextDependency=null;lastFullyObservedContext=null;var dependencies=workInProgress.dependencies;if(dependencies!==null){{var firstContext=dependencies.firstContext;if(firstContext!==null){if(includesSomeLane(dependencies.lanes,renderLanes)){// Context list has a pending update. Mark that this fiber performed work.
markWorkInProgressReceivedUpdate();}// Reset the work-in-progress list
dependencies.firstContext=null;}}}}function readContext(context){{// This warning would fire if you read context inside a Hook like useMemo.
// Unlike the class check below, it's not enforced in production for perf.
if(isDisallowedContextReadInDEV){error('Context can only be read while React is rendering. '+'In classes, you can read it in the render method or getDerivedStateFromProps. '+'In function components, you can read it directly in the function body, but not '+'inside Hooks like useReducer() or useMemo().');}}var value=context._currentValue;if(lastFullyObservedContext===context);else {var contextItem={context:context,memoizedValue:value,next:null};if(lastContextDependency===null){if(currentlyRenderingFiber===null){throw new Error('Context can only be read while React is rendering. '+'In classes, you can read it in the render method or getDerivedStateFromProps. '+'In function components, you can read it directly in the function body, but not '+'inside Hooks like useReducer() or useMemo().');}// This is the first dependency for this component. Create a new list.
lastContextDependency=contextItem;currentlyRenderingFiber.dependencies={lanes:NoLanes,firstContext:contextItem};}else {// Append a new context item.
lastContextDependency=lastContextDependency.next=contextItem;}}return value;}// render. When this render exits, either because it finishes or because it is
// interrupted, the interleaved updates will be transferred onto the main part
// of the queue.
var concurrentQueues=null;function pushConcurrentUpdateQueue(queue){if(concurrentQueues===null){concurrentQueues=[queue];}else {concurrentQueues.push(queue);}}function finishQueueingConcurrentUpdates(){// Transfer the interleaved updates onto the main queue. Each queue has a
// `pending` field and an `interleaved` field. When they are not null, they
// point to the last node in a circular linked list. We need to append the
// interleaved list to the end of the pending list by joining them into a
// single, circular list.
if(concurrentQueues!==null){for(var i=0;i<concurrentQueues.length;i++){var queue=concurrentQueues[i];var lastInterleavedUpdate=queue.interleaved;if(lastInterleavedUpdate!==null){queue.interleaved=null;var firstInterleavedUpdate=lastInterleavedUpdate.next;var lastPendingUpdate=queue.pending;if(lastPendingUpdate!==null){var firstPendingUpdate=lastPendingUpdate.next;lastPendingUpdate.next=firstInterleavedUpdate;lastInterleavedUpdate.next=firstPendingUpdate;}queue.pending=lastInterleavedUpdate;}}concurrentQueues=null;}}function enqueueConcurrentHookUpdate(fiber,queue,update,lane){var interleaved=queue.interleaved;if(interleaved===null){// This is the first update. Create a circular list.
update.next=update;// At the end of the current render, this queue's interleaved updates will
// be transferred to the pending queue.
pushConcurrentUpdateQueue(queue);}else {update.next=interleaved.next;interleaved.next=update;}queue.interleaved=update;return markUpdateLaneFromFiberToRoot(fiber,lane);}function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber,queue,update,lane){var interleaved=queue.interleaved;if(interleaved===null){// This is the first update. Create a circular list.
update.next=update;// At the end of the current render, this queue's interleaved updates will
// be transferred to the pending queue.
pushConcurrentUpdateQueue(queue);}else {update.next=interleaved.next;interleaved.next=update;}queue.interleaved=update;}function enqueueConcurrentClassUpdate(fiber,queue,update,lane){var interleaved=queue.interleaved;if(interleaved===null){// This is the first update. Create a circular list.
update.next=update;// At the end of the current render, this queue's interleaved updates will
// be transferred to the pending queue.
pushConcurrentUpdateQueue(queue);}else {update.next=interleaved.next;interleaved.next=update;}queue.interleaved=update;return markUpdateLaneFromFiberToRoot(fiber,lane);}function enqueueConcurrentRenderForLane(fiber,lane){return markUpdateLaneFromFiberToRoot(fiber,lane);}// Calling this function outside this module should only be done for backwards
// compatibility and should always be accompanied by a warning.
var unsafe_markUpdateLaneFromFiberToRoot=markUpdateLaneFromFiberToRoot;function markUpdateLaneFromFiberToRoot(sourceFiber,lane){// Update the source fiber's lanes
sourceFiber.lanes=mergeLanes(sourceFiber.lanes,lane);var alternate=sourceFiber.alternate;if(alternate!==null){alternate.lanes=mergeLanes(alternate.lanes,lane);}{if(alternate===null&&(sourceFiber.flags&(Placement|Hydrating))!==NoFlags){warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);}}// Walk the parent path to the root and update the child lanes.
var node=sourceFiber;var parent=sourceFiber.return;while(parent!==null){parent.childLanes=mergeLanes(parent.childLanes,lane);alternate=parent.alternate;if(alternate!==null){alternate.childLanes=mergeLanes(alternate.childLanes,lane);}else {{if((parent.flags&(Placement|Hydrating))!==NoFlags){warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);}}}node=parent;parent=parent.return;}if(node.tag===HostRoot){var root=node.stateNode;return root;}else {return null;}}var UpdateState=0;var ReplaceState=1;var ForceUpdate=2;var CaptureUpdate=3;// Global state that is reset at the beginning of calling `processUpdateQueue`.
// It should only be read right after calling `processUpdateQueue`, via
// `checkHasForceUpdateAfterProcessing`.
var hasForceUpdate=false;var didWarnUpdateInsideUpdate;var currentlyProcessingQueue;{didWarnUpdateInsideUpdate=false;currentlyProcessingQueue=null;}function initializeUpdateQueue(fiber){var queue={baseState:fiber.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:NoLanes},effects:null};fiber.updateQueue=queue;}function cloneUpdateQueue(current,workInProgress){// Clone the update queue from current. Unless it's already a clone.
var queue=workInProgress.updateQueue;var currentQueue=current.updateQueue;if(queue===currentQueue){var clone={baseState:currentQueue.baseState,firstBaseUpdate:currentQueue.firstBaseUpdate,lastBaseUpdate:currentQueue.lastBaseUpdate,shared:currentQueue.shared,effects:currentQueue.effects};workInProgress.updateQueue=clone;}}function createUpdate(eventTime,lane){var update={eventTime:eventTime,lane:lane,tag:UpdateState,payload:null,callback:null,next:null};return update;}function enqueueUpdate(fiber,update,lane){var updateQueue=fiber.updateQueue;if(updateQueue===null){// Only occurs if the fiber has been unmounted.
return null;}var sharedQueue=updateQueue.shared;{if(currentlyProcessingQueue===sharedQueue&&!didWarnUpdateInsideUpdate){error('An update (setState, replaceState, or forceUpdate) was scheduled '+'from inside an update function. Update functions should be pure, '+'with zero side-effects. Consider using componentDidUpdate or a '+'callback.');didWarnUpdateInsideUpdate=true;}}if(isUnsafeClassRenderPhaseUpdate()){// This is an unsafe render phase update. Add directly to the update
// queue so we can process it immediately during the current render.
var pending=sharedQueue.pending;if(pending===null){// This is the first update. Create a circular list.
update.next=update;}else {update.next=pending.next;pending.next=update;}sharedQueue.pending=update;// Update the childLanes even though we're most likely already rendering
// this fiber. This is for backwards compatibility in the case where you
// update a different component during render phase than the one that is
// currently renderings (a pattern that is accompanied by a warning).
return unsafe_markUpdateLaneFromFiberToRoot(fiber,lane);}else {return enqueueConcurrentClassUpdate(fiber,sharedQueue,update,lane);}}function entangleTransitions(root,fiber,lane){var updateQueue=fiber.updateQueue;if(updateQueue===null){// Only occurs if the fiber has been unmounted.
return;}var sharedQueue=updateQueue.shared;if(isTransitionLane(lane)){var queueLanes=sharedQueue.lanes;// If any entangled lanes are no longer pending on the root, then they must
// have finished. We can remove them from the shared queue, which represents
// a superset of the actually pending lanes. In some cases we may entangle
// more than we need to, but that's OK. In fact it's worse if we *don't*
// entangle when we should.
queueLanes=intersectLanes(queueLanes,root.pendingLanes);// Entangle the new transition lane with the other transition lanes.
var newQueueLanes=mergeLanes(queueLanes,lane);sharedQueue.lanes=newQueueLanes;// Even if queue.lanes already include lane, we don't know for certain if
// the lane finished since the last time we entangled it. So we need to
// entangle it again, just to be sure.
markRootEntangled(root,newQueueLanes);}}function enqueueCapturedUpdate(workInProgress,capturedUpdate){// Captured updates are updates that are thrown by a child during the render
// phase. They should be discarded if the render is aborted. Therefore,
// we should only put them on the work-in-progress queue, not the current one.
var queue=workInProgress.updateQueue;// Check if the work-in-progress queue is a clone.
var current=workInProgress.alternate;if(current!==null){var currentQueue=current.updateQueue;if(queue===currentQueue){// The work-in-progress queue is the same as current. This happens when
// we bail out on a parent fiber that then captures an error thrown by
// a child. Since we want to append the update only to the work-in
// -progress queue, we need to clone the updates. We usually clone during
// processUpdateQueue, but that didn't happen in this case because we
// skipped over the parent when we bailed out.
var newFirst=null;var newLast=null;var firstBaseUpdate=queue.firstBaseUpdate;if(firstBaseUpdate!==null){// Loop through the updates and clone them.
var update=firstBaseUpdate;do{var clone={eventTime:update.eventTime,lane:update.lane,tag:update.tag,payload:update.payload,callback:update.callback,next:null};if(newLast===null){newFirst=newLast=clone;}else {newLast.next=clone;newLast=clone;}update=update.next;}while(update!==null);// Append the captured update the end of the cloned list.
if(newLast===null){newFirst=newLast=capturedUpdate;}else {newLast.next=capturedUpdate;newLast=capturedUpdate;}}else {// There are no base updates.
newFirst=newLast=capturedUpdate;}queue={baseState:currentQueue.baseState,firstBaseUpdate:newFirst,lastBaseUpdate:newLast,shared:currentQueue.shared,effects:currentQueue.effects};workInProgress.updateQueue=queue;return;}}// Append the update to the end of the list.
var lastBaseUpdate=queue.lastBaseUpdate;if(lastBaseUpdate===null){queue.firstBaseUpdate=capturedUpdate;}else {lastBaseUpdate.next=capturedUpdate;}queue.lastBaseUpdate=capturedUpdate;}function getStateFromUpdate(workInProgress,queue,update,prevState,nextProps,instance){switch(update.tag){case ReplaceState:{var payload=update.payload;if(typeof payload==='function'){// Updater function
{enterDisallowedContextReadInDEV();}var nextState=payload.call(instance,prevState,nextProps);{if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{payload.call(instance,prevState,nextProps);}finally{setIsStrictModeForDevtools(false);}}exitDisallowedContextReadInDEV();}return nextState;}// State object
return payload;}case CaptureUpdate:{workInProgress.flags=workInProgress.flags&~ShouldCapture|DidCapture;}// Intentional fallthrough
case UpdateState:{var _payload=update.payload;var partialState;if(typeof _payload==='function'){// Updater function
{enterDisallowedContextReadInDEV();}partialState=_payload.call(instance,prevState,nextProps);{if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{_payload.call(instance,prevState,nextProps);}finally{setIsStrictModeForDevtools(false);}}exitDisallowedContextReadInDEV();}}else {// Partial state object
partialState=_payload;}if(partialState===null||partialState===undefined){// Null and undefined are treated as no-ops.
return prevState;}// Merge the partial state and the previous state.
return assign({},prevState,partialState);}case ForceUpdate:{hasForceUpdate=true;return prevState;}}return prevState;}function processUpdateQueue(workInProgress,props,instance,renderLanes){// This is always non-null on a ClassComponent or HostRoot
var queue=workInProgress.updateQueue;hasForceUpdate=false;{currentlyProcessingQueue=queue.shared;}var firstBaseUpdate=queue.firstBaseUpdate;var lastBaseUpdate=queue.lastBaseUpdate;// Check if there are pending updates. If so, transfer them to the base queue.
var pendingQueue=queue.shared.pending;if(pendingQueue!==null){queue.shared.pending=null;// The pending queue is circular. Disconnect the pointer between first
// and last so that it's non-circular.
var lastPendingUpdate=pendingQueue;var firstPendingUpdate=lastPendingUpdate.next;lastPendingUpdate.next=null;// Append pending updates to base queue
if(lastBaseUpdate===null){firstBaseUpdate=firstPendingUpdate;}else {lastBaseUpdate.next=firstPendingUpdate;}lastBaseUpdate=lastPendingUpdate;// If there's a current queue, and it's different from the base queue, then
// we need to transfer the updates to that queue, too. Because the base
// queue is a singly-linked list with no cycles, we can append to both
// lists and take advantage of structural sharing.
// TODO: Pass `current` as argument
var current=workInProgress.alternate;if(current!==null){// This is always non-null on a ClassComponent or HostRoot
var currentQueue=current.updateQueue;var currentLastBaseUpdate=currentQueue.lastBaseUpdate;if(currentLastBaseUpdate!==lastBaseUpdate){if(currentLastBaseUpdate===null){currentQueue.firstBaseUpdate=firstPendingUpdate;}else {currentLastBaseUpdate.next=firstPendingUpdate;}currentQueue.lastBaseUpdate=lastPendingUpdate;}}}// These values may change as we process the queue.
if(firstBaseUpdate!==null){// Iterate through the list of updates to compute the result.
var newState=queue.baseState;// TODO: Don't need to accumulate this. Instead, we can remove renderLanes
// from the original lanes.
var newLanes=NoLanes;var newBaseState=null;var newFirstBaseUpdate=null;var newLastBaseUpdate=null;var update=firstBaseUpdate;do{var updateLane=update.lane;var updateEventTime=update.eventTime;if(!isSubsetOfLanes(renderLanes,updateLane)){// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
var clone={eventTime:updateEventTime,lane:updateLane,tag:update.tag,payload:update.payload,callback:update.callback,next:null};if(newLastBaseUpdate===null){newFirstBaseUpdate=newLastBaseUpdate=clone;newBaseState=newState;}else {newLastBaseUpdate=newLastBaseUpdate.next=clone;}// Update the remaining priority in the queue.
newLanes=mergeLanes(newLanes,updateLane);}else {// This update does have sufficient priority.
if(newLastBaseUpdate!==null){var _clone={eventTime:updateEventTime,// This update is going to be committed so we never want uncommit
// it. Using NoLane works because 0 is a subset of all bitmasks, so
// this will never be skipped by the check above.
lane:NoLane,tag:update.tag,payload:update.payload,callback:update.callback,next:null};newLastBaseUpdate=newLastBaseUpdate.next=_clone;}// Process this update.
newState=getStateFromUpdate(workInProgress,queue,update,newState,props,instance);var callback=update.callback;if(callback!==null&&// If the update was already committed, we should not queue its
// callback again.
update.lane!==NoLane){workInProgress.flags|=Callback;var effects=queue.effects;if(effects===null){queue.effects=[update];}else {effects.push(update);}}}update=update.next;if(update===null){pendingQueue=queue.shared.pending;if(pendingQueue===null){break;}else {// An update was scheduled from inside a reducer. Add the new
// pending updates to the end of the list and keep processing.
var _lastPendingUpdate=pendingQueue;// Intentionally unsound. Pending updates form a circular list, but we
// unravel them when transferring them to the base queue.
var _firstPendingUpdate=_lastPendingUpdate.next;_lastPendingUpdate.next=null;update=_firstPendingUpdate;queue.lastBaseUpdate=_lastPendingUpdate;queue.shared.pending=null;}}}while(true);if(newLastBaseUpdate===null){newBaseState=newState;}queue.baseState=newBaseState;queue.firstBaseUpdate=newFirstBaseUpdate;queue.lastBaseUpdate=newLastBaseUpdate;// Interleaved updates are stored on a separate queue. We aren't going to
// process them during this render, but we do need to track which lanes
// are remaining.
var lastInterleaved=queue.shared.interleaved;if(lastInterleaved!==null){var interleaved=lastInterleaved;do{newLanes=mergeLanes(newLanes,interleaved.lane);interleaved=interleaved.next;}while(interleaved!==lastInterleaved);}else if(firstBaseUpdate===null){// `queue.lanes` is used for entangling transitions. We can set it back to
// zero once the queue is empty.
queue.shared.lanes=NoLanes;}// Set the remaining expiration time to be whatever is remaining in the queue.
// This should be fine because the only two other things that contribute to
// expiration time are props and context. We're already in the middle of the
// begin phase by the time we start processing the queue, so we've already
// dealt with the props. Context in components that specify
// shouldComponentUpdate is tricky; but we'll have to account for
// that regardless.
markSkippedUpdateLanes(newLanes);workInProgress.lanes=newLanes;workInProgress.memoizedState=newState;}{currentlyProcessingQueue=null;}}function callCallback(callback,context){if(typeof callback!=='function'){throw new Error('Invalid argument passed as callback. Expected a function. Instead '+("received: "+callback));}callback.call(context);}function resetHasForceUpdateBeforeProcessing(){hasForceUpdate=false;}function checkHasForceUpdateAfterProcessing(){return hasForceUpdate;}function commitUpdateQueue(finishedWork,finishedQueue,instance){// Commit the effects
var effects=finishedQueue.effects;finishedQueue.effects=null;if(effects!==null){for(var i=0;i<effects.length;i++){var effect=effects[i];var callback=effect.callback;if(callback!==null){effect.callback=null;callCallback(callback,instance);}}}}var fakeInternalInstance={};// React.Component uses a shared frozen object by default.
// We'll use it to determine whether we need to initialize legacy refs.
var emptyRefsObject=new React.Component().refs;var didWarnAboutStateAssignmentForComponent;var didWarnAboutUninitializedState;var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;var didWarnAboutLegacyLifecyclesAndDerivedState;var didWarnAboutUndefinedDerivedState;var warnOnUndefinedDerivedState;var warnOnInvalidCallback;var didWarnAboutDirectlyAssigningPropsToState;var didWarnAboutContextTypeAndContextTypes;var didWarnAboutInvalidateContextType;{didWarnAboutStateAssignmentForComponent=new Set();didWarnAboutUninitializedState=new Set();didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate=new Set();didWarnAboutLegacyLifecyclesAndDerivedState=new Set();didWarnAboutDirectlyAssigningPropsToState=new Set();didWarnAboutUndefinedDerivedState=new Set();didWarnAboutContextTypeAndContextTypes=new Set();didWarnAboutInvalidateContextType=new Set();var didWarnOnInvalidCallback=new Set();warnOnInvalidCallback=function(callback,callerName){if(callback===null||typeof callback==='function'){return;}var key=callerName+'_'+callback;if(!didWarnOnInvalidCallback.has(key)){didWarnOnInvalidCallback.add(key);error('%s(...): Expected the last optional `callback` argument to be a '+'function. Instead received: %s.',callerName,callback);}};warnOnUndefinedDerivedState=function(type,partialState){if(partialState===undefined){var componentName=getComponentNameFromType(type)||'Component';if(!didWarnAboutUndefinedDerivedState.has(componentName)){didWarnAboutUndefinedDerivedState.add(componentName);error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. '+'You have returned undefined.',componentName);}}};// This is so gross but it's at least non-critical and can be removed if
// it causes problems. This is meant to give a nicer error message for
// ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
// ...)) which otherwise throws a "_processChildContext is not a function"
// exception.
Object.defineProperty(fakeInternalInstance,'_processChildContext',{enumerable:false,value:function(){throw new Error('_processChildContext is not available in React 16+. This likely '+'means you have multiple copies of React and are attempting to nest '+'a React 15 tree inside a React 16 tree using '+"unstable_renderSubtreeIntoContainer, which isn't supported. Try "+'to make sure you have only one copy of React (and ideally, switch '+'to ReactDOM.createPortal).');}});Object.freeze(fakeInternalInstance);}function applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,nextProps){var prevState=workInProgress.memoizedState;var partialState=getDerivedStateFromProps(nextProps,prevState);{if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{// Invoke the function an extra time to help detect side-effects.
partialState=getDerivedStateFromProps(nextProps,prevState);}finally{setIsStrictModeForDevtools(false);}}warnOnUndefinedDerivedState(ctor,partialState);}// Merge the partial state and the previous state.
var memoizedState=partialState===null||partialState===undefined?prevState:assign({},prevState,partialState);workInProgress.memoizedState=memoizedState;// Once the update queue is empty, persist the derived state onto the
// base state.
if(workInProgress.lanes===NoLanes){// Queue is always non-null for classes
var updateQueue=workInProgress.updateQueue;updateQueue.baseState=memoizedState;}}var classComponentUpdater={isMounted:isMounted,enqueueSetState:function(inst,payload,callback){var fiber=get(inst);var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update=createUpdate(eventTime,lane);update.payload=payload;if(callback!==undefined&&callback!==null){{warnOnInvalidCallback(callback,'setState');}update.callback=callback;}var root=enqueueUpdate(fiber,update,lane);if(root!==null){scheduleUpdateOnFiber(root,fiber,lane,eventTime);entangleTransitions(root,fiber,lane);}{markStateUpdateScheduled(fiber,lane);}},enqueueReplaceState:function(inst,payload,callback){var fiber=get(inst);var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update=createUpdate(eventTime,lane);update.tag=ReplaceState;update.payload=payload;if(callback!==undefined&&callback!==null){{warnOnInvalidCallback(callback,'replaceState');}update.callback=callback;}var root=enqueueUpdate(fiber,update,lane);if(root!==null){scheduleUpdateOnFiber(root,fiber,lane,eventTime);entangleTransitions(root,fiber,lane);}{markStateUpdateScheduled(fiber,lane);}},enqueueForceUpdate:function(inst,callback){var fiber=get(inst);var eventTime=requestEventTime();var lane=requestUpdateLane(fiber);var update=createUpdate(eventTime,lane);update.tag=ForceUpdate;if(callback!==undefined&&callback!==null){{warnOnInvalidCallback(callback,'forceUpdate');}update.callback=callback;}var root=enqueueUpdate(fiber,update,lane);if(root!==null){scheduleUpdateOnFiber(root,fiber,lane,eventTime);entangleTransitions(root,fiber,lane);}{markForceUpdateScheduled(fiber,lane);}}};function checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext){var instance=workInProgress.stateNode;if(typeof instance.shouldComponentUpdate==='function'){var shouldUpdate=instance.shouldComponentUpdate(newProps,newState,nextContext);{if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{// Invoke the function an extra time to help detect side-effects.
shouldUpdate=instance.shouldComponentUpdate(newProps,newState,nextContext);}finally{setIsStrictModeForDevtools(false);}}if(shouldUpdate===undefined){error('%s.shouldComponentUpdate(): Returned undefined instead of a '+'boolean value. Make sure to return true or false.',getComponentNameFromType(ctor)||'Component');}}return shouldUpdate;}if(ctor.prototype&&ctor.prototype.isPureReactComponent){return !shallowEqual(oldProps,newProps)||!shallowEqual(oldState,newState);}return true;}function checkClassInstance(workInProgress,ctor,newProps){var instance=workInProgress.stateNode;{var name=getComponentNameFromType(ctor)||'Component';var renderPresent=instance.render;if(!renderPresent){if(ctor.prototype&&typeof ctor.prototype.render==='function'){error('%s(...): No `render` method found on the returned component '+'instance: did you accidentally return an object from the constructor?',name);}else {error('%s(...): No `render` method found on the returned component '+'instance: you may have forgotten to define `render`.',name);}}if(instance.getInitialState&&!instance.getInitialState.isReactClassApproved&&!instance.state){error('getInitialState was defined on %s, a plain JavaScript class. '+'This is only supported for classes created using React.createClass. '+'Did you mean to define a state property instead?',name);}if(instance.getDefaultProps&&!instance.getDefaultProps.isReactClassApproved){error('getDefaultProps was defined on %s, a plain JavaScript class. '+'This is only supported for classes created using React.createClass. '+'Use a static property to define defaultProps instead.',name);}if(instance.propTypes){error('propTypes was defined as an instance property on %s. Use a static '+'property to define propTypes instead.',name);}if(instance.contextType){error('contextType was defined as an instance property on %s. Use a static '+'property to define contextType instead.',name);}{if(instance.contextTypes){error('contextTypes was defined as an instance property on %s. Use a static '+'property to define contextTypes instead.',name);}if(ctor.contextType&&ctor.contextTypes&&!didWarnAboutContextTypeAndContextTypes.has(ctor)){didWarnAboutContextTypeAndContextTypes.add(ctor);error('%s declares both contextTypes and contextType static properties. '+'The legacy contextTypes property will be ignored.',name);}}if(typeof instance.componentShouldUpdate==='function'){error('%s has a method called '+'componentShouldUpdate(). Did you mean shouldComponentUpdate()? '+'The name is phrased as a question because the function is '+'expected to return a value.',name);}if(ctor.prototype&&ctor.prototype.isPureReactComponent&&typeof instance.shouldComponentUpdate!=='undefined'){error('%s has a method called shouldComponentUpdate(). '+'shouldComponentUpdate should not be used when extending React.PureComponent. '+'Please extend React.Component if shouldComponentUpdate is used.',getComponentNameFromType(ctor)||'A pure component');}if(typeof instance.componentDidUnmount==='function'){error('%s has a method called '+'componentDidUnmount(). But there is no such lifecycle method. '+'Did you mean componentWillUnmount()?',name);}if(typeof instance.componentDidReceiveProps==='function'){error('%s has a method called '+'componentDidReceiveProps(). But there is no such lifecycle method. '+'If you meant to update the state in response to changing props, '+'use componentWillReceiveProps(). If you meant to fetch data or '+'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',name);}if(typeof instance.componentWillRecieveProps==='function'){error('%s has a method called '+'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',name);}if(typeof instance.UNSAFE_componentWillRecieveProps==='function'){error('%s has a method called '+'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?',name);}var hasMutatedProps=instance.props!==newProps;if(instance.props!==undefined&&hasMutatedProps){error('%s(...): When calling super() in `%s`, make sure to pass '+"up the same props that your component's constructor was passed.",name,name);}if(instance.defaultProps){error('Setting defaultProps as an instance property on %s is not supported and will be ignored.'+' Instead, define defaultProps as a static property on %s.',name,name);}if(typeof instance.getSnapshotBeforeUpdate==='function'&&typeof instance.componentDidUpdate!=='function'&&!didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)){didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). '+'This component defines getSnapshotBeforeUpdate() only.',getComponentNameFromType(ctor));}if(typeof instance.getDerivedStateFromProps==='function'){error('%s: getDerivedStateFromProps() is defined as an instance method '+'and will be ignored. Instead, declare it as a static method.',name);}if(typeof instance.getDerivedStateFromError==='function'){error('%s: getDerivedStateFromError() is defined as an instance method '+'and will be ignored. Instead, declare it as a static method.',name);}if(typeof ctor.getSnapshotBeforeUpdate==='function'){error('%s: getSnapshotBeforeUpdate() is defined as a static method '+'and will be ignored. Instead, declare it as an instance method.',name);}var _state=instance.state;if(_state&&(typeof _state!=='object'||isArray(_state))){error('%s.state: must be set to an object or null',name);}if(typeof instance.getChildContext==='function'&&typeof ctor.childContextTypes!=='object'){error('%s.getChildContext(): childContextTypes must be defined in order to '+'use getChildContext().',name);}}}function adoptClassInstance(workInProgress,instance){instance.updater=classComponentUpdater;workInProgress.stateNode=instance;// The instance needs access to the fiber so that it can schedule updates
set(instance,workInProgress);{instance._reactInternalInstance=fakeInternalInstance;}}function constructClassInstance(workInProgress,ctor,props){var isLegacyContextConsumer=false;var unmaskedContext=emptyContextObject;var context=emptyContextObject;var contextType=ctor.contextType;{if('contextType'in ctor){var isValid=// Allow null for conditional declaration
contextType===null||contextType!==undefined&&contextType.$$typeof===REACT_CONTEXT_TYPE&&contextType._context===undefined;// Not a <Context.Consumer>
if(!isValid&&!didWarnAboutInvalidateContextType.has(ctor)){didWarnAboutInvalidateContextType.add(ctor);var addendum='';if(contextType===undefined){addendum=' However, it is set to undefined. '+'This can be caused by a typo or by mixing up named and default imports. '+'This can also happen due to a circular dependency, so '+'try moving the createContext() call to a separate file.';}else if(typeof contextType!=='object'){addendum=' However, it is set to a '+typeof contextType+'.';}else if(contextType.$$typeof===REACT_PROVIDER_TYPE){addendum=' Did you accidentally pass the Context.Provider instead?';}else if(contextType._context!==undefined){// <Context.Consumer>
addendum=' Did you accidentally pass the Context.Consumer instead?';}else {addendum=' However, it is set to an object with keys {'+Object.keys(contextType).join(', ')+'}.';}error('%s defines an invalid contextType. '+'contextType should point to the Context object returned by React.createContext().%s',getComponentNameFromType(ctor)||'Component',addendum);}}}if(typeof contextType==='object'&&contextType!==null){context=readContext(contextType);}else {unmaskedContext=getUnmaskedContext(workInProgress,ctor,true);var contextTypes=ctor.contextTypes;isLegacyContextConsumer=contextTypes!==null&&contextTypes!==undefined;context=isLegacyContextConsumer?getMaskedContext(workInProgress,unmaskedContext):emptyContextObject;}var instance=new ctor(props,context);// Instantiate twice to help detect side-effects.
{if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{instance=new ctor(props,context);// eslint-disable-line no-new
}finally{setIsStrictModeForDevtools(false);}}}var state=workInProgress.memoizedState=instance.state!==null&&instance.state!==undefined?instance.state:null;adoptClassInstance(workInProgress,instance);{if(typeof ctor.getDerivedStateFromProps==='function'&&state===null){var componentName=getComponentNameFromType(ctor)||'Component';if(!didWarnAboutUninitializedState.has(componentName)){didWarnAboutUninitializedState.add(componentName);error('`%s` uses `getDerivedStateFromProps` but its initial state is '+'%s. This is not recommended. Instead, define the initial state by '+'assigning an object to `this.state` in the constructor of `%s`. '+'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.',componentName,instance.state===null?'null':'undefined',componentName);}}// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Warn about these lifecycles if they are present.
// Don't warn about react-lifecycles-compat polyfilled methods though.
if(typeof ctor.getDerivedStateFromProps==='function'||typeof instance.getSnapshotBeforeUpdate==='function'){var foundWillMountName=null;var foundWillReceivePropsName=null;var foundWillUpdateName=null;if(typeof instance.componentWillMount==='function'&&instance.componentWillMount.__suppressDeprecationWarning!==true){foundWillMountName='componentWillMount';}else if(typeof instance.UNSAFE_componentWillMount==='function'){foundWillMountName='UNSAFE_componentWillMount';}if(typeof instance.componentWillReceiveProps==='function'&&instance.componentWillReceiveProps.__suppressDeprecationWarning!==true){foundWillReceivePropsName='componentWillReceiveProps';}else if(typeof instance.UNSAFE_componentWillReceiveProps==='function'){foundWillReceivePropsName='UNSAFE_componentWillReceiveProps';}if(typeof instance.componentWillUpdate==='function'&&instance.componentWillUpdate.__suppressDeprecationWarning!==true){foundWillUpdateName='componentWillUpdate';}else if(typeof instance.UNSAFE_componentWillUpdate==='function'){foundWillUpdateName='UNSAFE_componentWillUpdate';}if(foundWillMountName!==null||foundWillReceivePropsName!==null||foundWillUpdateName!==null){var _componentName=getComponentNameFromType(ctor)||'Component';var newApiName=typeof ctor.getDerivedStateFromProps==='function'?'getDerivedStateFromProps()':'getSnapshotBeforeUpdate()';if(!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)){didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n'+'%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n'+'The above lifecycles should be removed. Learn more about this warning here:\n'+'https://reactjs.org/link/unsafe-component-lifecycles',_componentName,newApiName,foundWillMountName!==null?"\n  "+foundWillMountName:'',foundWillReceivePropsName!==null?"\n  "+foundWillReceivePropsName:'',foundWillUpdateName!==null?"\n  "+foundWillUpdateName:'');}}}}// Cache unmasked context so we can avoid recreating masked context unless necessary.
// ReactFiberContext usually updates this cache but can't for newly-created instances.
if(isLegacyContextConsumer){cacheContext(workInProgress,unmaskedContext,context);}return instance;}function callComponentWillMount(workInProgress,instance){var oldState=instance.state;if(typeof instance.componentWillMount==='function'){instance.componentWillMount();}if(typeof instance.UNSAFE_componentWillMount==='function'){instance.UNSAFE_componentWillMount();}if(oldState!==instance.state){{error('%s.componentWillMount(): Assigning directly to this.state is '+"deprecated (except inside a component's "+'constructor). Use setState instead.',getComponentNameFromFiber(workInProgress)||'Component');}classComponentUpdater.enqueueReplaceState(instance,instance.state,null);}}function callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext){var oldState=instance.state;if(typeof instance.componentWillReceiveProps==='function'){instance.componentWillReceiveProps(newProps,nextContext);}if(typeof instance.UNSAFE_componentWillReceiveProps==='function'){instance.UNSAFE_componentWillReceiveProps(newProps,nextContext);}if(instance.state!==oldState){{var componentName=getComponentNameFromFiber(workInProgress)||'Component';if(!didWarnAboutStateAssignmentForComponent.has(componentName)){didWarnAboutStateAssignmentForComponent.add(componentName);error('%s.componentWillReceiveProps(): Assigning directly to '+"this.state is deprecated (except inside a component's "+'constructor). Use setState instead.',componentName);}}classComponentUpdater.enqueueReplaceState(instance,instance.state,null);}}// Invokes the mount life-cycles on a previously never rendered instance.
function mountClassInstance(workInProgress,ctor,newProps,renderLanes){{checkClassInstance(workInProgress,ctor,newProps);}var instance=workInProgress.stateNode;instance.props=newProps;instance.state=workInProgress.memoizedState;instance.refs=emptyRefsObject;initializeUpdateQueue(workInProgress);var contextType=ctor.contextType;if(typeof contextType==='object'&&contextType!==null){instance.context=readContext(contextType);}else {var unmaskedContext=getUnmaskedContext(workInProgress,ctor,true);instance.context=getMaskedContext(workInProgress,unmaskedContext);}{if(instance.state===newProps){var componentName=getComponentNameFromType(ctor)||'Component';if(!didWarnAboutDirectlyAssigningPropsToState.has(componentName)){didWarnAboutDirectlyAssigningPropsToState.add(componentName);error('%s: It is not recommended to assign props directly to state '+"because updates to props won't be reflected in state. "+'In most cases, it is better to use props directly.',componentName);}}if(workInProgress.mode&StrictLegacyMode){ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress,instance);}{ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress,instance);}}instance.state=workInProgress.memoizedState;var getDerivedStateFromProps=ctor.getDerivedStateFromProps;if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,newProps);instance.state=workInProgress.memoizedState;}// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(typeof ctor.getDerivedStateFromProps!=='function'&&typeof instance.getSnapshotBeforeUpdate!=='function'&&(typeof instance.UNSAFE_componentWillMount==='function'||typeof instance.componentWillMount==='function')){callComponentWillMount(workInProgress,instance);// If we had additional state updates during this life-cycle, let's
// process them now.
processUpdateQueue(workInProgress,newProps,instance,renderLanes);instance.state=workInProgress.memoizedState;}if(typeof instance.componentDidMount==='function'){var fiberFlags=Update;{fiberFlags|=LayoutStatic;}if((workInProgress.mode&StrictEffectsMode)!==NoMode){fiberFlags|=MountLayoutDev;}workInProgress.flags|=fiberFlags;}}function resumeMountClassInstance(workInProgress,ctor,newProps,renderLanes){var instance=workInProgress.stateNode;var oldProps=workInProgress.memoizedProps;instance.props=oldProps;var oldContext=instance.context;var contextType=ctor.contextType;var nextContext=emptyContextObject;if(typeof contextType==='object'&&contextType!==null){nextContext=readContext(contextType);}else {var nextLegacyUnmaskedContext=getUnmaskedContext(workInProgress,ctor,true);nextContext=getMaskedContext(workInProgress,nextLegacyUnmaskedContext);}var getDerivedStateFromProps=ctor.getDerivedStateFromProps;var hasNewLifecycles=typeof getDerivedStateFromProps==='function'||typeof instance.getSnapshotBeforeUpdate==='function';// Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillReceiveProps==='function'||typeof instance.componentWillReceiveProps==='function')){if(oldProps!==newProps||oldContext!==nextContext){callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext);}}resetHasForceUpdateBeforeProcessing();var oldState=workInProgress.memoizedState;var newState=instance.state=oldState;processUpdateQueue(workInProgress,newProps,instance,renderLanes);newState=workInProgress.memoizedState;if(oldProps===newProps&&oldState===newState&&!hasContextChanged()&&!checkHasForceUpdateAfterProcessing()){// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidMount==='function'){var fiberFlags=Update;{fiberFlags|=LayoutStatic;}if((workInProgress.mode&StrictEffectsMode)!==NoMode){fiberFlags|=MountLayoutDev;}workInProgress.flags|=fiberFlags;}return false;}if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,newProps);newState=workInProgress.memoizedState;}var shouldUpdate=checkHasForceUpdateAfterProcessing()||checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext);if(shouldUpdate){// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillMount==='function'||typeof instance.componentWillMount==='function')){if(typeof instance.componentWillMount==='function'){instance.componentWillMount();}if(typeof instance.UNSAFE_componentWillMount==='function'){instance.UNSAFE_componentWillMount();}}if(typeof instance.componentDidMount==='function'){var _fiberFlags=Update;{_fiberFlags|=LayoutStatic;}if((workInProgress.mode&StrictEffectsMode)!==NoMode){_fiberFlags|=MountLayoutDev;}workInProgress.flags|=_fiberFlags;}}else {// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidMount==='function'){var _fiberFlags2=Update;{_fiberFlags2|=LayoutStatic;}if((workInProgress.mode&StrictEffectsMode)!==NoMode){_fiberFlags2|=MountLayoutDev;}workInProgress.flags|=_fiberFlags2;}// If shouldComponentUpdate returned false, we should still update the
// memoized state to indicate that this work can be reused.
workInProgress.memoizedProps=newProps;workInProgress.memoizedState=newState;}// Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props=newProps;instance.state=newState;instance.context=nextContext;return shouldUpdate;}// Invokes the update life-cycles and returns false if it shouldn't rerender.
function updateClassInstance(current,workInProgress,ctor,newProps,renderLanes){var instance=workInProgress.stateNode;cloneUpdateQueue(current,workInProgress);var unresolvedOldProps=workInProgress.memoizedProps;var oldProps=workInProgress.type===workInProgress.elementType?unresolvedOldProps:resolveDefaultProps(workInProgress.type,unresolvedOldProps);instance.props=oldProps;var unresolvedNewProps=workInProgress.pendingProps;var oldContext=instance.context;var contextType=ctor.contextType;var nextContext=emptyContextObject;if(typeof contextType==='object'&&contextType!==null){nextContext=readContext(contextType);}else {var nextUnmaskedContext=getUnmaskedContext(workInProgress,ctor,true);nextContext=getMaskedContext(workInProgress,nextUnmaskedContext);}var getDerivedStateFromProps=ctor.getDerivedStateFromProps;var hasNewLifecycles=typeof getDerivedStateFromProps==='function'||typeof instance.getSnapshotBeforeUpdate==='function';// Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillReceiveProps==='function'||typeof instance.componentWillReceiveProps==='function')){if(unresolvedOldProps!==unresolvedNewProps||oldContext!==nextContext){callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext);}}resetHasForceUpdateBeforeProcessing();var oldState=workInProgress.memoizedState;var newState=instance.state=oldState;processUpdateQueue(workInProgress,newProps,instance,renderLanes);newState=workInProgress.memoizedState;if(unresolvedOldProps===unresolvedNewProps&&oldState===newState&&!hasContextChanged()&&!checkHasForceUpdateAfterProcessing()&&!enableLazyContextPropagation){// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Update;}}if(typeof instance.getSnapshotBeforeUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Snapshot;}}return false;}if(typeof getDerivedStateFromProps==='function'){applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,newProps);newState=workInProgress.memoizedState;}var shouldUpdate=checkHasForceUpdateAfterProcessing()||checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext)||// TODO: In some cases, we'll end up checking if context has changed twice,
// both before and after `shouldComponentUpdate` has been called. Not ideal,
// but I'm loath to refactor this function. This only happens for memoized
// components so it's not that common.
enableLazyContextPropagation;if(shouldUpdate){// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if(!hasNewLifecycles&&(typeof instance.UNSAFE_componentWillUpdate==='function'||typeof instance.componentWillUpdate==='function')){if(typeof instance.componentWillUpdate==='function'){instance.componentWillUpdate(newProps,newState,nextContext);}if(typeof instance.UNSAFE_componentWillUpdate==='function'){instance.UNSAFE_componentWillUpdate(newProps,newState,nextContext);}}if(typeof instance.componentDidUpdate==='function'){workInProgress.flags|=Update;}if(typeof instance.getSnapshotBeforeUpdate==='function'){workInProgress.flags|=Snapshot;}}else {// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if(typeof instance.componentDidUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Update;}}if(typeof instance.getSnapshotBeforeUpdate==='function'){if(unresolvedOldProps!==current.memoizedProps||oldState!==current.memoizedState){workInProgress.flags|=Snapshot;}}// If shouldComponentUpdate returned false, we should still update the
// memoized props/state to indicate that this work can be reused.
workInProgress.memoizedProps=newProps;workInProgress.memoizedState=newState;}// Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props=newProps;instance.state=newState;instance.context=nextContext;return shouldUpdate;}var didWarnAboutMaps;var didWarnAboutGenerators;var didWarnAboutStringRefs;var ownerHasKeyUseWarning;var ownerHasFunctionTypeWarning;var warnForMissingKey=function(child,returnFiber){};{didWarnAboutMaps=false;didWarnAboutGenerators=false;didWarnAboutStringRefs={};/**
   * Warn if there's no key explicitly set on dynamic arrays of children or
   * object keys are not valid. This allows us to keep track of children between
   * updates.
   */ownerHasKeyUseWarning={};ownerHasFunctionTypeWarning={};warnForMissingKey=function(child,returnFiber){if(child===null||typeof child!=='object'){return;}if(!child._store||child._store.validated||child.key!=null){return;}if(typeof child._store!=='object'){throw new Error('React Component in warnForMissingKey should have a _store. '+'This error is likely caused by a bug in React. Please file an issue.');}child._store.validated=true;var componentName=getComponentNameFromFiber(returnFiber)||'Component';if(ownerHasKeyUseWarning[componentName]){return;}ownerHasKeyUseWarning[componentName]=true;error('Each child in a list should have a unique '+'"key" prop. See https://reactjs.org/link/warning-keys for '+'more information.');};}function coerceRef(returnFiber,current,element){var mixedRef=element.ref;if(mixedRef!==null&&typeof mixedRef!=='function'&&typeof mixedRef!=='object'){{// TODO: Clean this up once we turn on the string ref warning for
// everyone, because the strict mode case will no longer be relevant
if((returnFiber.mode&StrictLegacyMode||warnAboutStringRefs)&&// We warn in ReactElement.js if owner and self are equal for string refs
// because these cannot be automatically converted to an arrow function
// using a codemod. Therefore, we don't have to warn about string refs again.
!(element._owner&&element._self&&element._owner.stateNode!==element._self)){var componentName=getComponentNameFromFiber(returnFiber)||'Component';if(!didWarnAboutStringRefs[componentName]){{error('A string ref, "%s", has been found within a strict mode tree. '+'String refs are a source of potential bugs and should be avoided. '+'We recommend using useRef() or createRef() instead. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-string-ref',mixedRef);}didWarnAboutStringRefs[componentName]=true;}}}if(element._owner){var owner=element._owner;var inst;if(owner){var ownerFiber=owner;if(ownerFiber.tag!==ClassComponent){throw new Error('Function components cannot have string refs. '+'We recommend using useRef() instead. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-string-ref');}inst=ownerFiber.stateNode;}if(!inst){throw new Error("Missing owner for string ref "+mixedRef+". This error is likely caused by a "+'bug in React. Please file an issue.');}// Assigning this to a const so Flow knows it won't change in the closure
var resolvedInst=inst;{checkPropStringCoercion(mixedRef,'ref');}var stringRef=''+mixedRef;// Check if previous string ref matches new string ref
if(current!==null&&current.ref!==null&&typeof current.ref==='function'&&current.ref._stringRef===stringRef){return current.ref;}var ref=function(value){var refs=resolvedInst.refs;if(refs===emptyRefsObject){// This is a lazy pooled frozen object, so we need to initialize.
refs=resolvedInst.refs={};}if(value===null){delete refs[stringRef];}else {refs[stringRef]=value;}};ref._stringRef=stringRef;return ref;}else {if(typeof mixedRef!=='string'){throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');}if(!element._owner){throw new Error("Element ref was specified as a string ("+mixedRef+") but no owner was set. This could happen for one of"+' the following reasons:\n'+'1. You may be adding a ref to a function component\n'+"2. You may be adding a ref to a component that was not created inside a component's render method\n"+'3. You have multiple copies of React loaded\n'+'See https://reactjs.org/link/refs-must-have-owner for more information.');}}}return mixedRef;}function throwOnInvalidObjectType(returnFiber,newChild){var childString=Object.prototype.toString.call(newChild);throw new Error("Objects are not valid as a React child (found: "+(childString==='[object Object]'?'object with keys {'+Object.keys(newChild).join(', ')+'}':childString)+"). "+'If you meant to render a collection of children, use an array '+'instead.');}function warnOnFunctionType(returnFiber){{var componentName=getComponentNameFromFiber(returnFiber)||'Component';if(ownerHasFunctionTypeWarning[componentName]){return;}ownerHasFunctionTypeWarning[componentName]=true;error('Functions are not valid as a React child. This may happen if '+'you return a Component instead of <Component /> from render. '+'Or maybe you meant to call this function rather than return it.');}}function resolveLazy(lazyType){var payload=lazyType._payload;var init=lazyType._init;return init(payload);}// This wrapper function exists because I expect to clone the code in each path
// to be able to optimize each path individually by branching early. This needs
// a compiler or we can do it manually. Helpers that don't need this branching
// live outside of this function.
function ChildReconciler(shouldTrackSideEffects){function deleteChild(returnFiber,childToDelete){if(!shouldTrackSideEffects){// Noop.
return;}var deletions=returnFiber.deletions;if(deletions===null){returnFiber.deletions=[childToDelete];returnFiber.flags|=ChildDeletion;}else {deletions.push(childToDelete);}}function deleteRemainingChildren(returnFiber,currentFirstChild){if(!shouldTrackSideEffects){// Noop.
return null;}// TODO: For the shouldClone case, this could be micro-optimized a bit by
// assuming that after the first child we've already added everything.
var childToDelete=currentFirstChild;while(childToDelete!==null){deleteChild(returnFiber,childToDelete);childToDelete=childToDelete.sibling;}return null;}function mapRemainingChildren(returnFiber,currentFirstChild){// Add the remaining children to a temporary map so that we can find them by
// keys quickly. Implicit (null) keys get added to this set with their index
// instead.
var existingChildren=new Map();var existingChild=currentFirstChild;while(existingChild!==null){if(existingChild.key!==null){existingChildren.set(existingChild.key,existingChild);}else {existingChildren.set(existingChild.index,existingChild);}existingChild=existingChild.sibling;}return existingChildren;}function useFiber(fiber,pendingProps){// We currently set sibling to null and index to 0 here because it is easy
// to forget to do before returning it. E.g. for the single child case.
var clone=createWorkInProgress(fiber,pendingProps);clone.index=0;clone.sibling=null;return clone;}function placeChild(newFiber,lastPlacedIndex,newIndex){newFiber.index=newIndex;if(!shouldTrackSideEffects){// During hydration, the useId algorithm needs to know which fibers are
// part of a list of children (arrays, iterators).
newFiber.flags|=Forked;return lastPlacedIndex;}var current=newFiber.alternate;if(current!==null){var oldIndex=current.index;if(oldIndex<lastPlacedIndex){// This is a move.
newFiber.flags|=Placement;return lastPlacedIndex;}else {// This item can stay in place.
return oldIndex;}}else {// This is an insertion.
newFiber.flags|=Placement;return lastPlacedIndex;}}function placeSingleChild(newFiber){// This is simpler for the single child case. We only need to do a
// placement for inserting new children.
if(shouldTrackSideEffects&&newFiber.alternate===null){newFiber.flags|=Placement;}return newFiber;}function updateTextNode(returnFiber,current,textContent,lanes){if(current===null||current.tag!==HostText){// Insert
var created=createFiberFromText(textContent,returnFiber.mode,lanes);created.return=returnFiber;return created;}else {// Update
var existing=useFiber(current,textContent);existing.return=returnFiber;return existing;}}function updateElement(returnFiber,current,element,lanes){var elementType=element.type;if(elementType===REACT_FRAGMENT_TYPE){return updateFragment(returnFiber,current,element.props.children,lanes,element.key);}if(current!==null){if(current.elementType===elementType||// Keep this check inline so it only runs on the false path:
isCompatibleFamilyForHotReloading(current,element)||// Lazy types should reconcile their resolved type.
// We need to do this after the Hot Reloading check above,
// because hot reloading has different semantics than prod because
// it doesn't resuspend. So we can't let the call below suspend.
typeof elementType==='object'&&elementType!==null&&elementType.$$typeof===REACT_LAZY_TYPE&&resolveLazy(elementType)===current.type){// Move based on index
var existing=useFiber(current,element.props);existing.ref=coerceRef(returnFiber,current,element);existing.return=returnFiber;{existing._debugSource=element._source;existing._debugOwner=element._owner;}return existing;}}// Insert
var created=createFiberFromElement(element,returnFiber.mode,lanes);created.ref=coerceRef(returnFiber,current,element);created.return=returnFiber;return created;}function updatePortal(returnFiber,current,portal,lanes){if(current===null||current.tag!==HostPortal||current.stateNode.containerInfo!==portal.containerInfo||current.stateNode.implementation!==portal.implementation){// Insert
var created=createFiberFromPortal(portal,returnFiber.mode,lanes);created.return=returnFiber;return created;}else {// Update
var existing=useFiber(current,portal.children||[]);existing.return=returnFiber;return existing;}}function updateFragment(returnFiber,current,fragment,lanes,key){if(current===null||current.tag!==Fragment){// Insert
var created=createFiberFromFragment(fragment,returnFiber.mode,lanes,key);created.return=returnFiber;return created;}else {// Update
var existing=useFiber(current,fragment);existing.return=returnFiber;return existing;}}function createChild(returnFiber,newChild,lanes){if(typeof newChild==='string'&&newChild!==''||typeof newChild==='number'){// Text nodes don't have keys. If the previous node is implicitly keyed
// we can continue to replace it without aborting even if it is not a text
// node.
var created=createFiberFromText(''+newChild,returnFiber.mode,lanes);created.return=returnFiber;return created;}if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:{var _created=createFiberFromElement(newChild,returnFiber.mode,lanes);_created.ref=coerceRef(returnFiber,null,newChild);_created.return=returnFiber;return _created;}case REACT_PORTAL_TYPE:{var _created2=createFiberFromPortal(newChild,returnFiber.mode,lanes);_created2.return=returnFiber;return _created2;}case REACT_LAZY_TYPE:{var payload=newChild._payload;var init=newChild._init;return createChild(returnFiber,init(payload),lanes);}}if(isArray(newChild)||getIteratorFn(newChild)){var _created3=createFiberFromFragment(newChild,returnFiber.mode,lanes,null);_created3.return=returnFiber;return _created3;}throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}return null;}function updateSlot(returnFiber,oldFiber,newChild,lanes){// Update the fiber if the keys match, otherwise return null.
var key=oldFiber!==null?oldFiber.key:null;if(typeof newChild==='string'&&newChild!==''||typeof newChild==='number'){// Text nodes don't have keys. If the previous node is implicitly keyed
// we can continue to replace it without aborting even if it is not a text
// node.
if(key!==null){return null;}return updateTextNode(returnFiber,oldFiber,''+newChild,lanes);}if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:{if(newChild.key===key){return updateElement(returnFiber,oldFiber,newChild,lanes);}else {return null;}}case REACT_PORTAL_TYPE:{if(newChild.key===key){return updatePortal(returnFiber,oldFiber,newChild,lanes);}else {return null;}}case REACT_LAZY_TYPE:{var payload=newChild._payload;var init=newChild._init;return updateSlot(returnFiber,oldFiber,init(payload),lanes);}}if(isArray(newChild)||getIteratorFn(newChild)){if(key!==null){return null;}return updateFragment(returnFiber,oldFiber,newChild,lanes,null);}throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}return null;}function updateFromMap(existingChildren,returnFiber,newIdx,newChild,lanes){if(typeof newChild==='string'&&newChild!==''||typeof newChild==='number'){// Text nodes don't have keys, so we neither have to check the old nor
// new node for the key. If both are text nodes, they match.
var matchedFiber=existingChildren.get(newIdx)||null;return updateTextNode(returnFiber,matchedFiber,''+newChild,lanes);}if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:{var _matchedFiber=existingChildren.get(newChild.key===null?newIdx:newChild.key)||null;return updateElement(returnFiber,_matchedFiber,newChild,lanes);}case REACT_PORTAL_TYPE:{var _matchedFiber2=existingChildren.get(newChild.key===null?newIdx:newChild.key)||null;return updatePortal(returnFiber,_matchedFiber2,newChild,lanes);}case REACT_LAZY_TYPE:var payload=newChild._payload;var init=newChild._init;return updateFromMap(existingChildren,returnFiber,newIdx,init(payload),lanes);}if(isArray(newChild)||getIteratorFn(newChild)){var _matchedFiber3=existingChildren.get(newIdx)||null;return updateFragment(returnFiber,_matchedFiber3,newChild,lanes,null);}throwOnInvalidObjectType(returnFiber,newChild);}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}return null;}/**
   * Warns if there is a duplicate or missing key
   */function warnOnInvalidKey(child,knownKeys,returnFiber){{if(typeof child!=='object'||child===null){return knownKeys;}switch(child.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:warnForMissingKey(child,returnFiber);var key=child.key;if(typeof key!=='string'){break;}if(knownKeys===null){knownKeys=new Set();knownKeys.add(key);break;}if(!knownKeys.has(key)){knownKeys.add(key);break;}error('Encountered two children with the same key, `%s`. '+'Keys should be unique so that components maintain their identity '+'across updates. Non-unique keys may cause children to be '+'duplicated and/or omitted — the behavior is unsupported and '+'could change in a future version.',key);break;case REACT_LAZY_TYPE:var payload=child._payload;var init=child._init;warnOnInvalidKey(init(payload),knownKeys,returnFiber);break;}}return knownKeys;}function reconcileChildrenArray(returnFiber,currentFirstChild,newChildren,lanes){// This algorithm can't optimize by searching from both ends since we
// don't have backpointers on fibers. I'm trying to see how far we can get
// with that model. If it ends up not being worth the tradeoffs, we can
// add it later.
// Even with a two ended optimization, we'd want to optimize for the case
// where there are few changes and brute force the comparison instead of
// going for the Map. It'd like to explore hitting that path first in
// forward-only mode and only go for the Map once we notice that we need
// lots of look ahead. This doesn't handle reversal as well as two ended
// search but that's unusual. Besides, for the two ended optimization to
// work on Iterables, we'd need to copy the whole set.
// In this first iteration, we'll just live with hitting the bad case
// (adding everything to a Map) in for every insert/move.
// If you change this code, also update reconcileChildrenIterator() which
// uses the same algorithm.
{// First, validate keys.
var knownKeys=null;for(var i=0;i<newChildren.length;i++){var child=newChildren[i];knownKeys=warnOnInvalidKey(child,knownKeys,returnFiber);}}var resultingFirstChild=null;var previousNewFiber=null;var oldFiber=currentFirstChild;var lastPlacedIndex=0;var newIdx=0;var nextOldFiber=null;for(;oldFiber!==null&&newIdx<newChildren.length;newIdx++){if(oldFiber.index>newIdx){nextOldFiber=oldFiber;oldFiber=null;}else {nextOldFiber=oldFiber.sibling;}var newFiber=updateSlot(returnFiber,oldFiber,newChildren[newIdx],lanes);if(newFiber===null){// TODO: This breaks on empty slots like null children. That's
// unfortunate because it triggers the slow path all the time. We need
// a better way to communicate whether this was a miss or null,
// boolean, undefined, etc.
if(oldFiber===null){oldFiber=nextOldFiber;}break;}if(shouldTrackSideEffects){if(oldFiber&&newFiber.alternate===null){// We matched the slot, but we didn't reuse the existing fiber, so we
// need to delete the existing child.
deleteChild(returnFiber,oldFiber);}}lastPlacedIndex=placeChild(newFiber,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=newFiber;}else {// TODO: Defer siblings if we're not at the right index for this slot.
// I.e. if we had null values before, then we want to defer this
// for each null value. However, we also don't want to call updateSlot
// with the previous one.
previousNewFiber.sibling=newFiber;}previousNewFiber=newFiber;oldFiber=nextOldFiber;}if(newIdx===newChildren.length){// We've reached the end of the new children. We can delete the rest.
deleteRemainingChildren(returnFiber,oldFiber);if(getIsHydrating()){var numberOfForks=newIdx;pushTreeFork(returnFiber,numberOfForks);}return resultingFirstChild;}if(oldFiber===null){// If we don't have any more existing children we can choose a fast path
// since the rest will all be insertions.
for(;newIdx<newChildren.length;newIdx++){var _newFiber=createChild(returnFiber,newChildren[newIdx],lanes);if(_newFiber===null){continue;}lastPlacedIndex=placeChild(_newFiber,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=_newFiber;}else {previousNewFiber.sibling=_newFiber;}previousNewFiber=_newFiber;}if(getIsHydrating()){var _numberOfForks=newIdx;pushTreeFork(returnFiber,_numberOfForks);}return resultingFirstChild;}// Add all children to a key map for quick lookups.
var existingChildren=mapRemainingChildren(returnFiber,oldFiber);// Keep scanning and use the map to restore deleted items as moves.
for(;newIdx<newChildren.length;newIdx++){var _newFiber2=updateFromMap(existingChildren,returnFiber,newIdx,newChildren[newIdx],lanes);if(_newFiber2!==null){if(shouldTrackSideEffects){if(_newFiber2.alternate!==null){// The new fiber is a work in progress, but if there exists a
// current, that means that we reused the fiber. We need to delete
// it from the child list so that we don't add it to the deletion
// list.
existingChildren.delete(_newFiber2.key===null?newIdx:_newFiber2.key);}}lastPlacedIndex=placeChild(_newFiber2,lastPlacedIndex,newIdx);if(previousNewFiber===null){resultingFirstChild=_newFiber2;}else {previousNewFiber.sibling=_newFiber2;}previousNewFiber=_newFiber2;}}if(shouldTrackSideEffects){// Any existing children that weren't consumed above were deleted. We need
// to add them to the deletion list.
existingChildren.forEach(function(child){return deleteChild(returnFiber,child);});}if(getIsHydrating()){var _numberOfForks2=newIdx;pushTreeFork(returnFiber,_numberOfForks2);}return resultingFirstChild;}function reconcileChildrenIterator(returnFiber,currentFirstChild,newChildrenIterable,lanes){// This is the same implementation as reconcileChildrenArray(),
// but using the iterator instead.
var iteratorFn=getIteratorFn(newChildrenIterable);if(typeof iteratorFn!=='function'){throw new Error('An object is not an iterable. This error is likely caused by a bug in '+'React. Please file an issue.');}{// We don't support rendering Generators because it's a mutation.
// See https://github.com/facebook/react/issues/12995
if(typeof Symbol==='function'&&// $FlowFixMe Flow doesn't know about toStringTag
newChildrenIterable[Symbol.toStringTag]==='Generator'){if(!didWarnAboutGenerators){error('Using Generators as children is unsupported and will likely yield '+'unexpected results because enumerating a generator mutates it. '+'You may convert it to an array with `Array.from()` or the '+'`[...spread]` operator before rendering. Keep in mind '+'you might need to polyfill these features for older browsers.');}didWarnAboutGenerators=true;}// Warn about using Maps as children
if(newChildrenIterable.entries===iteratorFn){if(!didWarnAboutMaps){error('Using Maps as children is not supported. '+'Use an array of keyed ReactElements instead.');}didWarnAboutMaps=true;}// First, validate keys.
// We'll get a different iterator later for the main pass.
var _newChildren=iteratorFn.call(newChildrenIterable);if(_newChildren){var knownKeys=null;var _step=_newChildren.next();for(;!_step.done;_step=_newChildren.next()){var child=_step.value;knownKeys=warnOnInvalidKey(child,knownKeys,returnFiber);}}}var newChildren=iteratorFn.call(newChildrenIterable);if(newChildren==null){throw new Error('An iterable object provided no iterator.');}var resultingFirstChild=null;var previousNewFiber=null;var oldFiber=currentFirstChild;var lastPlacedIndex=0;var newIdx=0;var nextOldFiber=null;var step=newChildren.next();for(;oldFiber!==null&&!step.done;newIdx++,step=newChildren.next()){if(oldFiber.index>newIdx){nextOldFiber=oldFiber;oldFiber=null;}else {nextOldFiber=oldFiber.sibling;}var newFiber=updateSlot(returnFiber,oldFiber,step.value,lanes);if(newFiber===null){// TODO: This breaks on empty slots like null children. That's
// unfortunate because it triggers the slow path all the time. We need
// a better way to communicate whether this was a miss or null,
// boolean, undefined, etc.
if(oldFiber===null){oldFiber=nextOldFiber;}break;}if(shouldTrackSideEffects){if(oldFiber&&newFiber.alternate===null){// We matched the slot, but we didn't reuse the existing fiber, so we
// need to delete the existing child.
deleteChild(returnFiber,oldFiber);}}lastPlacedIndex=placeChild(newFiber,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=newFiber;}else {// TODO: Defer siblings if we're not at the right index for this slot.
// I.e. if we had null values before, then we want to defer this
// for each null value. However, we also don't want to call updateSlot
// with the previous one.
previousNewFiber.sibling=newFiber;}previousNewFiber=newFiber;oldFiber=nextOldFiber;}if(step.done){// We've reached the end of the new children. We can delete the rest.
deleteRemainingChildren(returnFiber,oldFiber);if(getIsHydrating()){var numberOfForks=newIdx;pushTreeFork(returnFiber,numberOfForks);}return resultingFirstChild;}if(oldFiber===null){// If we don't have any more existing children we can choose a fast path
// since the rest will all be insertions.
for(;!step.done;newIdx++,step=newChildren.next()){var _newFiber3=createChild(returnFiber,step.value,lanes);if(_newFiber3===null){continue;}lastPlacedIndex=placeChild(_newFiber3,lastPlacedIndex,newIdx);if(previousNewFiber===null){// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild=_newFiber3;}else {previousNewFiber.sibling=_newFiber3;}previousNewFiber=_newFiber3;}if(getIsHydrating()){var _numberOfForks3=newIdx;pushTreeFork(returnFiber,_numberOfForks3);}return resultingFirstChild;}// Add all children to a key map for quick lookups.
var existingChildren=mapRemainingChildren(returnFiber,oldFiber);// Keep scanning and use the map to restore deleted items as moves.
for(;!step.done;newIdx++,step=newChildren.next()){var _newFiber4=updateFromMap(existingChildren,returnFiber,newIdx,step.value,lanes);if(_newFiber4!==null){if(shouldTrackSideEffects){if(_newFiber4.alternate!==null){// The new fiber is a work in progress, but if there exists a
// current, that means that we reused the fiber. We need to delete
// it from the child list so that we don't add it to the deletion
// list.
existingChildren.delete(_newFiber4.key===null?newIdx:_newFiber4.key);}}lastPlacedIndex=placeChild(_newFiber4,lastPlacedIndex,newIdx);if(previousNewFiber===null){resultingFirstChild=_newFiber4;}else {previousNewFiber.sibling=_newFiber4;}previousNewFiber=_newFiber4;}}if(shouldTrackSideEffects){// Any existing children that weren't consumed above were deleted. We need
// to add them to the deletion list.
existingChildren.forEach(function(child){return deleteChild(returnFiber,child);});}if(getIsHydrating()){var _numberOfForks4=newIdx;pushTreeFork(returnFiber,_numberOfForks4);}return resultingFirstChild;}function reconcileSingleTextNode(returnFiber,currentFirstChild,textContent,lanes){// There's no need to check for keys on text nodes since we don't have a
// way to define them.
if(currentFirstChild!==null&&currentFirstChild.tag===HostText){// We already have an existing node so let's just update it and delete
// the rest.
deleteRemainingChildren(returnFiber,currentFirstChild.sibling);var existing=useFiber(currentFirstChild,textContent);existing.return=returnFiber;return existing;}// The existing first child is not a text node so we need to create one
// and delete the existing ones.
deleteRemainingChildren(returnFiber,currentFirstChild);var created=createFiberFromText(textContent,returnFiber.mode,lanes);created.return=returnFiber;return created;}function reconcileSingleElement(returnFiber,currentFirstChild,element,lanes){var key=element.key;var child=currentFirstChild;while(child!==null){// TODO: If key === null and child.key === null, then this only applies to
// the first item in the list.
if(child.key===key){var elementType=element.type;if(elementType===REACT_FRAGMENT_TYPE){if(child.tag===Fragment){deleteRemainingChildren(returnFiber,child.sibling);var existing=useFiber(child,element.props.children);existing.return=returnFiber;{existing._debugSource=element._source;existing._debugOwner=element._owner;}return existing;}}else {if(child.elementType===elementType||// Keep this check inline so it only runs on the false path:
isCompatibleFamilyForHotReloading(child,element)||// Lazy types should reconcile their resolved type.
// We need to do this after the Hot Reloading check above,
// because hot reloading has different semantics than prod because
// it doesn't resuspend. So we can't let the call below suspend.
typeof elementType==='object'&&elementType!==null&&elementType.$$typeof===REACT_LAZY_TYPE&&resolveLazy(elementType)===child.type){deleteRemainingChildren(returnFiber,child.sibling);var _existing=useFiber(child,element.props);_existing.ref=coerceRef(returnFiber,child,element);_existing.return=returnFiber;{_existing._debugSource=element._source;_existing._debugOwner=element._owner;}return _existing;}}// Didn't match.
deleteRemainingChildren(returnFiber,child);break;}else {deleteChild(returnFiber,child);}child=child.sibling;}if(element.type===REACT_FRAGMENT_TYPE){var created=createFiberFromFragment(element.props.children,returnFiber.mode,lanes,element.key);created.return=returnFiber;return created;}else {var _created4=createFiberFromElement(element,returnFiber.mode,lanes);_created4.ref=coerceRef(returnFiber,currentFirstChild,element);_created4.return=returnFiber;return _created4;}}function reconcileSinglePortal(returnFiber,currentFirstChild,portal,lanes){var key=portal.key;var child=currentFirstChild;while(child!==null){// TODO: If key === null and child.key === null, then this only applies to
// the first item in the list.
if(child.key===key){if(child.tag===HostPortal&&child.stateNode.containerInfo===portal.containerInfo&&child.stateNode.implementation===portal.implementation){deleteRemainingChildren(returnFiber,child.sibling);var existing=useFiber(child,portal.children||[]);existing.return=returnFiber;return existing;}else {deleteRemainingChildren(returnFiber,child);break;}}else {deleteChild(returnFiber,child);}child=child.sibling;}var created=createFiberFromPortal(portal,returnFiber.mode,lanes);created.return=returnFiber;return created;}// This API will tag the children with the side-effect of the reconciliation
// itself. They will be added to the side-effect list as we pass through the
// children and the parent.
function reconcileChildFibers(returnFiber,currentFirstChild,newChild,lanes){// This function is not recursive.
// If the top level item is an array, we treat it as a set of children,
// not as a fragment. Nested arrays on the other hand will be treated as
// fragment nodes. Recursion happens at the normal flow.
// Handle top level unkeyed fragments as if they were arrays.
// This leads to an ambiguity between <>{[...]}</> and <>...</>.
// We treat the ambiguous cases above the same.
var isUnkeyedTopLevelFragment=typeof newChild==='object'&&newChild!==null&&newChild.type===REACT_FRAGMENT_TYPE&&newChild.key===null;if(isUnkeyedTopLevelFragment){newChild=newChild.props.children;}// Handle object types
if(typeof newChild==='object'&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:return placeSingleChild(reconcileSingleElement(returnFiber,currentFirstChild,newChild,lanes));case REACT_PORTAL_TYPE:return placeSingleChild(reconcileSinglePortal(returnFiber,currentFirstChild,newChild,lanes));case REACT_LAZY_TYPE:var payload=newChild._payload;var init=newChild._init;// TODO: This function is supposed to be non-recursive.
return reconcileChildFibers(returnFiber,currentFirstChild,init(payload),lanes);}if(isArray(newChild)){return reconcileChildrenArray(returnFiber,currentFirstChild,newChild,lanes);}if(getIteratorFn(newChild)){return reconcileChildrenIterator(returnFiber,currentFirstChild,newChild,lanes);}throwOnInvalidObjectType(returnFiber,newChild);}if(typeof newChild==='string'&&newChild!==''||typeof newChild==='number'){return placeSingleChild(reconcileSingleTextNode(returnFiber,currentFirstChild,''+newChild,lanes));}{if(typeof newChild==='function'){warnOnFunctionType(returnFiber);}}// Remaining cases are all treated as empty.
return deleteRemainingChildren(returnFiber,currentFirstChild);}return reconcileChildFibers;}var reconcileChildFibers=ChildReconciler(true);var mountChildFibers=ChildReconciler(false);function cloneChildFibers(current,workInProgress){if(current!==null&&workInProgress.child!==current.child){throw new Error('Resuming work not yet implemented.');}if(workInProgress.child===null){return;}var currentChild=workInProgress.child;var newChild=createWorkInProgress(currentChild,currentChild.pendingProps);workInProgress.child=newChild;newChild.return=workInProgress;while(currentChild.sibling!==null){currentChild=currentChild.sibling;newChild=newChild.sibling=createWorkInProgress(currentChild,currentChild.pendingProps);newChild.return=workInProgress;}newChild.sibling=null;}// Reset a workInProgress child set to prepare it for a second pass.
function resetChildFibers(workInProgress,lanes){var child=workInProgress.child;while(child!==null){resetWorkInProgress(child,lanes);child=child.sibling;}}var NO_CONTEXT={};var contextStackCursor$1=createCursor(NO_CONTEXT);var contextFiberStackCursor=createCursor(NO_CONTEXT);var rootInstanceStackCursor=createCursor(NO_CONTEXT);function requiredContext(c){if(c===NO_CONTEXT){throw new Error('Expected host context to exist. This error is likely caused by a bug '+'in React. Please file an issue.');}return c;}function getRootHostContainer(){var rootInstance=requiredContext(rootInstanceStackCursor.current);return rootInstance;}function pushHostContainer(fiber,nextRootInstance){// Push current root instance onto the stack;
// This allows us to reset root when portals are popped.
push(rootInstanceStackCursor,nextRootInstance,fiber);// Track the context and the Fiber that provided it.
// This enables us to pop only Fibers that provide unique contexts.
push(contextFiberStackCursor,fiber,fiber);// Finally, we need to push the host context to the stack.
// However, we can't just call getRootHostContext() and push it because
// we'd have a different number of entries on the stack depending on
// whether getRootHostContext() throws somewhere in renderer code or not.
// So we push an empty value first. This lets us safely unwind on errors.
push(contextStackCursor$1,NO_CONTEXT,fiber);var nextRootContext=getRootHostContext(nextRootInstance);// Now that we know this function doesn't throw, replace it.
pop(contextStackCursor$1,fiber);push(contextStackCursor$1,nextRootContext,fiber);}function popHostContainer(fiber){pop(contextStackCursor$1,fiber);pop(contextFiberStackCursor,fiber);pop(rootInstanceStackCursor,fiber);}function getHostContext(){var context=requiredContext(contextStackCursor$1.current);return context;}function pushHostContext(fiber){requiredContext(rootInstanceStackCursor.current);var context=requiredContext(contextStackCursor$1.current);var nextContext=getChildHostContext(context,fiber.type);// Don't push this Fiber's context unless it's unique.
if(context===nextContext){return;}// Track the context and the Fiber that provided it.
// This enables us to pop only Fibers that provide unique contexts.
push(contextFiberStackCursor,fiber,fiber);push(contextStackCursor$1,nextContext,fiber);}function popHostContext(fiber){// Do not pop unless this Fiber provided the current context.
// pushHostContext() only pushes Fibers that provide unique contexts.
if(contextFiberStackCursor.current!==fiber){return;}pop(contextStackCursor$1,fiber);pop(contextFiberStackCursor,fiber);}var DefaultSuspenseContext=0;// The Suspense Context is split into two parts. The lower bits is
// inherited deeply down the subtree. The upper bits only affect
// this immediate suspense boundary and gets reset each new
// boundary or suspense list.
var SubtreeSuspenseContextMask=1;// Subtree Flags:
// InvisibleParentSuspenseContext indicates that one of our parent Suspense
// boundaries is not currently showing visible main content.
// Either because it is already showing a fallback or is not mounted at all.
// We can use this to determine if it is desirable to trigger a fallback at
// the parent. If not, then we might need to trigger undesirable boundaries
// and/or suspend the commit to avoid hiding the parent content.
var InvisibleParentSuspenseContext=1;// Shallow Flags:
// ForceSuspenseFallback can be used by SuspenseList to force newly added
// items into their fallback state during one of the render passes.
var ForceSuspenseFallback=2;var suspenseStackCursor=createCursor(DefaultSuspenseContext);function hasSuspenseContext(parentContext,flag){return (parentContext&flag)!==0;}function setDefaultShallowSuspenseContext(parentContext){return parentContext&SubtreeSuspenseContextMask;}function setShallowSuspenseContext(parentContext,shallowContext){return parentContext&SubtreeSuspenseContextMask|shallowContext;}function addSubtreeSuspenseContext(parentContext,subtreeContext){return parentContext|subtreeContext;}function pushSuspenseContext(fiber,newContext){push(suspenseStackCursor,newContext,fiber);}function popSuspenseContext(fiber){pop(suspenseStackCursor,fiber);}function shouldCaptureSuspense(workInProgress,hasInvisibleParent){// If it was the primary children that just suspended, capture and render the
// fallback. Otherwise, don't capture and bubble to the next boundary.
var nextState=workInProgress.memoizedState;if(nextState!==null){if(nextState.dehydrated!==null){// A dehydrated boundary always captures.
return true;}return false;}workInProgress.memoizedProps;// Regular boundaries always capture.
{return true;}// If it's a boundary we should avoid, then we prefer to bubble up to the
}function findFirstSuspended(row){var node=row;while(node!==null){if(node.tag===SuspenseComponent){var state=node.memoizedState;if(state!==null){var dehydrated=state.dehydrated;if(dehydrated===null||isSuspenseInstancePending(dehydrated)||isSuspenseInstanceFallback(dehydrated)){return node;}}}else if(node.tag===SuspenseListComponent&&// revealOrder undefined can't be trusted because it don't
// keep track of whether it suspended or not.
node.memoizedProps.revealOrder!==undefined){var didSuspend=(node.flags&DidCapture)!==NoFlags;if(didSuspend){return node;}}else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===row){return null;}while(node.sibling===null){if(node.return===null||node.return===row){return null;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}return null;}var NoFlags$1=/*   */0;// Represents whether effect should fire.
var HasEffect=/* */1;// Represents the phase in which the effect (not the clean-up) fires.
var Insertion=/*  */2;var Layout=/*    */4;var Passive$1=/*   */8;// and should be reset before starting a new render.
// This tracks which mutable sources need to be reset after a render.
var workInProgressSources=[];function resetWorkInProgressVersions(){for(var i=0;i<workInProgressSources.length;i++){var mutableSource=workInProgressSources[i];{mutableSource._workInProgressVersionPrimary=null;}}workInProgressSources.length=0;}// This ensures that the version used for server rendering matches the one
// that is eventually read during hydration.
// If they don't match there's a potential tear and a full deopt render is required.
function registerMutableSourceForHydration(root,mutableSource){var getVersion=mutableSource._getVersion;var version=getVersion(mutableSource._source);// TODO Clear this data once all pending hydration work is finished.
// Retaining it forever may interfere with GC.
if(root.mutableSourceEagerHydrationData==null){root.mutableSourceEagerHydrationData=[mutableSource,version];}else {root.mutableSourceEagerHydrationData.push(mutableSource,version);}}var ReactCurrentDispatcher$1=ReactSharedInternals.ReactCurrentDispatcher,ReactCurrentBatchConfig$2=ReactSharedInternals.ReactCurrentBatchConfig;var didWarnAboutMismatchedHooksForComponent;var didWarnUncachedGetSnapshot;{didWarnAboutMismatchedHooksForComponent=new Set();}// These are set right before calling the component.
var renderLanes=NoLanes;// The work-in-progress fiber. I've named it differently to distinguish it from
// the work-in-progress hook.
var currentlyRenderingFiber$1=null;// Hooks are stored as a linked list on the fiber's memoizedState field. The
// current hook list is the list that belongs to the current fiber. The
// work-in-progress hook list is a new list that will be added to the
// work-in-progress fiber.
var currentHook=null;var workInProgressHook=null;// Whether an update was scheduled at any point during the render phase. This
// does not get reset if we do another render pass; only when we're completely
// finished evaluating this component. This is an optimization so we know
// whether we need to clear render phase updates after a throw.
var didScheduleRenderPhaseUpdate=false;// Where an update was scheduled only during the current render pass. This
// gets reset after each attempt.
// TODO: Maybe there's some way to consolidate this with
// `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
var didScheduleRenderPhaseUpdateDuringThisPass=false;// Counts the number of useId hooks in this component.
var localIdCounter=0;// Used for ids that are generated completely client-side (i.e. not during
// hydration). This counter is global, so client ids are not stable across
// render attempts.
var globalClientIdCounter=0;var RE_RENDER_LIMIT=25;// In DEV, this is the name of the currently executing primitive hook
var currentHookNameInDev=null;// In DEV, this list ensures that hooks are called in the same order between renders.
// The list stores the order of hooks used during the initial render (mount).
// Subsequent renders (updates) reference this list.
var hookTypesDev=null;var hookTypesUpdateIndexDev=-1;// In DEV, this tracks whether currently rendering component needs to ignore
// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
// When true, such Hooks will always be "remounted". Only used during hot reload.
var ignorePreviousDependencies=false;function mountHookTypesDev(){{var hookName=currentHookNameInDev;if(hookTypesDev===null){hookTypesDev=[hookName];}else {hookTypesDev.push(hookName);}}}function updateHookTypesDev(){{var hookName=currentHookNameInDev;if(hookTypesDev!==null){hookTypesUpdateIndexDev++;if(hookTypesDev[hookTypesUpdateIndexDev]!==hookName){warnOnHookMismatchInDev(hookName);}}}}function checkDepsAreArrayDev(deps){{if(deps!==undefined&&deps!==null&&!isArray(deps)){// Verify deps, but only on mount to avoid extra checks.
// It's unlikely their type would change as usually you define them inline.
error('%s received a final argument that is not an array (instead, received `%s`). When '+'specified, the final argument must be an array.',currentHookNameInDev,typeof deps);}}}function warnOnHookMismatchInDev(currentHookName){{var componentName=getComponentNameFromFiber(currentlyRenderingFiber$1);if(!didWarnAboutMismatchedHooksForComponent.has(componentName)){didWarnAboutMismatchedHooksForComponent.add(componentName);if(hookTypesDev!==null){var table='';var secondColumnStart=30;for(var i=0;i<=hookTypesUpdateIndexDev;i++){var oldHookName=hookTypesDev[i];var newHookName=i===hookTypesUpdateIndexDev?currentHookName:oldHookName;var row=i+1+". "+oldHookName;// Extra space so second column lines up
// lol @ IE not supporting String#repeat
while(row.length<secondColumnStart){row+=' ';}row+=newHookName+'\n';table+=row;}error('React has detected a change in the order of Hooks called by %s. '+'This will lead to bugs and errors if not fixed. '+'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n'+'   Previous render            Next render\n'+'   ------------------------------------------------------\n'+'%s'+'   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n',componentName,table);}}}}function throwInvalidHookError(){throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for'+' one of the following reasons:\n'+'1. You might have mismatching versions of React and the renderer (such as React DOM)\n'+'2. You might be breaking the Rules of Hooks\n'+'3. You might have more than one copy of React in the same app\n'+'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');}function areHookInputsEqual(nextDeps,prevDeps){{if(ignorePreviousDependencies){// Only true when this component is being hot reloaded.
return false;}}if(prevDeps===null){{error('%s received a final argument during this render, but not during '+'the previous render. Even though the final argument is optional, '+'its type cannot change between renders.',currentHookNameInDev);}return false;}{// Don't bother comparing lengths in prod because these arrays should be
// passed inline.
if(nextDeps.length!==prevDeps.length){error('The final argument passed to %s changed size between renders. The '+'order and size of this array must remain constant.\n\n'+'Previous: %s\n'+'Incoming: %s',currentHookNameInDev,"["+prevDeps.join(', ')+"]","["+nextDeps.join(', ')+"]");}}for(var i=0;i<prevDeps.length&&i<nextDeps.length;i++){if(objectIs(nextDeps[i],prevDeps[i])){continue;}return false;}return true;}function renderWithHooks(current,workInProgress,Component,props,secondArg,nextRenderLanes){renderLanes=nextRenderLanes;currentlyRenderingFiber$1=workInProgress;{hookTypesDev=current!==null?current._debugHookTypes:null;hookTypesUpdateIndexDev=-1;// Used for hot reloading:
ignorePreviousDependencies=current!==null&&current.type!==workInProgress.type;}workInProgress.memoizedState=null;workInProgress.updateQueue=null;workInProgress.lanes=NoLanes;// The following should have already been reset
// currentHook = null;
// workInProgressHook = null;
// didScheduleRenderPhaseUpdate = false;
// localIdCounter = 0;
// TODO Warn if no hooks are used at all during mount, then some are used during update.
// Currently we will identify the update render as a mount because memoizedState === null.
// This is tricky because it's valid for certain types of components (e.g. React.lazy)
// Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
// Non-stateful hooks (e.g. context) don't get added to memoizedState,
// so memoizedState would be null during updates and mounts.
{if(current!==null&&current.memoizedState!==null){ReactCurrentDispatcher$1.current=HooksDispatcherOnUpdateInDEV;}else if(hookTypesDev!==null){// This dispatcher handles an edge case where a component is updating,
// but no stateful hooks have been used.
// We want to match the production code behavior (which will use HooksDispatcherOnMount),
// but with the extra DEV validation to ensure hooks ordering hasn't changed.
// This dispatcher does that.
ReactCurrentDispatcher$1.current=HooksDispatcherOnMountWithHookTypesInDEV;}else {ReactCurrentDispatcher$1.current=HooksDispatcherOnMountInDEV;}}var children=Component(props,secondArg);// Check if there was a render phase update
if(didScheduleRenderPhaseUpdateDuringThisPass){// Keep rendering in a loop for as long as render phase updates continue to
// be scheduled. Use a counter to prevent infinite loops.
var numberOfReRenders=0;do{didScheduleRenderPhaseUpdateDuringThisPass=false;localIdCounter=0;if(numberOfReRenders>=RE_RENDER_LIMIT){throw new Error('Too many re-renders. React limits the number of renders to prevent '+'an infinite loop.');}numberOfReRenders+=1;{// Even when hot reloading, allow dependencies to stabilize
// after first render to prevent infinite render phase updates.
ignorePreviousDependencies=false;}// Start over from the beginning of the list
currentHook=null;workInProgressHook=null;workInProgress.updateQueue=null;{// Also validate hook order for cascading updates.
hookTypesUpdateIndexDev=-1;}ReactCurrentDispatcher$1.current=HooksDispatcherOnRerenderInDEV;children=Component(props,secondArg);}while(didScheduleRenderPhaseUpdateDuringThisPass);}// We can assume the previous dispatcher is always this one, since we set it
// at the beginning of the render phase and there's no re-entrance.
ReactCurrentDispatcher$1.current=ContextOnlyDispatcher;{workInProgress._debugHookTypes=hookTypesDev;}// This check uses currentHook so that it works the same in DEV and prod bundles.
// hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
var didRenderTooFewHooks=currentHook!==null&&currentHook.next!==null;renderLanes=NoLanes;currentlyRenderingFiber$1=null;currentHook=null;workInProgressHook=null;{currentHookNameInDev=null;hookTypesDev=null;hookTypesUpdateIndexDev=-1;// Confirm that a static flag was not added or removed since the last
// render. If this fires, it suggests that we incorrectly reset the static
// flags in some other part of the codebase. This has happened before, for
// example, in the SuspenseList implementation.
if(current!==null&&(current.flags&StaticMask)!==(workInProgress.flags&StaticMask)&&// Disable this warning in legacy mode, because legacy Suspense is weird
// and creates false positives. To make this work in legacy mode, we'd
// need to mark fibers that commit in an incomplete state, somehow. For
// now I'll disable the warning that most of the bugs that would trigger
// it are either exclusive to concurrent mode or exist in both.
(current.mode&ConcurrentMode)!==NoMode){error('Internal React error: Expected static flag was missing. Please '+'notify the React team.');}}didScheduleRenderPhaseUpdate=false;// This is reset by checkDidRenderIdHook
// localIdCounter = 0;
if(didRenderTooFewHooks){throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental '+'early return statement.');}return children;}function checkDidRenderIdHook(){// This should be called immediately after every renderWithHooks call.
// Conceptually, it's part of the return value of renderWithHooks; it's only a
// separate function to avoid using an array tuple.
var didRenderIdHook=localIdCounter!==0;localIdCounter=0;return didRenderIdHook;}function bailoutHooks(current,workInProgress,lanes){workInProgress.updateQueue=current.updateQueue;// TODO: Don't need to reset the flags here, because they're reset in the
// complete phase (bubbleProperties).
if((workInProgress.mode&StrictEffectsMode)!==NoMode){workInProgress.flags&=~(MountPassiveDev|MountLayoutDev|Passive|Update);}else {workInProgress.flags&=~(Passive|Update);}current.lanes=removeLanes(current.lanes,lanes);}function resetHooksAfterThrow(){// We can assume the previous dispatcher is always this one, since we set it
// at the beginning of the render phase and there's no re-entrance.
ReactCurrentDispatcher$1.current=ContextOnlyDispatcher;if(didScheduleRenderPhaseUpdate){// There were render phase updates. These are only valid for this render
// phase, which we are now aborting. Remove the updates from the queues so
// they do not persist to the next render. Do not remove updates from hooks
// that weren't processed.
//
// Only reset the updates from the queue if it has a clone. If it does
// not have a clone, that means it wasn't processed, and the updates were
// scheduled before we entered the render phase.
var hook=currentlyRenderingFiber$1.memoizedState;while(hook!==null){var queue=hook.queue;if(queue!==null){queue.pending=null;}hook=hook.next;}didScheduleRenderPhaseUpdate=false;}renderLanes=NoLanes;currentlyRenderingFiber$1=null;currentHook=null;workInProgressHook=null;{hookTypesDev=null;hookTypesUpdateIndexDev=-1;currentHookNameInDev=null;isUpdatingOpaqueValueInRenderPhase=false;}didScheduleRenderPhaseUpdateDuringThisPass=false;localIdCounter=0;}function mountWorkInProgressHook(){var hook={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};if(workInProgressHook===null){// This is the first hook in the list
currentlyRenderingFiber$1.memoizedState=workInProgressHook=hook;}else {// Append to the end of the list
workInProgressHook=workInProgressHook.next=hook;}return workInProgressHook;}function updateWorkInProgressHook(){// This function is used both for updates and for re-renders triggered by a
// render phase update. It assumes there is either a current hook we can
// clone, or a work-in-progress hook from a previous render pass that we can
// use as a base. When we reach the end of the base list, we must switch to
// the dispatcher used for mounts.
var nextCurrentHook;if(currentHook===null){var current=currentlyRenderingFiber$1.alternate;if(current!==null){nextCurrentHook=current.memoizedState;}else {nextCurrentHook=null;}}else {nextCurrentHook=currentHook.next;}var nextWorkInProgressHook;if(workInProgressHook===null){nextWorkInProgressHook=currentlyRenderingFiber$1.memoizedState;}else {nextWorkInProgressHook=workInProgressHook.next;}if(nextWorkInProgressHook!==null){// There's already a work-in-progress. Reuse it.
workInProgressHook=nextWorkInProgressHook;nextWorkInProgressHook=workInProgressHook.next;currentHook=nextCurrentHook;}else {// Clone from the current hook.
if(nextCurrentHook===null){throw new Error('Rendered more hooks than during the previous render.');}currentHook=nextCurrentHook;var newHook={memoizedState:currentHook.memoizedState,baseState:currentHook.baseState,baseQueue:currentHook.baseQueue,queue:currentHook.queue,next:null};if(workInProgressHook===null){// This is the first hook in the list.
currentlyRenderingFiber$1.memoizedState=workInProgressHook=newHook;}else {// Append to the end of the list.
workInProgressHook=workInProgressHook.next=newHook;}}return workInProgressHook;}function createFunctionComponentUpdateQueue(){return {lastEffect:null,stores:null};}function basicStateReducer(state,action){// $FlowFixMe: Flow doesn't like mixed types
return typeof action==='function'?action(state):action;}function mountReducer(reducer,initialArg,init){var hook=mountWorkInProgressHook();var initialState;if(init!==undefined){initialState=init(initialArg);}else {initialState=initialArg;}hook.memoizedState=hook.baseState=initialState;var queue={pending:null,interleaved:null,lanes:NoLanes,dispatch:null,lastRenderedReducer:reducer,lastRenderedState:initialState};hook.queue=queue;var dispatch=queue.dispatch=dispatchReducerAction.bind(null,currentlyRenderingFiber$1,queue);return [hook.memoizedState,dispatch];}function updateReducer(reducer,initialArg,init){var hook=updateWorkInProgressHook();var queue=hook.queue;if(queue===null){throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');}queue.lastRenderedReducer=reducer;var current=currentHook;// The last rebase update that is NOT part of the base state.
var baseQueue=current.baseQueue;// The last pending update that hasn't been processed yet.
var pendingQueue=queue.pending;if(pendingQueue!==null){// We have new updates that haven't been processed yet.
// We'll add them to the base queue.
if(baseQueue!==null){// Merge the pending queue and the base queue.
var baseFirst=baseQueue.next;var pendingFirst=pendingQueue.next;baseQueue.next=pendingFirst;pendingQueue.next=baseFirst;}{if(current.baseQueue!==baseQueue){// Internal invariant that should never happen, but feasibly could in
// the future if we implement resuming, or some form of that.
error('Internal error: Expected work-in-progress queue to be a clone. '+'This is a bug in React.');}}current.baseQueue=baseQueue=pendingQueue;queue.pending=null;}if(baseQueue!==null){// We have a queue to process.
var first=baseQueue.next;var newState=current.baseState;var newBaseState=null;var newBaseQueueFirst=null;var newBaseQueueLast=null;var update=first;do{var updateLane=update.lane;if(!isSubsetOfLanes(renderLanes,updateLane)){// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
var clone={lane:updateLane,action:update.action,hasEagerState:update.hasEagerState,eagerState:update.eagerState,next:null};if(newBaseQueueLast===null){newBaseQueueFirst=newBaseQueueLast=clone;newBaseState=newState;}else {newBaseQueueLast=newBaseQueueLast.next=clone;}// Update the remaining priority in the queue.
// TODO: Don't need to accumulate this. Instead, we can remove
// renderLanes from the original lanes.
currentlyRenderingFiber$1.lanes=mergeLanes(currentlyRenderingFiber$1.lanes,updateLane);markSkippedUpdateLanes(updateLane);}else {// This update does have sufficient priority.
if(newBaseQueueLast!==null){var _clone={// This update is going to be committed so we never want uncommit
// it. Using NoLane works because 0 is a subset of all bitmasks, so
// this will never be skipped by the check above.
lane:NoLane,action:update.action,hasEagerState:update.hasEagerState,eagerState:update.eagerState,next:null};newBaseQueueLast=newBaseQueueLast.next=_clone;}// Process this update.
if(update.hasEagerState){// If this update is a state update (not a reducer) and was processed eagerly,
// we can use the eagerly computed state
newState=update.eagerState;}else {var action=update.action;newState=reducer(newState,action);}}update=update.next;}while(update!==null&&update!==first);if(newBaseQueueLast===null){newBaseState=newState;}else {newBaseQueueLast.next=newBaseQueueFirst;}// Mark that the fiber performed work, but only if the new state is
// different from the current state.
if(!objectIs(newState,hook.memoizedState)){markWorkInProgressReceivedUpdate();}hook.memoizedState=newState;hook.baseState=newBaseState;hook.baseQueue=newBaseQueueLast;queue.lastRenderedState=newState;}// Interleaved updates are stored on a separate queue. We aren't going to
// process them during this render, but we do need to track which lanes
// are remaining.
var lastInterleaved=queue.interleaved;if(lastInterleaved!==null){var interleaved=lastInterleaved;do{var interleavedLane=interleaved.lane;currentlyRenderingFiber$1.lanes=mergeLanes(currentlyRenderingFiber$1.lanes,interleavedLane);markSkippedUpdateLanes(interleavedLane);interleaved=interleaved.next;}while(interleaved!==lastInterleaved);}else if(baseQueue===null){// `queue.lanes` is used for entangling transitions. We can set it back to
// zero once the queue is empty.
queue.lanes=NoLanes;}var dispatch=queue.dispatch;return [hook.memoizedState,dispatch];}function rerenderReducer(reducer,initialArg,init){var hook=updateWorkInProgressHook();var queue=hook.queue;if(queue===null){throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');}queue.lastRenderedReducer=reducer;// This is a re-render. Apply the new render phase updates to the previous
// work-in-progress hook.
var dispatch=queue.dispatch;var lastRenderPhaseUpdate=queue.pending;var newState=hook.memoizedState;if(lastRenderPhaseUpdate!==null){// The queue doesn't persist past this render pass.
queue.pending=null;var firstRenderPhaseUpdate=lastRenderPhaseUpdate.next;var update=firstRenderPhaseUpdate;do{// Process this render phase update. We don't have to check the
// priority because it will always be the same as the current
// render's.
var action=update.action;newState=reducer(newState,action);update=update.next;}while(update!==firstRenderPhaseUpdate);// Mark that the fiber performed work, but only if the new state is
// different from the current state.
if(!objectIs(newState,hook.memoizedState)){markWorkInProgressReceivedUpdate();}hook.memoizedState=newState;// Don't persist the state accumulated from the render phase updates to
// the base state unless the queue is empty.
// TODO: Not sure if this is the desired semantics, but it's what we
// do for gDSFP. I can't remember why.
if(hook.baseQueue===null){hook.baseState=newState;}queue.lastRenderedState=newState;}return [newState,dispatch];}function mountMutableSource(source,getSnapshot,subscribe){{return undefined;}}function updateMutableSource(source,getSnapshot,subscribe){{return undefined;}}function mountSyncExternalStore(subscribe,getSnapshot,getServerSnapshot){var fiber=currentlyRenderingFiber$1;var hook=mountWorkInProgressHook();var nextSnapshot;var isHydrating=getIsHydrating();if(isHydrating){if(getServerSnapshot===undefined){throw new Error('Missing getServerSnapshot, which is required for '+'server-rendered content. Will revert to client rendering.');}nextSnapshot=getServerSnapshot();{if(!didWarnUncachedGetSnapshot){if(nextSnapshot!==getServerSnapshot()){error('The result of getServerSnapshot should be cached to avoid an infinite loop');didWarnUncachedGetSnapshot=true;}}}}else {nextSnapshot=getSnapshot();{if(!didWarnUncachedGetSnapshot){var cachedSnapshot=getSnapshot();if(!objectIs(nextSnapshot,cachedSnapshot)){error('The result of getSnapshot should be cached to avoid an infinite loop');didWarnUncachedGetSnapshot=true;}}}// Unless we're rendering a blocking lane, schedule a consistency check.
// Right before committing, we will walk the tree and check if any of the
// stores were mutated.
//
// We won't do this if we're hydrating server-rendered content, because if
// the content is stale, it's already visible anyway. Instead we'll patch
// it up in a passive effect.
var root=getWorkInProgressRoot();if(root===null){throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');}if(!includesBlockingLane(root,renderLanes)){pushStoreConsistencyCheck(fiber,getSnapshot,nextSnapshot);}}// Read the current snapshot from the store on every render. This breaks the
// normal rules of React, and only works because store updates are
// always synchronous.
hook.memoizedState=nextSnapshot;var inst={value:nextSnapshot,getSnapshot:getSnapshot};hook.queue=inst;// Schedule an effect to subscribe to the store.
mountEffect(subscribeToStore.bind(null,fiber,inst,subscribe),[subscribe]);// Schedule an effect to update the mutable instance fields. We will update
// this whenever subscribe, getSnapshot, or value changes. Because there's no
// clean-up function, and we track the deps correctly, we can call pushEffect
// directly, without storing any additional state. For the same reason, we
// don't need to set a static flag, either.
// TODO: We can move this to the passive phase once we add a pre-commit
// consistency check. See the next comment.
fiber.flags|=Passive;pushEffect(HasEffect|Passive$1,updateStoreInstance.bind(null,fiber,inst,nextSnapshot,getSnapshot),undefined,null);return nextSnapshot;}function updateSyncExternalStore(subscribe,getSnapshot,getServerSnapshot){var fiber=currentlyRenderingFiber$1;var hook=updateWorkInProgressHook();// Read the current snapshot from the store on every render. This breaks the
// normal rules of React, and only works because store updates are
// always synchronous.
var nextSnapshot=getSnapshot();{if(!didWarnUncachedGetSnapshot){var cachedSnapshot=getSnapshot();if(!objectIs(nextSnapshot,cachedSnapshot)){error('The result of getSnapshot should be cached to avoid an infinite loop');didWarnUncachedGetSnapshot=true;}}}var prevSnapshot=hook.memoizedState;var snapshotChanged=!objectIs(prevSnapshot,nextSnapshot);if(snapshotChanged){hook.memoizedState=nextSnapshot;markWorkInProgressReceivedUpdate();}var inst=hook.queue;updateEffect(subscribeToStore.bind(null,fiber,inst,subscribe),[subscribe]);// Whenever getSnapshot or subscribe changes, we need to check in the
// commit phase if there was an interleaved mutation. In concurrent mode
// this can happen all the time, but even in synchronous mode, an earlier
// effect may have mutated the store.
if(inst.getSnapshot!==getSnapshot||snapshotChanged||// Check if the susbcribe function changed. We can save some memory by
// checking whether we scheduled a subscription effect above.
workInProgressHook!==null&&workInProgressHook.memoizedState.tag&HasEffect){fiber.flags|=Passive;pushEffect(HasEffect|Passive$1,updateStoreInstance.bind(null,fiber,inst,nextSnapshot,getSnapshot),undefined,null);// Unless we're rendering a blocking lane, schedule a consistency check.
// Right before committing, we will walk the tree and check if any of the
// stores were mutated.
var root=getWorkInProgressRoot();if(root===null){throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');}if(!includesBlockingLane(root,renderLanes)){pushStoreConsistencyCheck(fiber,getSnapshot,nextSnapshot);}}return nextSnapshot;}function pushStoreConsistencyCheck(fiber,getSnapshot,renderedSnapshot){fiber.flags|=StoreConsistency;var check={getSnapshot:getSnapshot,value:renderedSnapshot};var componentUpdateQueue=currentlyRenderingFiber$1.updateQueue;if(componentUpdateQueue===null){componentUpdateQueue=createFunctionComponentUpdateQueue();currentlyRenderingFiber$1.updateQueue=componentUpdateQueue;componentUpdateQueue.stores=[check];}else {var stores=componentUpdateQueue.stores;if(stores===null){componentUpdateQueue.stores=[check];}else {stores.push(check);}}}function updateStoreInstance(fiber,inst,nextSnapshot,getSnapshot){// These are updated in the passive phase
inst.value=nextSnapshot;inst.getSnapshot=getSnapshot;// Something may have been mutated in between render and commit. This could
// have been in an event that fired before the passive effects, or it could
// have been in a layout effect. In that case, we would have used the old
// snapsho and getSnapshot values to bail out. We need to check one more time.
if(checkIfSnapshotChanged(inst)){// Force a re-render.
forceStoreRerender(fiber);}}function subscribeToStore(fiber,inst,subscribe){var handleStoreChange=function(){// The store changed. Check if the snapshot changed since the last time we
// read from the store.
if(checkIfSnapshotChanged(inst)){// Force a re-render.
forceStoreRerender(fiber);}};// Subscribe to the store and return a clean-up function.
return subscribe(handleStoreChange);}function checkIfSnapshotChanged(inst){var latestGetSnapshot=inst.getSnapshot;var prevValue=inst.value;try{var nextValue=latestGetSnapshot();return !objectIs(prevValue,nextValue);}catch(error){return true;}}function forceStoreRerender(fiber){var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}}function mountState(initialState){var hook=mountWorkInProgressHook();if(typeof initialState==='function'){// $FlowFixMe: Flow doesn't like mixed types
initialState=initialState();}hook.memoizedState=hook.baseState=initialState;var queue={pending:null,interleaved:null,lanes:NoLanes,dispatch:null,lastRenderedReducer:basicStateReducer,lastRenderedState:initialState};hook.queue=queue;var dispatch=queue.dispatch=dispatchSetState.bind(null,currentlyRenderingFiber$1,queue);return [hook.memoizedState,dispatch];}function updateState(initialState){return updateReducer(basicStateReducer);}function rerenderState(initialState){return rerenderReducer(basicStateReducer);}function pushEffect(tag,create,destroy,deps){var effect={tag:tag,create:create,destroy:destroy,deps:deps,// Circular
next:null};var componentUpdateQueue=currentlyRenderingFiber$1.updateQueue;if(componentUpdateQueue===null){componentUpdateQueue=createFunctionComponentUpdateQueue();currentlyRenderingFiber$1.updateQueue=componentUpdateQueue;componentUpdateQueue.lastEffect=effect.next=effect;}else {var lastEffect=componentUpdateQueue.lastEffect;if(lastEffect===null){componentUpdateQueue.lastEffect=effect.next=effect;}else {var firstEffect=lastEffect.next;lastEffect.next=effect;effect.next=firstEffect;componentUpdateQueue.lastEffect=effect;}}return effect;}function mountRef(initialValue){var hook=mountWorkInProgressHook();{var _ref2={current:initialValue};hook.memoizedState=_ref2;return _ref2;}}function updateRef(initialValue){var hook=updateWorkInProgressHook();return hook.memoizedState;}function mountEffectImpl(fiberFlags,hookFlags,create,deps){var hook=mountWorkInProgressHook();var nextDeps=deps===undefined?null:deps;currentlyRenderingFiber$1.flags|=fiberFlags;hook.memoizedState=pushEffect(HasEffect|hookFlags,create,undefined,nextDeps);}function updateEffectImpl(fiberFlags,hookFlags,create,deps){var hook=updateWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var destroy=undefined;if(currentHook!==null){var prevEffect=currentHook.memoizedState;destroy=prevEffect.destroy;if(nextDeps!==null){var prevDeps=prevEffect.deps;if(areHookInputsEqual(nextDeps,prevDeps)){hook.memoizedState=pushEffect(hookFlags,create,destroy,nextDeps);return;}}}currentlyRenderingFiber$1.flags|=fiberFlags;hook.memoizedState=pushEffect(HasEffect|hookFlags,create,destroy,nextDeps);}function mountEffect(create,deps){if((currentlyRenderingFiber$1.mode&StrictEffectsMode)!==NoMode){return mountEffectImpl(MountPassiveDev|Passive|PassiveStatic,Passive$1,create,deps);}else {return mountEffectImpl(Passive|PassiveStatic,Passive$1,create,deps);}}function updateEffect(create,deps){return updateEffectImpl(Passive,Passive$1,create,deps);}function mountInsertionEffect(create,deps){return mountEffectImpl(Update,Insertion,create,deps);}function updateInsertionEffect(create,deps){return updateEffectImpl(Update,Insertion,create,deps);}function mountLayoutEffect(create,deps){var fiberFlags=Update;{fiberFlags|=LayoutStatic;}if((currentlyRenderingFiber$1.mode&StrictEffectsMode)!==NoMode){fiberFlags|=MountLayoutDev;}return mountEffectImpl(fiberFlags,Layout,create,deps);}function updateLayoutEffect(create,deps){return updateEffectImpl(Update,Layout,create,deps);}function imperativeHandleEffect(create,ref){if(typeof ref==='function'){var refCallback=ref;var _inst=create();refCallback(_inst);return function(){refCallback(null);};}else if(ref!==null&&ref!==undefined){var refObject=ref;{if(!refObject.hasOwnProperty('current')){error('Expected useImperativeHandle() first argument to either be a '+'ref callback or React.createRef() object. Instead received: %s.','an object with keys {'+Object.keys(refObject).join(', ')+'}');}}var _inst2=create();refObject.current=_inst2;return function(){refObject.current=null;};}}function mountImperativeHandle(ref,create,deps){{if(typeof create!=='function'){error('Expected useImperativeHandle() second argument to be a function '+'that creates a handle. Instead received: %s.',create!==null?typeof create:'null');}}// TODO: If deps are provided, should we skip comparing the ref itself?
var effectDeps=deps!==null&&deps!==undefined?deps.concat([ref]):null;var fiberFlags=Update;{fiberFlags|=LayoutStatic;}if((currentlyRenderingFiber$1.mode&StrictEffectsMode)!==NoMode){fiberFlags|=MountLayoutDev;}return mountEffectImpl(fiberFlags,Layout,imperativeHandleEffect.bind(null,create,ref),effectDeps);}function updateImperativeHandle(ref,create,deps){{if(typeof create!=='function'){error('Expected useImperativeHandle() second argument to be a function '+'that creates a handle. Instead received: %s.',create!==null?typeof create:'null');}}// TODO: If deps are provided, should we skip comparing the ref itself?
var effectDeps=deps!==null&&deps!==undefined?deps.concat([ref]):null;return updateEffectImpl(Update,Layout,imperativeHandleEffect.bind(null,create,ref),effectDeps);}function mountDebugValue(value,formatterFn){// This hook is normally a no-op.
// The react-debug-hooks package injects its own implementation
// so that e.g. DevTools can display custom hook values.
}var updateDebugValue=mountDebugValue;function mountCallback(callback,deps){var hook=mountWorkInProgressHook();var nextDeps=deps===undefined?null:deps;hook.memoizedState=[callback,nextDeps];return callback;}function updateCallback(callback,deps){var hook=updateWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var prevState=hook.memoizedState;if(prevState!==null){if(nextDeps!==null){var prevDeps=prevState[1];if(areHookInputsEqual(nextDeps,prevDeps)){return prevState[0];}}}hook.memoizedState=[callback,nextDeps];return callback;}function mountMemo(nextCreate,deps){var hook=mountWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var nextValue=nextCreate();hook.memoizedState=[nextValue,nextDeps];return nextValue;}function updateMemo(nextCreate,deps){var hook=updateWorkInProgressHook();var nextDeps=deps===undefined?null:deps;var prevState=hook.memoizedState;if(prevState!==null){// Assume these are defined. If they're not, areHookInputsEqual will warn.
if(nextDeps!==null){var prevDeps=prevState[1];if(areHookInputsEqual(nextDeps,prevDeps)){return prevState[0];}}}var nextValue=nextCreate();hook.memoizedState=[nextValue,nextDeps];return nextValue;}function mountDeferredValue(value){var hook=mountWorkInProgressHook();hook.memoizedState=value;return value;}function updateDeferredValue(value){var hook=updateWorkInProgressHook();var resolvedCurrentHook=currentHook;var prevValue=resolvedCurrentHook.memoizedState;return updateDeferredValueImpl(hook,prevValue,value);}function rerenderDeferredValue(value){var hook=updateWorkInProgressHook();if(currentHook===null){// This is a rerender during a mount.
hook.memoizedState=value;return value;}else {// This is a rerender during an update.
var prevValue=currentHook.memoizedState;return updateDeferredValueImpl(hook,prevValue,value);}}function updateDeferredValueImpl(hook,prevValue,value){var shouldDeferValue=!includesOnlyNonUrgentLanes(renderLanes);if(shouldDeferValue){// This is an urgent update. If the value has changed, keep using the
// previous value and spawn a deferred render to update it later.
if(!objectIs(value,prevValue)){// Schedule a deferred render
var deferredLane=claimNextTransitionLane();currentlyRenderingFiber$1.lanes=mergeLanes(currentlyRenderingFiber$1.lanes,deferredLane);markSkippedUpdateLanes(deferredLane);// Set this to true to indicate that the rendered value is inconsistent
// from the latest value. The name "baseState" doesn't really match how we
// use it because we're reusing a state hook field instead of creating a
// new one.
hook.baseState=true;}// Reuse the previous value
return prevValue;}else {// This is not an urgent update, so we can use the latest value regardless
// of what it is. No need to defer it.
// However, if we're currently inside a spawned render, then we need to mark
// this as an update to prevent the fiber from bailing out.
//
// `baseState` is true when the current value is different from the rendered
// value. The name doesn't really match how we use it because we're reusing
// a state hook field instead of creating a new one.
if(hook.baseState){// Flip this back to false.
hook.baseState=false;markWorkInProgressReceivedUpdate();}hook.memoizedState=value;return value;}}function startTransition(setPending,callback,options){var previousPriority=getCurrentUpdatePriority();setCurrentUpdatePriority(higherEventPriority(previousPriority,ContinuousEventPriority));setPending(true);var prevTransition=ReactCurrentBatchConfig$2.transition;ReactCurrentBatchConfig$2.transition={};var currentTransition=ReactCurrentBatchConfig$2.transition;{ReactCurrentBatchConfig$2.transition._updatedFibers=new Set();}try{setPending(false);callback();}finally{setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig$2.transition=prevTransition;{if(prevTransition===null&&currentTransition._updatedFibers){var updatedFibersCount=currentTransition._updatedFibers.size;if(updatedFibersCount>10){warn('Detected a large number of updates inside startTransition. '+'If this is due to a subscription please re-write it to use React provided hooks. '+'Otherwise concurrent mode guarantees are off the table.');}currentTransition._updatedFibers.clear();}}}}function mountTransition(){var _mountState=mountState(false),isPending=_mountState[0],setPending=_mountState[1];// The `start` method never changes.
var start=startTransition.bind(null,setPending);var hook=mountWorkInProgressHook();hook.memoizedState=start;return [isPending,start];}function updateTransition(){var _updateState=updateState(),isPending=_updateState[0];var hook=updateWorkInProgressHook();var start=hook.memoizedState;return [isPending,start];}function rerenderTransition(){var _rerenderState=rerenderState(),isPending=_rerenderState[0];var hook=updateWorkInProgressHook();var start=hook.memoizedState;return [isPending,start];}var isUpdatingOpaqueValueInRenderPhase=false;function getIsUpdatingOpaqueValueInRenderPhaseInDEV(){{return isUpdatingOpaqueValueInRenderPhase;}}function mountId(){var hook=mountWorkInProgressHook();var root=getWorkInProgressRoot();// TODO: In Fizz, id generation is specific to each server config. Maybe we
// should do this in Fiber, too? Deferring this decision for now because
// there's no other place to store the prefix except for an internal field on
// the public createRoot object, which the fiber tree does not currently have
// a reference to.
var identifierPrefix=root.identifierPrefix;var id;if(getIsHydrating()){var treeId=getTreeId();// Use a captial R prefix for server-generated ids.
id=':'+identifierPrefix+'R'+treeId;// Unless this is the first id at this level, append a number at the end
// that represents the position of this useId hook among all the useId
// hooks for this fiber.
var localId=localIdCounter++;if(localId>0){id+='H'+localId.toString(32);}id+=':';}else {// Use a lowercase r prefix for client-generated ids.
var globalClientId=globalClientIdCounter++;id=':'+identifierPrefix+'r'+globalClientId.toString(32)+':';}hook.memoizedState=id;return id;}function updateId(){var hook=updateWorkInProgressHook();var id=hook.memoizedState;return id;}function dispatchReducerAction(fiber,queue,action){{if(typeof arguments[3]==='function'){error("State updates from the useState() and useReducer() Hooks don't support the "+'second callback argument. To execute a side effect after '+'rendering, declare it in the component body with useEffect().');}}var lane=requestUpdateLane(fiber);var update={lane:lane,action:action,hasEagerState:false,eagerState:null,next:null};if(isRenderPhaseUpdate(fiber)){enqueueRenderPhaseUpdate(queue,update);}else {var root=enqueueConcurrentHookUpdate(fiber,queue,update,lane);if(root!==null){var eventTime=requestEventTime();scheduleUpdateOnFiber(root,fiber,lane,eventTime);entangleTransitionUpdate(root,queue,lane);}}markUpdateInDevTools(fiber,lane);}function dispatchSetState(fiber,queue,action){{if(typeof arguments[3]==='function'){error("State updates from the useState() and useReducer() Hooks don't support the "+'second callback argument. To execute a side effect after '+'rendering, declare it in the component body with useEffect().');}}var lane=requestUpdateLane(fiber);var update={lane:lane,action:action,hasEagerState:false,eagerState:null,next:null};if(isRenderPhaseUpdate(fiber)){enqueueRenderPhaseUpdate(queue,update);}else {var alternate=fiber.alternate;if(fiber.lanes===NoLanes&&(alternate===null||alternate.lanes===NoLanes)){// The queue is currently empty, which means we can eagerly compute the
// next state before entering the render phase. If the new state is the
// same as the current state, we may be able to bail out entirely.
var lastRenderedReducer=queue.lastRenderedReducer;if(lastRenderedReducer!==null){var prevDispatcher;{prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;}try{var currentState=queue.lastRenderedState;var eagerState=lastRenderedReducer(currentState,action);// Stash the eagerly computed state, and the reducer used to compute
// it, on the update object. If the reducer hasn't changed by the
// time we enter the render phase, then the eager state can be used
// without calling the reducer again.
update.hasEagerState=true;update.eagerState=eagerState;if(objectIs(eagerState,currentState)){// Fast path. We can bail out without scheduling React to re-render.
// It's still possible that we'll need to rebase this update later,
// if the component re-renders for a different reason and by that
// time the reducer has changed.
// TODO: Do we still need to entangle transitions in this case?
enqueueConcurrentHookUpdateAndEagerlyBailout(fiber,queue,update,lane);return;}}catch(error){// Suppress the error. It will throw again in the render phase.
}finally{{ReactCurrentDispatcher$1.current=prevDispatcher;}}}}var root=enqueueConcurrentHookUpdate(fiber,queue,update,lane);if(root!==null){var eventTime=requestEventTime();scheduleUpdateOnFiber(root,fiber,lane,eventTime);entangleTransitionUpdate(root,queue,lane);}}markUpdateInDevTools(fiber,lane);}function isRenderPhaseUpdate(fiber){var alternate=fiber.alternate;return fiber===currentlyRenderingFiber$1||alternate!==null&&alternate===currentlyRenderingFiber$1;}function enqueueRenderPhaseUpdate(queue,update){// This is a render phase update. Stash it in a lazily-created map of
// queue -> linked list of updates. After this render pass, we'll restart
// and apply the stashed updates on top of the work-in-progress hook.
didScheduleRenderPhaseUpdateDuringThisPass=didScheduleRenderPhaseUpdate=true;var pending=queue.pending;if(pending===null){// This is the first update. Create a circular list.
update.next=update;}else {update.next=pending.next;pending.next=update;}queue.pending=update;}// TODO: Move to ReactFiberConcurrentUpdates?
function entangleTransitionUpdate(root,queue,lane){if(isTransitionLane(lane)){var queueLanes=queue.lanes;// If any entangled lanes are no longer pending on the root, then they
// must have finished. We can remove them from the shared queue, which
// represents a superset of the actually pending lanes. In some cases we
// may entangle more than we need to, but that's OK. In fact it's worse if
// we *don't* entangle when we should.
queueLanes=intersectLanes(queueLanes,root.pendingLanes);// Entangle the new transition lane with the other transition lanes.
var newQueueLanes=mergeLanes(queueLanes,lane);queue.lanes=newQueueLanes;// Even if queue.lanes already include lane, we don't know for certain if
// the lane finished since the last time we entangled it. So we need to
// entangle it again, just to be sure.
markRootEntangled(root,newQueueLanes);}}function markUpdateInDevTools(fiber,lane,action){{markStateUpdateScheduled(fiber,lane);}}var ContextOnlyDispatcher={readContext:readContext,useCallback:throwInvalidHookError,useContext:throwInvalidHookError,useEffect:throwInvalidHookError,useImperativeHandle:throwInvalidHookError,useInsertionEffect:throwInvalidHookError,useLayoutEffect:throwInvalidHookError,useMemo:throwInvalidHookError,useReducer:throwInvalidHookError,useRef:throwInvalidHookError,useState:throwInvalidHookError,useDebugValue:throwInvalidHookError,useDeferredValue:throwInvalidHookError,useTransition:throwInvalidHookError,useMutableSource:throwInvalidHookError,useSyncExternalStore:throwInvalidHookError,useId:throwInvalidHookError,unstable_isNewReconciler:enableNewReconciler};var HooksDispatcherOnMountInDEV=null;var HooksDispatcherOnMountWithHookTypesInDEV=null;var HooksDispatcherOnUpdateInDEV=null;var HooksDispatcherOnRerenderInDEV=null;var InvalidNestedHooksDispatcherOnMountInDEV=null;var InvalidNestedHooksDispatcherOnUpdateInDEV=null;var InvalidNestedHooksDispatcherOnRerenderInDEV=null;{var warnInvalidContextAccess=function(){error('Context can only be read while React is rendering. '+'In classes, you can read it in the render method or getDerivedStateFromProps. '+'In function components, you can read it directly in the function body, but not '+'inside Hooks like useReducer() or useMemo().');};var warnInvalidHookAccess=function(){error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. '+'You can only call Hooks at the top level of your React function. '+'For more information, see '+'https://reactjs.org/link/rules-of-hooks');};HooksDispatcherOnMountInDEV={readContext:function(context){return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';mountHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';mountHookTypesDev();checkDepsAreArrayDev(deps);return mountLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';mountHookTypesDev();checkDepsAreArrayDev(deps);var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';mountHookTypesDev();return mountRef(initialValue);},useState:function(initialState){currentHookNameInDev='useState';mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';mountHookTypesDev();return mountDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';mountHookTypesDev();return mountDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';mountHookTypesDev();return mountTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';mountHookTypesDev();return mountMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';mountHookTypesDev();return mountSyncExternalStore(subscribe,getSnapshot,getServerSnapshot);},useId:function(){currentHookNameInDev='useId';mountHookTypesDev();return mountId();},unstable_isNewReconciler:enableNewReconciler};HooksDispatcherOnMountWithHookTypesInDEV={readContext:function(context){return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';updateHookTypesDev();return mountCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';updateHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';updateHookTypesDev();return mountEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';updateHookTypesDev();return mountImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';updateHookTypesDev();return mountInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';updateHookTypesDev();return mountLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';updateHookTypesDev();return mountRef(initialValue);},useState:function(initialState){currentHookNameInDev='useState';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';updateHookTypesDev();return mountDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';updateHookTypesDev();return mountDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';updateHookTypesDev();return mountTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';updateHookTypesDev();return mountMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';updateHookTypesDev();return mountSyncExternalStore(subscribe,getSnapshot,getServerSnapshot);},useId:function(){currentHookNameInDev='useId';updateHookTypesDev();return mountId();},unstable_isNewReconciler:enableNewReconciler};HooksDispatcherOnUpdateInDEV={readContext:function(context){return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';updateHookTypesDev();return updateCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';updateHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';updateHookTypesDev();return updateEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';updateHookTypesDev();return updateImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';updateHookTypesDev();return updateInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';updateHookTypesDev();return updateLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';updateHookTypesDev();return updateRef();},useState:function(initialState){currentHookNameInDev='useState';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';updateHookTypesDev();return updateDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';updateHookTypesDev();return updateDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';updateHookTypesDev();return updateTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';updateHookTypesDev();return updateMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';updateHookTypesDev();return updateSyncExternalStore(subscribe,getSnapshot);},useId:function(){currentHookNameInDev='useId';updateHookTypesDev();return updateId();},unstable_isNewReconciler:enableNewReconciler};HooksDispatcherOnRerenderInDEV={readContext:function(context){return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';updateHookTypesDev();return updateCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';updateHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';updateHookTypesDev();return updateEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';updateHookTypesDev();return updateImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';updateHookTypesDev();return updateInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';updateHookTypesDev();return updateLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnRerenderInDEV;try{return updateMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnRerenderInDEV;try{return rerenderReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';updateHookTypesDev();return updateRef();},useState:function(initialState){currentHookNameInDev='useState';updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnRerenderInDEV;try{return rerenderState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';updateHookTypesDev();return updateDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';updateHookTypesDev();return rerenderDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';updateHookTypesDev();return rerenderTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';updateHookTypesDev();return updateMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';updateHookTypesDev();return updateSyncExternalStore(subscribe,getSnapshot);},useId:function(){currentHookNameInDev='useId';updateHookTypesDev();return updateId();},unstable_isNewReconciler:enableNewReconciler};InvalidNestedHooksDispatcherOnMountInDEV={readContext:function(context){warnInvalidContextAccess();return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';warnInvalidHookAccess();mountHookTypesDev();return mountCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';warnInvalidHookAccess();mountHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';warnInvalidHookAccess();mountHookTypesDev();return mountEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';warnInvalidHookAccess();mountHookTypesDev();return mountImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';warnInvalidHookAccess();mountHookTypesDev();return mountInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';warnInvalidHookAccess();mountHookTypesDev();return mountLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';warnInvalidHookAccess();mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';warnInvalidHookAccess();mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';warnInvalidHookAccess();mountHookTypesDev();return mountRef(initialValue);},useState:function(initialState){currentHookNameInDev='useState';warnInvalidHookAccess();mountHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnMountInDEV;try{return mountState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';warnInvalidHookAccess();mountHookTypesDev();return mountDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';warnInvalidHookAccess();mountHookTypesDev();return mountDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';warnInvalidHookAccess();mountHookTypesDev();return mountTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';warnInvalidHookAccess();mountHookTypesDev();return mountMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';warnInvalidHookAccess();mountHookTypesDev();return mountSyncExternalStore(subscribe,getSnapshot,getServerSnapshot);},useId:function(){currentHookNameInDev='useId';warnInvalidHookAccess();mountHookTypesDev();return mountId();},unstable_isNewReconciler:enableNewReconciler};InvalidNestedHooksDispatcherOnUpdateInDEV={readContext:function(context){warnInvalidContextAccess();return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';warnInvalidHookAccess();updateHookTypesDev();return updateCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';warnInvalidHookAccess();updateHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';warnInvalidHookAccess();updateHookTypesDev();return updateEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';warnInvalidHookAccess();updateHookTypesDev();return updateImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';warnInvalidHookAccess();updateHookTypesDev();return updateInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';warnInvalidHookAccess();updateHookTypesDev();return updateLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';warnInvalidHookAccess();updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';warnInvalidHookAccess();updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';warnInvalidHookAccess();updateHookTypesDev();return updateRef();},useState:function(initialState){currentHookNameInDev='useState';warnInvalidHookAccess();updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';warnInvalidHookAccess();updateHookTypesDev();return updateDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';warnInvalidHookAccess();updateHookTypesDev();return updateDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';warnInvalidHookAccess();updateHookTypesDev();return updateTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';warnInvalidHookAccess();updateHookTypesDev();return updateMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';warnInvalidHookAccess();updateHookTypesDev();return updateSyncExternalStore(subscribe,getSnapshot);},useId:function(){currentHookNameInDev='useId';warnInvalidHookAccess();updateHookTypesDev();return updateId();},unstable_isNewReconciler:enableNewReconciler};InvalidNestedHooksDispatcherOnRerenderInDEV={readContext:function(context){warnInvalidContextAccess();return readContext(context);},useCallback:function(callback,deps){currentHookNameInDev='useCallback';warnInvalidHookAccess();updateHookTypesDev();return updateCallback(callback,deps);},useContext:function(context){currentHookNameInDev='useContext';warnInvalidHookAccess();updateHookTypesDev();return readContext(context);},useEffect:function(create,deps){currentHookNameInDev='useEffect';warnInvalidHookAccess();updateHookTypesDev();return updateEffect(create,deps);},useImperativeHandle:function(ref,create,deps){currentHookNameInDev='useImperativeHandle';warnInvalidHookAccess();updateHookTypesDev();return updateImperativeHandle(ref,create,deps);},useInsertionEffect:function(create,deps){currentHookNameInDev='useInsertionEffect';warnInvalidHookAccess();updateHookTypesDev();return updateInsertionEffect(create,deps);},useLayoutEffect:function(create,deps){currentHookNameInDev='useLayoutEffect';warnInvalidHookAccess();updateHookTypesDev();return updateLayoutEffect(create,deps);},useMemo:function(create,deps){currentHookNameInDev='useMemo';warnInvalidHookAccess();updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return updateMemo(create,deps);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useReducer:function(reducer,initialArg,init){currentHookNameInDev='useReducer';warnInvalidHookAccess();updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return rerenderReducer(reducer,initialArg,init);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useRef:function(initialValue){currentHookNameInDev='useRef';warnInvalidHookAccess();updateHookTypesDev();return updateRef();},useState:function(initialState){currentHookNameInDev='useState';warnInvalidHookAccess();updateHookTypesDev();var prevDispatcher=ReactCurrentDispatcher$1.current;ReactCurrentDispatcher$1.current=InvalidNestedHooksDispatcherOnUpdateInDEV;try{return rerenderState(initialState);}finally{ReactCurrentDispatcher$1.current=prevDispatcher;}},useDebugValue:function(value,formatterFn){currentHookNameInDev='useDebugValue';warnInvalidHookAccess();updateHookTypesDev();return updateDebugValue();},useDeferredValue:function(value){currentHookNameInDev='useDeferredValue';warnInvalidHookAccess();updateHookTypesDev();return rerenderDeferredValue(value);},useTransition:function(){currentHookNameInDev='useTransition';warnInvalidHookAccess();updateHookTypesDev();return rerenderTransition();},useMutableSource:function(source,getSnapshot,subscribe){currentHookNameInDev='useMutableSource';warnInvalidHookAccess();updateHookTypesDev();return updateMutableSource();},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){currentHookNameInDev='useSyncExternalStore';warnInvalidHookAccess();updateHookTypesDev();return updateSyncExternalStore(subscribe,getSnapshot);},useId:function(){currentHookNameInDev='useId';warnInvalidHookAccess();updateHookTypesDev();return updateId();},unstable_isNewReconciler:enableNewReconciler};}var now$1=Scheduler.unstable_now;var commitTime=0;var layoutEffectStartTime=-1;var profilerStartTime=-1;var passiveEffectStartTime=-1;/**
 * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect).
 *
 * The overall sequence is:
 *   1. render
 *   2. commit (and call `onRender`, `onCommit`)
 *   3. check for nested updates
 *   4. flush passive effects (and call `onPostCommit`)
 *
 * Nested updates are identified in step 3 above,
 * but step 4 still applies to the work that was just committed.
 * We use two flags to track nested updates then:
 * one tracks whether the upcoming update is a nested update,
 * and the other tracks whether the current update was a nested update.
 * The first value gets synced to the second at the start of the render phase.
 */var currentUpdateIsNested=false;var nestedUpdateScheduled=false;function isCurrentUpdateNested(){return currentUpdateIsNested;}function markNestedUpdateScheduled(){{nestedUpdateScheduled=true;}}function resetNestedUpdateFlag(){{currentUpdateIsNested=false;nestedUpdateScheduled=false;}}function syncNestedUpdateFlag(){{currentUpdateIsNested=nestedUpdateScheduled;nestedUpdateScheduled=false;}}function getCommitTime(){return commitTime;}function recordCommitTime(){commitTime=now$1();}function startProfilerTimer(fiber){profilerStartTime=now$1();if(fiber.actualStartTime<0){fiber.actualStartTime=now$1();}}function stopProfilerTimerIfRunning(fiber){profilerStartTime=-1;}function stopProfilerTimerIfRunningAndRecordDelta(fiber,overrideBaseTime){if(profilerStartTime>=0){var elapsedTime=now$1()-profilerStartTime;fiber.actualDuration+=elapsedTime;if(overrideBaseTime){fiber.selfBaseDuration=elapsedTime;}profilerStartTime=-1;}}function recordLayoutEffectDuration(fiber){if(layoutEffectStartTime>=0){var elapsedTime=now$1()-layoutEffectStartTime;layoutEffectStartTime=-1;// Store duration on the next nearest Profiler ancestor
// Or the root (for the DevTools Profiler to read)
var parentFiber=fiber.return;while(parentFiber!==null){switch(parentFiber.tag){case HostRoot:var root=parentFiber.stateNode;root.effectDuration+=elapsedTime;return;case Profiler:var parentStateNode=parentFiber.stateNode;parentStateNode.effectDuration+=elapsedTime;return;}parentFiber=parentFiber.return;}}}function recordPassiveEffectDuration(fiber){if(passiveEffectStartTime>=0){var elapsedTime=now$1()-passiveEffectStartTime;passiveEffectStartTime=-1;// Store duration on the next nearest Profiler ancestor
// Or the root (for the DevTools Profiler to read)
var parentFiber=fiber.return;while(parentFiber!==null){switch(parentFiber.tag){case HostRoot:var root=parentFiber.stateNode;if(root!==null){root.passiveEffectDuration+=elapsedTime;}return;case Profiler:var parentStateNode=parentFiber.stateNode;if(parentStateNode!==null){// Detached fibers have their state node cleared out.
// In this case, the return pointer is also cleared out,
// so we won't be able to report the time spent in this Profiler's subtree.
parentStateNode.passiveEffectDuration+=elapsedTime;}return;}parentFiber=parentFiber.return;}}}function startLayoutEffectTimer(){layoutEffectStartTime=now$1();}function startPassiveEffectTimer(){passiveEffectStartTime=now$1();}function transferActualDuration(fiber){// Transfer time spent rendering these children so we don't lose it
// after we rerender. This is used as a helper in special cases
// where we should count the work of multiple passes.
var child=fiber.child;while(child){fiber.actualDuration+=child.actualDuration;child=child.sibling;}}function createCapturedValueAtFiber(value,source){// If the value is an error, call this function immediately after it is thrown
// so the stack is accurate.
return {value:value,source:source,stack:getStackByFiberInDevAndProd(source),digest:null};}function createCapturedValue(value,digest,stack){return {value:value,source:null,stack:stack!=null?stack:null,digest:digest!=null?digest:null};}// This module is forked in different environments.
// By default, return `true` to log errors to the console.
// Forks can return `false` if this isn't desirable.
function showErrorDialog(boundary,errorInfo){return true;}function logCapturedError(boundary,errorInfo){try{var logError=showErrorDialog(boundary,errorInfo);// Allow injected showErrorDialog() to prevent default console.error logging.
// This enables renderers like ReactNative to better manage redbox behavior.
if(logError===false){return;}var error=errorInfo.value;if(true){var source=errorInfo.source;var stack=errorInfo.stack;var componentStack=stack!==null?stack:'';// Browsers support silencing uncaught errors by calling
// `preventDefault()` in window `error` handler.
// We record this information as an expando on the error.
if(error!=null&&error._suppressLogging){if(boundary.tag===ClassComponent){// The error is recoverable and was silenced.
// Ignore it and don't print the stack addendum.
// This is handy for testing error boundaries without noise.
return;}// The error is fatal. Since the silencing might have
// been accidental, we'll surface it anyway.
// However, the browser would have silenced the original error
// so we'll print it first, and then print the stack addendum.
console['error'](error);// Don't transform to our wrapper
// For a more detailed description of this block, see:
// https://github.com/facebook/react/pull/13384
}var componentName=source?getComponentNameFromFiber(source):null;var componentNameMessage=componentName?"The above error occurred in the <"+componentName+"> component:":'The above error occurred in one of your React components:';var errorBoundaryMessage;if(boundary.tag===HostRoot){errorBoundaryMessage='Consider adding an error boundary to your tree to customize error handling behavior.\n'+'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';}else {var errorBoundaryName=getComponentNameFromFiber(boundary)||'Anonymous';errorBoundaryMessage="React will try to recreate this component tree from scratch "+("using the error boundary you provided, "+errorBoundaryName+".");}var combinedMessage=componentNameMessage+"\n"+componentStack+"\n\n"+(""+errorBoundaryMessage);// In development, we provide our own message with just the component stack.
// We don't include the original error message and JS stack because the browser
// has already printed it. Even if the application swallows the error, it is still
// displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
console['error'](combinedMessage);// Don't transform to our wrapper
}}catch(e){// This method must not throw, or React internal state will get messed up.
// If console.error is overridden, or logCapturedError() shows a dialog that throws,
// we want to report this error outside of the normal stack as a last resort.
// https://github.com/facebook/react/issues/13188
setTimeout(function(){throw e;});}}var PossiblyWeakMap$1=typeof WeakMap==='function'?WeakMap:Map;function createRootErrorUpdate(fiber,errorInfo,lane){var update=createUpdate(NoTimestamp,lane);// Unmount the root by rendering null.
update.tag=CaptureUpdate;// Caution: React DevTools currently depends on this property
// being called "element".
update.payload={element:null};var error=errorInfo.value;update.callback=function(){onUncaughtError(error);logCapturedError(fiber,errorInfo);};return update;}function createClassErrorUpdate(fiber,errorInfo,lane){var update=createUpdate(NoTimestamp,lane);update.tag=CaptureUpdate;var getDerivedStateFromError=fiber.type.getDerivedStateFromError;if(typeof getDerivedStateFromError==='function'){var error$1=errorInfo.value;update.payload=function(){return getDerivedStateFromError(error$1);};update.callback=function(){{markFailedErrorBoundaryForHotReloading(fiber);}logCapturedError(fiber,errorInfo);};}var inst=fiber.stateNode;if(inst!==null&&typeof inst.componentDidCatch==='function'){update.callback=function callback(){{markFailedErrorBoundaryForHotReloading(fiber);}logCapturedError(fiber,errorInfo);if(typeof getDerivedStateFromError!=='function'){// To preserve the preexisting retry behavior of error boundaries,
// we keep track of which ones already failed during this batch.
// This gets reset before we yield back to the browser.
// TODO: Warn in strict mode if getDerivedStateFromError is
// not defined.
markLegacyErrorBoundaryAsFailed(this);}var error$1=errorInfo.value;var stack=errorInfo.stack;this.componentDidCatch(error$1,{componentStack:stack!==null?stack:''});{if(typeof getDerivedStateFromError!=='function'){// If componentDidCatch is the only error boundary method defined,
// then it needs to call setState to recover from errors.
// If no state update is scheduled then the boundary will swallow the error.
if(!includesSomeLane(fiber.lanes,SyncLane)){error('%s: Error boundaries should implement getDerivedStateFromError(). '+'In that method, return a state update to display an error message or fallback UI.',getComponentNameFromFiber(fiber)||'Unknown');}}}};}return update;}function attachPingListener(root,wakeable,lanes){// Attach a ping listener
//
// The data might resolve before we have a chance to commit the fallback. Or,
// in the case of a refresh, we'll never commit a fallback. So we need to
// attach a listener now. When it resolves ("pings"), we can decide whether to
// try rendering the tree again.
//
// Only attach a listener if one does not already exist for the lanes
// we're currently rendering (which acts like a "thread ID" here).
//
// We only need to do this in concurrent mode. Legacy Suspense always
// commits fallbacks synchronously, so there are no pings.
var pingCache=root.pingCache;var threadIDs;if(pingCache===null){pingCache=root.pingCache=new PossiblyWeakMap$1();threadIDs=new Set();pingCache.set(wakeable,threadIDs);}else {threadIDs=pingCache.get(wakeable);if(threadIDs===undefined){threadIDs=new Set();pingCache.set(wakeable,threadIDs);}}if(!threadIDs.has(lanes)){// Memoize using the thread ID to prevent redundant listeners.
threadIDs.add(lanes);var ping=pingSuspendedRoot.bind(null,root,wakeable,lanes);{if(isDevToolsPresent){// If we have pending work still, restore the original updaters
restorePendingUpdaters(root,lanes);}}wakeable.then(ping,ping);}}function attachRetryListener(suspenseBoundary,root,wakeable,lanes){// Retry listener
//
// If the fallback does commit, we need to attach a different type of
// listener. This one schedules an update on the Suspense boundary to turn
// the fallback state off.
//
// Stash the wakeable on the boundary fiber so we can access it in the
// commit phase.
//
// When the wakeable resolves, we'll attempt to render the boundary
// again ("retry").
var wakeables=suspenseBoundary.updateQueue;if(wakeables===null){var updateQueue=new Set();updateQueue.add(wakeable);suspenseBoundary.updateQueue=updateQueue;}else {wakeables.add(wakeable);}}function resetSuspendedComponent(sourceFiber,rootRenderLanes){// A legacy mode Suspense quirk, only relevant to hook components.
var tag=sourceFiber.tag;if((sourceFiber.mode&ConcurrentMode)===NoMode&&(tag===FunctionComponent||tag===ForwardRef||tag===SimpleMemoComponent)){var currentSource=sourceFiber.alternate;if(currentSource){sourceFiber.updateQueue=currentSource.updateQueue;sourceFiber.memoizedState=currentSource.memoizedState;sourceFiber.lanes=currentSource.lanes;}else {sourceFiber.updateQueue=null;sourceFiber.memoizedState=null;}}}function getNearestSuspenseBoundaryToCapture(returnFiber){var node=returnFiber;do{if(node.tag===SuspenseComponent&&shouldCaptureSuspense(node)){return node;}// This boundary already captured during this render. Continue to the next
// boundary.
node=node.return;}while(node!==null);return null;}function markSuspenseBoundaryShouldCapture(suspenseBoundary,returnFiber,sourceFiber,root,rootRenderLanes){// This marks a Suspense boundary so that when we're unwinding the stack,
// it captures the suspended "exception" and does a second (fallback) pass.
if((suspenseBoundary.mode&ConcurrentMode)===NoMode){// Legacy Mode Suspense
//
// If the boundary is in legacy mode, we should *not*
// suspend the commit. Pretend as if the suspended component rendered
// null and keep rendering. When the Suspense boundary completes,
// we'll do a second pass to render the fallback.
if(suspenseBoundary===returnFiber){// Special case where we suspended while reconciling the children of
// a Suspense boundary's inner Offscreen wrapper fiber. This happens
// when a React.lazy component is a direct child of a
// Suspense boundary.
//
// Suspense boundaries are implemented as multiple fibers, but they
// are a single conceptual unit. The legacy mode behavior where we
// pretend the suspended fiber committed as `null` won't work,
// because in this case the "suspended" fiber is the inner
// Offscreen wrapper.
//
// Because the contents of the boundary haven't started rendering
// yet (i.e. nothing in the tree has partially rendered) we can
// switch to the regular, concurrent mode behavior: mark the
// boundary with ShouldCapture and enter the unwind phase.
suspenseBoundary.flags|=ShouldCapture;}else {suspenseBoundary.flags|=DidCapture;sourceFiber.flags|=ForceUpdateForLegacySuspense;// We're going to commit this fiber even though it didn't complete.
// But we shouldn't call any lifecycle methods or callbacks. Remove
// all lifecycle effect tags.
sourceFiber.flags&=~(LifecycleEffectMask|Incomplete);if(sourceFiber.tag===ClassComponent){var currentSourceFiber=sourceFiber.alternate;if(currentSourceFiber===null){// This is a new mount. Change the tag so it's not mistaken for a
// completed class component. For example, we should not call
// componentWillUnmount if it is deleted.
sourceFiber.tag=IncompleteClassComponent;}else {// When we try rendering again, we should not reuse the current fiber,
// since it's known to be in an inconsistent state. Use a force update to
// prevent a bail out.
var update=createUpdate(NoTimestamp,SyncLane);update.tag=ForceUpdate;enqueueUpdate(sourceFiber,update,SyncLane);}}// The source fiber did not complete. Mark it with Sync priority to
// indicate that it still has pending work.
sourceFiber.lanes=mergeLanes(sourceFiber.lanes,SyncLane);}return suspenseBoundary;}// Confirmed that the boundary is in a concurrent mode tree. Continue
// with the normal suspend path.
//
// After this we'll use a set of heuristics to determine whether this
// render pass will run to completion or restart or "suspend" the commit.
// The actual logic for this is spread out in different places.
//
// This first principle is that if we're going to suspend when we complete
// a root, then we should also restart if we get an update or ping that
// might unsuspend it, and vice versa. The only reason to suspend is
// because you think you might want to restart before committing. However,
// it doesn't make sense to restart only while in the period we're suspended.
//
// Restarting too aggressively is also not good because it starves out any
// intermediate loading state. So we use heuristics to determine when.
// Suspense Heuristics
//
// If nothing threw a Promise or all the same fallbacks are already showing,
// then don't suspend/restart.
//
// If this is an initial render of a new tree of Suspense boundaries and
// those trigger a fallback, then don't suspend/restart. We want to ensure
// that we can show the initial loading state as quickly as possible.
//
// If we hit a "Delayed" case, such as when we'd switch from content back into
// a fallback, then we should always suspend/restart. Transitions apply
// to this case. If none is defined, JND is used instead.
//
// If we're already showing a fallback and it gets "retried", allowing us to show
// another level, but there's still an inner boundary that would show a fallback,
// then we suspend/restart for 500ms since the last time we showed a fallback
// anywhere in the tree. This effectively throttles progressive loading into a
// consistent train of commits. This also gives us an opportunity to restart to
// get to the completed state slightly earlier.
//
// If there's ambiguity due to batching it's resolved in preference of:
// 1) "delayed", 2) "initial render", 3) "retry".
//
// We want to ensure that a "busy" state doesn't get force committed. We want to
// ensure that new initial loading states can commit as soon as possible.
suspenseBoundary.flags|=ShouldCapture;// TODO: I think we can remove this, since we now use `DidCapture` in
// the begin phase to prevent an early bailout.
suspenseBoundary.lanes=rootRenderLanes;return suspenseBoundary;}function throwException(root,returnFiber,sourceFiber,value,rootRenderLanes){// The source fiber did not complete.
sourceFiber.flags|=Incomplete;{if(isDevToolsPresent){// If we have pending work still, restore the original updaters
restorePendingUpdaters(root,rootRenderLanes);}}if(value!==null&&typeof value==='object'&&typeof value.then==='function'){// This is a wakeable. The component suspended.
var wakeable=value;resetSuspendedComponent(sourceFiber);{if(getIsHydrating()&&sourceFiber.mode&ConcurrentMode){markDidThrowWhileHydratingDEV();}}var suspenseBoundary=getNearestSuspenseBoundaryToCapture(returnFiber);if(suspenseBoundary!==null){suspenseBoundary.flags&=~ForceClientRender;markSuspenseBoundaryShouldCapture(suspenseBoundary,returnFiber,sourceFiber,root,rootRenderLanes);// We only attach ping listeners in concurrent mode. Legacy Suspense always
// commits fallbacks synchronously, so there are no pings.
if(suspenseBoundary.mode&ConcurrentMode){attachPingListener(root,wakeable,rootRenderLanes);}attachRetryListener(suspenseBoundary,root,wakeable);return;}else {// No boundary was found. Unless this is a sync update, this is OK.
// We can suspend and wait for more data to arrive.
if(!includesSyncLane(rootRenderLanes)){// This is not a sync update. Suspend. Since we're not activating a
// Suspense boundary, this will unwind all the way to the root without
// performing a second pass to render a fallback. (This is arguably how
// refresh transitions should work, too, since we're not going to commit
// the fallbacks anyway.)
//
// This case also applies to initial hydration.
attachPingListener(root,wakeable,rootRenderLanes);renderDidSuspendDelayIfPossible();return;}// This is a sync/discrete update. We treat this case like an error
// because discrete renders are expected to produce a complete tree
// synchronously to maintain consistency with external state.
var uncaughtSuspenseError=new Error('A component suspended while responding to synchronous input. This '+'will cause the UI to be replaced with a loading indicator. To '+'fix, updates that suspend should be wrapped '+'with startTransition.');// If we're outside a transition, fall through to the regular error path.
// The error will be caught by the nearest suspense boundary.
value=uncaughtSuspenseError;}}else {// This is a regular error, not a Suspense wakeable.
if(getIsHydrating()&&sourceFiber.mode&ConcurrentMode){markDidThrowWhileHydratingDEV();var _suspenseBoundary=getNearestSuspenseBoundaryToCapture(returnFiber);// If the error was thrown during hydration, we may be able to recover by
// discarding the dehydrated content and switching to a client render.
// Instead of surfacing the error, find the nearest Suspense boundary
// and render it again without hydration.
if(_suspenseBoundary!==null){if((_suspenseBoundary.flags&ShouldCapture)===NoFlags){// Set a flag to indicate that we should try rendering the normal
// children again, not the fallback.
_suspenseBoundary.flags|=ForceClientRender;}markSuspenseBoundaryShouldCapture(_suspenseBoundary,returnFiber,sourceFiber,root,rootRenderLanes);// Even though the user may not be affected by this error, we should
// still log it so it can be fixed.
queueHydrationError(createCapturedValueAtFiber(value,sourceFiber));return;}}}value=createCapturedValueAtFiber(value,sourceFiber);renderDidError(value);// We didn't find a boundary that could handle this type of exception. Start
// over and traverse parent path again, this time treating the exception
// as an error.
var workInProgress=returnFiber;do{switch(workInProgress.tag){case HostRoot:{var _errorInfo=value;workInProgress.flags|=ShouldCapture;var lane=pickArbitraryLane(rootRenderLanes);workInProgress.lanes=mergeLanes(workInProgress.lanes,lane);var update=createRootErrorUpdate(workInProgress,_errorInfo,lane);enqueueCapturedUpdate(workInProgress,update);return;}case ClassComponent:// Capture and retry
var errorInfo=value;var ctor=workInProgress.type;var instance=workInProgress.stateNode;if((workInProgress.flags&DidCapture)===NoFlags&&(typeof ctor.getDerivedStateFromError==='function'||instance!==null&&typeof instance.componentDidCatch==='function'&&!isAlreadyFailedLegacyErrorBoundary(instance))){workInProgress.flags|=ShouldCapture;var _lane=pickArbitraryLane(rootRenderLanes);workInProgress.lanes=mergeLanes(workInProgress.lanes,_lane);// Schedule the error boundary to re-render using updated state
var _update=createClassErrorUpdate(workInProgress,errorInfo,_lane);enqueueCapturedUpdate(workInProgress,_update);return;}break;}workInProgress=workInProgress.return;}while(workInProgress!==null);}function getSuspendedCache(){{return null;}// This function is called when a Suspense boundary suspends. It returns the
}var ReactCurrentOwner$1=ReactSharedInternals.ReactCurrentOwner;var didReceiveUpdate=false;var didWarnAboutBadClass;var didWarnAboutModulePatternComponent;var didWarnAboutContextTypeOnFunctionComponent;var didWarnAboutGetDerivedStateOnFunctionComponent;var didWarnAboutFunctionRefs;var didWarnAboutReassigningProps;var didWarnAboutRevealOrder;var didWarnAboutTailOptions;{didWarnAboutBadClass={};didWarnAboutModulePatternComponent={};didWarnAboutContextTypeOnFunctionComponent={};didWarnAboutGetDerivedStateOnFunctionComponent={};didWarnAboutFunctionRefs={};didWarnAboutReassigningProps=false;didWarnAboutRevealOrder={};didWarnAboutTailOptions={};}function reconcileChildren(current,workInProgress,nextChildren,renderLanes){if(current===null){// If this is a fresh new component that hasn't been rendered yet, we
// won't update its child set by applying minimal side-effects. Instead,
// we will add them all to the child before it gets rendered. That means
// we can optimize this reconciliation pass by not tracking side-effects.
workInProgress.child=mountChildFibers(workInProgress,null,nextChildren,renderLanes);}else {// If the current child is the same as the work in progress, it means that
// we haven't yet started any work on these children. Therefore, we use
// the clone algorithm to create a copy of all the current children.
// If we had any progressed work already, that is invalid at this point so
// let's throw it out.
workInProgress.child=reconcileChildFibers(workInProgress,current.child,nextChildren,renderLanes);}}function forceUnmountCurrentAndReconcile(current,workInProgress,nextChildren,renderLanes){// This function is fork of reconcileChildren. It's used in cases where we
// want to reconcile without matching against the existing set. This has the
// effect of all current children being unmounted; even if the type and key
// are the same, the old child is unmounted and a new child is created.
//
// To do this, we're going to go through the reconcile algorithm twice. In
// the first pass, we schedule a deletion for all the current children by
// passing null.
workInProgress.child=reconcileChildFibers(workInProgress,current.child,null,renderLanes);// In the second pass, we mount the new children. The trick here is that we
// pass null in place of where we usually pass the current child set. This has
// the effect of remounting all children regardless of whether their
// identities match.
workInProgress.child=reconcileChildFibers(workInProgress,null,nextChildren,renderLanes);}function updateForwardRef(current,workInProgress,Component,nextProps,renderLanes){// TODO: current can be non-null here even if the component
// hasn't yet mounted. This happens after the first render suspends.
// We'll need to figure out if this is fine or can cause issues.
{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes=Component.propTypes;if(innerPropTypes){checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentNameFromType(Component));}}}var render=Component.render;var ref=workInProgress.ref;// The rest is a fork of updateFunctionComponent
var nextChildren;var hasId;prepareToReadContext(workInProgress,renderLanes);{markComponentRenderStarted(workInProgress);}{ReactCurrentOwner$1.current=workInProgress;setIsRendering(true);nextChildren=renderWithHooks(current,workInProgress,render,nextProps,ref,renderLanes);hasId=checkDidRenderIdHook();if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{nextChildren=renderWithHooks(current,workInProgress,render,nextProps,ref,renderLanes);hasId=checkDidRenderIdHook();}finally{setIsStrictModeForDevtools(false);}}setIsRendering(false);}{markComponentRenderStopped();}if(current!==null&&!didReceiveUpdate){bailoutHooks(current,workInProgress,renderLanes);return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}if(getIsHydrating()&&hasId){pushMaterializedTreeId(workInProgress);}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateMemoComponent(current,workInProgress,Component,nextProps,renderLanes){if(current===null){var type=Component.type;if(isSimpleFunctionComponent(type)&&Component.compare===null&&// SimpleMemoComponent codepath doesn't resolve outer props either.
Component.defaultProps===undefined){var resolvedType=type;{resolvedType=resolveFunctionForHotReloading(type);}// If this is a plain function component without default props,
// and with only the default shallow comparison, we upgrade it
// to a SimpleMemoComponent to allow fast path updates.
workInProgress.tag=SimpleMemoComponent;workInProgress.type=resolvedType;{validateFunctionComponentInDev(workInProgress,type);}return updateSimpleMemoComponent(current,workInProgress,resolvedType,nextProps,renderLanes);}{var innerPropTypes=type.propTypes;if(innerPropTypes){// Inner memo component props aren't currently validated in createElement.
// We could move it there, but we'd still need this for lazy code path.
checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentNameFromType(type));}}var child=createFiberFromTypeAndProps(Component.type,null,nextProps,workInProgress,workInProgress.mode,renderLanes);child.ref=workInProgress.ref;child.return=workInProgress;workInProgress.child=child;return child;}{var _type=Component.type;var _innerPropTypes=_type.propTypes;if(_innerPropTypes){// Inner memo component props aren't currently validated in createElement.
// We could move it there, but we'd still need this for lazy code path.
checkPropTypes(_innerPropTypes,nextProps,// Resolved props
'prop',getComponentNameFromType(_type));}}var currentChild=current.child;// This is always exactly one child
var hasScheduledUpdateOrContext=checkScheduledUpdateOrContext(current,renderLanes);if(!hasScheduledUpdateOrContext){// This will be the props with resolved defaultProps,
// unlike current.memoizedProps which will be the unresolved ones.
var prevProps=currentChild.memoizedProps;// Default to shallow comparison
var compare=Component.compare;compare=compare!==null?compare:shallowEqual;if(compare(prevProps,nextProps)&&current.ref===workInProgress.ref){return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;var newChild=createWorkInProgress(currentChild,nextProps);newChild.ref=workInProgress.ref;newChild.return=workInProgress;workInProgress.child=newChild;return newChild;}function updateSimpleMemoComponent(current,workInProgress,Component,nextProps,renderLanes){// TODO: current can be non-null here even if the component
// hasn't yet mounted. This happens when the inner render suspends.
// We'll need to figure out if this is fine or can cause issues.
{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var outerMemoType=workInProgress.elementType;if(outerMemoType.$$typeof===REACT_LAZY_TYPE){// We warn when you define propTypes on lazy()
// so let's just skip over it to find memo() outer wrapper.
// Inner props for memo are validated later.
var lazyComponent=outerMemoType;var payload=lazyComponent._payload;var init=lazyComponent._init;try{outerMemoType=init(payload);}catch(x){outerMemoType=null;}// Inner propTypes will be validated in the function component path.
var outerPropTypes=outerMemoType&&outerMemoType.propTypes;if(outerPropTypes){checkPropTypes(outerPropTypes,nextProps,// Resolved (SimpleMemoComponent has no defaultProps)
'prop',getComponentNameFromType(outerMemoType));}}}}if(current!==null){var prevProps=current.memoizedProps;if(shallowEqual(prevProps,nextProps)&&current.ref===workInProgress.ref&&// Prevent bailout if the implementation changed due to hot reload.
workInProgress.type===current.type){didReceiveUpdate=false;// The props are shallowly equal. Reuse the previous props object, like we
// would during a normal fiber bailout.
//
// We don't have strong guarantees that the props object is referentially
// equal during updates where we can't bail out anyway — like if the props
// are shallowly equal, but there's a local state or context update in the
// same batch.
//
// However, as a principle, we should aim to make the behavior consistent
// across different ways of memoizing a component. For example, React.memo
// has a different internal Fiber layout if you pass a normal function
// component (SimpleMemoComponent) versus if you pass a different type
// like forwardRef (MemoComponent). But this is an implementation detail.
// Wrapping a component in forwardRef (or React.lazy, etc) shouldn't
// affect whether the props object is reused during a bailout.
workInProgress.pendingProps=nextProps=prevProps;if(!checkScheduledUpdateOrContext(current,renderLanes)){// The pending lanes were cleared at the beginning of beginWork. We're
// about to bail out, but there might be other lanes that weren't
// included in the current render. Usually, the priority level of the
// remaining updates is accumulated during the evaluation of the
// component (i.e. when processing the update queue). But since since
// we're bailing out early *without* evaluating the component, we need
// to account for it here, too. Reset to the value of the current fiber.
// NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
// because a MemoComponent fiber does not have hooks or an update queue;
// rather, it wraps around an inner component, which may or may not
// contains hooks.
// TODO: Move the reset at in beginWork out of the common path so that
// this is no longer necessary.
workInProgress.lanes=current.lanes;return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}else if((current.flags&ForceUpdateForLegacySuspense)!==NoFlags){// This is a special case that only exists for legacy mode.
// See https://github.com/facebook/react/pull/19216.
didReceiveUpdate=true;}}}return updateFunctionComponent(current,workInProgress,Component,nextProps,renderLanes);}function updateOffscreenComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps;var nextChildren=nextProps.children;var prevState=current!==null?current.memoizedState:null;if(nextProps.mode==='hidden'||enableLegacyHidden){// Rendering a hidden tree.
if((workInProgress.mode&ConcurrentMode)===NoMode){// In legacy sync mode, don't defer the subtree. Render it now.
// TODO: Consider how Offscreen should work with transitions in the future
var nextState={baseLanes:NoLanes,cachePool:null,transitions:null};workInProgress.memoizedState=nextState;pushRenderLanes(workInProgress,renderLanes);}else if(!includesSomeLane(renderLanes,OffscreenLane)){var spawnedCachePool=null;// We're hidden, and we're not rendering at Offscreen. We will bail out
// and resume this tree later.
var nextBaseLanes;if(prevState!==null){var prevBaseLanes=prevState.baseLanes;nextBaseLanes=mergeLanes(prevBaseLanes,renderLanes);}else {nextBaseLanes=renderLanes;}// Schedule this fiber to re-render at offscreen priority. Then bailout.
workInProgress.lanes=workInProgress.childLanes=laneToLanes(OffscreenLane);var _nextState={baseLanes:nextBaseLanes,cachePool:spawnedCachePool,transitions:null};workInProgress.memoizedState=_nextState;workInProgress.updateQueue=null;// to avoid a push/pop misalignment.
pushRenderLanes(workInProgress,nextBaseLanes);return null;}else {// This is the second render. The surrounding visible content has already
// committed. Now we resume rendering the hidden tree.
// Rendering at offscreen, so we can clear the base lanes.
var _nextState2={baseLanes:NoLanes,cachePool:null,transitions:null};workInProgress.memoizedState=_nextState2;// Push the lanes that were skipped when we bailed out.
var subtreeRenderLanes=prevState!==null?prevState.baseLanes:renderLanes;pushRenderLanes(workInProgress,subtreeRenderLanes);}}else {// Rendering a visible tree.
var _subtreeRenderLanes;if(prevState!==null){// We're going from hidden -> visible.
_subtreeRenderLanes=mergeLanes(prevState.baseLanes,renderLanes);workInProgress.memoizedState=null;}else {// We weren't previously hidden, and we still aren't, so there's nothing
// special to do. Need to push to the stack regardless, though, to avoid
// a push/pop misalignment.
_subtreeRenderLanes=renderLanes;}pushRenderLanes(workInProgress,_subtreeRenderLanes);}reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}// Note: These happen to have identical begin phases, for now. We shouldn't hold
function updateFragment(current,workInProgress,renderLanes){var nextChildren=workInProgress.pendingProps;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateMode(current,workInProgress,renderLanes){var nextChildren=workInProgress.pendingProps.children;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateProfiler(current,workInProgress,renderLanes){{workInProgress.flags|=Update;{// Reset effect durations for the next eventual effect phase.
// These are reset during render to allow the DevTools commit hook a chance to read them,
var stateNode=workInProgress.stateNode;stateNode.effectDuration=0;stateNode.passiveEffectDuration=0;}}var nextProps=workInProgress.pendingProps;var nextChildren=nextProps.children;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function markRef(current,workInProgress){var ref=workInProgress.ref;if(current===null&&ref!==null||current!==null&&current.ref!==ref){// Schedule a Ref effect
workInProgress.flags|=Ref;{workInProgress.flags|=RefStatic;}}}function updateFunctionComponent(current,workInProgress,Component,nextProps,renderLanes){{if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes=Component.propTypes;if(innerPropTypes){checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentNameFromType(Component));}}}var context;{var unmaskedContext=getUnmaskedContext(workInProgress,Component,true);context=getMaskedContext(workInProgress,unmaskedContext);}var nextChildren;var hasId;prepareToReadContext(workInProgress,renderLanes);{markComponentRenderStarted(workInProgress);}{ReactCurrentOwner$1.current=workInProgress;setIsRendering(true);nextChildren=renderWithHooks(current,workInProgress,Component,nextProps,context,renderLanes);hasId=checkDidRenderIdHook();if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{nextChildren=renderWithHooks(current,workInProgress,Component,nextProps,context,renderLanes);hasId=checkDidRenderIdHook();}finally{setIsStrictModeForDevtools(false);}}setIsRendering(false);}{markComponentRenderStopped();}if(current!==null&&!didReceiveUpdate){bailoutHooks(current,workInProgress,renderLanes);return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}if(getIsHydrating()&&hasId){pushMaterializedTreeId(workInProgress);}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateClassComponent(current,workInProgress,Component,nextProps,renderLanes){{// This is used by DevTools to force a boundary to error.
switch(shouldError(workInProgress)){case false:{var _instance=workInProgress.stateNode;var ctor=workInProgress.type;// TODO This way of resetting the error boundary state is a hack.
// Is there a better way to do this?
var tempInstance=new ctor(workInProgress.memoizedProps,_instance.context);var state=tempInstance.state;_instance.updater.enqueueSetState(_instance,state,null);break;}case true:{workInProgress.flags|=DidCapture;workInProgress.flags|=ShouldCapture;// eslint-disable-next-line react-internal/prod-error-codes
var error$1=new Error('Simulated error coming from DevTools');var lane=pickArbitraryLane(renderLanes);workInProgress.lanes=mergeLanes(workInProgress.lanes,lane);// Schedule the error boundary to re-render using updated state
var update=createClassErrorUpdate(workInProgress,createCapturedValueAtFiber(error$1,workInProgress),lane);enqueueCapturedUpdate(workInProgress,update);break;}}if(workInProgress.type!==workInProgress.elementType){// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes=Component.propTypes;if(innerPropTypes){checkPropTypes(innerPropTypes,nextProps,// Resolved props
'prop',getComponentNameFromType(Component));}}}// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext;if(isContextProvider(Component)){hasContext=true;pushContextProvider(workInProgress);}else {hasContext=false;}prepareToReadContext(workInProgress,renderLanes);var instance=workInProgress.stateNode;var shouldUpdate;if(instance===null){resetSuspendedCurrentOnMountInLegacyMode(current,workInProgress);// In the initial pass we might need to construct the instance.
constructClassInstance(workInProgress,Component,nextProps);mountClassInstance(workInProgress,Component,nextProps,renderLanes);shouldUpdate=true;}else if(current===null){// In a resume, we'll already have an instance we can reuse.
shouldUpdate=resumeMountClassInstance(workInProgress,Component,nextProps,renderLanes);}else {shouldUpdate=updateClassInstance(current,workInProgress,Component,nextProps,renderLanes);}var nextUnitOfWork=finishClassComponent(current,workInProgress,Component,shouldUpdate,hasContext,renderLanes);{var inst=workInProgress.stateNode;if(shouldUpdate&&inst.props!==nextProps){if(!didWarnAboutReassigningProps){error('It looks like %s is reassigning its own `this.props` while rendering. '+'This is not supported and can lead to confusing bugs.',getComponentNameFromFiber(workInProgress)||'a component');}didWarnAboutReassigningProps=true;}}return nextUnitOfWork;}function finishClassComponent(current,workInProgress,Component,shouldUpdate,hasContext,renderLanes){// Refs should update even if shouldComponentUpdate returns false
markRef(current,workInProgress);var didCaptureError=(workInProgress.flags&DidCapture)!==NoFlags;if(!shouldUpdate&&!didCaptureError){// Context providers should defer to sCU for rendering
if(hasContext){invalidateContextProvider(workInProgress,Component,false);}return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}var instance=workInProgress.stateNode;// Rerender
ReactCurrentOwner$1.current=workInProgress;var nextChildren;if(didCaptureError&&typeof Component.getDerivedStateFromError!=='function'){// If we captured an error, but getDerivedStateFromError is not defined,
// unmount all the children. componentDidCatch will schedule an update to
// re-render a fallback. This is temporary until we migrate everyone to
// the new API.
// TODO: Warn in a future release.
nextChildren=null;{stopProfilerTimerIfRunning();}}else {{markComponentRenderStarted(workInProgress);}{setIsRendering(true);nextChildren=instance.render();if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{instance.render();}finally{setIsStrictModeForDevtools(false);}}setIsRendering(false);}{markComponentRenderStopped();}}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;if(current!==null&&didCaptureError){// If we're recovering from an error, reconcile without reusing any of
// the existing children. Conceptually, the normal children and the children
// that are shown on error are two different sets, so we shouldn't reuse
// normal children even if their identities match.
forceUnmountCurrentAndReconcile(current,workInProgress,nextChildren,renderLanes);}else {reconcileChildren(current,workInProgress,nextChildren,renderLanes);}// Memoize state using the values we just used to render.
// TODO: Restructure so we never read values from the instance.
workInProgress.memoizedState=instance.state;// The context might have changed so we need to recalculate it.
if(hasContext){invalidateContextProvider(workInProgress,Component,true);}return workInProgress.child;}function pushHostRootContext(workInProgress){var root=workInProgress.stateNode;if(root.pendingContext){pushTopLevelContextObject(workInProgress,root.pendingContext,root.pendingContext!==root.context);}else if(root.context){// Should always be set
pushTopLevelContextObject(workInProgress,root.context,false);}pushHostContainer(workInProgress,root.containerInfo);}function updateHostRoot(current,workInProgress,renderLanes){pushHostRootContext(workInProgress);if(current===null){throw new Error('Should have a current fiber. This is a bug in React.');}var nextProps=workInProgress.pendingProps;var prevState=workInProgress.memoizedState;var prevChildren=prevState.element;cloneUpdateQueue(current,workInProgress);processUpdateQueue(workInProgress,nextProps,null,renderLanes);var nextState=workInProgress.memoizedState;workInProgress.stateNode;// being called "element".
var nextChildren=nextState.element;if(prevState.isDehydrated){// This is a hydration root whose shell has not yet hydrated. We should
// attempt to hydrate.
// Flip isDehydrated to false to indicate that when this render
// finishes, the root will no longer be dehydrated.
var overrideState={element:nextChildren,isDehydrated:false,cache:nextState.cache,pendingSuspenseBoundaries:nextState.pendingSuspenseBoundaries,transitions:nextState.transitions};var updateQueue=workInProgress.updateQueue;// `baseState` can always be the last state because the root doesn't
// have reducer functions so it doesn't need rebasing.
updateQueue.baseState=overrideState;workInProgress.memoizedState=overrideState;if(workInProgress.flags&ForceClientRender){// Something errored during a previous attempt to hydrate the shell, so we
// forced a client render.
var recoverableError=createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside '+'of a Suspense boundary, the entire root will switch to '+'client rendering.'),workInProgress);return mountHostRootWithoutHydrating(current,workInProgress,nextChildren,renderLanes,recoverableError);}else if(nextChildren!==prevChildren){var _recoverableError=createCapturedValueAtFiber(new Error('This root received an early update, before anything was able '+'hydrate. Switched the entire root to client rendering.'),workInProgress);return mountHostRootWithoutHydrating(current,workInProgress,nextChildren,renderLanes,_recoverableError);}else {// The outermost shell has not hydrated yet. Start hydrating.
enterHydrationState(workInProgress);var child=mountChildFibers(workInProgress,null,nextChildren,renderLanes);workInProgress.child=child;var node=child;while(node){// Mark each child as hydrating. This is a fast path to know whether this
// tree is part of a hydrating tree. This is used to determine if a child
// node has fully mounted yet, and for scheduling event replaying.
// Conceptually this is similar to Placement in that a new subtree is
// inserted into the React tree here. It just happens to not need DOM
// mutations because it already exists.
node.flags=node.flags&~Placement|Hydrating;node=node.sibling;}}}else {// Root is not dehydrated. Either this is a client-only root, or it
// already hydrated.
resetHydrationState();if(nextChildren===prevChildren){return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}reconcileChildren(current,workInProgress,nextChildren,renderLanes);}return workInProgress.child;}function mountHostRootWithoutHydrating(current,workInProgress,nextChildren,renderLanes,recoverableError){// Revert to client rendering.
resetHydrationState();queueHydrationError(recoverableError);workInProgress.flags|=ForceClientRender;reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateHostComponent(current,workInProgress,renderLanes){pushHostContext(workInProgress);if(current===null){tryToClaimNextHydratableInstance(workInProgress);}var type=workInProgress.type;var nextProps=workInProgress.pendingProps;var prevProps=current!==null?current.memoizedProps:null;var nextChildren=nextProps.children;var isDirectTextChild=shouldSetTextContent(type,nextProps);if(isDirectTextChild){// We special case a direct text child of a host node. This is a common
// case. We won't handle it as a reified child. We will instead handle
// this in the host environment that also has access to this prop. That
// avoids allocating another HostText fiber and traversing it.
nextChildren=null;}else if(prevProps!==null&&shouldSetTextContent(type,prevProps)){// If we're switching from a direct text child to a normal child, or to
// empty, we need to schedule the text content to be reset.
workInProgress.flags|=ContentReset;}markRef(current,workInProgress);reconcileChildren(current,workInProgress,nextChildren,renderLanes);return workInProgress.child;}function updateHostText(current,workInProgress){if(current===null){tryToClaimNextHydratableInstance(workInProgress);}// Nothing to do here. This is terminal. We'll do the completion step
// immediately after.
return null;}function mountLazyComponent(_current,workInProgress,elementType,renderLanes){resetSuspendedCurrentOnMountInLegacyMode(_current,workInProgress);var props=workInProgress.pendingProps;var lazyComponent=elementType;var payload=lazyComponent._payload;var init=lazyComponent._init;var Component=init(payload);// Store the unwrapped component in the type.
workInProgress.type=Component;var resolvedTag=workInProgress.tag=resolveLazyComponentTag(Component);var resolvedProps=resolveDefaultProps(Component,props);var child;switch(resolvedTag){case FunctionComponent:{{validateFunctionComponentInDev(workInProgress,Component);workInProgress.type=Component=resolveFunctionForHotReloading(Component);}child=updateFunctionComponent(null,workInProgress,Component,resolvedProps,renderLanes);return child;}case ClassComponent:{{workInProgress.type=Component=resolveClassForHotReloading(Component);}child=updateClassComponent(null,workInProgress,Component,resolvedProps,renderLanes);return child;}case ForwardRef:{{workInProgress.type=Component=resolveForwardRefForHotReloading(Component);}child=updateForwardRef(null,workInProgress,Component,resolvedProps,renderLanes);return child;}case MemoComponent:{{if(workInProgress.type!==workInProgress.elementType){var outerPropTypes=Component.propTypes;if(outerPropTypes){checkPropTypes(outerPropTypes,resolvedProps,// Resolved for outer only
'prop',getComponentNameFromType(Component));}}}child=updateMemoComponent(null,workInProgress,Component,resolveDefaultProps(Component.type,resolvedProps),// The inner type can have defaults too
renderLanes);return child;}}var hint='';{if(Component!==null&&typeof Component==='object'&&Component.$$typeof===REACT_LAZY_TYPE){hint=' Did you wrap a component in React.lazy() more than once?';}}// This message intentionally doesn't mention ForwardRef or MemoComponent
// because the fact that it's a separate type of work is an
// implementation detail.
throw new Error("Element type is invalid. Received a promise that resolves to: "+Component+". "+("Lazy element type must resolve to a class or function."+hint));}function mountIncompleteClassComponent(_current,workInProgress,Component,nextProps,renderLanes){resetSuspendedCurrentOnMountInLegacyMode(_current,workInProgress);// Promote the fiber to a class and try rendering again.
workInProgress.tag=ClassComponent;// The rest of this function is a fork of `updateClassComponent`
// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext;if(isContextProvider(Component)){hasContext=true;pushContextProvider(workInProgress);}else {hasContext=false;}prepareToReadContext(workInProgress,renderLanes);constructClassInstance(workInProgress,Component,nextProps);mountClassInstance(workInProgress,Component,nextProps,renderLanes);return finishClassComponent(null,workInProgress,Component,true,hasContext,renderLanes);}function mountIndeterminateComponent(_current,workInProgress,Component,renderLanes){resetSuspendedCurrentOnMountInLegacyMode(_current,workInProgress);var props=workInProgress.pendingProps;var context;{var unmaskedContext=getUnmaskedContext(workInProgress,Component,false);context=getMaskedContext(workInProgress,unmaskedContext);}prepareToReadContext(workInProgress,renderLanes);var value;var hasId;{markComponentRenderStarted(workInProgress);}{if(Component.prototype&&typeof Component.prototype.render==='function'){var componentName=getComponentNameFromType(Component)||'Unknown';if(!didWarnAboutBadClass[componentName]){error("The <%s /> component appears to have a render method, but doesn't extend React.Component. "+'This is likely to cause errors. Change %s to extend React.Component instead.',componentName,componentName);didWarnAboutBadClass[componentName]=true;}}if(workInProgress.mode&StrictLegacyMode){ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress,null);}setIsRendering(true);ReactCurrentOwner$1.current=workInProgress;value=renderWithHooks(null,workInProgress,Component,props,context,renderLanes);hasId=checkDidRenderIdHook();setIsRendering(false);}{markComponentRenderStopped();}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;{// Support for module components is deprecated and is removed behind a flag.
// Whether or not it would crash later, we want to show a good message in DEV first.
if(typeof value==='object'&&value!==null&&typeof value.render==='function'&&value.$$typeof===undefined){var _componentName=getComponentNameFromType(Component)||'Unknown';if(!didWarnAboutModulePatternComponent[_componentName]){error('The <%s /> component appears to be a function component that returns a class instance. '+'Change %s to a class that extends React.Component instead. '+"If you can't use a class try assigning the prototype on the function as a workaround. "+"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it "+'cannot be called with `new` by React.',_componentName,_componentName,_componentName);didWarnAboutModulePatternComponent[_componentName]=true;}}}if(// Run these checks in production only if the flag is off.
// Eventually we'll delete this branch altogether.
typeof value==='object'&&value!==null&&typeof value.render==='function'&&value.$$typeof===undefined){{var _componentName2=getComponentNameFromType(Component)||'Unknown';if(!didWarnAboutModulePatternComponent[_componentName2]){error('The <%s /> component appears to be a function component that returns a class instance. '+'Change %s to a class that extends React.Component instead. '+"If you can't use a class try assigning the prototype on the function as a workaround. "+"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it "+'cannot be called with `new` by React.',_componentName2,_componentName2,_componentName2);didWarnAboutModulePatternComponent[_componentName2]=true;}}// Proceed under the assumption that this is a class instance
workInProgress.tag=ClassComponent;// Throw out any hooks that were used.
workInProgress.memoizedState=null;workInProgress.updateQueue=null;// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext=false;if(isContextProvider(Component)){hasContext=true;pushContextProvider(workInProgress);}else {hasContext=false;}workInProgress.memoizedState=value.state!==null&&value.state!==undefined?value.state:null;initializeUpdateQueue(workInProgress);adoptClassInstance(workInProgress,value);mountClassInstance(workInProgress,Component,props,renderLanes);return finishClassComponent(null,workInProgress,Component,true,hasContext,renderLanes);}else {// Proceed under the assumption that this is a function component
workInProgress.tag=FunctionComponent;{if(workInProgress.mode&StrictLegacyMode){setIsStrictModeForDevtools(true);try{value=renderWithHooks(null,workInProgress,Component,props,context,renderLanes);hasId=checkDidRenderIdHook();}finally{setIsStrictModeForDevtools(false);}}}if(getIsHydrating()&&hasId){pushMaterializedTreeId(workInProgress);}reconcileChildren(null,workInProgress,value,renderLanes);{validateFunctionComponentInDev(workInProgress,Component);}return workInProgress.child;}}function validateFunctionComponentInDev(workInProgress,Component){{if(Component){if(Component.childContextTypes){error('%s(...): childContextTypes cannot be defined on a function component.',Component.displayName||Component.name||'Component');}}if(workInProgress.ref!==null){var info='';var ownerName=getCurrentFiberOwnerNameInDevOrNull();if(ownerName){info+='\n\nCheck the render method of `'+ownerName+'`.';}var warningKey=ownerName||'';var debugSource=workInProgress._debugSource;if(debugSource){warningKey=debugSource.fileName+':'+debugSource.lineNumber;}if(!didWarnAboutFunctionRefs[warningKey]){didWarnAboutFunctionRefs[warningKey]=true;error('Function components cannot be given refs. '+'Attempts to access this ref will fail. '+'Did you mean to use React.forwardRef()?%s',info);}}if(typeof Component.getDerivedStateFromProps==='function'){var _componentName3=getComponentNameFromType(Component)||'Unknown';if(!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]){error('%s: Function components do not support getDerivedStateFromProps.',_componentName3);didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]=true;}}if(typeof Component.contextType==='object'&&Component.contextType!==null){var _componentName4=getComponentNameFromType(Component)||'Unknown';if(!didWarnAboutContextTypeOnFunctionComponent[_componentName4]){error('%s: Function components do not support contextType.',_componentName4);didWarnAboutContextTypeOnFunctionComponent[_componentName4]=true;}}}}var SUSPENDED_MARKER={dehydrated:null,treeContext:null,retryLane:NoLane};function mountSuspenseOffscreenState(renderLanes){return {baseLanes:renderLanes,cachePool:getSuspendedCache(),transitions:null};}function updateSuspenseOffscreenState(prevOffscreenState,renderLanes){var cachePool=null;return {baseLanes:mergeLanes(prevOffscreenState.baseLanes,renderLanes),cachePool:cachePool,transitions:prevOffscreenState.transitions};}// TODO: Probably should inline this back
function shouldRemainOnFallback(suspenseContext,current,workInProgress,renderLanes){// If we're already showing a fallback, there are cases where we need to
// remain on that fallback regardless of whether the content has resolved.
// For example, SuspenseList coordinates when nested content appears.
if(current!==null){var suspenseState=current.memoizedState;if(suspenseState===null){// Currently showing content. Don't hide it, even if ForceSuspenseFallback
// is true. More precise name might be "ForceRemainSuspenseFallback".
// Note: This is a factoring smell. Can't remain on a fallback if there's
// no fallback to remain on.
return false;}}// Not currently showing content. Consult the Suspense context.
return hasSuspenseContext(suspenseContext,ForceSuspenseFallback);}function getRemainingWorkInPrimaryTree(current,renderLanes){// TODO: Should not remove render lanes that were pinged during this render
return removeLanes(current.childLanes,renderLanes);}function updateSuspenseComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps;// This is used by DevTools to force a boundary to suspend.
{if(shouldSuspend(workInProgress)){workInProgress.flags|=DidCapture;}}var suspenseContext=suspenseStackCursor.current;var showFallback=false;var didSuspend=(workInProgress.flags&DidCapture)!==NoFlags;if(didSuspend||shouldRemainOnFallback(suspenseContext,current)){// Something in this boundary's subtree already suspended. Switch to
// rendering the fallback children.
showFallback=true;workInProgress.flags&=~DidCapture;}else {// Attempting the main content
if(current===null||current.memoizedState!==null){// This is a new mount or this boundary is already showing a fallback state.
// Mark this subtree context as having at least one invisible parent that could
// handle the fallback state.
// Avoided boundaries are not considered since they cannot handle preferred fallback states.
{suspenseContext=addSubtreeSuspenseContext(suspenseContext,InvisibleParentSuspenseContext);}}}suspenseContext=setDefaultShallowSuspenseContext(suspenseContext);pushSuspenseContext(workInProgress,suspenseContext);// OK, the next part is confusing. We're about to reconcile the Suspense
// boundary's children. This involves some custom reconciliation logic. Two
// main reasons this is so complicated.
//
// First, Legacy Mode has different semantics for backwards compatibility. The
// primary tree will commit in an inconsistent state, so when we do the
// second pass to render the fallback, we do some exceedingly, uh, clever
// hacks to make that not totally break. Like transferring effects and
// deletions from hidden tree. In Concurrent Mode, it's much simpler,
// because we bailout on the primary tree completely and leave it in its old
// state, no effects. Same as what we do for Offscreen (except that
// Offscreen doesn't have the first render pass).
//
// Second is hydration. During hydration, the Suspense fiber has a slightly
// different layout, where the child points to a dehydrated fragment, which
// contains the DOM rendered by the server.
//
// Third, even if you set all that aside, Suspense is like error boundaries in
// that we first we try to render one tree, and if that fails, we render again
// and switch to a different tree. Like a try/catch block. So we have to track
// which branch we're currently rendering. Ideally we would model this using
// a stack.
if(current===null){// Initial mount
// Special path for hydration
// If we're currently hydrating, try to hydrate this boundary.
tryToClaimNextHydratableInstance(workInProgress);// This could've been a dehydrated suspense component.
var suspenseState=workInProgress.memoizedState;if(suspenseState!==null){var dehydrated=suspenseState.dehydrated;if(dehydrated!==null){return mountDehydratedSuspenseComponent(workInProgress,dehydrated);}}var nextPrimaryChildren=nextProps.children;var nextFallbackChildren=nextProps.fallback;if(showFallback){var fallbackFragment=mountSuspenseFallbackChildren(workInProgress,nextPrimaryChildren,nextFallbackChildren,renderLanes);var primaryChildFragment=workInProgress.child;primaryChildFragment.memoizedState=mountSuspenseOffscreenState(renderLanes);workInProgress.memoizedState=SUSPENDED_MARKER;return fallbackFragment;}else {return mountSuspensePrimaryChildren(workInProgress,nextPrimaryChildren);}}else {// This is an update.
// Special path for hydration
var prevState=current.memoizedState;if(prevState!==null){var _dehydrated=prevState.dehydrated;if(_dehydrated!==null){return updateDehydratedSuspenseComponent(current,workInProgress,didSuspend,nextProps,_dehydrated,prevState,renderLanes);}}if(showFallback){var _nextFallbackChildren=nextProps.fallback;var _nextPrimaryChildren=nextProps.children;var fallbackChildFragment=updateSuspenseFallbackChildren(current,workInProgress,_nextPrimaryChildren,_nextFallbackChildren,renderLanes);var _primaryChildFragment2=workInProgress.child;var prevOffscreenState=current.child.memoizedState;_primaryChildFragment2.memoizedState=prevOffscreenState===null?mountSuspenseOffscreenState(renderLanes):updateSuspenseOffscreenState(prevOffscreenState,renderLanes);_primaryChildFragment2.childLanes=getRemainingWorkInPrimaryTree(current,renderLanes);workInProgress.memoizedState=SUSPENDED_MARKER;return fallbackChildFragment;}else {var _nextPrimaryChildren2=nextProps.children;var _primaryChildFragment3=updateSuspensePrimaryChildren(current,workInProgress,_nextPrimaryChildren2,renderLanes);workInProgress.memoizedState=null;return _primaryChildFragment3;}}}function mountSuspensePrimaryChildren(workInProgress,primaryChildren,renderLanes){var mode=workInProgress.mode;var primaryChildProps={mode:'visible',children:primaryChildren};var primaryChildFragment=mountWorkInProgressOffscreenFiber(primaryChildProps,mode);primaryChildFragment.return=workInProgress;workInProgress.child=primaryChildFragment;return primaryChildFragment;}function mountSuspenseFallbackChildren(workInProgress,primaryChildren,fallbackChildren,renderLanes){var mode=workInProgress.mode;var progressedPrimaryFragment=workInProgress.child;var primaryChildProps={mode:'hidden',children:primaryChildren};var primaryChildFragment;var fallbackChildFragment;if((mode&ConcurrentMode)===NoMode&&progressedPrimaryFragment!==null){// In legacy mode, we commit the primary tree as if it successfully
// completed, even though it's in an inconsistent state.
primaryChildFragment=progressedPrimaryFragment;primaryChildFragment.childLanes=NoLanes;primaryChildFragment.pendingProps=primaryChildProps;if(workInProgress.mode&ProfileMode){// Reset the durations from the first pass so they aren't included in the
// final amounts. This seems counterintuitive, since we're intentionally
// not measuring part of the render phase, but this makes it match what we
// do in Concurrent Mode.
primaryChildFragment.actualDuration=0;primaryChildFragment.actualStartTime=-1;primaryChildFragment.selfBaseDuration=0;primaryChildFragment.treeBaseDuration=0;}fallbackChildFragment=createFiberFromFragment(fallbackChildren,mode,renderLanes,null);}else {primaryChildFragment=mountWorkInProgressOffscreenFiber(primaryChildProps,mode);fallbackChildFragment=createFiberFromFragment(fallbackChildren,mode,renderLanes,null);}primaryChildFragment.return=workInProgress;fallbackChildFragment.return=workInProgress;primaryChildFragment.sibling=fallbackChildFragment;workInProgress.child=primaryChildFragment;return fallbackChildFragment;}function mountWorkInProgressOffscreenFiber(offscreenProps,mode,renderLanes){// The props argument to `createFiberFromOffscreen` is `any` typed, so we use
// this wrapper function to constrain it.
return createFiberFromOffscreen(offscreenProps,mode,NoLanes,null);}function updateWorkInProgressOffscreenFiber(current,offscreenProps){// The props argument to `createWorkInProgress` is `any` typed, so we use this
// wrapper function to constrain it.
return createWorkInProgress(current,offscreenProps);}function updateSuspensePrimaryChildren(current,workInProgress,primaryChildren,renderLanes){var currentPrimaryChildFragment=current.child;var currentFallbackChildFragment=currentPrimaryChildFragment.sibling;var primaryChildFragment=updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment,{mode:'visible',children:primaryChildren});if((workInProgress.mode&ConcurrentMode)===NoMode){primaryChildFragment.lanes=renderLanes;}primaryChildFragment.return=workInProgress;primaryChildFragment.sibling=null;if(currentFallbackChildFragment!==null){// Delete the fallback child fragment
var deletions=workInProgress.deletions;if(deletions===null){workInProgress.deletions=[currentFallbackChildFragment];workInProgress.flags|=ChildDeletion;}else {deletions.push(currentFallbackChildFragment);}}workInProgress.child=primaryChildFragment;return primaryChildFragment;}function updateSuspenseFallbackChildren(current,workInProgress,primaryChildren,fallbackChildren,renderLanes){var mode=workInProgress.mode;var currentPrimaryChildFragment=current.child;var currentFallbackChildFragment=currentPrimaryChildFragment.sibling;var primaryChildProps={mode:'hidden',children:primaryChildren};var primaryChildFragment;if(// In legacy mode, we commit the primary tree as if it successfully
// completed, even though it's in an inconsistent state.
(mode&ConcurrentMode)===NoMode&&// Make sure we're on the second pass, i.e. the primary child fragment was
// already cloned. In legacy mode, the only case where this isn't true is
// when DevTools forces us to display a fallback; we skip the first render
// pass entirely and go straight to rendering the fallback. (In Concurrent
// Mode, SuspenseList can also trigger this scenario, but this is a legacy-
// only codepath.)
workInProgress.child!==currentPrimaryChildFragment){var progressedPrimaryFragment=workInProgress.child;primaryChildFragment=progressedPrimaryFragment;primaryChildFragment.childLanes=NoLanes;primaryChildFragment.pendingProps=primaryChildProps;if(workInProgress.mode&ProfileMode){// Reset the durations from the first pass so they aren't included in the
// final amounts. This seems counterintuitive, since we're intentionally
// not measuring part of the render phase, but this makes it match what we
// do in Concurrent Mode.
primaryChildFragment.actualDuration=0;primaryChildFragment.actualStartTime=-1;primaryChildFragment.selfBaseDuration=currentPrimaryChildFragment.selfBaseDuration;primaryChildFragment.treeBaseDuration=currentPrimaryChildFragment.treeBaseDuration;}// The fallback fiber was added as a deletion during the first pass.
// However, since we're going to remain on the fallback, we no longer want
// to delete it.
workInProgress.deletions=null;}else {primaryChildFragment=updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment,primaryChildProps);// Since we're reusing a current tree, we need to reuse the flags, too.
// (We don't do this in legacy mode, because in legacy mode we don't re-use
// the current tree; see previous branch.)
primaryChildFragment.subtreeFlags=currentPrimaryChildFragment.subtreeFlags&StaticMask;}var fallbackChildFragment;if(currentFallbackChildFragment!==null){fallbackChildFragment=createWorkInProgress(currentFallbackChildFragment,fallbackChildren);}else {fallbackChildFragment=createFiberFromFragment(fallbackChildren,mode,renderLanes,null);// Needs a placement effect because the parent (the Suspense boundary) already
// mounted but this is a new fiber.
fallbackChildFragment.flags|=Placement;}fallbackChildFragment.return=workInProgress;primaryChildFragment.return=workInProgress;primaryChildFragment.sibling=fallbackChildFragment;workInProgress.child=primaryChildFragment;return fallbackChildFragment;}function retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes,recoverableError){// Falling back to client rendering. Because this has performance
// implications, it's considered a recoverable error, even though the user
// likely won't observe anything wrong with the UI.
//
// The error is passed in as an argument to enforce that every caller provide
// a custom message, or explicitly opt out (currently the only path that opts
// out is legacy mode; every concurrent path provides an error).
if(recoverableError!==null){queueHydrationError(recoverableError);}// This will add the old fiber to the deletion list
reconcileChildFibers(workInProgress,current.child,null,renderLanes);// We're now not suspended nor dehydrated.
var nextProps=workInProgress.pendingProps;var primaryChildren=nextProps.children;var primaryChildFragment=mountSuspensePrimaryChildren(workInProgress,primaryChildren);// Needs a placement effect because the parent (the Suspense boundary) already
// mounted but this is a new fiber.
primaryChildFragment.flags|=Placement;workInProgress.memoizedState=null;return primaryChildFragment;}function mountSuspenseFallbackAfterRetryWithoutHydrating(current,workInProgress,primaryChildren,fallbackChildren,renderLanes){var fiberMode=workInProgress.mode;var primaryChildProps={mode:'visible',children:primaryChildren};var primaryChildFragment=mountWorkInProgressOffscreenFiber(primaryChildProps,fiberMode);var fallbackChildFragment=createFiberFromFragment(fallbackChildren,fiberMode,renderLanes,null);// Needs a placement effect because the parent (the Suspense
// boundary) already mounted but this is a new fiber.
fallbackChildFragment.flags|=Placement;primaryChildFragment.return=workInProgress;fallbackChildFragment.return=workInProgress;primaryChildFragment.sibling=fallbackChildFragment;workInProgress.child=primaryChildFragment;if((workInProgress.mode&ConcurrentMode)!==NoMode){// We will have dropped the effect list which contains the
// deletion. We need to reconcile to delete the current child.
reconcileChildFibers(workInProgress,current.child,null,renderLanes);}return fallbackChildFragment;}function mountDehydratedSuspenseComponent(workInProgress,suspenseInstance,renderLanes){// During the first pass, we'll bail out and not drill into the children.
// Instead, we'll leave the content in place and try to hydrate it later.
if((workInProgress.mode&ConcurrentMode)===NoMode){{error('Cannot hydrate Suspense in legacy mode. Switch from '+'ReactDOM.hydrate(element, container) to '+'ReactDOMClient.hydrateRoot(container, <App />)'+'.render(element) or remove the Suspense components from '+'the server rendered components.');}workInProgress.lanes=laneToLanes(SyncLane);}else if(isSuspenseInstanceFallback(suspenseInstance)){// This is a client-only boundary. Since we won't get any content from the server
// for this, we need to schedule that at a higher priority based on when it would
// have timed out. In theory we could render it in this pass but it would have the
// wrong priority associated with it and will prevent hydration of parent path.
// Instead, we'll leave work left on it to render it in a separate commit.
// TODO This time should be the time at which the server rendered response that is
// a parent to this boundary was displayed. However, since we currently don't have
// a protocol to transfer that time, we'll just estimate it by using the current
// time. This will mean that Suspense timeouts are slightly shifted to later than
// they should be.
// Schedule a normal pri update to render this content.
workInProgress.lanes=laneToLanes(DefaultHydrationLane);}else {// We'll continue hydrating the rest at offscreen priority since we'll already
// be showing the right content coming from the server, it is no rush.
workInProgress.lanes=laneToLanes(OffscreenLane);}return null;}function updateDehydratedSuspenseComponent(current,workInProgress,didSuspend,nextProps,suspenseInstance,suspenseState,renderLanes){if(!didSuspend){// This is the first render pass. Attempt to hydrate.
// We should never be hydrating at this point because it is the first pass,
// but after we've already committed once.
warnIfHydrating();if((workInProgress.mode&ConcurrentMode)===NoMode){return retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes,// TODO: When we delete legacy mode, we should make this error argument
// required — every concurrent mode path that causes hydration to
// de-opt to client rendering should have an error message.
null);}if(isSuspenseInstanceFallback(suspenseInstance)){// This boundary is in a permanent fallback state. In this case, we'll never
// get an update and we'll never be able to hydrate the final content. Let's just try the
// client side render instead.
var digest,message,stack;{var _getSuspenseInstanceF=getSuspenseInstanceFallbackErrorDetails(suspenseInstance);digest=_getSuspenseInstanceF.digest;message=_getSuspenseInstanceF.message;stack=_getSuspenseInstanceF.stack;}var error;if(message){// eslint-disable-next-line react-internal/prod-error-codes
error=new Error(message);}else {error=new Error('The server could not finish this Suspense boundary, likely '+'due to an error during server rendering. Switched to '+'client rendering.');}var capturedValue=createCapturedValue(error,digest,stack);return retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes,capturedValue);}// any context has changed, we need to treat is as if the input might have changed.
var hasContextChanged=includesSomeLane(renderLanes,current.childLanes);if(didReceiveUpdate||hasContextChanged){// This boundary has changed since the first render. This means that we are now unable to
// hydrate it. We might still be able to hydrate it using a higher priority lane.
var root=getWorkInProgressRoot();if(root!==null){var attemptHydrationAtLane=getBumpedLaneForHydration(root,renderLanes);if(attemptHydrationAtLane!==NoLane&&attemptHydrationAtLane!==suspenseState.retryLane){// Intentionally mutating since this render will get interrupted. This
// is one of the very rare times where we mutate the current tree
// during the render phase.
suspenseState.retryLane=attemptHydrationAtLane;// TODO: Ideally this would inherit the event time of the current render
var eventTime=NoTimestamp;enqueueConcurrentRenderForLane(current,attemptHydrationAtLane);scheduleUpdateOnFiber(root,current,attemptHydrationAtLane,eventTime);}}// If we have scheduled higher pri work above, this will probably just abort the render
// since we now have higher priority work, but in case it doesn't, we need to prepare to
// render something, if we time out. Even if that requires us to delete everything and
// skip hydration.
// Delay having to do this as long as the suspense timeout allows us.
renderDidSuspendDelayIfPossible();var _capturedValue=createCapturedValue(new Error('This Suspense boundary received an update before it finished '+'hydrating. This caused the boundary to switch to client rendering. '+'The usual way to fix this is to wrap the original update '+'in startTransition.'));return retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes,_capturedValue);}else if(isSuspenseInstancePending(suspenseInstance)){// This component is still pending more data from the server, so we can't hydrate its
// content. We treat it as if this component suspended itself. It might seem as if
// we could just try to render it client-side instead. However, this will perform a
// lot of unnecessary work and is unlikely to complete since it often will suspend
// on missing data anyway. Additionally, the server might be able to render more
// than we can on the client yet. In that case we'd end up with more fallback states
// on the client than if we just leave it alone. If the server times out or errors
// these should update this boundary to the permanent Fallback state instead.
// Mark it as having captured (i.e. suspended).
workInProgress.flags|=DidCapture;// Leave the child in place. I.e. the dehydrated fragment.
workInProgress.child=current.child;// Register a callback to retry this boundary once the server has sent the result.
var retry=retryDehydratedSuspenseBoundary.bind(null,current);registerSuspenseInstanceRetry(suspenseInstance,retry);return null;}else {// This is the first attempt.
reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress,suspenseInstance,suspenseState.treeContext);var primaryChildren=nextProps.children;var primaryChildFragment=mountSuspensePrimaryChildren(workInProgress,primaryChildren);// Mark the children as hydrating. This is a fast path to know whether this
// tree is part of a hydrating tree. This is used to determine if a child
// node has fully mounted yet, and for scheduling event replaying.
// Conceptually this is similar to Placement in that a new subtree is
// inserted into the React tree here. It just happens to not need DOM
// mutations because it already exists.
primaryChildFragment.flags|=Hydrating;return primaryChildFragment;}}else {// This is the second render pass. We already attempted to hydrated, but
// something either suspended or errored.
if(workInProgress.flags&ForceClientRender){// Something errored during hydration. Try again without hydrating.
workInProgress.flags&=~ForceClientRender;var _capturedValue2=createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. '+'Switched to client rendering.'));return retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes,_capturedValue2);}else if(workInProgress.memoizedState!==null){// Something suspended and we should still be in dehydrated mode.
// Leave the existing child in place.
workInProgress.child=current.child;// The dehydrated completion pass expects this flag to be there
// but the normal suspense pass doesn't.
workInProgress.flags|=DidCapture;return null;}else {// Suspended but we should no longer be in dehydrated mode.
// Therefore we now have to render the fallback.
var nextPrimaryChildren=nextProps.children;var nextFallbackChildren=nextProps.fallback;var fallbackChildFragment=mountSuspenseFallbackAfterRetryWithoutHydrating(current,workInProgress,nextPrimaryChildren,nextFallbackChildren,renderLanes);var _primaryChildFragment4=workInProgress.child;_primaryChildFragment4.memoizedState=mountSuspenseOffscreenState(renderLanes);workInProgress.memoizedState=SUSPENDED_MARKER;return fallbackChildFragment;}}}function scheduleSuspenseWorkOnFiber(fiber,renderLanes,propagationRoot){fiber.lanes=mergeLanes(fiber.lanes,renderLanes);var alternate=fiber.alternate;if(alternate!==null){alternate.lanes=mergeLanes(alternate.lanes,renderLanes);}scheduleContextWorkOnParentPath(fiber.return,renderLanes,propagationRoot);}function propagateSuspenseContextChange(workInProgress,firstChild,renderLanes){// Mark any Suspense boundaries with fallbacks as having work to do.
// If they were previously forced into fallbacks, they may now be able
// to unblock.
var node=firstChild;while(node!==null){if(node.tag===SuspenseComponent){var state=node.memoizedState;if(state!==null){scheduleSuspenseWorkOnFiber(node,renderLanes,workInProgress);}}else if(node.tag===SuspenseListComponent){// If the tail is hidden there might not be an Suspense boundaries
// to schedule work on. In this case we have to schedule it on the
// list itself.
// We don't have to traverse to the children of the list since
// the list will propagate the change when it rerenders.
scheduleSuspenseWorkOnFiber(node,renderLanes,workInProgress);}else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===workInProgress){return;}while(node.sibling===null){if(node.return===null||node.return===workInProgress){return;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}}function findLastContentRow(firstChild){// This is going to find the last row among these children that is already
// showing content on the screen, as opposed to being in fallback state or
// new. If a row has multiple Suspense boundaries, any of them being in the
// fallback state, counts as the whole row being in a fallback state.
// Note that the "rows" will be workInProgress, but any nested children
// will still be current since we haven't rendered them yet. The mounted
// order may not be the same as the new order. We use the new order.
var row=firstChild;var lastContentRow=null;while(row!==null){var currentRow=row.alternate;// New rows can't be content rows.
if(currentRow!==null&&findFirstSuspended(currentRow)===null){lastContentRow=row;}row=row.sibling;}return lastContentRow;}function validateRevealOrder(revealOrder){{if(revealOrder!==undefined&&revealOrder!=='forwards'&&revealOrder!=='backwards'&&revealOrder!=='together'&&!didWarnAboutRevealOrder[revealOrder]){didWarnAboutRevealOrder[revealOrder]=true;if(typeof revealOrder==='string'){switch(revealOrder.toLowerCase()){case'together':case'forwards':case'backwards':{error('"%s" is not a valid value for revealOrder on <SuspenseList />. '+'Use lowercase "%s" instead.',revealOrder,revealOrder.toLowerCase());break;}case'forward':case'backward':{error('"%s" is not a valid value for revealOrder on <SuspenseList />. '+'React uses the -s suffix in the spelling. Use "%ss" instead.',revealOrder,revealOrder.toLowerCase());break;}default:error('"%s" is not a supported revealOrder on <SuspenseList />. '+'Did you mean "together", "forwards" or "backwards"?',revealOrder);break;}}else {error('%s is not a supported value for revealOrder on <SuspenseList />. '+'Did you mean "together", "forwards" or "backwards"?',revealOrder);}}}}function validateTailOptions(tailMode,revealOrder){{if(tailMode!==undefined&&!didWarnAboutTailOptions[tailMode]){if(tailMode!=='collapsed'&&tailMode!=='hidden'){didWarnAboutTailOptions[tailMode]=true;error('"%s" is not a supported value for tail on <SuspenseList />. '+'Did you mean "collapsed" or "hidden"?',tailMode);}else if(revealOrder!=='forwards'&&revealOrder!=='backwards'){didWarnAboutTailOptions[tailMode]=true;error('<SuspenseList tail="%s" /> is only valid if revealOrder is '+'"forwards" or "backwards". '+'Did you mean to specify revealOrder="forwards"?',tailMode);}}}}function validateSuspenseListNestedChild(childSlot,index){{var isAnArray=isArray(childSlot);var isIterable=!isAnArray&&typeof getIteratorFn(childSlot)==='function';if(isAnArray||isIterable){var type=isAnArray?'array':'iterable';error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in '+'an additional SuspenseList to configure its revealOrder: '+'<SuspenseList revealOrder=...> ... '+'<SuspenseList revealOrder=...>{%s}</SuspenseList> ... '+'</SuspenseList>',type,index,type);return false;}}return true;}function validateSuspenseListChildren(children,revealOrder){{if((revealOrder==='forwards'||revealOrder==='backwards')&&children!==undefined&&children!==null&&children!==false){if(isArray(children)){for(var i=0;i<children.length;i++){if(!validateSuspenseListNestedChild(children[i],i)){return;}}}else {var iteratorFn=getIteratorFn(children);if(typeof iteratorFn==='function'){var childrenIterator=iteratorFn.call(children);if(childrenIterator){var step=childrenIterator.next();var _i=0;for(;!step.done;step=childrenIterator.next()){if(!validateSuspenseListNestedChild(step.value,_i)){return;}_i++;}}}else {error('A single row was passed to a <SuspenseList revealOrder="%s" />. '+'This is not useful since it needs multiple rows. '+'Did you mean to pass multiple children or an array?',revealOrder);}}}}}function initSuspenseListRenderState(workInProgress,isBackwards,tail,lastContentRow,tailMode){var renderState=workInProgress.memoizedState;if(renderState===null){workInProgress.memoizedState={isBackwards:isBackwards,rendering:null,renderingStartTime:0,last:lastContentRow,tail:tail,tailMode:tailMode};}else {// We can reuse the existing object from previous renders.
renderState.isBackwards=isBackwards;renderState.rendering=null;renderState.renderingStartTime=0;renderState.last=lastContentRow;renderState.tail=tail;renderState.tailMode=tailMode;}}// This can end up rendering this component multiple passes.
// The first pass splits the children fibers into two sets. A head and tail.
// We first render the head. If anything is in fallback state, we do another
// pass through beginWork to rerender all children (including the tail) with
// the force suspend context. If the first render didn't have anything in
// in fallback state. Then we render each row in the tail one-by-one.
// That happens in the completeWork phase without going back to beginWork.
function updateSuspenseListComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps;var revealOrder=nextProps.revealOrder;var tailMode=nextProps.tail;var newChildren=nextProps.children;validateRevealOrder(revealOrder);validateTailOptions(tailMode,revealOrder);validateSuspenseListChildren(newChildren,revealOrder);reconcileChildren(current,workInProgress,newChildren,renderLanes);var suspenseContext=suspenseStackCursor.current;var shouldForceFallback=hasSuspenseContext(suspenseContext,ForceSuspenseFallback);if(shouldForceFallback){suspenseContext=setShallowSuspenseContext(suspenseContext,ForceSuspenseFallback);workInProgress.flags|=DidCapture;}else {var didSuspendBefore=current!==null&&(current.flags&DidCapture)!==NoFlags;if(didSuspendBefore){// If we previously forced a fallback, we need to schedule work
// on any nested boundaries to let them know to try to render
// again. This is the same as context updating.
propagateSuspenseContextChange(workInProgress,workInProgress.child,renderLanes);}suspenseContext=setDefaultShallowSuspenseContext(suspenseContext);}pushSuspenseContext(workInProgress,suspenseContext);if((workInProgress.mode&ConcurrentMode)===NoMode){// In legacy mode, SuspenseList doesn't work so we just
// use make it a noop by treating it as the default revealOrder.
workInProgress.memoizedState=null;}else {switch(revealOrder){case'forwards':{var lastContentRow=findLastContentRow(workInProgress.child);var tail;if(lastContentRow===null){// The whole list is part of the tail.
// TODO: We could fast path by just rendering the tail now.
tail=workInProgress.child;workInProgress.child=null;}else {// Disconnect the tail rows after the content row.
// We're going to render them separately later.
tail=lastContentRow.sibling;lastContentRow.sibling=null;}initSuspenseListRenderState(workInProgress,false,// isBackwards
tail,lastContentRow,tailMode);break;}case'backwards':{// We're going to find the first row that has existing content.
// At the same time we're going to reverse the list of everything
// we pass in the meantime. That's going to be our tail in reverse
// order.
var _tail=null;var row=workInProgress.child;workInProgress.child=null;while(row!==null){var currentRow=row.alternate;// New rows can't be content rows.
if(currentRow!==null&&findFirstSuspended(currentRow)===null){// This is the beginning of the main content.
workInProgress.child=row;break;}var nextRow=row.sibling;row.sibling=_tail;_tail=row;row=nextRow;}// TODO: If workInProgress.child is null, we can continue on the tail immediately.
initSuspenseListRenderState(workInProgress,true,// isBackwards
_tail,null,// last
tailMode);break;}case'together':{initSuspenseListRenderState(workInProgress,false,// isBackwards
null,// tail
null,// last
undefined);break;}default:{// The default reveal order is the same as not having
// a boundary.
workInProgress.memoizedState=null;}}}return workInProgress.child;}function updatePortalComponent(current,workInProgress,renderLanes){pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo);var nextChildren=workInProgress.pendingProps;if(current===null){// Portals are special because we don't append the children during mount
// but at commit. Therefore we need to track insertions which the normal
// flow doesn't do during mount. This doesn't happen at the root because
// the root always starts with a "current" with a null child.
// TODO: Consider unifying this with how the root works.
workInProgress.child=reconcileChildFibers(workInProgress,null,nextChildren,renderLanes);}else {reconcileChildren(current,workInProgress,nextChildren,renderLanes);}return workInProgress.child;}var hasWarnedAboutUsingNoValuePropOnContextProvider=false;function updateContextProvider(current,workInProgress,renderLanes){var providerType=workInProgress.type;var context=providerType._context;var newProps=workInProgress.pendingProps;var oldProps=workInProgress.memoizedProps;var newValue=newProps.value;{if(!('value'in newProps)){if(!hasWarnedAboutUsingNoValuePropOnContextProvider){hasWarnedAboutUsingNoValuePropOnContextProvider=true;error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');}}var providerPropTypes=workInProgress.type.propTypes;if(providerPropTypes){checkPropTypes(providerPropTypes,newProps,'prop','Context.Provider');}}pushProvider(workInProgress,context,newValue);{if(oldProps!==null){var oldValue=oldProps.value;if(objectIs(oldValue,newValue)){// No change. Bailout early if children are the same.
if(oldProps.children===newProps.children&&!hasContextChanged()){return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}}else {// The context value changed. Search for matching consumers and schedule
// them to update.
propagateContextChange(workInProgress,context,renderLanes);}}}var newChildren=newProps.children;reconcileChildren(current,workInProgress,newChildren,renderLanes);return workInProgress.child;}var hasWarnedAboutUsingContextAsConsumer=false;function updateContextConsumer(current,workInProgress,renderLanes){var context=workInProgress.type;// The logic below for Context differs depending on PROD or DEV mode. In
// DEV mode, we create a separate object for Context.Consumer that acts
// like a proxy to Context. This proxy object adds unnecessary code in PROD
// so we use the old behaviour (Context.Consumer references Context) to
// reduce size and overhead. The separate object references context via
// a property called "_context", which also gives us the ability to check
// in DEV mode if this property exists or not and warn if it does not.
{if(context._context===undefined){// This may be because it's a Context (rather than a Consumer).
// Or it may be because it's older React where they're the same thing.
// We only want to warn if we're sure it's a new React.
if(context!==context.Consumer){if(!hasWarnedAboutUsingContextAsConsumer){hasWarnedAboutUsingContextAsConsumer=true;error('Rendering <Context> directly is not supported and will be removed in '+'a future major release. Did you mean to render <Context.Consumer> instead?');}}}else {context=context._context;}}var newProps=workInProgress.pendingProps;var render=newProps.children;{if(typeof render!=='function'){error('A context consumer was rendered with multiple children, or a child '+"that isn't a function. A context consumer expects a single child "+'that is a function. If you did pass a function, make sure there '+'is no trailing or leading whitespace around it.');}}prepareToReadContext(workInProgress,renderLanes);var newValue=readContext(context);{markComponentRenderStarted(workInProgress);}var newChildren;{ReactCurrentOwner$1.current=workInProgress;setIsRendering(true);newChildren=render(newValue);setIsRendering(false);}{markComponentRenderStopped();}// React DevTools reads this flag.
workInProgress.flags|=PerformedWork;reconcileChildren(current,workInProgress,newChildren,renderLanes);return workInProgress.child;}function markWorkInProgressReceivedUpdate(){didReceiveUpdate=true;}function resetSuspendedCurrentOnMountInLegacyMode(current,workInProgress){if((workInProgress.mode&ConcurrentMode)===NoMode){if(current!==null){// A lazy component only mounts if it suspended inside a non-
// concurrent tree, in an inconsistent state. We want to treat it like
// a new mount, even though an empty version of it already committed.
// Disconnect the alternate pointers.
current.alternate=null;workInProgress.alternate=null;// Since this is conceptually a new fiber, schedule a Placement effect
workInProgress.flags|=Placement;}}}function bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes){if(current!==null){// Reuse previous dependencies
workInProgress.dependencies=current.dependencies;}{// Don't update "base" render times for bailouts.
stopProfilerTimerIfRunning();}markSkippedUpdateLanes(workInProgress.lanes);// Check if the children have any pending work.
if(!includesSomeLane(renderLanes,workInProgress.childLanes)){// The children don't have any work either. We can skip them.
// TODO: Once we add back resuming, we should check if the children are
// a work-in-progress set. If so, we need to transfer their effects.
{return null;}}// This fiber doesn't have work, but its subtree does. Clone the child
// fibers and continue.
cloneChildFibers(current,workInProgress);return workInProgress.child;}function remountFiber(current,oldWorkInProgress,newWorkInProgress){{var returnFiber=oldWorkInProgress.return;if(returnFiber===null){// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('Cannot swap the root fiber.');}// Disconnect from the old current.
// It will get deleted.
current.alternate=null;oldWorkInProgress.alternate=null;// Connect to the new tree.
newWorkInProgress.index=oldWorkInProgress.index;newWorkInProgress.sibling=oldWorkInProgress.sibling;newWorkInProgress.return=oldWorkInProgress.return;newWorkInProgress.ref=oldWorkInProgress.ref;// Replace the child/sibling pointers above it.
if(oldWorkInProgress===returnFiber.child){returnFiber.child=newWorkInProgress;}else {var prevSibling=returnFiber.child;if(prevSibling===null){// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('Expected parent to have a child.');}while(prevSibling.sibling!==oldWorkInProgress){prevSibling=prevSibling.sibling;if(prevSibling===null){// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('Expected to find the previous sibling.');}}prevSibling.sibling=newWorkInProgress;}// Delete the old fiber and place the new one.
// Since the old fiber is disconnected, we have to schedule it manually.
var deletions=returnFiber.deletions;if(deletions===null){returnFiber.deletions=[current];returnFiber.flags|=ChildDeletion;}else {deletions.push(current);}newWorkInProgress.flags|=Placement;// Restart work from the new fiber.
return newWorkInProgress;}}function checkScheduledUpdateOrContext(current,renderLanes){// Before performing an early bailout, we must check if there are pending
// updates or context.
var updateLanes=current.lanes;if(includesSomeLane(updateLanes,renderLanes)){return true;}// No pending update, but because context is propagated lazily, we need
return false;}function attemptEarlyBailoutIfNoScheduledUpdate(current,workInProgress,renderLanes){// This fiber does not have any pending work. Bailout without entering
// the begin phase. There's still some bookkeeping we that needs to be done
// in this optimized path, mostly pushing stuff onto the stack.
switch(workInProgress.tag){case HostRoot:pushHostRootContext(workInProgress);workInProgress.stateNode;resetHydrationState();break;case HostComponent:pushHostContext(workInProgress);break;case ClassComponent:{var Component=workInProgress.type;if(isContextProvider(Component)){pushContextProvider(workInProgress);}break;}case HostPortal:pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo);break;case ContextProvider:{var newValue=workInProgress.memoizedProps.value;var context=workInProgress.type._context;pushProvider(workInProgress,context,newValue);break;}case Profiler:{// Profiler should only call onRender when one of its descendants actually rendered.
var hasChildWork=includesSomeLane(renderLanes,workInProgress.childLanes);if(hasChildWork){workInProgress.flags|=Update;}{// Reset effect durations for the next eventual effect phase.
// These are reset during render to allow the DevTools commit hook a chance to read them,
var stateNode=workInProgress.stateNode;stateNode.effectDuration=0;stateNode.passiveEffectDuration=0;}}break;case SuspenseComponent:{var state=workInProgress.memoizedState;if(state!==null){if(state.dehydrated!==null){pushSuspenseContext(workInProgress,setDefaultShallowSuspenseContext(suspenseStackCursor.current));// We know that this component will suspend again because if it has
// been unsuspended it has committed as a resolved Suspense component.
// If it needs to be retried, it should have work scheduled on it.
workInProgress.flags|=DidCapture;// We should never render the children of a dehydrated boundary until we
// upgrade it. We return null instead of bailoutOnAlreadyFinishedWork.
return null;}// If this boundary is currently timed out, we need to decide
// whether to retry the primary children, or to skip over it and
// go straight to the fallback. Check the priority of the primary
// child fragment.
var primaryChildFragment=workInProgress.child;var primaryChildLanes=primaryChildFragment.childLanes;if(includesSomeLane(renderLanes,primaryChildLanes)){// The primary children have pending work. Use the normal path
// to attempt to render the primary children again.
return updateSuspenseComponent(current,workInProgress,renderLanes);}else {// The primary child fragment does not have pending work marked
// on it
pushSuspenseContext(workInProgress,setDefaultShallowSuspenseContext(suspenseStackCursor.current));// The primary children do not have pending work with sufficient
// priority. Bailout.
var child=bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);if(child!==null){// The fallback children have pending work. Skip over the
// primary children and work on the fallback.
return child.sibling;}else {// Note: We can return `null` here because we already checked
// whether there were nested context consumers, via the call to
// `bailoutOnAlreadyFinishedWork` above.
return null;}}}else {pushSuspenseContext(workInProgress,setDefaultShallowSuspenseContext(suspenseStackCursor.current));}break;}case SuspenseListComponent:{var didSuspendBefore=(current.flags&DidCapture)!==NoFlags;var _hasChildWork=includesSomeLane(renderLanes,workInProgress.childLanes);if(didSuspendBefore){if(_hasChildWork){// If something was in fallback state last time, and we have all the
// same children then we're still in progressive loading state.
// Something might get unblocked by state updates or retries in the
// tree which will affect the tail. So we need to use the normal
// path to compute the correct tail.
return updateSuspenseListComponent(current,workInProgress,renderLanes);}// If none of the children had any work, that means that none of
// them got retried so they'll still be blocked in the same way
// as before. We can fast bail out.
workInProgress.flags|=DidCapture;}// If nothing suspended before and we're rendering the same children,
// then the tail doesn't matter. Anything new that suspends will work
// in the "together" mode, so we can continue from the state we had.
var renderState=workInProgress.memoizedState;if(renderState!==null){// Reset to the "together" mode in case we've started a different
// update in the past but didn't complete it.
renderState.rendering=null;renderState.tail=null;renderState.lastEffect=null;}pushSuspenseContext(workInProgress,suspenseStackCursor.current);if(_hasChildWork){break;}else {// If none of the children had any work, that means that none of
// them got retried so they'll still be blocked in the same way
// as before. We can fast bail out.
return null;}}case OffscreenComponent:case LegacyHiddenComponent:{// Need to check if the tree still needs to be deferred. This is
// almost identical to the logic used in the normal update path,
// so we'll just enter that. The only difference is we'll bail out
// at the next level instead of this one, because the child props
// have not changed. Which is fine.
// TODO: Probably should refactor `beginWork` to split the bailout
// path from the normal path. I'm tempted to do a labeled break here
// but I won't :)
workInProgress.lanes=NoLanes;return updateOffscreenComponent(current,workInProgress,renderLanes);}}return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);}function beginWork(current,workInProgress,renderLanes){{if(workInProgress._debugNeedsRemount&&current!==null){// This will restart the begin phase with a new fiber.
return remountFiber(current,workInProgress,createFiberFromTypeAndProps(workInProgress.type,workInProgress.key,workInProgress.pendingProps,workInProgress._debugOwner||null,workInProgress.mode,workInProgress.lanes));}}if(current!==null){var oldProps=current.memoizedProps;var newProps=workInProgress.pendingProps;if(oldProps!==newProps||hasContextChanged()||// Force a re-render if the implementation changed due to hot reload:
workInProgress.type!==current.type){// If props or context changed, mark the fiber as having performed work.
// This may be unset if the props are determined to be equal later (memo).
didReceiveUpdate=true;}else {// Neither props nor legacy context changes. Check if there's a pending
// update or context change.
var hasScheduledUpdateOrContext=checkScheduledUpdateOrContext(current,renderLanes);if(!hasScheduledUpdateOrContext&&// If this is the second pass of an error or suspense boundary, there
// may not be work scheduled on `current`, so we check for this flag.
(workInProgress.flags&DidCapture)===NoFlags){// No pending updates or context. Bail out now.
didReceiveUpdate=false;return attemptEarlyBailoutIfNoScheduledUpdate(current,workInProgress,renderLanes);}if((current.flags&ForceUpdateForLegacySuspense)!==NoFlags){// This is a special case that only exists for legacy mode.
// See https://github.com/facebook/react/pull/19216.
didReceiveUpdate=true;}else {// An update was scheduled on this fiber, but there are no new props
// nor legacy context. Set this to false. If an update queue or context
// consumer produces a changed value, it will set this to true. Otherwise,
// the component will assume the children have not changed and bail out.
didReceiveUpdate=false;}}}else {didReceiveUpdate=false;if(getIsHydrating()&&isForkedChild(workInProgress)){// Check if this child belongs to a list of muliple children in
// its parent.
//
// In a true multi-threaded implementation, we would render children on
// parallel threads. This would represent the beginning of a new render
// thread for this subtree.
//
// We only use this for id generation during hydration, which is why the
// logic is located in this special branch.
var slotIndex=workInProgress.index;var numberOfForks=getForksAtLevel();pushTreeId(workInProgress,numberOfForks,slotIndex);}}// Before entering the begin phase, clear pending update priority.
// TODO: This assumes that we're about to evaluate the component and process
// the update queue. However, there's an exception: SimpleMemoComponent
// sometimes bails out later in the begin phase. This indicates that we should
// move this assignment out of the common path and into each branch.
workInProgress.lanes=NoLanes;switch(workInProgress.tag){case IndeterminateComponent:{return mountIndeterminateComponent(current,workInProgress,workInProgress.type,renderLanes);}case LazyComponent:{var elementType=workInProgress.elementType;return mountLazyComponent(current,workInProgress,elementType,renderLanes);}case FunctionComponent:{var Component=workInProgress.type;var unresolvedProps=workInProgress.pendingProps;var resolvedProps=workInProgress.elementType===Component?unresolvedProps:resolveDefaultProps(Component,unresolvedProps);return updateFunctionComponent(current,workInProgress,Component,resolvedProps,renderLanes);}case ClassComponent:{var _Component=workInProgress.type;var _unresolvedProps=workInProgress.pendingProps;var _resolvedProps=workInProgress.elementType===_Component?_unresolvedProps:resolveDefaultProps(_Component,_unresolvedProps);return updateClassComponent(current,workInProgress,_Component,_resolvedProps,renderLanes);}case HostRoot:return updateHostRoot(current,workInProgress,renderLanes);case HostComponent:return updateHostComponent(current,workInProgress,renderLanes);case HostText:return updateHostText(current,workInProgress);case SuspenseComponent:return updateSuspenseComponent(current,workInProgress,renderLanes);case HostPortal:return updatePortalComponent(current,workInProgress,renderLanes);case ForwardRef:{var type=workInProgress.type;var _unresolvedProps2=workInProgress.pendingProps;var _resolvedProps2=workInProgress.elementType===type?_unresolvedProps2:resolveDefaultProps(type,_unresolvedProps2);return updateForwardRef(current,workInProgress,type,_resolvedProps2,renderLanes);}case Fragment:return updateFragment(current,workInProgress,renderLanes);case Mode:return updateMode(current,workInProgress,renderLanes);case Profiler:return updateProfiler(current,workInProgress,renderLanes);case ContextProvider:return updateContextProvider(current,workInProgress,renderLanes);case ContextConsumer:return updateContextConsumer(current,workInProgress,renderLanes);case MemoComponent:{var _type2=workInProgress.type;var _unresolvedProps3=workInProgress.pendingProps;// Resolve outer props first, then resolve inner props.
var _resolvedProps3=resolveDefaultProps(_type2,_unresolvedProps3);{if(workInProgress.type!==workInProgress.elementType){var outerPropTypes=_type2.propTypes;if(outerPropTypes){checkPropTypes(outerPropTypes,_resolvedProps3,// Resolved for outer only
'prop',getComponentNameFromType(_type2));}}}_resolvedProps3=resolveDefaultProps(_type2.type,_resolvedProps3);return updateMemoComponent(current,workInProgress,_type2,_resolvedProps3,renderLanes);}case SimpleMemoComponent:{return updateSimpleMemoComponent(current,workInProgress,workInProgress.type,workInProgress.pendingProps,renderLanes);}case IncompleteClassComponent:{var _Component2=workInProgress.type;var _unresolvedProps4=workInProgress.pendingProps;var _resolvedProps4=workInProgress.elementType===_Component2?_unresolvedProps4:resolveDefaultProps(_Component2,_unresolvedProps4);return mountIncompleteClassComponent(current,workInProgress,_Component2,_resolvedProps4,renderLanes);}case SuspenseListComponent:{return updateSuspenseListComponent(current,workInProgress,renderLanes);}case ScopeComponent:{break;}case OffscreenComponent:{return updateOffscreenComponent(current,workInProgress,renderLanes);}}throw new Error("Unknown unit of work tag ("+workInProgress.tag+"). This error is likely caused by a bug in "+'React. Please file an issue.');}function markUpdate(workInProgress){// Tag the fiber with an update effect. This turns a Placement into
// a PlacementAndUpdate.
workInProgress.flags|=Update;}function markRef$1(workInProgress){workInProgress.flags|=Ref;{workInProgress.flags|=RefStatic;}}var appendAllChildren;var updateHostContainer;var updateHostComponent$1;var updateHostText$1;{// Mutation mode
appendAllChildren=function(parent,workInProgress,needsVisibilityToggle,isHidden){// We only have the top Fiber that was created but we need recurse down its
// children to find all the terminal nodes.
var node=workInProgress.child;while(node!==null){if(node.tag===HostComponent||node.tag===HostText){appendInitialChild(parent,node.stateNode);}else if(node.tag===HostPortal);else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===workInProgress){return;}while(node.sibling===null){if(node.return===null||node.return===workInProgress){return;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}};updateHostContainer=function(current,workInProgress){// Noop
};updateHostComponent$1=function(current,workInProgress,type,newProps,rootContainerInstance){// If we have an alternate, that means this is an update and we need to
// schedule a side-effect to do the updates.
var oldProps=current.memoizedProps;if(oldProps===newProps){// In mutation mode, this is sufficient for a bailout because
// we won't touch this node even if children changed.
return;}// If we get updated because one of our children updated, we don't
// have newProps so we'll have to reuse them.
// TODO: Split the update API as separate for the props vs. children.
// Even better would be if children weren't special cased at all tho.
var instance=workInProgress.stateNode;var currentHostContext=getHostContext();// TODO: Experiencing an error where oldProps is null. Suggests a host
// component is hitting the resume path. Figure out why. Possibly
// related to `hidden`.
var updatePayload=prepareUpdate(instance,type,oldProps,newProps,rootContainerInstance,currentHostContext);// TODO: Type this specific to this type of component.
workInProgress.updateQueue=updatePayload;// If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update. All the work is done in commitWork.
if(updatePayload){markUpdate(workInProgress);}};updateHostText$1=function(current,workInProgress,oldText,newText){// If the text differs, mark it as an update. All the work in done in commitWork.
if(oldText!==newText){markUpdate(workInProgress);}};}function cutOffTailIfNeeded(renderState,hasRenderedATailFallback){if(getIsHydrating()){// If we're hydrating, we should consume as many items as we can
// so we don't leave any behind.
return;}switch(renderState.tailMode){case'hidden':{// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
var tailNode=renderState.tail;var lastTailNode=null;while(tailNode!==null){if(tailNode.alternate!==null){lastTailNode=tailNode;}tailNode=tailNode.sibling;}// Next we're simply going to delete all insertions after the
// last rendered item.
if(lastTailNode===null){// All remaining items in the tail are insertions.
renderState.tail=null;}else {// Detach the insertion after the last node that was already
// inserted.
lastTailNode.sibling=null;}break;}case'collapsed':{// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
var _tailNode=renderState.tail;var _lastTailNode=null;while(_tailNode!==null){if(_tailNode.alternate!==null){_lastTailNode=_tailNode;}_tailNode=_tailNode.sibling;}// Next we're simply going to delete all insertions after the
// last rendered item.
if(_lastTailNode===null){// All remaining items in the tail are insertions.
if(!hasRenderedATailFallback&&renderState.tail!==null){// We suspended during the head. We want to show at least one
// row at the tail. So we'll keep on and cut off the rest.
renderState.tail.sibling=null;}else {renderState.tail=null;}}else {// Detach the insertion after the last node that was already
// inserted.
_lastTailNode.sibling=null;}break;}}}function bubbleProperties(completedWork){var didBailout=completedWork.alternate!==null&&completedWork.alternate.child===completedWork.child;var newChildLanes=NoLanes;var subtreeFlags=NoFlags;if(!didBailout){// Bubble up the earliest expiration time.
if((completedWork.mode&ProfileMode)!==NoMode){// In profiling mode, resetChildExpirationTime is also used to reset
// profiler durations.
var actualDuration=completedWork.actualDuration;var treeBaseDuration=completedWork.selfBaseDuration;var child=completedWork.child;while(child!==null){newChildLanes=mergeLanes(newChildLanes,mergeLanes(child.lanes,child.childLanes));subtreeFlags|=child.subtreeFlags;subtreeFlags|=child.flags;// When a fiber is cloned, its actualDuration is reset to 0. This value will
// only be updated if work is done on the fiber (i.e. it doesn't bailout).
// When work is done, it should bubble to the parent's actualDuration. If
// the fiber has not been cloned though, (meaning no work was done), then
// this value will reflect the amount of time spent working on a previous
// render. In that case it should not bubble. We determine whether it was
// cloned by comparing the child pointer.
actualDuration+=child.actualDuration;treeBaseDuration+=child.treeBaseDuration;child=child.sibling;}completedWork.actualDuration=actualDuration;completedWork.treeBaseDuration=treeBaseDuration;}else {var _child=completedWork.child;while(_child!==null){newChildLanes=mergeLanes(newChildLanes,mergeLanes(_child.lanes,_child.childLanes));subtreeFlags|=_child.subtreeFlags;subtreeFlags|=_child.flags;// Update the return pointer so the tree is consistent. This is a code
// smell because it assumes the commit phase is never concurrent with
// the render phase. Will address during refactor to alternate model.
_child.return=completedWork;_child=_child.sibling;}}completedWork.subtreeFlags|=subtreeFlags;}else {// Bubble up the earliest expiration time.
if((completedWork.mode&ProfileMode)!==NoMode){// In profiling mode, resetChildExpirationTime is also used to reset
// profiler durations.
var _treeBaseDuration=completedWork.selfBaseDuration;var _child2=completedWork.child;while(_child2!==null){newChildLanes=mergeLanes(newChildLanes,mergeLanes(_child2.lanes,_child2.childLanes));// "Static" flags share the lifetime of the fiber/hook they belong to,
// so we should bubble those up even during a bailout. All the other
// flags have a lifetime only of a single render + commit, so we should
// ignore them.
subtreeFlags|=_child2.subtreeFlags&StaticMask;subtreeFlags|=_child2.flags&StaticMask;_treeBaseDuration+=_child2.treeBaseDuration;_child2=_child2.sibling;}completedWork.treeBaseDuration=_treeBaseDuration;}else {var _child3=completedWork.child;while(_child3!==null){newChildLanes=mergeLanes(newChildLanes,mergeLanes(_child3.lanes,_child3.childLanes));// "Static" flags share the lifetime of the fiber/hook they belong to,
// so we should bubble those up even during a bailout. All the other
// flags have a lifetime only of a single render + commit, so we should
// ignore them.
subtreeFlags|=_child3.subtreeFlags&StaticMask;subtreeFlags|=_child3.flags&StaticMask;// Update the return pointer so the tree is consistent. This is a code
// smell because it assumes the commit phase is never concurrent with
// the render phase. Will address during refactor to alternate model.
_child3.return=completedWork;_child3=_child3.sibling;}}completedWork.subtreeFlags|=subtreeFlags;}completedWork.childLanes=newChildLanes;return didBailout;}function completeDehydratedSuspenseBoundary(current,workInProgress,nextState){if(hasUnhydratedTailNodes()&&(workInProgress.mode&ConcurrentMode)!==NoMode&&(workInProgress.flags&DidCapture)===NoFlags){warnIfUnhydratedTailNodes(workInProgress);resetHydrationState();workInProgress.flags|=ForceClientRender|Incomplete|ShouldCapture;return false;}var wasHydrated=popHydrationState(workInProgress);if(nextState!==null&&nextState.dehydrated!==null){// We might be inside a hydration state the first time we're picking up this
// Suspense boundary, and also after we've reentered it for further hydration.
if(current===null){if(!wasHydrated){throw new Error('A dehydrated suspense component was completed without a hydrated node. '+'This is probably a bug in React.');}prepareToHydrateHostSuspenseInstance(workInProgress);bubbleProperties(workInProgress);{if((workInProgress.mode&ProfileMode)!==NoMode){var isTimedOutSuspense=nextState!==null;if(isTimedOutSuspense){// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var primaryChildFragment=workInProgress.child;if(primaryChildFragment!==null){// $FlowFixMe Flow doesn't support type casting in combination with the -= operator
workInProgress.treeBaseDuration-=primaryChildFragment.treeBaseDuration;}}}}return false;}else {// We might have reentered this boundary to hydrate it. If so, we need to reset the hydration
// state since we're now exiting out of it. popHydrationState doesn't do that for us.
resetHydrationState();if((workInProgress.flags&DidCapture)===NoFlags){// This boundary did not suspend so it's now hydrated and unsuspended.
workInProgress.memoizedState=null;}// If nothing suspended, we need to schedule an effect to mark this boundary
// as having hydrated so events know that they're free to be invoked.
// It's also a signal to replay events and the suspense callback.
// If something suspended, schedule an effect to attach retry listeners.
// So we might as well always mark this.
workInProgress.flags|=Update;bubbleProperties(workInProgress);{if((workInProgress.mode&ProfileMode)!==NoMode){var _isTimedOutSuspense=nextState!==null;if(_isTimedOutSuspense){// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var _primaryChildFragment=workInProgress.child;if(_primaryChildFragment!==null){// $FlowFixMe Flow doesn't support type casting in combination with the -= operator
workInProgress.treeBaseDuration-=_primaryChildFragment.treeBaseDuration;}}}}return false;}}else {// Successfully completed this tree. If this was a forced client render,
// there may have been recoverable errors during first hydration
// attempt. If so, add them to a queue so we can log them in the
// commit phase.
upgradeHydrationErrorsToRecoverable();// Fall through to normal Suspense path
return true;}}function completeWork(current,workInProgress,renderLanes){var newProps=workInProgress.pendingProps;// Note: This intentionally doesn't check if we're hydrating because comparing
// to the current tree provider fiber is just as fast and less error-prone.
// Ideally we would have a special version of the work loop only
// for hydration.
popTreeContext(workInProgress);switch(workInProgress.tag){case IndeterminateComponent:case LazyComponent:case SimpleMemoComponent:case FunctionComponent:case ForwardRef:case Fragment:case Mode:case Profiler:case ContextConsumer:case MemoComponent:bubbleProperties(workInProgress);return null;case ClassComponent:{var Component=workInProgress.type;if(isContextProvider(Component)){popContext(workInProgress);}bubbleProperties(workInProgress);return null;}case HostRoot:{var fiberRoot=workInProgress.stateNode;popHostContainer(workInProgress);popTopLevelContextObject(workInProgress);resetWorkInProgressVersions();if(fiberRoot.pendingContext){fiberRoot.context=fiberRoot.pendingContext;fiberRoot.pendingContext=null;}if(current===null||current.child===null){// If we hydrated, pop so that we can delete any remaining children
// that weren't hydrated.
var wasHydrated=popHydrationState(workInProgress);if(wasHydrated){// If we hydrated, then we'll need to schedule an update for
// the commit side-effects on the root.
markUpdate(workInProgress);}else {if(current!==null){var prevState=current.memoizedState;if(// Check if this is a client root
!prevState.isDehydrated||// Check if we reverted to client rendering (e.g. due to an error)
(workInProgress.flags&ForceClientRender)!==NoFlags){// Schedule an effect to clear this container at the start of the
// next commit. This handles the case of React rendering into a
// container with previous children. It's also safe to do for
// updates too, because current.child would only be null if the
// previous render was null (so the container would already
// be empty).
workInProgress.flags|=Snapshot;// If this was a forced client render, there may have been
// recoverable errors during first hydration attempt. If so, add
// them to a queue so we can log them in the commit phase.
upgradeHydrationErrorsToRecoverable();}}}}updateHostContainer(current,workInProgress);bubbleProperties(workInProgress);return null;}case HostComponent:{popHostContext(workInProgress);var rootContainerInstance=getRootHostContainer();var type=workInProgress.type;if(current!==null&&workInProgress.stateNode!=null){updateHostComponent$1(current,workInProgress,type,newProps,rootContainerInstance);if(current.ref!==workInProgress.ref){markRef$1(workInProgress);}}else {if(!newProps){if(workInProgress.stateNode===null){throw new Error('We must have new props for new mounts. This error is likely '+'caused by a bug in React. Please file an issue.');}// This can happen when we abort work.
bubbleProperties(workInProgress);return null;}var currentHostContext=getHostContext();// TODO: Move createInstance to beginWork and keep it on a context
// "stack" as the parent. Then append children as we go in beginWork
// or completeWork depending on whether we want to add them top->down or
// bottom->up. Top->down is faster in IE11.
var _wasHydrated=popHydrationState(workInProgress);if(_wasHydrated){// TODO: Move this and createInstance step into the beginPhase
// to consolidate.
if(prepareToHydrateHostInstance(workInProgress,rootContainerInstance,currentHostContext)){// If changes to the hydrated node need to be applied at the
// commit-phase we mark this as such.
markUpdate(workInProgress);}}else {var instance=createInstance(type,newProps,rootContainerInstance,currentHostContext,workInProgress);appendAllChildren(instance,workInProgress,false,false);workInProgress.stateNode=instance;// Certain renderers require commit-time effects for initial mount.
// (eg DOM renderer supports auto-focus for certain elements).
// Make sure such renderers get scheduled for later work.
if(finalizeInitialChildren(instance,type,newProps,rootContainerInstance)){markUpdate(workInProgress);}}if(workInProgress.ref!==null){// If there is a ref on a host node we need to schedule a callback
markRef$1(workInProgress);}}bubbleProperties(workInProgress);return null;}case HostText:{var newText=newProps;if(current&&workInProgress.stateNode!=null){var oldText=current.memoizedProps;// If we have an alternate, that means this is an update and we need
// to schedule a side-effect to do the updates.
updateHostText$1(current,workInProgress,oldText,newText);}else {if(typeof newText!=='string'){if(workInProgress.stateNode===null){throw new Error('We must have new props for new mounts. This error is likely '+'caused by a bug in React. Please file an issue.');}// This can happen when we abort work.
}var _rootContainerInstance=getRootHostContainer();var _currentHostContext=getHostContext();var _wasHydrated2=popHydrationState(workInProgress);if(_wasHydrated2){if(prepareToHydrateHostTextInstance(workInProgress)){markUpdate(workInProgress);}}else {workInProgress.stateNode=createTextInstance(newText,_rootContainerInstance,_currentHostContext,workInProgress);}}bubbleProperties(workInProgress);return null;}case SuspenseComponent:{popSuspenseContext(workInProgress);var nextState=workInProgress.memoizedState;// Special path for dehydrated boundaries. We may eventually move this
// to its own fiber type so that we can add other kinds of hydration
// boundaries that aren't associated with a Suspense tree. In anticipation
// of such a refactor, all the hydration logic is contained in
// this branch.
if(current===null||current.memoizedState!==null&&current.memoizedState.dehydrated!==null){var fallthroughToNormalSuspensePath=completeDehydratedSuspenseBoundary(current,workInProgress,nextState);if(!fallthroughToNormalSuspensePath){if(workInProgress.flags&ShouldCapture){// Special case. There were remaining unhydrated nodes. We treat
// this as a mismatch. Revert to client rendering.
return workInProgress;}else {// Did not finish hydrating, either because this is the initial
// render or because something suspended.
return null;}}// Continue with the normal Suspense path.
}if((workInProgress.flags&DidCapture)!==NoFlags){// Something suspended. Re-render with the fallback children.
workInProgress.lanes=renderLanes;// Do not reset the effect list.
if((workInProgress.mode&ProfileMode)!==NoMode){transferActualDuration(workInProgress);}// Don't bubble properties in this case.
return workInProgress;}var nextDidTimeout=nextState!==null;var prevDidTimeout=current!==null&&current.memoizedState!==null;// a passive effect, which is when we process the transitions
if(nextDidTimeout!==prevDidTimeout){// an effect to toggle the subtree's visibility. When we switch from
// fallback -> primary, the inner Offscreen fiber schedules this effect
// as part of its normal complete phase. But when we switch from
// primary -> fallback, the inner Offscreen fiber does not have a complete
// phase. So we need to schedule its effect here.
//
// We also use this flag to connect/disconnect the effects, but the same
// logic applies: when re-connecting, the Offscreen fiber's complete
// phase will handle scheduling the effect. It's only when the fallback
// is active that we have to do anything special.
if(nextDidTimeout){var _offscreenFiber2=workInProgress.child;_offscreenFiber2.flags|=Visibility;// TODO: This will still suspend a synchronous tree if anything
// in the concurrent tree already suspended during this render.
// This is a known bug.
if((workInProgress.mode&ConcurrentMode)!==NoMode){// TODO: Move this back to throwException because this is too late
// if this is a large tree which is common for initial loads. We
// don't know if we should restart a render or not until we get
// this marker, and this is too late.
// If this render already had a ping or lower pri updates,
// and this is the first time we know we're going to suspend we
// should be able to immediately restart from within throwException.
var hasInvisibleChildContext=current===null&&(workInProgress.memoizedProps.unstable_avoidThisFallback!==true||!enableSuspenseAvoidThisFallback);if(hasInvisibleChildContext||hasSuspenseContext(suspenseStackCursor.current,InvisibleParentSuspenseContext)){// If this was in an invisible tree or a new render, then showing
// this boundary is ok.
renderDidSuspend();}else {// Otherwise, we're going to have to hide content so we should
// suspend for longer if possible.
renderDidSuspendDelayIfPossible();}}}}var wakeables=workInProgress.updateQueue;if(wakeables!==null){// Schedule an effect to attach a retry listener to the promise.
// TODO: Move to passive phase
workInProgress.flags|=Update;}bubbleProperties(workInProgress);{if((workInProgress.mode&ProfileMode)!==NoMode){if(nextDidTimeout){// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var primaryChildFragment=workInProgress.child;if(primaryChildFragment!==null){// $FlowFixMe Flow doesn't support type casting in combination with the -= operator
workInProgress.treeBaseDuration-=primaryChildFragment.treeBaseDuration;}}}}return null;}case HostPortal:popHostContainer(workInProgress);updateHostContainer(current,workInProgress);if(current===null){preparePortalMount(workInProgress.stateNode.containerInfo);}bubbleProperties(workInProgress);return null;case ContextProvider:// Pop provider fiber
var context=workInProgress.type._context;popProvider(context,workInProgress);bubbleProperties(workInProgress);return null;case IncompleteClassComponent:{// Same as class component case. I put it down here so that the tags are
// sequential to ensure this switch is compiled to a jump table.
var _Component=workInProgress.type;if(isContextProvider(_Component)){popContext(workInProgress);}bubbleProperties(workInProgress);return null;}case SuspenseListComponent:{popSuspenseContext(workInProgress);var renderState=workInProgress.memoizedState;if(renderState===null){// We're running in the default, "independent" mode.
// We don't do anything in this mode.
bubbleProperties(workInProgress);return null;}var didSuspendAlready=(workInProgress.flags&DidCapture)!==NoFlags;var renderedTail=renderState.rendering;if(renderedTail===null){// We just rendered the head.
if(!didSuspendAlready){// This is the first pass. We need to figure out if anything is still
// suspended in the rendered set.
// If new content unsuspended, but there's still some content that
// didn't. Then we need to do a second pass that forces everything
// to keep showing their fallbacks.
// We might be suspended if something in this render pass suspended, or
// something in the previous committed pass suspended. Otherwise,
// there's no chance so we can skip the expensive call to
// findFirstSuspended.
var cannotBeSuspended=renderHasNotSuspendedYet()&&(current===null||(current.flags&DidCapture)===NoFlags);if(!cannotBeSuspended){var row=workInProgress.child;while(row!==null){var suspended=findFirstSuspended(row);if(suspended!==null){didSuspendAlready=true;workInProgress.flags|=DidCapture;cutOffTailIfNeeded(renderState,false);// If this is a newly suspended tree, it might not get committed as
// part of the second pass. In that case nothing will subscribe to
// its thenables. Instead, we'll transfer its thenables to the
// SuspenseList so that it can retry if they resolve.
// There might be multiple of these in the list but since we're
// going to wait for all of them anyway, it doesn't really matter
// which ones gets to ping. In theory we could get clever and keep
// track of how many dependencies remain but it gets tricky because
// in the meantime, we can add/remove/change items and dependencies.
// We might bail out of the loop before finding any but that
// doesn't matter since that means that the other boundaries that
// we did find already has their listeners attached.
var newThenables=suspended.updateQueue;if(newThenables!==null){workInProgress.updateQueue=newThenables;workInProgress.flags|=Update;}// Rerender the whole list, but this time, we'll force fallbacks
// to stay in place.
// Reset the effect flags before doing the second pass since that's now invalid.
// Reset the child fibers to their original state.
workInProgress.subtreeFlags=NoFlags;resetChildFibers(workInProgress,renderLanes);// Set up the Suspense Context to force suspense and immediately
// rerender the children.
pushSuspenseContext(workInProgress,setShallowSuspenseContext(suspenseStackCursor.current,ForceSuspenseFallback));// Don't bubble properties in this case.
return workInProgress.child;}row=row.sibling;}}if(renderState.tail!==null&&now()>getRenderTargetTime()){// We have already passed our CPU deadline but we still have rows
// left in the tail. We'll just give up further attempts to render
// the main content and only render fallbacks.
workInProgress.flags|=DidCapture;didSuspendAlready=true;cutOffTailIfNeeded(renderState,false);// Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. While in terms
// of priority this work has the same priority as this current render,
// it's not part of the same transition once the transition has
// committed. If it's sync, we still want to yield so that it can be
// painted. Conceptually, this is really the same as pinging.
// We can use any RetryLane even if it's the one currently rendering
// since we're leaving it behind on this node.
workInProgress.lanes=SomeRetryLane;}}else {cutOffTailIfNeeded(renderState,false);}// Next we're going to render the tail.
}else {// Append the rendered row to the child list.
if(!didSuspendAlready){var _suspended=findFirstSuspended(renderedTail);if(_suspended!==null){workInProgress.flags|=DidCapture;didSuspendAlready=true;// Ensure we transfer the update queue to the parent so that it doesn't
// get lost if this row ends up dropped during a second pass.
var _newThenables=_suspended.updateQueue;if(_newThenables!==null){workInProgress.updateQueue=_newThenables;workInProgress.flags|=Update;}cutOffTailIfNeeded(renderState,true);// This might have been modified.
if(renderState.tail===null&&renderState.tailMode==='hidden'&&!renderedTail.alternate&&!getIsHydrating()// We don't cut it if we're hydrating.
){// We're done.
bubbleProperties(workInProgress);return null;}}else if(// The time it took to render last row is greater than the remaining
// time we have to render. So rendering one more row would likely
// exceed it.
now()*2-renderState.renderingStartTime>getRenderTargetTime()&&renderLanes!==OffscreenLane){// We have now passed our CPU deadline and we'll just give up further
// attempts to render the main content and only render fallbacks.
// The assumption is that this is usually faster.
workInProgress.flags|=DidCapture;didSuspendAlready=true;cutOffTailIfNeeded(renderState,false);// Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. While in terms
// of priority this work has the same priority as this current render,
// it's not part of the same transition once the transition has
// committed. If it's sync, we still want to yield so that it can be
// painted. Conceptually, this is really the same as pinging.
// We can use any RetryLane even if it's the one currently rendering
// since we're leaving it behind on this node.
workInProgress.lanes=SomeRetryLane;}}if(renderState.isBackwards){// The effect list of the backwards tail will have been added
// to the end. This breaks the guarantee that life-cycles fire in
// sibling order but that isn't a strong guarantee promised by React.
// Especially since these might also just pop in during future commits.
// Append to the beginning of the list.
renderedTail.sibling=workInProgress.child;workInProgress.child=renderedTail;}else {var previousSibling=renderState.last;if(previousSibling!==null){previousSibling.sibling=renderedTail;}else {workInProgress.child=renderedTail;}renderState.last=renderedTail;}}if(renderState.tail!==null){// We still have tail rows to render.
// Pop a row.
var next=renderState.tail;renderState.rendering=next;renderState.tail=next.sibling;renderState.renderingStartTime=now();next.sibling=null;// Restore the context.
// TODO: We can probably just avoid popping it instead and only
// setting it the first time we go from not suspended to suspended.
var suspenseContext=suspenseStackCursor.current;if(didSuspendAlready){suspenseContext=setShallowSuspenseContext(suspenseContext,ForceSuspenseFallback);}else {suspenseContext=setDefaultShallowSuspenseContext(suspenseContext);}pushSuspenseContext(workInProgress,suspenseContext);// Do a pass over the next row.
// Don't bubble properties in this case.
return next;}bubbleProperties(workInProgress);return null;}case ScopeComponent:{break;}case OffscreenComponent:case LegacyHiddenComponent:{popRenderLanes(workInProgress);var _nextState=workInProgress.memoizedState;var nextIsHidden=_nextState!==null;if(current!==null){var _prevState=current.memoizedState;var prevIsHidden=_prevState!==null;if(prevIsHidden!==nextIsHidden&&// LegacyHidden doesn't do any hiding — it only pre-renders.
!enableLegacyHidden){workInProgress.flags|=Visibility;}}if(!nextIsHidden||(workInProgress.mode&ConcurrentMode)===NoMode){bubbleProperties(workInProgress);}else {// Don't bubble properties for hidden children unless we're rendering
// at offscreen priority.
if(includesSomeLane(subtreeRenderLanes,OffscreenLane)){bubbleProperties(workInProgress);{// Check if there was an insertion or update in the hidden subtree.
// If so, we need to hide those nodes in the commit phase, so
// schedule a visibility effect.
if(workInProgress.subtreeFlags&(Placement|Update)){workInProgress.flags|=Visibility;}}}}return null;}case CacheComponent:{return null;}case TracingMarkerComponent:{return null;}}throw new Error("Unknown unit of work tag ("+workInProgress.tag+"). This error is likely caused by a bug in "+'React. Please file an issue.');}function unwindWork(current,workInProgress,renderLanes){// Note: This intentionally doesn't check if we're hydrating because comparing
// to the current tree provider fiber is just as fast and less error-prone.
// Ideally we would have a special version of the work loop only
// for hydration.
popTreeContext(workInProgress);switch(workInProgress.tag){case ClassComponent:{var Component=workInProgress.type;if(isContextProvider(Component)){popContext(workInProgress);}var flags=workInProgress.flags;if(flags&ShouldCapture){workInProgress.flags=flags&~ShouldCapture|DidCapture;if((workInProgress.mode&ProfileMode)!==NoMode){transferActualDuration(workInProgress);}return workInProgress;}return null;}case HostRoot:{workInProgress.stateNode;popHostContainer(workInProgress);popTopLevelContextObject(workInProgress);resetWorkInProgressVersions();var _flags=workInProgress.flags;if((_flags&ShouldCapture)!==NoFlags&&(_flags&DidCapture)===NoFlags){// There was an error during render that wasn't captured by a suspense
// boundary. Do a second pass on the root to unmount the children.
workInProgress.flags=_flags&~ShouldCapture|DidCapture;return workInProgress;}// We unwound to the root without completing it. Exit.
return null;}case HostComponent:{// TODO: popHydrationState
popHostContext(workInProgress);return null;}case SuspenseComponent:{popSuspenseContext(workInProgress);var suspenseState=workInProgress.memoizedState;if(suspenseState!==null&&suspenseState.dehydrated!==null){if(workInProgress.alternate===null){throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in '+'React. Please file an issue.');}resetHydrationState();}var _flags2=workInProgress.flags;if(_flags2&ShouldCapture){workInProgress.flags=_flags2&~ShouldCapture|DidCapture;// Captured a suspense effect. Re-render the boundary.
if((workInProgress.mode&ProfileMode)!==NoMode){transferActualDuration(workInProgress);}return workInProgress;}return null;}case SuspenseListComponent:{popSuspenseContext(workInProgress);// SuspenseList doesn't actually catch anything. It should've been
// caught by a nested boundary. If not, it should bubble through.
return null;}case HostPortal:popHostContainer(workInProgress);return null;case ContextProvider:var context=workInProgress.type._context;popProvider(context,workInProgress);return null;case OffscreenComponent:case LegacyHiddenComponent:popRenderLanes(workInProgress);return null;case CacheComponent:return null;default:return null;}}function unwindInterruptedWork(current,interruptedWork,renderLanes){// Note: This intentionally doesn't check if we're hydrating because comparing
// to the current tree provider fiber is just as fast and less error-prone.
// Ideally we would have a special version of the work loop only
// for hydration.
popTreeContext(interruptedWork);switch(interruptedWork.tag){case ClassComponent:{var childContextTypes=interruptedWork.type.childContextTypes;if(childContextTypes!==null&&childContextTypes!==undefined){popContext(interruptedWork);}break;}case HostRoot:{interruptedWork.stateNode;popHostContainer(interruptedWork);popTopLevelContextObject(interruptedWork);resetWorkInProgressVersions();break;}case HostComponent:{popHostContext(interruptedWork);break;}case HostPortal:popHostContainer(interruptedWork);break;case SuspenseComponent:popSuspenseContext(interruptedWork);break;case SuspenseListComponent:popSuspenseContext(interruptedWork);break;case ContextProvider:var context=interruptedWork.type._context;popProvider(context,interruptedWork);break;case OffscreenComponent:case LegacyHiddenComponent:popRenderLanes(interruptedWork);break;}}var didWarnAboutUndefinedSnapshotBeforeUpdate=null;{didWarnAboutUndefinedSnapshotBeforeUpdate=new Set();}// Used during the commit phase to track the state of the Offscreen component stack.
// Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
// Only used when enableSuspenseLayoutEffectSemantics is enabled.
var offscreenSubtreeIsHidden=false;var offscreenSubtreeWasHidden=false;var PossiblyWeakSet=typeof WeakSet==='function'?WeakSet:Set;var nextEffect=null;// Used for Profiling builds to track updaters.
var inProgressLanes=null;var inProgressRoot=null;function reportUncaughtErrorInDEV(error){// Wrapping each small part of the commit phase into a guarded
// callback is a bit too slow (https://github.com/facebook/react/pull/21666).
// But we rely on it to surface errors to DEV tools like overlays
// (https://github.com/facebook/react/issues/21712).
// As a compromise, rethrow only caught errors in a guard.
{invokeGuardedCallback(null,function(){throw error;});clearCaughtError();}}var callComponentWillUnmountWithTimer=function(current,instance){instance.props=current.memoizedProps;instance.state=current.memoizedState;if(current.mode&ProfileMode){try{startLayoutEffectTimer();instance.componentWillUnmount();}finally{recordLayoutEffectDuration(current);}}else {instance.componentWillUnmount();}};// Capture errors so they don't interrupt mounting.
function safelyCallCommitHookLayoutEffectListMount(current,nearestMountedAncestor){try{commitHookEffectListMount(Layout,current);}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error);}}// Capture errors so they don't interrupt unmounting.
function safelyCallComponentWillUnmount(current,nearestMountedAncestor,instance){try{callComponentWillUnmountWithTimer(current,instance);}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error);}}// Capture errors so they don't interrupt mounting.
function safelyCallComponentDidMount(current,nearestMountedAncestor,instance){try{instance.componentDidMount();}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error);}}// Capture errors so they don't interrupt mounting.
function safelyAttachRef(current,nearestMountedAncestor){try{commitAttachRef(current);}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error);}}function safelyDetachRef(current,nearestMountedAncestor){var ref=current.ref;if(ref!==null){if(typeof ref==='function'){var retVal;try{if(enableProfilerTimer&&enableProfilerCommitHooks&&current.mode&ProfileMode){try{startLayoutEffectTimer();retVal=ref(null);}finally{recordLayoutEffectDuration(current);}}else {retVal=ref(null);}}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error);}{if(typeof retVal==='function'){error('Unexpected return value from a callback ref in %s. '+'A callback ref should not return a function.',getComponentNameFromFiber(current));}}}else {ref.current=null;}}}function safelyCallDestroy(current,nearestMountedAncestor,destroy){try{destroy();}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error);}}var shouldFireAfterActiveInstanceBlur=false;function commitBeforeMutationEffects(root,firstChild){prepareForCommit(root.containerInfo);nextEffect=firstChild;commitBeforeMutationEffects_begin();// We no longer need to track the active instance fiber
var shouldFire=shouldFireAfterActiveInstanceBlur;shouldFireAfterActiveInstanceBlur=false;return shouldFire;}function commitBeforeMutationEffects_begin(){while(nextEffect!==null){var fiber=nextEffect;// This phase is only used for beforeActiveInstanceBlur.
var child=fiber.child;if((fiber.subtreeFlags&BeforeMutationMask)!==NoFlags&&child!==null){child.return=fiber;nextEffect=child;}else {commitBeforeMutationEffects_complete();}}}function commitBeforeMutationEffects_complete(){while(nextEffect!==null){var fiber=nextEffect;setCurrentFiber(fiber);try{commitBeforeMutationEffectsOnFiber(fiber);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}resetCurrentFiber();var sibling=fiber.sibling;if(sibling!==null){sibling.return=fiber.return;nextEffect=sibling;return;}nextEffect=fiber.return;}}function commitBeforeMutationEffectsOnFiber(finishedWork){var current=finishedWork.alternate;var flags=finishedWork.flags;if((flags&Snapshot)!==NoFlags){setCurrentFiber(finishedWork);switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{break;}case ClassComponent:{if(current!==null){var prevProps=current.memoizedProps;var prevState=current.memoizedState;var instance=finishedWork.stateNode;// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'getSnapshotBeforeUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'getSnapshotBeforeUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}}}var snapshot=instance.getSnapshotBeforeUpdate(finishedWork.elementType===finishedWork.type?prevProps:resolveDefaultProps(finishedWork.type,prevProps),prevState);{var didWarnSet=didWarnAboutUndefinedSnapshotBeforeUpdate;if(snapshot===undefined&&!didWarnSet.has(finishedWork.type)){didWarnSet.add(finishedWork.type);error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) '+'must be returned. You have returned undefined.',getComponentNameFromFiber(finishedWork));}}instance.__reactInternalSnapshotBeforeUpdate=snapshot;}break;}case HostRoot:{{var root=finishedWork.stateNode;clearContainer(root.containerInfo);}break;}case HostComponent:case HostText:case HostPortal:case IncompleteClassComponent:// Nothing to do for these component types
break;default:{throw new Error('This unit of work tag should not have side-effects. This error is '+'likely caused by a bug in React. Please file an issue.');}}resetCurrentFiber();}}function commitHookEffectListUnmount(flags,finishedWork,nearestMountedAncestor){var updateQueue=finishedWork.updateQueue;var lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{if((effect.tag&flags)===flags){// Unmount
var destroy=effect.destroy;effect.destroy=undefined;if(destroy!==undefined){{if((flags&Passive$1)!==NoFlags$1){markComponentPassiveEffectUnmountStarted(finishedWork);}else if((flags&Layout)!==NoFlags$1){markComponentLayoutEffectUnmountStarted(finishedWork);}}{if((flags&Insertion)!==NoFlags$1){setIsRunningInsertionEffect(true);}}safelyCallDestroy(finishedWork,nearestMountedAncestor,destroy);{if((flags&Insertion)!==NoFlags$1){setIsRunningInsertionEffect(false);}}{if((flags&Passive$1)!==NoFlags$1){markComponentPassiveEffectUnmountStopped();}else if((flags&Layout)!==NoFlags$1){markComponentLayoutEffectUnmountStopped();}}}}effect=effect.next;}while(effect!==firstEffect);}}function commitHookEffectListMount(flags,finishedWork){var updateQueue=finishedWork.updateQueue;var lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{if((effect.tag&flags)===flags){{if((flags&Passive$1)!==NoFlags$1){markComponentPassiveEffectMountStarted(finishedWork);}else if((flags&Layout)!==NoFlags$1){markComponentLayoutEffectMountStarted(finishedWork);}}// Mount
var create=effect.create;{if((flags&Insertion)!==NoFlags$1){setIsRunningInsertionEffect(true);}}effect.destroy=create();{if((flags&Insertion)!==NoFlags$1){setIsRunningInsertionEffect(false);}}{if((flags&Passive$1)!==NoFlags$1){markComponentPassiveEffectMountStopped();}else if((flags&Layout)!==NoFlags$1){markComponentLayoutEffectMountStopped();}}{var destroy=effect.destroy;if(destroy!==undefined&&typeof destroy!=='function'){var hookName=void 0;if((effect.tag&Layout)!==NoFlags){hookName='useLayoutEffect';}else if((effect.tag&Insertion)!==NoFlags){hookName='useInsertionEffect';}else {hookName='useEffect';}var addendum=void 0;if(destroy===null){addendum=' You returned null. If your effect does not require clean '+'up, return undefined (or nothing).';}else if(typeof destroy.then==='function'){addendum='\n\nIt looks like you wrote '+hookName+'(async () => ...) or returned a Promise. '+'Instead, write the async function inside your effect '+'and call it immediately:\n\n'+hookName+'(() => {\n'+'  async function fetchData() {\n'+'    // You can await here\n'+'    const response = await MyAPI.getData(someId);\n'+'    // ...\n'+'  }\n'+'  fetchData();\n'+"}, [someId]); // Or [] if effect doesn't need props or state\n\n"+'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';}else {addendum=' You returned: '+destroy;}error('%s must not return anything besides a function, '+'which is used for clean-up.%s',hookName,addendum);}}}effect=effect.next;}while(effect!==firstEffect);}}function commitPassiveEffectDurations(finishedRoot,finishedWork){{// Only Profilers with work in their subtree will have an Update effect scheduled.
if((finishedWork.flags&Update)!==NoFlags){switch(finishedWork.tag){case Profiler:{var passiveEffectDuration=finishedWork.stateNode.passiveEffectDuration;var _finishedWork$memoize=finishedWork.memoizedProps,id=_finishedWork$memoize.id,onPostCommit=_finishedWork$memoize.onPostCommit;// This value will still reflect the previous commit phase.
// It does not get reset until the start of the next commit phase.
var commitTime=getCommitTime();var phase=finishedWork.alternate===null?'mount':'update';{if(isCurrentUpdateNested()){phase='nested-update';}}if(typeof onPostCommit==='function'){onPostCommit(id,phase,passiveEffectDuration,commitTime);}// Bubble times to the next nearest ancestor Profiler.
// After we process that Profiler, we'll bubble further up.
var parentFiber=finishedWork.return;outer:while(parentFiber!==null){switch(parentFiber.tag){case HostRoot:var root=parentFiber.stateNode;root.passiveEffectDuration+=passiveEffectDuration;break outer;case Profiler:var parentStateNode=parentFiber.stateNode;parentStateNode.passiveEffectDuration+=passiveEffectDuration;break outer;}parentFiber=parentFiber.return;}break;}}}}}function commitLayoutEffectOnFiber(finishedRoot,current,finishedWork,committedLanes){if((finishedWork.flags&LayoutMask)!==NoFlags){switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{if(!offscreenSubtreeWasHidden){// At this point layout effects have already been destroyed (during mutation phase).
// This is done to prevent sibling component effects from interfering with each other,
// e.g. a destroy function in one component should never override a ref set
// by a create function in another component during the same commit.
if(finishedWork.mode&ProfileMode){try{startLayoutEffectTimer();commitHookEffectListMount(Layout|HasEffect,finishedWork);}finally{recordLayoutEffectDuration(finishedWork);}}else {commitHookEffectListMount(Layout|HasEffect,finishedWork);}}break;}case ClassComponent:{var instance=finishedWork.stateNode;if(finishedWork.flags&Update){if(!offscreenSubtreeWasHidden){if(current===null){// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'componentDidMount. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'componentDidMount. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}}}if(finishedWork.mode&ProfileMode){try{startLayoutEffectTimer();instance.componentDidMount();}finally{recordLayoutEffectDuration(finishedWork);}}else {instance.componentDidMount();}}else {var prevProps=finishedWork.elementType===finishedWork.type?current.memoizedProps:resolveDefaultProps(finishedWork.type,current.memoizedProps);var prevState=current.memoizedState;// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'componentDidUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'componentDidUpdate. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}}}if(finishedWork.mode&ProfileMode){try{startLayoutEffectTimer();instance.componentDidUpdate(prevProps,prevState,instance.__reactInternalSnapshotBeforeUpdate);}finally{recordLayoutEffectDuration(finishedWork);}}else {instance.componentDidUpdate(prevProps,prevState,instance.__reactInternalSnapshotBeforeUpdate);}}}}// TODO: I think this is now always non-null by the time it reaches the
// commit phase. Consider removing the type check.
var updateQueue=finishedWork.updateQueue;if(updateQueue!==null){{if(finishedWork.type===finishedWork.elementType&&!didWarnAboutReassigningProps){if(instance.props!==finishedWork.memoizedProps){error('Expected %s props to match memoized props before '+'processing the update queue. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.props`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}if(instance.state!==finishedWork.memoizedState){error('Expected %s state to match memoized state before '+'processing the update queue. '+'This might either be because of a bug in React, or because '+'a component reassigns its own `this.state`. '+'Please file an issue.',getComponentNameFromFiber(finishedWork)||'instance');}}}// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
commitUpdateQueue(finishedWork,updateQueue,instance);}break;}case HostRoot:{// TODO: I think this is now always non-null by the time it reaches the
// commit phase. Consider removing the type check.
var _updateQueue=finishedWork.updateQueue;if(_updateQueue!==null){var _instance=null;if(finishedWork.child!==null){switch(finishedWork.child.tag){case HostComponent:_instance=getPublicInstance(finishedWork.child.stateNode);break;case ClassComponent:_instance=finishedWork.child.stateNode;break;}}commitUpdateQueue(finishedWork,_updateQueue,_instance);}break;}case HostComponent:{var _instance2=finishedWork.stateNode;// Renderers may schedule work to be done after host components are mounted
// (eg DOM renderer may schedule auto-focus for inputs and form controls).
// These effects should only be committed when components are first mounted,
// aka when there is no current/alternate.
if(current===null&&finishedWork.flags&Update){var type=finishedWork.type;var props=finishedWork.memoizedProps;commitMount(_instance2,type,props);}break;}case HostText:{// We have no life-cycles associated with text.
break;}case HostPortal:{// We have no life-cycles associated with portals.
break;}case Profiler:{{var _finishedWork$memoize2=finishedWork.memoizedProps,onCommit=_finishedWork$memoize2.onCommit,onRender=_finishedWork$memoize2.onRender;var effectDuration=finishedWork.stateNode.effectDuration;var commitTime=getCommitTime();var phase=current===null?'mount':'update';{if(isCurrentUpdateNested()){phase='nested-update';}}if(typeof onRender==='function'){onRender(finishedWork.memoizedProps.id,phase,finishedWork.actualDuration,finishedWork.treeBaseDuration,finishedWork.actualStartTime,commitTime);}{if(typeof onCommit==='function'){onCommit(finishedWork.memoizedProps.id,phase,effectDuration,commitTime);}// Schedule a passive effect for this Profiler to call onPostCommit hooks.
// This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
// because the effect is also where times bubble to parent Profilers.
enqueuePendingPassiveProfilerEffect(finishedWork);// Propagate layout effect durations to the next nearest Profiler ancestor.
// Do not reset these values until the next render so DevTools has a chance to read them first.
var parentFiber=finishedWork.return;outer:while(parentFiber!==null){switch(parentFiber.tag){case HostRoot:var root=parentFiber.stateNode;root.effectDuration+=effectDuration;break outer;case Profiler:var parentStateNode=parentFiber.stateNode;parentStateNode.effectDuration+=effectDuration;break outer;}parentFiber=parentFiber.return;}}}break;}case SuspenseComponent:{commitSuspenseHydrationCallbacks(finishedRoot,finishedWork);break;}case SuspenseListComponent:case IncompleteClassComponent:case ScopeComponent:case OffscreenComponent:case LegacyHiddenComponent:case TracingMarkerComponent:{break;}default:throw new Error('This unit of work tag should not have side-effects. This error is '+'likely caused by a bug in React. Please file an issue.');}}if(!offscreenSubtreeWasHidden){{if(finishedWork.flags&Ref){commitAttachRef(finishedWork);}}}}function reappearLayoutEffectsOnFiber(node){// Turn on layout effects in a tree that previously disappeared.
// TODO (Offscreen) Check: flags & LayoutStatic
switch(node.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{if(node.mode&ProfileMode){try{startLayoutEffectTimer();safelyCallCommitHookLayoutEffectListMount(node,node.return);}finally{recordLayoutEffectDuration(node);}}else {safelyCallCommitHookLayoutEffectListMount(node,node.return);}break;}case ClassComponent:{var instance=node.stateNode;if(typeof instance.componentDidMount==='function'){safelyCallComponentDidMount(node,node.return,instance);}safelyAttachRef(node,node.return);break;}case HostComponent:{safelyAttachRef(node,node.return);break;}}}function hideOrUnhideAllChildren(finishedWork,isHidden){// Only hide or unhide the top-most host nodes.
var hostSubtreeRoot=null;{// We only have the top Fiber that was inserted but we need to recurse down its
// children to find all the terminal nodes.
var node=finishedWork;while(true){if(node.tag===HostComponent){if(hostSubtreeRoot===null){hostSubtreeRoot=node;try{var instance=node.stateNode;if(isHidden){hideInstance(instance);}else {unhideInstance(node.stateNode,node.memoizedProps);}}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}}else if(node.tag===HostText){if(hostSubtreeRoot===null){try{var _instance3=node.stateNode;if(isHidden){hideTextInstance(_instance3);}else {unhideTextInstance(_instance3,node.memoizedProps);}}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}}else if((node.tag===OffscreenComponent||node.tag===LegacyHiddenComponent)&&node.memoizedState!==null&&node!==finishedWork);else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===finishedWork){return;}while(node.sibling===null){if(node.return===null||node.return===finishedWork){return;}if(hostSubtreeRoot===node){hostSubtreeRoot=null;}node=node.return;}if(hostSubtreeRoot===node){hostSubtreeRoot=null;}node.sibling.return=node.return;node=node.sibling;}}}function commitAttachRef(finishedWork){var ref=finishedWork.ref;if(ref!==null){var instance=finishedWork.stateNode;var instanceToUse;switch(finishedWork.tag){case HostComponent:instanceToUse=getPublicInstance(instance);break;default:instanceToUse=instance;}// Moved outside to ensure DCE works with this flag
if(typeof ref==='function'){var retVal;if(finishedWork.mode&ProfileMode){try{startLayoutEffectTimer();retVal=ref(instanceToUse);}finally{recordLayoutEffectDuration(finishedWork);}}else {retVal=ref(instanceToUse);}{if(typeof retVal==='function'){error('Unexpected return value from a callback ref in %s. '+'A callback ref should not return a function.',getComponentNameFromFiber(finishedWork));}}}else {{if(!ref.hasOwnProperty('current')){error('Unexpected ref object provided for %s. '+'Use either a ref-setter function or React.createRef().',getComponentNameFromFiber(finishedWork));}}ref.current=instanceToUse;}}}function detachFiberMutation(fiber){// Cut off the return pointer to disconnect it from the tree.
// This enables us to detect and warn against state updates on an unmounted component.
// It also prevents events from bubbling from within disconnected components.
//
// Ideally, we should also clear the child pointer of the parent alternate to let this
// get GC:ed but we don't know which for sure which parent is the current
// one so we'll settle for GC:ing the subtree of this child.
// This child itself will be GC:ed when the parent updates the next time.
//
// Note that we can't clear child or sibling pointers yet.
// They're needed for passive effects and for findDOMNode.
// We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects).
//
// Don't reset the alternate yet, either. We need that so we can detach the
// alternate's fields in the passive phase. Clearing the return pointer is
// sufficient for findDOMNode semantics.
var alternate=fiber.alternate;if(alternate!==null){alternate.return=null;}fiber.return=null;}function detachFiberAfterEffects(fiber){var alternate=fiber.alternate;if(alternate!==null){fiber.alternate=null;detachFiberAfterEffects(alternate);}// Note: Defensively using negation instead of < in case
// `deletedTreeCleanUpLevel` is undefined.
{// Clear cyclical Fiber fields. This level alone is designed to roughly
// approximate the planned Fiber refactor. In that world, `setState` will be
// bound to a special "instance" object instead of a Fiber. The Instance
// object will not have any of these fields. It will only be connected to
// the fiber tree via a single link at the root. So if this level alone is
// sufficient to fix memory issues, that bodes well for our plans.
fiber.child=null;fiber.deletions=null;fiber.sibling=null;// The `stateNode` is cyclical because on host nodes it points to the host
// tree, which has its own pointers to children, parents, and siblings.
// The other host nodes also point back to fibers, so we should detach that
// one, too.
if(fiber.tag===HostComponent){var hostInstance=fiber.stateNode;if(hostInstance!==null){detachDeletedInstance(hostInstance);}}fiber.stateNode=null;// I'm intentionally not clearing the `return` field in this level. We
// already disconnect the `return` pointer at the root of the deleted
// subtree (in `detachFiberMutation`). Besides, `return` by itself is not
// cyclical — it's only cyclical when combined with `child`, `sibling`, and
// `alternate`. But we'll clear it in the next level anyway, just in case.
{fiber._debugOwner=null;}{// Theoretically, nothing in here should be necessary, because we already
// disconnected the fiber from the tree. So even if something leaks this
// particular fiber, it won't leak anything else
//
// The purpose of this branch is to be super aggressive so we can measure
// if there's any difference in memory impact. If there is, that could
// indicate a React leak we don't know about.
fiber.return=null;fiber.dependencies=null;fiber.memoizedProps=null;fiber.memoizedState=null;fiber.pendingProps=null;fiber.stateNode=null;// TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead.
fiber.updateQueue=null;}}}function getHostParentFiber(fiber){var parent=fiber.return;while(parent!==null){if(isHostParent(parent)){return parent;}parent=parent.return;}throw new Error('Expected to find a host parent. This error is likely caused by a bug '+'in React. Please file an issue.');}function isHostParent(fiber){return fiber.tag===HostComponent||fiber.tag===HostRoot||fiber.tag===HostPortal;}function getHostSibling(fiber){// We're going to search forward into the tree until we find a sibling host
// node. Unfortunately, if multiple insertions are done in a row we have to
// search past them. This leads to exponential search for the next sibling.
// TODO: Find a more efficient way to do this.
var node=fiber;siblings:while(true){// If we didn't find anything, let's try the next sibling.
while(node.sibling===null){if(node.return===null||isHostParent(node.return)){// If we pop out of the root or hit the parent the fiber we are the
// last sibling.
return null;}node=node.return;}node.sibling.return=node.return;node=node.sibling;while(node.tag!==HostComponent&&node.tag!==HostText&&node.tag!==DehydratedFragment){// If it is not host node and, we might have a host node inside it.
// Try to search down until we find one.
if(node.flags&Placement){// If we don't have a child, try the siblings instead.
continue siblings;}// If we don't have a child, try the siblings instead.
// We also skip portals because they are not part of this host tree.
if(node.child===null||node.tag===HostPortal){continue siblings;}else {node.child.return=node;node=node.child;}}// Check if this host node is stable or about to be placed.
if(!(node.flags&Placement)){// Found it!
return node.stateNode;}}}function commitPlacement(finishedWork){var parentFiber=getHostParentFiber(finishedWork);// Note: these two variables *must* always be updated together.
switch(parentFiber.tag){case HostComponent:{var parent=parentFiber.stateNode;if(parentFiber.flags&ContentReset){// Reset the text content of the parent before doing any insertions
resetTextContent(parent);// Clear ContentReset from the effect tag
parentFiber.flags&=~ContentReset;}var before=getHostSibling(finishedWork);// We only have the top Fiber that was inserted but we need to recurse down its
// children to find all the terminal nodes.
insertOrAppendPlacementNode(finishedWork,before,parent);break;}case HostRoot:case HostPortal:{var _parent=parentFiber.stateNode.containerInfo;var _before=getHostSibling(finishedWork);insertOrAppendPlacementNodeIntoContainer(finishedWork,_before,_parent);break;}// eslint-disable-next-line-no-fallthrough
default:throw new Error('Invalid host parent fiber. This error is likely caused by a bug '+'in React. Please file an issue.');}}function insertOrAppendPlacementNodeIntoContainer(node,before,parent){var tag=node.tag;var isHost=tag===HostComponent||tag===HostText;if(isHost){var stateNode=node.stateNode;if(before){insertInContainerBefore(parent,stateNode,before);}else {appendChildToContainer(parent,stateNode);}}else if(tag===HostPortal);else {var child=node.child;if(child!==null){insertOrAppendPlacementNodeIntoContainer(child,before,parent);var sibling=child.sibling;while(sibling!==null){insertOrAppendPlacementNodeIntoContainer(sibling,before,parent);sibling=sibling.sibling;}}}}function insertOrAppendPlacementNode(node,before,parent){var tag=node.tag;var isHost=tag===HostComponent||tag===HostText;if(isHost){var stateNode=node.stateNode;if(before){insertBefore(parent,stateNode,before);}else {appendChild(parent,stateNode);}}else if(tag===HostPortal);else {var child=node.child;if(child!==null){insertOrAppendPlacementNode(child,before,parent);var sibling=child.sibling;while(sibling!==null){insertOrAppendPlacementNode(sibling,before,parent);sibling=sibling.sibling;}}}}// These are tracked on the stack as we recursively traverse a
// deleted subtree.
// TODO: Update these during the whole mutation phase, not just during
// a deletion.
var hostParent=null;var hostParentIsContainer=false;function commitDeletionEffects(root,returnFiber,deletedFiber){{// We only have the top Fiber that was deleted but we need to recurse down its
// children to find all the terminal nodes.
// Recursively delete all host nodes from the parent, detach refs, clean
// up mounted layout effects, and call componentWillUnmount.
// We only need to remove the topmost host child in each branch. But then we
// still need to keep traversing to unmount effects, refs, and cWU. TODO: We
// could split this into two separate traversals functions, where the second
// one doesn't include any removeChild logic. This is maybe the same
// function as "disappearLayoutEffects" (or whatever that turns into after
// the layout phase is refactored to use recursion).
// Before starting, find the nearest host parent on the stack so we know
// which instance/container to remove the children from.
// TODO: Instead of searching up the fiber return path on every deletion, we
// can track the nearest host component on the JS stack as we traverse the
// tree during the commit phase. This would make insertions faster, too.
var parent=returnFiber;findParent:while(parent!==null){switch(parent.tag){case HostComponent:{hostParent=parent.stateNode;hostParentIsContainer=false;break findParent;}case HostRoot:{hostParent=parent.stateNode.containerInfo;hostParentIsContainer=true;break findParent;}case HostPortal:{hostParent=parent.stateNode.containerInfo;hostParentIsContainer=true;break findParent;}}parent=parent.return;}if(hostParent===null){throw new Error('Expected to find a host parent. This error is likely caused by '+'a bug in React. Please file an issue.');}commitDeletionEffectsOnFiber(root,returnFiber,deletedFiber);hostParent=null;hostParentIsContainer=false;}detachFiberMutation(deletedFiber);}function recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,parent){// TODO: Use a static flag to skip trees that don't have unmount effects
var child=parent.child;while(child!==null){commitDeletionEffectsOnFiber(finishedRoot,nearestMountedAncestor,child);child=child.sibling;}}function commitDeletionEffectsOnFiber(finishedRoot,nearestMountedAncestor,deletedFiber){onCommitUnmount(deletedFiber);// The cases in this outer switch modify the stack before they traverse
// into their subtree. There are simpler cases in the inner switch
// that don't modify the stack.
switch(deletedFiber.tag){case HostComponent:{if(!offscreenSubtreeWasHidden){safelyDetachRef(deletedFiber,nearestMountedAncestor);}// Intentional fallthrough to next branch
}// eslint-disable-next-line-no-fallthrough
case HostText:{// We only need to remove the nearest host child. Set the host parent
// to `null` on the stack to indicate that nested children don't
// need to be removed.
{var prevHostParent=hostParent;var prevHostParentIsContainer=hostParentIsContainer;hostParent=null;recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);hostParent=prevHostParent;hostParentIsContainer=prevHostParentIsContainer;if(hostParent!==null){// Now that all the child effects have unmounted, we can remove the
// node from the tree.
if(hostParentIsContainer){removeChildFromContainer(hostParent,deletedFiber.stateNode);}else {removeChild(hostParent,deletedFiber.stateNode);}}}return;}case DehydratedFragment:{// Delete the dehydrated suspense boundary and all of its content.
{if(hostParent!==null){if(hostParentIsContainer){clearSuspenseBoundaryFromContainer(hostParent,deletedFiber.stateNode);}else {clearSuspenseBoundary(hostParent,deletedFiber.stateNode);}}}return;}case HostPortal:{{// When we go into a portal, it becomes the parent to remove from.
var _prevHostParent=hostParent;var _prevHostParentIsContainer=hostParentIsContainer;hostParent=deletedFiber.stateNode.containerInfo;hostParentIsContainer=true;recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);hostParent=_prevHostParent;hostParentIsContainer=_prevHostParentIsContainer;}return;}case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:{if(!offscreenSubtreeWasHidden){var updateQueue=deletedFiber.updateQueue;if(updateQueue!==null){var lastEffect=updateQueue.lastEffect;if(lastEffect!==null){var firstEffect=lastEffect.next;var effect=firstEffect;do{var _effect=effect,destroy=_effect.destroy,tag=_effect.tag;if(destroy!==undefined){if((tag&Insertion)!==NoFlags$1){safelyCallDestroy(deletedFiber,nearestMountedAncestor,destroy);}else if((tag&Layout)!==NoFlags$1){{markComponentLayoutEffectUnmountStarted(deletedFiber);}if(deletedFiber.mode&ProfileMode){startLayoutEffectTimer();safelyCallDestroy(deletedFiber,nearestMountedAncestor,destroy);recordLayoutEffectDuration(deletedFiber);}else {safelyCallDestroy(deletedFiber,nearestMountedAncestor,destroy);}{markComponentLayoutEffectUnmountStopped();}}}effect=effect.next;}while(effect!==firstEffect);}}}recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);return;}case ClassComponent:{if(!offscreenSubtreeWasHidden){safelyDetachRef(deletedFiber,nearestMountedAncestor);var instance=deletedFiber.stateNode;if(typeof instance.componentWillUnmount==='function'){safelyCallComponentWillUnmount(deletedFiber,nearestMountedAncestor,instance);}}recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);return;}case ScopeComponent:{recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);return;}case OffscreenComponent:{if(// TODO: Remove this dead flag
deletedFiber.mode&ConcurrentMode){// If this offscreen component is hidden, we already unmounted it. Before
// deleting the children, track that it's already unmounted so that we
// don't attempt to unmount the effects again.
// TODO: If the tree is hidden, in most cases we should be able to skip
// over the nested children entirely. An exception is we haven't yet found
// the topmost host node to delete, which we already track on the stack.
// But the other case is portals, which need to be detached no matter how
// deeply they are nested. We should use a subtree flag to track whether a
// subtree includes a nested portal.
var prevOffscreenSubtreeWasHidden=offscreenSubtreeWasHidden;offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden||deletedFiber.memoizedState!==null;recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden;}else {recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);}break;}default:{recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);return;}}}function commitSuspenseCallback(finishedWork){// TODO: Move this to passive phase
finishedWork.memoizedState;}function commitSuspenseHydrationCallbacks(finishedRoot,finishedWork){var newState=finishedWork.memoizedState;if(newState===null){var current=finishedWork.alternate;if(current!==null){var prevState=current.memoizedState;if(prevState!==null){var suspenseInstance=prevState.dehydrated;if(suspenseInstance!==null){commitHydratedSuspenseInstance(suspenseInstance);}}}}}function attachSuspenseRetryListeners(finishedWork){// If this boundary just timed out, then it will have a set of wakeables.
// For each wakeable, attach a listener so that when it resolves, React
// attempts to re-render the boundary in the primary (pre-timeout) state.
var wakeables=finishedWork.updateQueue;if(wakeables!==null){finishedWork.updateQueue=null;var retryCache=finishedWork.stateNode;if(retryCache===null){retryCache=finishedWork.stateNode=new PossiblyWeakSet();}wakeables.forEach(function(wakeable){// Memoize using the boundary fiber to prevent redundant listeners.
var retry=resolveRetryWakeable.bind(null,finishedWork,wakeable);if(!retryCache.has(wakeable)){retryCache.add(wakeable);{if(isDevToolsPresent){if(inProgressLanes!==null&&inProgressRoot!==null){// If we have pending work still, associate the original updaters with it.
restorePendingUpdaters(inProgressRoot,inProgressLanes);}else {throw Error('Expected finished root and lanes to be set. This is a bug in React.');}}}wakeable.then(retry,retry);}});}}// This function detects when a Suspense boundary goes from visible to hidden.
function commitMutationEffects(root,finishedWork,committedLanes){inProgressLanes=committedLanes;inProgressRoot=root;setCurrentFiber(finishedWork);commitMutationEffectsOnFiber(finishedWork,root);setCurrentFiber(finishedWork);inProgressLanes=null;inProgressRoot=null;}function recursivelyTraverseMutationEffects(root,parentFiber,lanes){// Deletions effects can be scheduled on any fiber type. They need to happen
// before the children effects hae fired.
var deletions=parentFiber.deletions;if(deletions!==null){for(var i=0;i<deletions.length;i++){var childToDelete=deletions[i];try{commitDeletionEffects(root,parentFiber,childToDelete);}catch(error){captureCommitPhaseError(childToDelete,parentFiber,error);}}}var prevDebugFiber=getCurrentFiber();if(parentFiber.subtreeFlags&MutationMask){var child=parentFiber.child;while(child!==null){setCurrentFiber(child);commitMutationEffectsOnFiber(child,root);child=child.sibling;}}setCurrentFiber(prevDebugFiber);}function commitMutationEffectsOnFiber(finishedWork,root,lanes){var current=finishedWork.alternate;var flags=finishedWork.flags;// The effect flag should be checked *after* we refine the type of fiber,
// because the fiber tag is more specific. An exception is any flag related
// to reconcilation, because those can be set on all fiber types.
switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);if(flags&Update){try{commitHookEffectListUnmount(Insertion|HasEffect,finishedWork,finishedWork.return);commitHookEffectListMount(Insertion|HasEffect,finishedWork);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}// Layout effects are destroyed during the mutation phase so that all
// destroy functions for all fibers are called before any create functions.
// This prevents sibling component effects from interfering with each other,
// e.g. a destroy function in one component should never override a ref set
// by a create function in another component during the same commit.
if(finishedWork.mode&ProfileMode){try{startLayoutEffectTimer();commitHookEffectListUnmount(Layout|HasEffect,finishedWork,finishedWork.return);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}recordLayoutEffectDuration(finishedWork);}else {try{commitHookEffectListUnmount(Layout|HasEffect,finishedWork,finishedWork.return);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}}return;}case ClassComponent:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);if(flags&Ref){if(current!==null){safelyDetachRef(current,current.return);}}return;}case HostComponent:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);if(flags&Ref){if(current!==null){safelyDetachRef(current,current.return);}}{// TODO: ContentReset gets cleared by the children during the commit
// phase. This is a refactor hazard because it means we must read
// flags the flags after `commitReconciliationEffects` has already run;
// the order matters. We should refactor so that ContentReset does not
// rely on mutating the flag during commit. Like by setting a flag
// during the render phase instead.
if(finishedWork.flags&ContentReset){var instance=finishedWork.stateNode;try{resetTextContent(instance);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}if(flags&Update){var _instance4=finishedWork.stateNode;if(_instance4!=null){// Commit the work prepared earlier.
var newProps=finishedWork.memoizedProps;// For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
var oldProps=current!==null?current.memoizedProps:newProps;var type=finishedWork.type;// TODO: Type the updateQueue to be specific to host components.
var updatePayload=finishedWork.updateQueue;finishedWork.updateQueue=null;if(updatePayload!==null){try{commitUpdate(_instance4,updatePayload,type,oldProps,newProps,finishedWork);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}}}}return;}case HostText:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);if(flags&Update){{if(finishedWork.stateNode===null){throw new Error('This should have a text node initialized. This error is likely '+'caused by a bug in React. Please file an issue.');}var textInstance=finishedWork.stateNode;var newText=finishedWork.memoizedProps;// For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
var oldText=current!==null?current.memoizedProps:newText;try{commitTextUpdate(textInstance,oldText,newText);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}}return;}case HostRoot:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);if(flags&Update){{if(current!==null){var prevRootState=current.memoizedState;if(prevRootState.isDehydrated){try{commitHydratedContainer(root.containerInfo);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}}}}}return;}case HostPortal:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);return;}case SuspenseComponent:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);var offscreenFiber=finishedWork.child;if(offscreenFiber.flags&Visibility){var offscreenInstance=offscreenFiber.stateNode;var newState=offscreenFiber.memoizedState;var isHidden=newState!==null;// Track the current state on the Offscreen instance so we can
// read it during an event
offscreenInstance.isHidden=isHidden;if(isHidden){var wasHidden=offscreenFiber.alternate!==null&&offscreenFiber.alternate.memoizedState!==null;if(!wasHidden){// TODO: Move to passive phase
markCommitTimeOfFallback();}}}if(flags&Update){try{commitSuspenseCallback(finishedWork);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}attachSuspenseRetryListeners(finishedWork);}return;}case OffscreenComponent:{var _wasHidden=current!==null&&current.memoizedState!==null;if(// TODO: Remove this dead flag
finishedWork.mode&ConcurrentMode){// Before committing the children, track on the stack whether this
// offscreen subtree was already hidden, so that we don't unmount the
// effects again.
var prevOffscreenSubtreeWasHidden=offscreenSubtreeWasHidden;offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden||_wasHidden;recursivelyTraverseMutationEffects(root,finishedWork);offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden;}else {recursivelyTraverseMutationEffects(root,finishedWork);}commitReconciliationEffects(finishedWork);if(flags&Visibility){var _offscreenInstance=finishedWork.stateNode;var _newState=finishedWork.memoizedState;var _isHidden=_newState!==null;var offscreenBoundary=finishedWork;// Track the current state on the Offscreen instance so we can
// read it during an event
_offscreenInstance.isHidden=_isHidden;{if(_isHidden){if(!_wasHidden){if((offscreenBoundary.mode&ConcurrentMode)!==NoMode){nextEffect=offscreenBoundary;var offscreenChild=offscreenBoundary.child;while(offscreenChild!==null){nextEffect=offscreenChild;disappearLayoutEffects_begin(offscreenChild);offscreenChild=offscreenChild.sibling;}}}}}{// TODO: This needs to run whenever there's an insertion or update
// inside a hidden Offscreen tree.
hideOrUnhideAllChildren(offscreenBoundary,_isHidden);}}return;}case SuspenseListComponent:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);if(flags&Update){attachSuspenseRetryListeners(finishedWork);}return;}case ScopeComponent:{return;}default:{recursivelyTraverseMutationEffects(root,finishedWork);commitReconciliationEffects(finishedWork);return;}}}function commitReconciliationEffects(finishedWork){// Placement effects (insertions, reorders) can be scheduled on any fiber
// type. They needs to happen after the children effects have fired, but
// before the effects on this fiber have fired.
var flags=finishedWork.flags;if(flags&Placement){try{commitPlacement(finishedWork);}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error);}// Clear the "placement" from effect tag so that we know that this is
// inserted, before any life-cycles like componentDidMount gets called.
// TODO: findDOMNode doesn't rely on this any more but isMounted does
// and isMounted is deprecated anyway so we should be able to kill this.
finishedWork.flags&=~Placement;}if(flags&Hydrating){finishedWork.flags&=~Hydrating;}}function commitLayoutEffects(finishedWork,root,committedLanes){inProgressLanes=committedLanes;inProgressRoot=root;nextEffect=finishedWork;commitLayoutEffects_begin(finishedWork,root,committedLanes);inProgressLanes=null;inProgressRoot=null;}function commitLayoutEffects_begin(subtreeRoot,root,committedLanes){// Suspense layout effects semantics don't change for legacy roots.
var isModernRoot=(subtreeRoot.mode&ConcurrentMode)!==NoMode;while(nextEffect!==null){var fiber=nextEffect;var firstChild=fiber.child;if(fiber.tag===OffscreenComponent&&isModernRoot){// Keep track of the current Offscreen stack's state.
var isHidden=fiber.memoizedState!==null;var newOffscreenSubtreeIsHidden=isHidden||offscreenSubtreeIsHidden;if(newOffscreenSubtreeIsHidden){// The Offscreen tree is hidden. Skip over its layout effects.
commitLayoutMountEffects_complete(subtreeRoot,root,committedLanes);continue;}else {// TODO (Offscreen) Also check: subtreeFlags & LayoutMask
var current=fiber.alternate;var wasHidden=current!==null&&current.memoizedState!==null;var newOffscreenSubtreeWasHidden=wasHidden||offscreenSubtreeWasHidden;var prevOffscreenSubtreeIsHidden=offscreenSubtreeIsHidden;var prevOffscreenSubtreeWasHidden=offscreenSubtreeWasHidden;// Traverse the Offscreen subtree with the current Offscreen as the root.
offscreenSubtreeIsHidden=newOffscreenSubtreeIsHidden;offscreenSubtreeWasHidden=newOffscreenSubtreeWasHidden;if(offscreenSubtreeWasHidden&&!prevOffscreenSubtreeWasHidden){// This is the root of a reappearing boundary. Turn its layout effects
// back on.
nextEffect=fiber;reappearLayoutEffects_begin(fiber);}var child=firstChild;while(child!==null){nextEffect=child;commitLayoutEffects_begin(child,// New root; bubble back up to here and stop.
root,committedLanes);child=child.sibling;}// Restore Offscreen state and resume in our-progress traversal.
nextEffect=fiber;offscreenSubtreeIsHidden=prevOffscreenSubtreeIsHidden;offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden;commitLayoutMountEffects_complete(subtreeRoot,root,committedLanes);continue;}}if((fiber.subtreeFlags&LayoutMask)!==NoFlags&&firstChild!==null){firstChild.return=fiber;nextEffect=firstChild;}else {commitLayoutMountEffects_complete(subtreeRoot,root,committedLanes);}}}function commitLayoutMountEffects_complete(subtreeRoot,root,committedLanes){while(nextEffect!==null){var fiber=nextEffect;if((fiber.flags&LayoutMask)!==NoFlags){var current=fiber.alternate;setCurrentFiber(fiber);try{commitLayoutEffectOnFiber(root,current,fiber,committedLanes);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}resetCurrentFiber();}if(fiber===subtreeRoot){nextEffect=null;return;}var sibling=fiber.sibling;if(sibling!==null){sibling.return=fiber.return;nextEffect=sibling;return;}nextEffect=fiber.return;}}function disappearLayoutEffects_begin(subtreeRoot){while(nextEffect!==null){var fiber=nextEffect;var firstChild=fiber.child;// TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)
switch(fiber.tag){case FunctionComponent:case ForwardRef:case MemoComponent:case SimpleMemoComponent:{if(fiber.mode&ProfileMode){try{startLayoutEffectTimer();commitHookEffectListUnmount(Layout,fiber,fiber.return);}finally{recordLayoutEffectDuration(fiber);}}else {commitHookEffectListUnmount(Layout,fiber,fiber.return);}break;}case ClassComponent:{// TODO (Offscreen) Check: flags & RefStatic
safelyDetachRef(fiber,fiber.return);var instance=fiber.stateNode;if(typeof instance.componentWillUnmount==='function'){safelyCallComponentWillUnmount(fiber,fiber.return,instance);}break;}case HostComponent:{safelyDetachRef(fiber,fiber.return);break;}case OffscreenComponent:{// Check if this is a
var isHidden=fiber.memoizedState!==null;if(isHidden){// Nested Offscreen tree is already hidden. Don't disappear
// its effects.
disappearLayoutEffects_complete(subtreeRoot);continue;}break;}}// TODO (Offscreen) Check: subtreeFlags & LayoutStatic
if(firstChild!==null){firstChild.return=fiber;nextEffect=firstChild;}else {disappearLayoutEffects_complete(subtreeRoot);}}}function disappearLayoutEffects_complete(subtreeRoot){while(nextEffect!==null){var fiber=nextEffect;if(fiber===subtreeRoot){nextEffect=null;return;}var sibling=fiber.sibling;if(sibling!==null){sibling.return=fiber.return;nextEffect=sibling;return;}nextEffect=fiber.return;}}function reappearLayoutEffects_begin(subtreeRoot){while(nextEffect!==null){var fiber=nextEffect;var firstChild=fiber.child;if(fiber.tag===OffscreenComponent){var isHidden=fiber.memoizedState!==null;if(isHidden){// Nested Offscreen tree is still hidden. Don't re-appear its effects.
reappearLayoutEffects_complete(subtreeRoot);continue;}}// TODO (Offscreen) Check: subtreeFlags & LayoutStatic
if(firstChild!==null){// This node may have been reused from a previous render, so we can't
// assume its return pointer is correct.
firstChild.return=fiber;nextEffect=firstChild;}else {reappearLayoutEffects_complete(subtreeRoot);}}}function reappearLayoutEffects_complete(subtreeRoot){while(nextEffect!==null){var fiber=nextEffect;// TODO (Offscreen) Check: flags & LayoutStatic
setCurrentFiber(fiber);try{reappearLayoutEffectsOnFiber(fiber);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}resetCurrentFiber();if(fiber===subtreeRoot){nextEffect=null;return;}var sibling=fiber.sibling;if(sibling!==null){// This node may have been reused from a previous render, so we can't
// assume its return pointer is correct.
sibling.return=fiber.return;nextEffect=sibling;return;}nextEffect=fiber.return;}}function commitPassiveMountEffects(root,finishedWork,committedLanes,committedTransitions){nextEffect=finishedWork;commitPassiveMountEffects_begin(finishedWork,root,committedLanes,committedTransitions);}function commitPassiveMountEffects_begin(subtreeRoot,root,committedLanes,committedTransitions){while(nextEffect!==null){var fiber=nextEffect;var firstChild=fiber.child;if((fiber.subtreeFlags&PassiveMask)!==NoFlags&&firstChild!==null){firstChild.return=fiber;nextEffect=firstChild;}else {commitPassiveMountEffects_complete(subtreeRoot,root,committedLanes,committedTransitions);}}}function commitPassiveMountEffects_complete(subtreeRoot,root,committedLanes,committedTransitions){while(nextEffect!==null){var fiber=nextEffect;if((fiber.flags&Passive)!==NoFlags){setCurrentFiber(fiber);try{commitPassiveMountOnFiber(root,fiber,committedLanes,committedTransitions);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}resetCurrentFiber();}if(fiber===subtreeRoot){nextEffect=null;return;}var sibling=fiber.sibling;if(sibling!==null){sibling.return=fiber.return;nextEffect=sibling;return;}nextEffect=fiber.return;}}function commitPassiveMountOnFiber(finishedRoot,finishedWork,committedLanes,committedTransitions){switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{if(finishedWork.mode&ProfileMode){startPassiveEffectTimer();try{commitHookEffectListMount(Passive$1|HasEffect,finishedWork);}finally{recordPassiveEffectDuration(finishedWork);}}else {commitHookEffectListMount(Passive$1|HasEffect,finishedWork);}break;}}}function commitPassiveUnmountEffects(firstChild){nextEffect=firstChild;commitPassiveUnmountEffects_begin();}function commitPassiveUnmountEffects_begin(){while(nextEffect!==null){var fiber=nextEffect;var child=fiber.child;if((nextEffect.flags&ChildDeletion)!==NoFlags){var deletions=fiber.deletions;if(deletions!==null){for(var i=0;i<deletions.length;i++){var fiberToDelete=deletions[i];nextEffect=fiberToDelete;commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete,fiber);}{// A fiber was deleted from this parent fiber, but it's still part of
// the previous (alternate) parent fiber's list of children. Because
// children are a linked list, an earlier sibling that's still alive
// will be connected to the deleted fiber via its `alternate`:
//
//   live fiber
//   --alternate--> previous live fiber
//   --sibling--> deleted fiber
//
// We can't disconnect `alternate` on nodes that haven't been deleted
// yet, but we can disconnect the `sibling` and `child` pointers.
var previousFiber=fiber.alternate;if(previousFiber!==null){var detachedChild=previousFiber.child;if(detachedChild!==null){previousFiber.child=null;do{var detachedSibling=detachedChild.sibling;detachedChild.sibling=null;detachedChild=detachedSibling;}while(detachedChild!==null);}}}nextEffect=fiber;}}if((fiber.subtreeFlags&PassiveMask)!==NoFlags&&child!==null){child.return=fiber;nextEffect=child;}else {commitPassiveUnmountEffects_complete();}}}function commitPassiveUnmountEffects_complete(){while(nextEffect!==null){var fiber=nextEffect;if((fiber.flags&Passive)!==NoFlags){setCurrentFiber(fiber);commitPassiveUnmountOnFiber(fiber);resetCurrentFiber();}var sibling=fiber.sibling;if(sibling!==null){sibling.return=fiber.return;nextEffect=sibling;return;}nextEffect=fiber.return;}}function commitPassiveUnmountOnFiber(finishedWork){switch(finishedWork.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{if(finishedWork.mode&ProfileMode){startPassiveEffectTimer();commitHookEffectListUnmount(Passive$1|HasEffect,finishedWork,finishedWork.return);recordPassiveEffectDuration(finishedWork);}else {commitHookEffectListUnmount(Passive$1|HasEffect,finishedWork,finishedWork.return);}break;}}}function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot,nearestMountedAncestor){while(nextEffect!==null){var fiber=nextEffect;// Deletion effects fire in parent -> child order
// TODO: Check if fiber has a PassiveStatic flag
setCurrentFiber(fiber);commitPassiveUnmountInsideDeletedTreeOnFiber(fiber,nearestMountedAncestor);resetCurrentFiber();var child=fiber.child;// TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we
// do this, still need to handle `deletedTreeCleanUpLevel` correctly.)
if(child!==null){child.return=fiber;nextEffect=child;}else {commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);}}}function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot){while(nextEffect!==null){var fiber=nextEffect;var sibling=fiber.sibling;var returnFiber=fiber.return;{// Recursively traverse the entire deleted tree and clean up fiber fields.
// This is more aggressive than ideal, and the long term goal is to only
// have to detach the deleted tree at the root.
detachFiberAfterEffects(fiber);if(fiber===deletedSubtreeRoot){nextEffect=null;return;}}if(sibling!==null){sibling.return=returnFiber;nextEffect=sibling;return;}nextEffect=returnFiber;}}function commitPassiveUnmountInsideDeletedTreeOnFiber(current,nearestMountedAncestor){switch(current.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{if(current.mode&ProfileMode){startPassiveEffectTimer();commitHookEffectListUnmount(Passive$1,current,nearestMountedAncestor);recordPassiveEffectDuration(current);}else {commitHookEffectListUnmount(Passive$1,current,nearestMountedAncestor);}break;}}}// TODO: Reuse reappearLayoutEffects traversal here?
function invokeLayoutEffectMountInDEV(fiber){{// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch(fiber.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{try{commitHookEffectListMount(Layout|HasEffect,fiber);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}break;}case ClassComponent:{var instance=fiber.stateNode;try{instance.componentDidMount();}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}break;}}}}function invokePassiveEffectMountInDEV(fiber){{// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch(fiber.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{try{commitHookEffectListMount(Passive$1|HasEffect,fiber);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}break;}}}}function invokeLayoutEffectUnmountInDEV(fiber){{// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch(fiber.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{try{commitHookEffectListUnmount(Layout|HasEffect,fiber,fiber.return);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}break;}case ClassComponent:{var instance=fiber.stateNode;if(typeof instance.componentWillUnmount==='function'){safelyCallComponentWillUnmount(fiber,fiber.return,instance);}break;}}}}function invokePassiveEffectUnmountInDEV(fiber){{// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch(fiber.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{try{commitHookEffectListUnmount(Passive$1|HasEffect,fiber,fiber.return);}catch(error){captureCommitPhaseError(fiber,fiber.return,error);}}}}}if(typeof Symbol==='function'&&Symbol.for){var symbolFor=Symbol.for;symbolFor('selector.component');symbolFor('selector.has_pseudo_class');symbolFor('selector.role');symbolFor('selector.test_id');symbolFor('selector.text');}var commitHooks=[];function onCommitRoot$1(){{commitHooks.forEach(function(commitHook){return commitHook();});}}var ReactCurrentActQueue=ReactSharedInternals.ReactCurrentActQueue;function isLegacyActEnvironment(fiber){{// Legacy mode. We preserve the behavior of React 17's act. It assumes an
// act environment whenever `jest` is defined, but you can still turn off
// spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
// to false.
var isReactActEnvironmentGlobal=// $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
typeof IS_REACT_ACT_ENVIRONMENT!=='undefined'?IS_REACT_ACT_ENVIRONMENT:undefined;// $FlowExpectedError - Flow doesn't know about jest
var jestIsDefined=typeof jest!=='undefined';return jestIsDefined&&isReactActEnvironmentGlobal!==false;}}function isConcurrentActEnvironment(){{var isReactActEnvironmentGlobal=// $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
typeof IS_REACT_ACT_ENVIRONMENT!=='undefined'?IS_REACT_ACT_ENVIRONMENT:undefined;if(!isReactActEnvironmentGlobal&&ReactCurrentActQueue.current!==null){// TODO: Include link to relevant documentation page.
error('The current testing environment is not configured to support '+'act(...)');}return isReactActEnvironmentGlobal;}}var ceil=Math.ceil;var ReactCurrentDispatcher$2=ReactSharedInternals.ReactCurrentDispatcher,ReactCurrentOwner$2=ReactSharedInternals.ReactCurrentOwner,ReactCurrentBatchConfig$3=ReactSharedInternals.ReactCurrentBatchConfig,ReactCurrentActQueue$1=ReactSharedInternals.ReactCurrentActQueue;var NoContext=/*             */0;var BatchedContext=/*               */1;var RenderContext=/*                */2;var CommitContext=/*                */4;var RootInProgress=0;var RootFatalErrored=1;var RootErrored=2;var RootSuspended=3;var RootSuspendedWithDelay=4;var RootCompleted=5;var RootDidNotComplete=6;// Describes where we are in the React execution stack
var executionContext=NoContext;// The root we're working on
var workInProgressRoot=null;// The fiber we're working on
var workInProgress=null;// The lanes we're rendering
var workInProgressRootRenderLanes=NoLanes;// Stack that allows components to change the render lanes for its subtree
// This is a superset of the lanes we started working on at the root. The only
// case where it's different from `workInProgressRootRenderLanes` is when we
// enter a subtree that is hidden and needs to be unhidden: Suspense and
// Offscreen component.
//
// Most things in the work loop should deal with workInProgressRootRenderLanes.
// Most things in begin/complete phases should deal with subtreeRenderLanes.
var subtreeRenderLanes=NoLanes;var subtreeRenderLanesCursor=createCursor(NoLanes);// Whether to root completed, errored, suspended, etc.
var workInProgressRootExitStatus=RootInProgress;// A fatal error, if one is thrown
var workInProgressRootFatalError=null;// "Included" lanes refer to lanes that were worked on during this render. It's
// includes unprocessed updates, not work in bailed out children.
var workInProgressRootSkippedLanes=NoLanes;// Lanes that were updated (in an interleaved event) during this render.
var workInProgressRootInterleavedUpdatedLanes=NoLanes;// Lanes that were updated during the render phase (*not* an interleaved event).
var workInProgressRootPingedLanes=NoLanes;// Errors that are thrown during the render phase.
var workInProgressRootConcurrentErrors=null;// These are errors that we recovered from without surfacing them to the UI.
// We will log them once the tree commits.
var workInProgressRootRecoverableErrors=null;// The most recent time we committed a fallback. This lets us ensure a train
// model where we don't commit new loading states in too quick succession.
var globalMostRecentFallbackTime=0;var FALLBACK_THROTTLE_MS=500;// The absolute time for when we should start giving up on rendering
// more and prefer CPU suspense heuristics instead.
var workInProgressRootRenderTargetTime=Infinity;// How long a render is supposed to take before we start following CPU
// suspense heuristics and opt out of rendering more content.
var RENDER_TIMEOUT_MS=500;var workInProgressTransitions=null;function resetRenderTimer(){workInProgressRootRenderTargetTime=now()+RENDER_TIMEOUT_MS;}function getRenderTargetTime(){return workInProgressRootRenderTargetTime;}var hasUncaughtError=false;var firstUncaughtError=null;var legacyErrorBoundariesThatAlreadyFailed=null;// Only used when enableProfilerNestedUpdateScheduledHook is true;
var rootDoesHavePassiveEffects=false;var rootWithPendingPassiveEffects=null;var pendingPassiveEffectsLanes=NoLanes;var pendingPassiveProfilerEffects=[];var pendingPassiveTransitions=null;// Use these to prevent an infinite loop of nested updates
var NESTED_UPDATE_LIMIT=50;var nestedUpdateCount=0;var rootWithNestedUpdates=null;var isFlushingPassiveEffects=false;var didScheduleUpdateDuringPassiveEffects=false;var NESTED_PASSIVE_UPDATE_LIMIT=50;var nestedPassiveUpdateCount=0;var rootWithPassiveNestedUpdates=null;// If two updates are scheduled within the same event, we should treat their
// event times as simultaneous, even if the actual clock time has advanced
// between the first and second call.
var currentEventTime=NoTimestamp;var currentEventTransitionLane=NoLanes;var isRunningInsertionEffect=false;function getWorkInProgressRoot(){return workInProgressRoot;}function requestEventTime(){if((executionContext&(RenderContext|CommitContext))!==NoContext){// We're inside React, so it's fine to read the actual time.
return now();}// We're not inside React, so we may be in the middle of a browser event.
if(currentEventTime!==NoTimestamp){// Use the same start time for all updates until we enter React again.
return currentEventTime;}// This is the first update since React yielded. Compute a new start time.
currentEventTime=now();return currentEventTime;}function requestUpdateLane(fiber){// Special cases
var mode=fiber.mode;if((mode&ConcurrentMode)===NoMode){return SyncLane;}else if((executionContext&RenderContext)!==NoContext&&workInProgressRootRenderLanes!==NoLanes){// This is a render phase update. These are not officially supported. The
// old behavior is to give this the same "thread" (lanes) as
// whatever is currently rendering. So if you call `setState` on a component
// that happens later in the same render, it will flush. Ideally, we want to
// remove the special case and treat them as if they came from an
// interleaved event. Regardless, this pattern is not officially supported.
// This behavior is only a fallback. The flag only exists until we can roll
// out the setState warning, since existing code might accidentally rely on
// the current behavior.
return pickArbitraryLane(workInProgressRootRenderLanes);}var isTransition=requestCurrentTransition()!==NoTransition;if(isTransition){if(ReactCurrentBatchConfig$3.transition!==null){var transition=ReactCurrentBatchConfig$3.transition;if(!transition._updatedFibers){transition._updatedFibers=new Set();}transition._updatedFibers.add(fiber);}// The algorithm for assigning an update to a lane should be stable for all
// updates at the same priority within the same event. To do this, the
// inputs to the algorithm must be the same.
//
// The trick we use is to cache the first of each of these inputs within an
// event. Then reset the cached values once we can be sure the event is
// over. Our heuristic for that is whenever we enter a concurrent work loop.
if(currentEventTransitionLane===NoLane){// All transitions within the same event are assigned the same lane.
currentEventTransitionLane=claimNextTransitionLane();}return currentEventTransitionLane;}// Updates originating inside certain React methods, like flushSync, have
// their priority set by tracking it with a context variable.
//
// The opaque type returned by the host config is internally a lane, so we can
// use that directly.
// TODO: Move this type conversion to the event priority module.
var updateLane=getCurrentUpdatePriority();if(updateLane!==NoLane){return updateLane;}// This update originated outside React. Ask the host environment for an
// appropriate priority, based on the type of event.
//
// The opaque type returned by the host config is internally a lane, so we can
// use that directly.
// TODO: Move this type conversion to the event priority module.
var eventLane=getCurrentEventPriority();return eventLane;}function requestRetryLane(fiber){// This is a fork of `requestUpdateLane` designed specifically for Suspense
// "retries" — a special update that attempts to flip a Suspense boundary
// from its placeholder state to its primary/resolved state.
// Special cases
var mode=fiber.mode;if((mode&ConcurrentMode)===NoMode){return SyncLane;}return claimNextRetryLane();}function scheduleUpdateOnFiber(root,fiber,lane,eventTime){checkForNestedUpdates();{if(isRunningInsertionEffect){error('useInsertionEffect must not schedule updates.');}}{if(isFlushingPassiveEffects){didScheduleUpdateDuringPassiveEffects=true;}}// Mark that the root has a pending update.
markRootUpdated(root,lane,eventTime);if((executionContext&RenderContext)!==NoLanes&&root===workInProgressRoot){// This update was dispatched during the render phase. This is a mistake
// if the update originates from user space (with the exception of local
// hook updates, which are handled differently and don't reach this
// function), but there are some internal React features that use this as
// an implementation detail, like selective hydration.
warnAboutRenderPhaseUpdatesInDEV(fiber);// Track lanes that were updated during the render phase
}else {// This is a normal update, scheduled from outside the render phase. For
// example, during an input event.
{if(isDevToolsPresent){addFiberToLanesMap(root,fiber,lane);}}warnIfUpdatesNotWrappedWithActDEV(fiber);if(root===workInProgressRoot){// Received an update to a tree that's in the middle of rendering. Mark
// that there was an interleaved update work on this root. Unless the
// `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
// phase update. In that case, we don't treat render phase updates as if
// they were interleaved, for backwards compat reasons.
if((executionContext&RenderContext)===NoContext){workInProgressRootInterleavedUpdatedLanes=mergeLanes(workInProgressRootInterleavedUpdatedLanes,lane);}if(workInProgressRootExitStatus===RootSuspendedWithDelay){// The root already suspended with a delay, which means this render
// definitely won't finish. Since we have a new update, let's mark it as
// suspended now, right before marking the incoming update. This has the
// effect of interrupting the current render and switching to the update.
// TODO: Make sure this doesn't override pings that happen while we've
// already started rendering.
markRootSuspended$1(root,workInProgressRootRenderLanes);}}ensureRootIsScheduled(root,eventTime);if(lane===SyncLane&&executionContext===NoContext&&(fiber.mode&ConcurrentMode)===NoMode&&// Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
!ReactCurrentActQueue$1.isBatchingLegacy){// Flush the synchronous work now, unless we're already working or inside
// a batch. This is intentionally inside scheduleUpdateOnFiber instead of
// scheduleCallbackForFiber to preserve the ability to schedule a callback
// without immediately flushing it. We only do this for user-initiated
// updates, to preserve historical behavior of legacy mode.
resetRenderTimer();flushSyncCallbacksOnlyInLegacyMode();}}}function scheduleInitialHydrationOnRoot(root,lane,eventTime){// This is a special fork of scheduleUpdateOnFiber that is only used to
// schedule the initial hydration of a root that has just been created. Most
// of the stuff in scheduleUpdateOnFiber can be skipped.
//
// The main reason for this separate path, though, is to distinguish the
// initial children from subsequent updates. In fully client-rendered roots
// (createRoot instead of hydrateRoot), all top-level renders are modeled as
// updates, but hydration roots are special because the initial render must
// match what was rendered on the server.
var current=root.current;current.lanes=lane;markRootUpdated(root,lane,eventTime);ensureRootIsScheduled(root,eventTime);}function isUnsafeClassRenderPhaseUpdate(fiber){// Check if this is a render phase update. Only called by class components,
// which special (deprecated) behavior for UNSAFE_componentWillReceive props.
return(// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
// decided not to enable it.
(executionContext&RenderContext)!==NoContext);}// Use this function to schedule a task for a root. There's only one task per
// root; if a task was already scheduled, we'll check to make sure the priority
// of the existing task is the same as the priority of the next level that the
// root has work on. This function is called on every update, and right before
// exiting a task.
function ensureRootIsScheduled(root,currentTime){var existingCallbackNode=root.callbackNode;// Check if any lanes are being starved by other work. If so, mark them as
// expired so we know to work on those next.
markStarvedLanesAsExpired(root,currentTime);// Determine the next lanes to work on, and their priority.
var nextLanes=getNextLanes(root,root===workInProgressRoot?workInProgressRootRenderLanes:NoLanes);if(nextLanes===NoLanes){// Special case: There's nothing to work on.
if(existingCallbackNode!==null){cancelCallback$1(existingCallbackNode);}root.callbackNode=null;root.callbackPriority=NoLane;return;}// We use the highest priority lane to represent the priority of the callback.
var newCallbackPriority=getHighestPriorityLane(nextLanes);// Check if there's an existing task. We may be able to reuse it.
var existingCallbackPriority=root.callbackPriority;if(existingCallbackPriority===newCallbackPriority&&// Special case related to `act`. If the currently scheduled task is a
// Scheduler task, rather than an `act` task, cancel it and re-scheduled
// on the `act` queue.
!(ReactCurrentActQueue$1.current!==null&&existingCallbackNode!==fakeActCallbackNode)){{// If we're going to re-use an existing task, it needs to exist.
// Assume that discrete update microtasks are non-cancellable and null.
// TODO: Temporary until we confirm this warning is not fired.
if(existingCallbackNode==null&&existingCallbackPriority!==SyncLane){error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.');}}// The priority hasn't changed. We can reuse the existing task. Exit.
return;}if(existingCallbackNode!=null){// Cancel the existing callback. We'll schedule a new one below.
cancelCallback$1(existingCallbackNode);}// Schedule a new callback.
var newCallbackNode;if(newCallbackPriority===SyncLane){// Special case: Sync React callbacks are scheduled on a special
// internal queue
if(root.tag===LegacyRoot){if(ReactCurrentActQueue$1.isBatchingLegacy!==null){ReactCurrentActQueue$1.didScheduleLegacyUpdate=true;}scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null,root));}else {scheduleSyncCallback(performSyncWorkOnRoot.bind(null,root));}{// Flush the queue in a microtask.
if(ReactCurrentActQueue$1.current!==null){// Inside `act`, use our internal `act` queue so that these get flushed
// at the end of the current scope even when using the sync version
// of `act`.
ReactCurrentActQueue$1.current.push(flushSyncCallbacks);}else {scheduleMicrotask(function(){// In Safari, appending an iframe forces microtasks to run.
// https://github.com/facebook/react/issues/22459
// We don't support running callbacks in the middle of render
// or commit so we need to check against that.
if((executionContext&(RenderContext|CommitContext))===NoContext){// Note that this would still prematurely flush the callbacks
// if this happens outside render or commit phase (e.g. in an event).
flushSyncCallbacks();}});}}newCallbackNode=null;}else {var schedulerPriorityLevel;switch(lanesToEventPriority(nextLanes)){case DiscreteEventPriority:schedulerPriorityLevel=ImmediatePriority;break;case ContinuousEventPriority:schedulerPriorityLevel=UserBlockingPriority;break;case DefaultEventPriority:schedulerPriorityLevel=NormalPriority;break;case IdleEventPriority:schedulerPriorityLevel=IdlePriority;break;default:schedulerPriorityLevel=NormalPriority;break;}newCallbackNode=scheduleCallback$1(schedulerPriorityLevel,performConcurrentWorkOnRoot.bind(null,root));}root.callbackPriority=newCallbackPriority;root.callbackNode=newCallbackNode;}// This is the entry point for every concurrent task, i.e. anything that
// goes through Scheduler.
function performConcurrentWorkOnRoot(root,didTimeout){{resetNestedUpdateFlag();}// Since we know we're in a React event, we can clear the current
// event time. The next update will compute a new event time.
currentEventTime=NoTimestamp;currentEventTransitionLane=NoLanes;if((executionContext&(RenderContext|CommitContext))!==NoContext){throw new Error('Should not already be working.');}// Flush any pending passive effects before deciding which lanes to work on,
// in case they schedule additional work.
var originalCallbackNode=root.callbackNode;var didFlushPassiveEffects=flushPassiveEffects();if(didFlushPassiveEffects){// Something in the passive effect phase may have canceled the current task.
// Check if the task node for this root was changed.
if(root.callbackNode!==originalCallbackNode){// The current task was canceled. Exit. We don't need to call
// `ensureRootIsScheduled` because the check above implies either that
// there's a new task, or that there's no remaining work on this root.
return null;}}// Determine the next lanes to work on, using the fields stored
// on the root.
var lanes=getNextLanes(root,root===workInProgressRoot?workInProgressRootRenderLanes:NoLanes);if(lanes===NoLanes){// Defensive coding. This is never expected to happen.
return null;}// We disable time-slicing in some cases: if the work has been CPU-bound
// for too long ("expired" work, to prevent starvation), or we're in
// sync-updates-by-default mode.
// TODO: We only check `didTimeout` defensively, to account for a Scheduler
// bug we're still investigating. Once the bug in Scheduler is fixed,
// we can remove this, since we track expiration ourselves.
var shouldTimeSlice=!includesBlockingLane(root,lanes)&&!includesExpiredLane(root,lanes)&&!didTimeout;var exitStatus=shouldTimeSlice?renderRootConcurrent(root,lanes):renderRootSync(root,lanes);if(exitStatus!==RootInProgress){if(exitStatus===RootErrored){// If something threw an error, try rendering one more time. We'll
// render synchronously to block concurrent data mutations, and we'll
// includes all pending updates are included. If it still fails after
// the second attempt, we'll give up and commit the resulting tree.
var errorRetryLanes=getLanesToRetrySynchronouslyOnError(root);if(errorRetryLanes!==NoLanes){lanes=errorRetryLanes;exitStatus=recoverFromConcurrentError(root,errorRetryLanes);}}if(exitStatus===RootFatalErrored){var fatalError=workInProgressRootFatalError;prepareFreshStack(root,NoLanes);markRootSuspended$1(root,lanes);ensureRootIsScheduled(root,now());throw fatalError;}if(exitStatus===RootDidNotComplete){// The render unwound without completing the tree. This happens in special
// cases where need to exit the current render without producing a
// consistent tree or committing.
//
// This should only happen during a concurrent render, not a discrete or
// synchronous update. We should have already checked for this when we
// unwound the stack.
markRootSuspended$1(root,lanes);}else {// The render completed.
// Check if this render may have yielded to a concurrent event, and if so,
// confirm that any newly rendered stores are consistent.
// TODO: It's possible that even a concurrent render may never have yielded
// to the main thread, if it was fast enough, or if it expired. We could
// skip the consistency check in that case, too.
var renderWasConcurrent=!includesBlockingLane(root,lanes);var finishedWork=root.current.alternate;if(renderWasConcurrent&&!isRenderConsistentWithExternalStores(finishedWork)){// A store was mutated in an interleaved event. Render again,
// synchronously, to block further mutations.
exitStatus=renderRootSync(root,lanes);// We need to check again if something threw
if(exitStatus===RootErrored){var _errorRetryLanes=getLanesToRetrySynchronouslyOnError(root);if(_errorRetryLanes!==NoLanes){lanes=_errorRetryLanes;exitStatus=recoverFromConcurrentError(root,_errorRetryLanes);// We assume the tree is now consistent because we didn't yield to any
// concurrent events.
}}if(exitStatus===RootFatalErrored){var _fatalError=workInProgressRootFatalError;prepareFreshStack(root,NoLanes);markRootSuspended$1(root,lanes);ensureRootIsScheduled(root,now());throw _fatalError;}}// We now have a consistent tree. The next step is either to commit it,
// or, if something suspended, wait to commit it after a timeout.
root.finishedWork=finishedWork;root.finishedLanes=lanes;finishConcurrentRender(root,exitStatus,lanes);}}ensureRootIsScheduled(root,now());if(root.callbackNode===originalCallbackNode){// The task node scheduled for this root is the same one that's
// currently executed. Need to return a continuation.
return performConcurrentWorkOnRoot.bind(null,root);}return null;}function recoverFromConcurrentError(root,errorRetryLanes){// If an error occurred during hydration, discard server response and fall
// back to client side render.
// Before rendering again, save the errors from the previous attempt.
var errorsFromFirstAttempt=workInProgressRootConcurrentErrors;if(isRootDehydrated(root)){// The shell failed to hydrate. Set a flag to force a client rendering
// during the next attempt. To do this, we call prepareFreshStack now
// to create the root work-in-progress fiber. This is a bit weird in terms
// of factoring, because it relies on renderRootSync not calling
// prepareFreshStack again in the call below, which happens because the
// root and lanes haven't changed.
//
// TODO: I think what we should do is set ForceClientRender inside
// throwException, like we do for nested Suspense boundaries. The reason
// it's here instead is so we can switch to the synchronous work loop, too.
// Something to consider for a future refactor.
var rootWorkInProgress=prepareFreshStack(root,errorRetryLanes);rootWorkInProgress.flags|=ForceClientRender;{errorHydratingContainer(root.containerInfo);}}var exitStatus=renderRootSync(root,errorRetryLanes);if(exitStatus!==RootErrored){// Successfully finished rendering on retry
// The errors from the failed first attempt have been recovered. Add
// them to the collection of recoverable errors. We'll log them in the
// commit phase.
var errorsFromSecondAttempt=workInProgressRootRecoverableErrors;workInProgressRootRecoverableErrors=errorsFromFirstAttempt;// The errors from the second attempt should be queued after the errors
// from the first attempt, to preserve the causal sequence.
if(errorsFromSecondAttempt!==null){queueRecoverableErrors(errorsFromSecondAttempt);}}return exitStatus;}function queueRecoverableErrors(errors){if(workInProgressRootRecoverableErrors===null){workInProgressRootRecoverableErrors=errors;}else {workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors,errors);}}function finishConcurrentRender(root,exitStatus,lanes){switch(exitStatus){case RootInProgress:case RootFatalErrored:{throw new Error('Root did not complete. This is a bug in React.');}// Flow knows about invariant, so it complains if I add a break
// statement, but eslint doesn't know about invariant, so it complains
// if I do. eslint-disable-next-line no-fallthrough
case RootErrored:{// We should have already attempted to retry this tree. If we reached
// this point, it errored again. Commit it.
commitRoot(root,workInProgressRootRecoverableErrors,workInProgressTransitions);break;}case RootSuspended:{markRootSuspended$1(root,lanes);// We have an acceptable loading state. We need to figure out if we
// should immediately commit it or wait a bit.
if(includesOnlyRetries(lanes)&&// do not delay if we're inside an act() scope
!shouldForceFlushFallbacksInDEV()){// This render only included retries, no updates. Throttle committing
// retries so that we don't show too many loading states too quickly.
var msUntilTimeout=globalMostRecentFallbackTime+FALLBACK_THROTTLE_MS-now();// Don't bother with a very short suspense time.
if(msUntilTimeout>10){var nextLanes=getNextLanes(root,NoLanes);if(nextLanes!==NoLanes){// There's additional work on this root.
break;}var suspendedLanes=root.suspendedLanes;if(!isSubsetOfLanes(suspendedLanes,lanes)){// We should prefer to render the fallback of at the last
// suspended level. Ping the last suspended level to try
// rendering it again.
// FIXME: What if the suspended lanes are Idle? Should not restart.
requestEventTime();markRootPinged(root,suspendedLanes);break;}// The render is suspended, it hasn't timed out, and there's no
// lower priority work to do. Instead of committing the fallback
// immediately, wait for more data to arrive.
root.timeoutHandle=scheduleTimeout(commitRoot.bind(null,root,workInProgressRootRecoverableErrors,workInProgressTransitions),msUntilTimeout);break;}}// The work expired. Commit immediately.
commitRoot(root,workInProgressRootRecoverableErrors,workInProgressTransitions);break;}case RootSuspendedWithDelay:{markRootSuspended$1(root,lanes);if(includesOnlyTransitions(lanes)){// This is a transition, so we should exit without committing a
// placeholder and without scheduling a timeout. Delay indefinitely
// until we receive more data.
break;}if(!shouldForceFlushFallbacksInDEV()){// This is not a transition, but we did trigger an avoided state.
// Schedule a placeholder to display after a short delay, using the Just
// Noticeable Difference.
// TODO: Is the JND optimization worth the added complexity? If this is
// the only reason we track the event time, then probably not.
// Consider removing.
var mostRecentEventTime=getMostRecentEventTime(root,lanes);var eventTimeMs=mostRecentEventTime;var timeElapsedMs=now()-eventTimeMs;var _msUntilTimeout=jnd(timeElapsedMs)-timeElapsedMs;// Don't bother with a very short suspense time.
if(_msUntilTimeout>10){// Instead of committing the fallback immediately, wait for more data
// to arrive.
root.timeoutHandle=scheduleTimeout(commitRoot.bind(null,root,workInProgressRootRecoverableErrors,workInProgressTransitions),_msUntilTimeout);break;}}// Commit the placeholder.
commitRoot(root,workInProgressRootRecoverableErrors,workInProgressTransitions);break;}case RootCompleted:{// The work completed. Ready to commit.
commitRoot(root,workInProgressRootRecoverableErrors,workInProgressTransitions);break;}default:{throw new Error('Unknown root exit status.');}}}function isRenderConsistentWithExternalStores(finishedWork){// Search the rendered tree for external store reads, and check whether the
// stores were mutated in a concurrent event. Intentionally using an iterative
// loop instead of recursion so we can exit early.
var node=finishedWork;while(true){if(node.flags&StoreConsistency){var updateQueue=node.updateQueue;if(updateQueue!==null){var checks=updateQueue.stores;if(checks!==null){for(var i=0;i<checks.length;i++){var check=checks[i];var getSnapshot=check.getSnapshot;var renderedValue=check.value;try{if(!objectIs(getSnapshot(),renderedValue)){// Found an inconsistent store.
return false;}}catch(error){// If `getSnapshot` throws, return `false`. This will schedule
// a re-render, and the error will be rethrown during render.
return false;}}}}}var child=node.child;if(node.subtreeFlags&StoreConsistency&&child!==null){child.return=node;node=child;continue;}if(node===finishedWork){return true;}while(node.sibling===null){if(node.return===null||node.return===finishedWork){return true;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}// Flow doesn't know this is unreachable, but eslint does
// eslint-disable-next-line no-unreachable
return true;}function markRootSuspended$1(root,suspendedLanes){// When suspending, we should always exclude lanes that were pinged or (more
// rarely, since we try to avoid it) updated during the render phase.
// TODO: Lol maybe there's a better way to factor this besides this
// obnoxiously named function :)
suspendedLanes=removeLanes(suspendedLanes,workInProgressRootPingedLanes);suspendedLanes=removeLanes(suspendedLanes,workInProgressRootInterleavedUpdatedLanes);markRootSuspended(root,suspendedLanes);}// This is the entry point for synchronous tasks that don't go
// through Scheduler
function performSyncWorkOnRoot(root){{syncNestedUpdateFlag();}if((executionContext&(RenderContext|CommitContext))!==NoContext){throw new Error('Should not already be working.');}flushPassiveEffects();var lanes=getNextLanes(root,NoLanes);if(!includesSomeLane(lanes,SyncLane)){// There's no remaining sync work left.
ensureRootIsScheduled(root,now());return null;}var exitStatus=renderRootSync(root,lanes);if(root.tag!==LegacyRoot&&exitStatus===RootErrored){// If something threw an error, try rendering one more time. We'll render
// synchronously to block concurrent data mutations, and we'll includes
// all pending updates are included. If it still fails after the second
// attempt, we'll give up and commit the resulting tree.
var errorRetryLanes=getLanesToRetrySynchronouslyOnError(root);if(errorRetryLanes!==NoLanes){lanes=errorRetryLanes;exitStatus=recoverFromConcurrentError(root,errorRetryLanes);}}if(exitStatus===RootFatalErrored){var fatalError=workInProgressRootFatalError;prepareFreshStack(root,NoLanes);markRootSuspended$1(root,lanes);ensureRootIsScheduled(root,now());throw fatalError;}if(exitStatus===RootDidNotComplete){throw new Error('Root did not complete. This is a bug in React.');}// We now have a consistent tree. Because this is a sync render, we
// will commit it even if something suspended.
var finishedWork=root.current.alternate;root.finishedWork=finishedWork;root.finishedLanes=lanes;commitRoot(root,workInProgressRootRecoverableErrors,workInProgressTransitions);// Before exiting, make sure there's a callback scheduled for the next
// pending level.
ensureRootIsScheduled(root,now());return null;}function flushRoot(root,lanes){if(lanes!==NoLanes){markRootEntangled(root,mergeLanes(lanes,SyncLane));ensureRootIsScheduled(root,now());if((executionContext&(RenderContext|CommitContext))===NoContext){resetRenderTimer();flushSyncCallbacks();}}}function batchedUpdates$1(fn,a){var prevExecutionContext=executionContext;executionContext|=BatchedContext;try{return fn(a);}finally{executionContext=prevExecutionContext;// If there were legacy sync updates, flush them at the end of the outer
// most batchedUpdates-like method.
if(executionContext===NoContext&&// Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
!ReactCurrentActQueue$1.isBatchingLegacy){resetRenderTimer();flushSyncCallbacksOnlyInLegacyMode();}}}function discreteUpdates(fn,a,b,c,d){var previousPriority=getCurrentUpdatePriority();var prevTransition=ReactCurrentBatchConfig$3.transition;try{ReactCurrentBatchConfig$3.transition=null;setCurrentUpdatePriority(DiscreteEventPriority);return fn(a,b,c,d);}finally{setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig$3.transition=prevTransition;if(executionContext===NoContext){resetRenderTimer();}}}// Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.
// eslint-disable-next-line no-redeclare
function flushSync(fn){// In legacy mode, we flush pending passive effects at the beginning of the
// next event, not at the end of the previous one.
if(rootWithPendingPassiveEffects!==null&&rootWithPendingPassiveEffects.tag===LegacyRoot&&(executionContext&(RenderContext|CommitContext))===NoContext){flushPassiveEffects();}var prevExecutionContext=executionContext;executionContext|=BatchedContext;var prevTransition=ReactCurrentBatchConfig$3.transition;var previousPriority=getCurrentUpdatePriority();try{ReactCurrentBatchConfig$3.transition=null;setCurrentUpdatePriority(DiscreteEventPriority);if(fn){return fn();}else {return undefined;}}finally{setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig$3.transition=prevTransition;executionContext=prevExecutionContext;// Flush the immediate callbacks that were scheduled during this batch.
// Note that this will happen even if batchedUpdates is higher up
// the stack.
if((executionContext&(RenderContext|CommitContext))===NoContext){flushSyncCallbacks();}}}function isAlreadyRendering(){// Used by the renderer to print a warning if certain APIs are called from
// the wrong context.
return (executionContext&(RenderContext|CommitContext))!==NoContext;}function pushRenderLanes(fiber,lanes){push(subtreeRenderLanesCursor,subtreeRenderLanes,fiber);subtreeRenderLanes=mergeLanes(subtreeRenderLanes,lanes);}function popRenderLanes(fiber){subtreeRenderLanes=subtreeRenderLanesCursor.current;pop(subtreeRenderLanesCursor,fiber);}function prepareFreshStack(root,lanes){root.finishedWork=null;root.finishedLanes=NoLanes;var timeoutHandle=root.timeoutHandle;if(timeoutHandle!==noTimeout){// The root previous suspended and scheduled a timeout to commit a fallback
// state. Now that we have additional work, cancel the timeout.
root.timeoutHandle=noTimeout;// $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
cancelTimeout(timeoutHandle);}if(workInProgress!==null){var interruptedWork=workInProgress.return;while(interruptedWork!==null){var current=interruptedWork.alternate;unwindInterruptedWork(current,interruptedWork);interruptedWork=interruptedWork.return;}}workInProgressRoot=root;var rootWorkInProgress=createWorkInProgress(root.current,null);workInProgress=rootWorkInProgress;workInProgressRootRenderLanes=subtreeRenderLanes=lanes;workInProgressRootExitStatus=RootInProgress;workInProgressRootFatalError=null;workInProgressRootSkippedLanes=NoLanes;workInProgressRootInterleavedUpdatedLanes=NoLanes;workInProgressRootPingedLanes=NoLanes;workInProgressRootConcurrentErrors=null;workInProgressRootRecoverableErrors=null;finishQueueingConcurrentUpdates();{ReactStrictModeWarnings.discardPendingWarnings();}return rootWorkInProgress;}function handleError(root,thrownValue){do{var erroredWork=workInProgress;try{// Reset module-level state that was set during the render phase.
resetContextDependencies();resetHooksAfterThrow();resetCurrentFiber();// TODO: I found and added this missing line while investigating a
// separate issue. Write a regression test using string refs.
ReactCurrentOwner$2.current=null;if(erroredWork===null||erroredWork.return===null){// Expected to be working on a non-root fiber. This is a fatal error
// because there's no ancestor that can handle it; the root is
// supposed to capture all errors that weren't caught by an error
// boundary.
workInProgressRootExitStatus=RootFatalErrored;workInProgressRootFatalError=thrownValue;// Set `workInProgress` to null. This represents advancing to the next
// sibling, or the parent if there are no siblings. But since the root
// has no siblings nor a parent, we set it to null. Usually this is
// handled by `completeUnitOfWork` or `unwindWork`, but since we're
// intentionally not calling those, we need set it here.
// TODO: Consider calling `unwindWork` to pop the contexts.
workInProgress=null;return;}if(enableProfilerTimer&&erroredWork.mode&ProfileMode){// Record the time spent rendering before an error was thrown. This
// avoids inaccurate Profiler durations in the case of a
// suspended render.
stopProfilerTimerIfRunningAndRecordDelta(erroredWork,true);}if(enableSchedulingProfiler){markComponentRenderStopped();if(thrownValue!==null&&typeof thrownValue==='object'&&typeof thrownValue.then==='function'){var wakeable=thrownValue;markComponentSuspended(erroredWork,wakeable,workInProgressRootRenderLanes);}else {markComponentErrored(erroredWork,thrownValue,workInProgressRootRenderLanes);}}throwException(root,erroredWork.return,erroredWork,thrownValue,workInProgressRootRenderLanes);completeUnitOfWork(erroredWork);}catch(yetAnotherThrownValue){// Something in the return path also threw.
thrownValue=yetAnotherThrownValue;if(workInProgress===erroredWork&&erroredWork!==null){// If this boundary has already errored, then we had trouble processing
// the error. Bubble it to the next boundary.
erroredWork=erroredWork.return;workInProgress=erroredWork;}else {erroredWork=workInProgress;}continue;}// Return to the normal work loop.
return;}while(true);}function pushDispatcher(){var prevDispatcher=ReactCurrentDispatcher$2.current;ReactCurrentDispatcher$2.current=ContextOnlyDispatcher;if(prevDispatcher===null){// The React isomorphic package does not include a default dispatcher.
// Instead the first renderer will lazily attach one, in order to give
// nicer error messages.
return ContextOnlyDispatcher;}else {return prevDispatcher;}}function popDispatcher(prevDispatcher){ReactCurrentDispatcher$2.current=prevDispatcher;}function markCommitTimeOfFallback(){globalMostRecentFallbackTime=now();}function markSkippedUpdateLanes(lane){workInProgressRootSkippedLanes=mergeLanes(lane,workInProgressRootSkippedLanes);}function renderDidSuspend(){if(workInProgressRootExitStatus===RootInProgress){workInProgressRootExitStatus=RootSuspended;}}function renderDidSuspendDelayIfPossible(){if(workInProgressRootExitStatus===RootInProgress||workInProgressRootExitStatus===RootSuspended||workInProgressRootExitStatus===RootErrored){workInProgressRootExitStatus=RootSuspendedWithDelay;}// Check if there are updates that we skipped tree that might have unblocked
// this render.
if(workInProgressRoot!==null&&(includesNonIdleWork(workInProgressRootSkippedLanes)||includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))){// Mark the current render as suspended so that we switch to working on
// the updates that were skipped. Usually we only suspend at the end of
// the render phase.
// TODO: We should probably always mark the root as suspended immediately
// (inside this function), since by suspending at the end of the render
// phase introduces a potential mistake where we suspend lanes that were
// pinged or updated while we were rendering.
markRootSuspended$1(workInProgressRoot,workInProgressRootRenderLanes);}}function renderDidError(error){if(workInProgressRootExitStatus!==RootSuspendedWithDelay){workInProgressRootExitStatus=RootErrored;}if(workInProgressRootConcurrentErrors===null){workInProgressRootConcurrentErrors=[error];}else {workInProgressRootConcurrentErrors.push(error);}}// Called during render to determine if anything has suspended.
// Returns false if we're not sure.
function renderHasNotSuspendedYet(){// If something errored or completed, we can't really be sure,
// so those are false.
return workInProgressRootExitStatus===RootInProgress;}function renderRootSync(root,lanes){var prevExecutionContext=executionContext;executionContext|=RenderContext;var prevDispatcher=pushDispatcher();// If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if(workInProgressRoot!==root||workInProgressRootRenderLanes!==lanes){{if(isDevToolsPresent){var memoizedUpdaters=root.memoizedUpdaters;if(memoizedUpdaters.size>0){restorePendingUpdaters(root,workInProgressRootRenderLanes);memoizedUpdaters.clear();}// At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
// If we bailout on this work, we'll move them back (like above).
// It's important to move them now in case the work spawns more work at the same priority with different updaters.
// That way we can keep the current update and future updates separate.
movePendingFibersToMemoized(root,lanes);}}workInProgressTransitions=getTransitionsForLanes();prepareFreshStack(root,lanes);}{markRenderStarted(lanes);}do{try{workLoopSync();break;}catch(thrownValue){handleError(root,thrownValue);}}while(true);resetContextDependencies();executionContext=prevExecutionContext;popDispatcher(prevDispatcher);if(workInProgress!==null){// This is a sync render, so we should have finished the whole tree.
throw new Error('Cannot commit an incomplete root. This error is likely caused by a '+'bug in React. Please file an issue.');}{markRenderStopped();}// Set this to null to indicate there's no in-progress render.
workInProgressRoot=null;workInProgressRootRenderLanes=NoLanes;return workInProgressRootExitStatus;}// The work loop is an extremely hot path. Tell Closure not to inline it.
/** @noinline */function workLoopSync(){// Already timed out, so perform work without checking if we need to yield.
while(workInProgress!==null){performUnitOfWork(workInProgress);}}function renderRootConcurrent(root,lanes){var prevExecutionContext=executionContext;executionContext|=RenderContext;var prevDispatcher=pushDispatcher();// If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if(workInProgressRoot!==root||workInProgressRootRenderLanes!==lanes){{if(isDevToolsPresent){var memoizedUpdaters=root.memoizedUpdaters;if(memoizedUpdaters.size>0){restorePendingUpdaters(root,workInProgressRootRenderLanes);memoizedUpdaters.clear();}// At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
// If we bailout on this work, we'll move them back (like above).
// It's important to move them now in case the work spawns more work at the same priority with different updaters.
// That way we can keep the current update and future updates separate.
movePendingFibersToMemoized(root,lanes);}}workInProgressTransitions=getTransitionsForLanes();resetRenderTimer();prepareFreshStack(root,lanes);}{markRenderStarted(lanes);}do{try{workLoopConcurrent();break;}catch(thrownValue){handleError(root,thrownValue);}}while(true);resetContextDependencies();popDispatcher(prevDispatcher);executionContext=prevExecutionContext;if(workInProgress!==null){// Still work remaining.
{markRenderYielded();}return RootInProgress;}else {// Completed the tree.
{markRenderStopped();}// Set this to null to indicate there's no in-progress render.
workInProgressRoot=null;workInProgressRootRenderLanes=NoLanes;// Return the final exit status.
return workInProgressRootExitStatus;}}/** @noinline */function workLoopConcurrent(){// Perform work until Scheduler asks us to yield
while(workInProgress!==null&&!shouldYield()){performUnitOfWork(workInProgress);}}function performUnitOfWork(unitOfWork){// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
var current=unitOfWork.alternate;setCurrentFiber(unitOfWork);var next;if((unitOfWork.mode&ProfileMode)!==NoMode){startProfilerTimer(unitOfWork);next=beginWork$1(current,unitOfWork,subtreeRenderLanes);stopProfilerTimerIfRunningAndRecordDelta(unitOfWork,true);}else {next=beginWork$1(current,unitOfWork,subtreeRenderLanes);}resetCurrentFiber();unitOfWork.memoizedProps=unitOfWork.pendingProps;if(next===null){// If this doesn't spawn new work, complete the current work.
completeUnitOfWork(unitOfWork);}else {workInProgress=next;}ReactCurrentOwner$2.current=null;}function completeUnitOfWork(unitOfWork){// Attempt to complete the current unit of work, then move to the next
// sibling. If there are no more siblings, return to the parent fiber.
var completedWork=unitOfWork;do{// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
var current=completedWork.alternate;var returnFiber=completedWork.return;// Check if the work completed or if something threw.
if((completedWork.flags&Incomplete)===NoFlags){setCurrentFiber(completedWork);var next=void 0;if((completedWork.mode&ProfileMode)===NoMode){next=completeWork(current,completedWork,subtreeRenderLanes);}else {startProfilerTimer(completedWork);next=completeWork(current,completedWork,subtreeRenderLanes);// Update render duration assuming we didn't error.
stopProfilerTimerIfRunningAndRecordDelta(completedWork,false);}resetCurrentFiber();if(next!==null){// Completing this fiber spawned new work. Work on that next.
workInProgress=next;return;}}else {// This fiber did not complete because something threw. Pop values off
// the stack without entering the complete phase. If this is a boundary,
// capture values if possible.
var _next=unwindWork(current,completedWork);// Because this fiber did not complete, don't reset its lanes.
if(_next!==null){// If completing this work spawned new work, do that next. We'll come
// back here again.
// Since we're restarting, remove anything that is not a host effect
// from the effect tag.
_next.flags&=HostEffectMask;workInProgress=_next;return;}if((completedWork.mode&ProfileMode)!==NoMode){// Record the render duration for the fiber that errored.
stopProfilerTimerIfRunningAndRecordDelta(completedWork,false);// Include the time spent working on failed children before continuing.
var actualDuration=completedWork.actualDuration;var child=completedWork.child;while(child!==null){actualDuration+=child.actualDuration;child=child.sibling;}completedWork.actualDuration=actualDuration;}if(returnFiber!==null){// Mark the parent fiber as incomplete and clear its subtree flags.
returnFiber.flags|=Incomplete;returnFiber.subtreeFlags=NoFlags;returnFiber.deletions=null;}else {// We've unwound all the way to the root.
workInProgressRootExitStatus=RootDidNotComplete;workInProgress=null;return;}}var siblingFiber=completedWork.sibling;if(siblingFiber!==null){// If there is more work to do in this returnFiber, do that next.
workInProgress=siblingFiber;return;}// Otherwise, return to the parent
completedWork=returnFiber;// Update the next thing we're working on in case something throws.
workInProgress=completedWork;}while(completedWork!==null);// We've reached the root.
if(workInProgressRootExitStatus===RootInProgress){workInProgressRootExitStatus=RootCompleted;}}function commitRoot(root,recoverableErrors,transitions){// TODO: This no longer makes any sense. We already wrap the mutation and
// layout phases. Should be able to remove.
var previousUpdateLanePriority=getCurrentUpdatePriority();var prevTransition=ReactCurrentBatchConfig$3.transition;try{ReactCurrentBatchConfig$3.transition=null;setCurrentUpdatePriority(DiscreteEventPriority);commitRootImpl(root,recoverableErrors,transitions,previousUpdateLanePriority);}finally{ReactCurrentBatchConfig$3.transition=prevTransition;setCurrentUpdatePriority(previousUpdateLanePriority);}return null;}function commitRootImpl(root,recoverableErrors,transitions,renderPriorityLevel){do{// `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
// means `flushPassiveEffects` will sometimes result in additional
// passive effects. So we need to keep flushing in a loop until there are
// no more pending effects.
// TODO: Might be better if `flushPassiveEffects` did not automatically
// flush synchronous work at the end, to avoid factoring hazards like this.
flushPassiveEffects();}while(rootWithPendingPassiveEffects!==null);flushRenderPhaseStrictModeWarningsInDEV();if((executionContext&(RenderContext|CommitContext))!==NoContext){throw new Error('Should not already be working.');}var finishedWork=root.finishedWork;var lanes=root.finishedLanes;{markCommitStarted(lanes);}if(finishedWork===null){{markCommitStopped();}return null;}else {{if(lanes===NoLanes){error('root.finishedLanes should not be empty during a commit. This is a '+'bug in React.');}}}root.finishedWork=null;root.finishedLanes=NoLanes;if(finishedWork===root.current){throw new Error('Cannot commit the same tree as before. This error is likely caused by '+'a bug in React. Please file an issue.');}// commitRoot never returns a continuation; it always finishes synchronously.
// So we can clear these now to allow a new callback to be scheduled.
root.callbackNode=null;root.callbackPriority=NoLane;// Update the first and last pending times on this root. The new first
// pending time is whatever is left on the root fiber.
var remainingLanes=mergeLanes(finishedWork.lanes,finishedWork.childLanes);markRootFinished(root,remainingLanes);if(root===workInProgressRoot){// We can reset these now that they are finished.
workInProgressRoot=null;workInProgress=null;workInProgressRootRenderLanes=NoLanes;}// If there are pending passive effects, schedule a callback to process them.
// Do this as early as possible, so it is queued before anything else that
// might get scheduled in the commit phase. (See #16714.)
// TODO: Delete all other places that schedule the passive effect callback
// They're redundant.
if((finishedWork.subtreeFlags&PassiveMask)!==NoFlags||(finishedWork.flags&PassiveMask)!==NoFlags){if(!rootDoesHavePassiveEffects){rootDoesHavePassiveEffects=true;// to store it in pendingPassiveTransitions until they get processed
// We need to pass this through as an argument to commitRoot
// because workInProgressTransitions might have changed between
// the previous render and commit if we throttle the commit
// with setTimeout
pendingPassiveTransitions=transitions;scheduleCallback$1(NormalPriority,function(){flushPassiveEffects();// This render triggered passive effects: release the root cache pool
// *after* passive effects fire to avoid freeing a cache pool that may
// be referenced by a node in the tree (HostRoot, Cache boundary etc)
return null;});}}// Check if there are any effects in the whole tree.
// TODO: This is left over from the effect list implementation, where we had
// to check for the existence of `firstEffect` to satisfy Flow. I think the
// only other reason this optimization exists is because it affects profiling.
// Reconsider whether this is necessary.
var subtreeHasEffects=(finishedWork.subtreeFlags&(BeforeMutationMask|MutationMask|LayoutMask|PassiveMask))!==NoFlags;var rootHasEffect=(finishedWork.flags&(BeforeMutationMask|MutationMask|LayoutMask|PassiveMask))!==NoFlags;if(subtreeHasEffects||rootHasEffect){var prevTransition=ReactCurrentBatchConfig$3.transition;ReactCurrentBatchConfig$3.transition=null;var previousPriority=getCurrentUpdatePriority();setCurrentUpdatePriority(DiscreteEventPriority);var prevExecutionContext=executionContext;executionContext|=CommitContext;// Reset this to null before calling lifecycles
ReactCurrentOwner$2.current=null;// The commit phase is broken into several sub-phases. We do a separate pass
// of the effect list for each phase: all mutation effects come before all
// layout effects, and so on.
// The first phase a "before mutation" phase. We use this phase to read the
// state of the host tree right before we mutate it. This is where
// getSnapshotBeforeUpdate is called.
commitBeforeMutationEffects(root,finishedWork);{// Mark the current commit time to be shared by all Profilers in this
// batch. This enables them to be grouped later.
recordCommitTime();}commitMutationEffects(root,finishedWork,lanes);resetAfterCommit(root.containerInfo);// The work-in-progress tree is now the current tree. This must come after
// the mutation phase, so that the previous tree is still current during
// componentWillUnmount, but before the layout phase, so that the finished
// work is current during componentDidMount/Update.
root.current=finishedWork;// The next phase is the layout phase, where we call effects that read
{markLayoutEffectsStarted(lanes);}commitLayoutEffects(finishedWork,root,lanes);{markLayoutEffectsStopped();}// opportunity to paint.
requestPaint();executionContext=prevExecutionContext;// Reset the priority to the previous non-sync value.
setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig$3.transition=prevTransition;}else {// No effects.
root.current=finishedWork;// Measure these anyway so the flamegraph explicitly shows that there were
// no effects.
// TODO: Maybe there's a better way to report this.
{recordCommitTime();}}var rootDidHavePassiveEffects=rootDoesHavePassiveEffects;if(rootDoesHavePassiveEffects){// This commit has passive effects. Stash a reference to them. But don't
// schedule a callback until after flushing layout work.
rootDoesHavePassiveEffects=false;rootWithPendingPassiveEffects=root;pendingPassiveEffectsLanes=lanes;}else {{nestedPassiveUpdateCount=0;rootWithPassiveNestedUpdates=null;}}// Read this again, since an effect might have updated it
remainingLanes=root.pendingLanes;// Check if there's remaining work on this root
// TODO: This is part of the `componentDidCatch` implementation. Its purpose
// is to detect whether something might have called setState inside
// `componentDidCatch`. The mechanism is known to be flawed because `setState`
// inside `componentDidCatch` is itself flawed — that's why we recommend
// `getDerivedStateFromError` instead. However, it could be improved by
// checking if remainingLanes includes Sync work, instead of whether there's
// any work remaining at all (which would also include stuff like Suspense
// retries or transitions). It's been like this for a while, though, so fixing
// it probably isn't that urgent.
if(remainingLanes===NoLanes){// If there's no remaining work, we can clear the set of already failed
// error boundaries.
legacyErrorBoundariesThatAlreadyFailed=null;}{if(!rootDidHavePassiveEffects){commitDoubleInvokeEffectsInDEV(root.current,false);}}onCommitRoot(finishedWork.stateNode,renderPriorityLevel);{if(isDevToolsPresent){root.memoizedUpdaters.clear();}}{onCommitRoot$1();}// Always call this before exiting `commitRoot`, to ensure that any
// additional work on this root is scheduled.
ensureRootIsScheduled(root,now());if(recoverableErrors!==null){// There were errors during this render, but recovered from them without
// needing to surface it to the UI. We log them here.
var onRecoverableError=root.onRecoverableError;for(var i=0;i<recoverableErrors.length;i++){var recoverableError=recoverableErrors[i];var componentStack=recoverableError.stack;var digest=recoverableError.digest;onRecoverableError(recoverableError.value,{componentStack:componentStack,digest:digest});}}if(hasUncaughtError){hasUncaughtError=false;var error$1=firstUncaughtError;firstUncaughtError=null;throw error$1;}// If the passive effects are the result of a discrete render, flush them
// synchronously at the end of the current task so that the result is
// immediately observable. Otherwise, we assume that they are not
// order-dependent and do not need to be observed by external systems, so we
// can wait until after paint.
// TODO: We can optimize this by not scheduling the callback earlier. Since we
// currently schedule the callback in multiple places, will wait until those
// are consolidated.
if(includesSomeLane(pendingPassiveEffectsLanes,SyncLane)&&root.tag!==LegacyRoot){flushPassiveEffects();}// Read this again, since a passive effect might have updated it
remainingLanes=root.pendingLanes;if(includesSomeLane(remainingLanes,SyncLane)){{markNestedUpdateScheduled();}// Count the number of times the root synchronously re-renders without
// finishing. If there are too many, it indicates an infinite update loop.
if(root===rootWithNestedUpdates){nestedUpdateCount++;}else {nestedUpdateCount=0;rootWithNestedUpdates=root;}}else {nestedUpdateCount=0;}// If layout work was scheduled, flush it now.
flushSyncCallbacks();{markCommitStopped();}return null;}function flushPassiveEffects(){// Returns whether passive effects were flushed.
// TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
// probably just combine the two functions. I believe they were only separate
// in the first place because we used to wrap it with
// `Scheduler.runWithPriority`, which accepts a function. But now we track the
// priority within React itself, so we can mutate the variable directly.
if(rootWithPendingPassiveEffects!==null){var renderPriority=lanesToEventPriority(pendingPassiveEffectsLanes);var priority=lowerEventPriority(DefaultEventPriority,renderPriority);var prevTransition=ReactCurrentBatchConfig$3.transition;var previousPriority=getCurrentUpdatePriority();try{ReactCurrentBatchConfig$3.transition=null;setCurrentUpdatePriority(priority);return flushPassiveEffectsImpl();}finally{setCurrentUpdatePriority(previousPriority);ReactCurrentBatchConfig$3.transition=prevTransition;// Once passive effects have run for the tree - giving components a
}}return false;}function enqueuePendingPassiveProfilerEffect(fiber){{pendingPassiveProfilerEffects.push(fiber);if(!rootDoesHavePassiveEffects){rootDoesHavePassiveEffects=true;scheduleCallback$1(NormalPriority,function(){flushPassiveEffects();return null;});}}}function flushPassiveEffectsImpl(){if(rootWithPendingPassiveEffects===null){return false;}// Cache and clear the transitions flag
var transitions=pendingPassiveTransitions;pendingPassiveTransitions=null;var root=rootWithPendingPassiveEffects;var lanes=pendingPassiveEffectsLanes;rootWithPendingPassiveEffects=null;// TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
// Figure out why and fix it. It's not causing any known issues (probably
// because it's only used for profiling), but it's a refactor hazard.
pendingPassiveEffectsLanes=NoLanes;if((executionContext&(RenderContext|CommitContext))!==NoContext){throw new Error('Cannot flush passive effects while already rendering.');}{isFlushingPassiveEffects=true;didScheduleUpdateDuringPassiveEffects=false;}{markPassiveEffectsStarted(lanes);}var prevExecutionContext=executionContext;executionContext|=CommitContext;commitPassiveUnmountEffects(root.current);commitPassiveMountEffects(root,root.current,lanes,transitions);// TODO: Move to commitPassiveMountEffects
{var profilerEffects=pendingPassiveProfilerEffects;pendingPassiveProfilerEffects=[];for(var i=0;i<profilerEffects.length;i++){var _fiber=profilerEffects[i];commitPassiveEffectDurations(root,_fiber);}}{markPassiveEffectsStopped();}{commitDoubleInvokeEffectsInDEV(root.current,true);}executionContext=prevExecutionContext;flushSyncCallbacks();{// If additional passive effects were scheduled, increment a counter. If this
// exceeds the limit, we'll fire a warning.
if(didScheduleUpdateDuringPassiveEffects){if(root===rootWithPassiveNestedUpdates){nestedPassiveUpdateCount++;}else {nestedPassiveUpdateCount=0;rootWithPassiveNestedUpdates=root;}}else {nestedPassiveUpdateCount=0;}isFlushingPassiveEffects=false;didScheduleUpdateDuringPassiveEffects=false;}// TODO: Move to commitPassiveMountEffects
onPostCommitRoot(root);{var stateNode=root.current.stateNode;stateNode.effectDuration=0;stateNode.passiveEffectDuration=0;}return true;}function isAlreadyFailedLegacyErrorBoundary(instance){return legacyErrorBoundariesThatAlreadyFailed!==null&&legacyErrorBoundariesThatAlreadyFailed.has(instance);}function markLegacyErrorBoundaryAsFailed(instance){if(legacyErrorBoundariesThatAlreadyFailed===null){legacyErrorBoundariesThatAlreadyFailed=new Set([instance]);}else {legacyErrorBoundariesThatAlreadyFailed.add(instance);}}function prepareToThrowUncaughtError(error){if(!hasUncaughtError){hasUncaughtError=true;firstUncaughtError=error;}}var onUncaughtError=prepareToThrowUncaughtError;function captureCommitPhaseErrorOnRoot(rootFiber,sourceFiber,error){var errorInfo=createCapturedValueAtFiber(error,sourceFiber);var update=createRootErrorUpdate(rootFiber,errorInfo,SyncLane);var root=enqueueUpdate(rootFiber,update,SyncLane);var eventTime=requestEventTime();if(root!==null){markRootUpdated(root,SyncLane,eventTime);ensureRootIsScheduled(root,eventTime);}}function captureCommitPhaseError(sourceFiber,nearestMountedAncestor,error$1){{reportUncaughtErrorInDEV(error$1);setIsRunningInsertionEffect(false);}if(sourceFiber.tag===HostRoot){// Error was thrown at the root. There is no parent, so the root
// itself should capture it.
captureCommitPhaseErrorOnRoot(sourceFiber,sourceFiber,error$1);return;}var fiber=null;{fiber=nearestMountedAncestor;}while(fiber!==null){if(fiber.tag===HostRoot){captureCommitPhaseErrorOnRoot(fiber,sourceFiber,error$1);return;}else if(fiber.tag===ClassComponent){var ctor=fiber.type;var instance=fiber.stateNode;if(typeof ctor.getDerivedStateFromError==='function'||typeof instance.componentDidCatch==='function'&&!isAlreadyFailedLegacyErrorBoundary(instance)){var errorInfo=createCapturedValueAtFiber(error$1,sourceFiber);var update=createClassErrorUpdate(fiber,errorInfo,SyncLane);var root=enqueueUpdate(fiber,update,SyncLane);var eventTime=requestEventTime();if(root!==null){markRootUpdated(root,SyncLane,eventTime);ensureRootIsScheduled(root,eventTime);}return;}}fiber=fiber.return;}{// TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning
// will fire for errors that are thrown by destroy functions inside deleted
// trees. What it should instead do is propagate the error to the parent of
// the deleted tree. In the meantime, do not add this warning to the
// allowlist; this is only for our internal use.
error('Internal React error: Attempted to capture a commit phase error '+'inside a detached tree. This indicates a bug in React. Likely '+'causes include deleting the same fiber more than once, committing an '+'already-finished tree, or an inconsistent return pointer.\n\n'+'Error message:\n\n%s',error$1);}}function pingSuspendedRoot(root,wakeable,pingedLanes){var pingCache=root.pingCache;if(pingCache!==null){// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
pingCache.delete(wakeable);}var eventTime=requestEventTime();markRootPinged(root,pingedLanes);warnIfSuspenseResolutionNotWrappedWithActDEV(root);if(workInProgressRoot===root&&isSubsetOfLanes(workInProgressRootRenderLanes,pingedLanes)){// Received a ping at the same priority level at which we're currently
// rendering. We might want to restart this render. This should mirror
// the logic of whether or not a root suspends once it completes.
// TODO: If we're rendering sync either due to Sync, Batched or expired,
// we should probably never restart.
// If we're suspended with delay, or if it's a retry, we'll always suspend
// so we can always restart.
if(workInProgressRootExitStatus===RootSuspendedWithDelay||workInProgressRootExitStatus===RootSuspended&&includesOnlyRetries(workInProgressRootRenderLanes)&&now()-globalMostRecentFallbackTime<FALLBACK_THROTTLE_MS){// Restart from the root.
prepareFreshStack(root,NoLanes);}else {// Even though we can't restart right now, we might get an
// opportunity later. So we mark this render as having a ping.
workInProgressRootPingedLanes=mergeLanes(workInProgressRootPingedLanes,pingedLanes);}}ensureRootIsScheduled(root,eventTime);}function retryTimedOutBoundary(boundaryFiber,retryLane){// The boundary fiber (a Suspense component or SuspenseList component)
// previously was rendered in its fallback state. One of the promises that
// suspended it has resolved, which means at least part of the tree was
// likely unblocked. Try rendering again, at a new lanes.
if(retryLane===NoLane){// TODO: Assign this to `suspenseState.retryLane`? to avoid
// unnecessary entanglement?
retryLane=requestRetryLane(boundaryFiber);}// TODO: Special case idle priority?
var eventTime=requestEventTime();var root=enqueueConcurrentRenderForLane(boundaryFiber,retryLane);if(root!==null){markRootUpdated(root,retryLane,eventTime);ensureRootIsScheduled(root,eventTime);}}function retryDehydratedSuspenseBoundary(boundaryFiber){var suspenseState=boundaryFiber.memoizedState;var retryLane=NoLane;if(suspenseState!==null){retryLane=suspenseState.retryLane;}retryTimedOutBoundary(boundaryFiber,retryLane);}function resolveRetryWakeable(boundaryFiber,wakeable){var retryLane=NoLane;// Default
var retryCache;switch(boundaryFiber.tag){case SuspenseComponent:retryCache=boundaryFiber.stateNode;var suspenseState=boundaryFiber.memoizedState;if(suspenseState!==null){retryLane=suspenseState.retryLane;}break;case SuspenseListComponent:retryCache=boundaryFiber.stateNode;break;default:throw new Error('Pinged unknown suspense boundary type. '+'This is probably a bug in React.');}if(retryCache!==null){// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
retryCache.delete(wakeable);}retryTimedOutBoundary(boundaryFiber,retryLane);}// Computes the next Just Noticeable Difference (JND) boundary.
// The theory is that a person can't tell the difference between small differences in time.
// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
// difference in the experience. However, waiting for longer might mean that we can avoid
// showing an intermediate loading state. The longer we have already waited, the harder it
// is to tell small differences in time. Therefore, the longer we've already waited,
// the longer we can wait additionally. At some point we have to give up though.
// We pick a train model where the next boundary commits at a consistent schedule.
// These particular numbers are vague estimates. We expect to adjust them based on research.
function jnd(timeElapsed){return timeElapsed<120?120:timeElapsed<480?480:timeElapsed<1080?1080:timeElapsed<1920?1920:timeElapsed<3000?3000:timeElapsed<4320?4320:ceil(timeElapsed/1960)*1960;}function checkForNestedUpdates(){if(nestedUpdateCount>NESTED_UPDATE_LIMIT){nestedUpdateCount=0;rootWithNestedUpdates=null;throw new Error('Maximum update depth exceeded. This can happen when a component '+'repeatedly calls setState inside componentWillUpdate or '+'componentDidUpdate. React limits the number of nested updates to '+'prevent infinite loops.');}{if(nestedPassiveUpdateCount>NESTED_PASSIVE_UPDATE_LIMIT){nestedPassiveUpdateCount=0;rootWithPassiveNestedUpdates=null;error('Maximum update depth exceeded. This can happen when a component '+"calls setState inside useEffect, but useEffect either doesn't "+'have a dependency array, or one of the dependencies changes on '+'every render.');}}}function flushRenderPhaseStrictModeWarningsInDEV(){{ReactStrictModeWarnings.flushLegacyContextWarning();{ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();}}}function commitDoubleInvokeEffectsInDEV(fiber,hasPassiveEffects){{// TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
// so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
// Maybe not a big deal since this is DEV only behavior.
setCurrentFiber(fiber);invokeEffectsInDev(fiber,MountLayoutDev,invokeLayoutEffectUnmountInDEV);if(hasPassiveEffects){invokeEffectsInDev(fiber,MountPassiveDev,invokePassiveEffectUnmountInDEV);}invokeEffectsInDev(fiber,MountLayoutDev,invokeLayoutEffectMountInDEV);if(hasPassiveEffects){invokeEffectsInDev(fiber,MountPassiveDev,invokePassiveEffectMountInDEV);}resetCurrentFiber();}}function invokeEffectsInDev(firstChild,fiberFlags,invokeEffectFn){{// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
var current=firstChild;var subtreeRoot=null;while(current!==null){var primarySubtreeFlag=current.subtreeFlags&fiberFlags;if(current!==subtreeRoot&&current.child!==null&&primarySubtreeFlag!==NoFlags){current=current.child;}else {if((current.flags&fiberFlags)!==NoFlags){invokeEffectFn(current);}if(current.sibling!==null){current=current.sibling;}else {current=subtreeRoot=current.return;}}}}}var didWarnStateUpdateForNotYetMountedComponent=null;function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber){{if((executionContext&RenderContext)!==NoContext){// We let the other warning about render phase updates deal with this one.
return;}if(!(fiber.mode&ConcurrentMode)){return;}var tag=fiber.tag;if(tag!==IndeterminateComponent&&tag!==HostRoot&&tag!==ClassComponent&&tag!==FunctionComponent&&tag!==ForwardRef&&tag!==MemoComponent&&tag!==SimpleMemoComponent){// Only warn for user-defined components, not internal ones like Suspense.
return;}// We show the whole stack but dedupe on the top component's name because
// the problematic code almost always lies inside that component.
var componentName=getComponentNameFromFiber(fiber)||'ReactComponent';if(didWarnStateUpdateForNotYetMountedComponent!==null){if(didWarnStateUpdateForNotYetMountedComponent.has(componentName)){return;}didWarnStateUpdateForNotYetMountedComponent.add(componentName);}else {didWarnStateUpdateForNotYetMountedComponent=new Set([componentName]);}var previousFiber=current;try{setCurrentFiber(fiber);error("Can't perform a React state update on a component that hasn't mounted yet. "+'This indicates that you have a side-effect in your render function that '+'asynchronously later calls tries to update the component. Move this work to '+'useEffect instead.');}finally{if(previousFiber){setCurrentFiber(fiber);}else {resetCurrentFiber();}}}}var beginWork$1;{var dummyFiber=null;beginWork$1=function(current,unitOfWork,lanes){// If a component throws an error, we replay it again in a synchronously
// dispatched event, so that the debugger will treat it as an uncaught
// error See ReactErrorUtils for more information.
// Before entering the begin phase, copy the work-in-progress onto a dummy
// fiber. If beginWork throws, we'll use this to reset the state.
var originalWorkInProgressCopy=assignFiberPropertiesInDEV(dummyFiber,unitOfWork);try{return beginWork(current,unitOfWork,lanes);}catch(originalError){if(didSuspendOrErrorWhileHydratingDEV()||originalError!==null&&typeof originalError==='object'&&typeof originalError.then==='function'){// Don't replay promises.
// Don't replay errors if we are hydrating and have already suspended or handled an error
throw originalError;}// Keep this code in sync with handleError; any changes here must have
// corresponding changes there.
resetContextDependencies();resetHooksAfterThrow();// Don't reset current debug fiber, since we're about to work on the
// same fiber again.
// Unwind the failed stack frame
unwindInterruptedWork(current,unitOfWork);// Restore the original properties of the fiber.
assignFiberPropertiesInDEV(unitOfWork,originalWorkInProgressCopy);if(unitOfWork.mode&ProfileMode){// Reset the profiler timer.
startProfilerTimer(unitOfWork);}// Run beginWork again.
invokeGuardedCallback(null,beginWork,null,current,unitOfWork,lanes);if(hasCaughtError()){var replayError=clearCaughtError();if(typeof replayError==='object'&&replayError!==null&&replayError._suppressLogging&&typeof originalError==='object'&&originalError!==null&&!originalError._suppressLogging){// If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
originalError._suppressLogging=true;}}// We always throw the original error in case the second render pass is not idempotent.
// This can happen if a memoized function or CommonJS module doesn't throw after first invocation.
throw originalError;}};}var didWarnAboutUpdateInRender=false;var didWarnAboutUpdateInRenderForAnotherComponent;{didWarnAboutUpdateInRenderForAnotherComponent=new Set();}function warnAboutRenderPhaseUpdatesInDEV(fiber){{if(isRendering&&!getIsUpdatingOpaqueValueInRenderPhaseInDEV()){switch(fiber.tag){case FunctionComponent:case ForwardRef:case SimpleMemoComponent:{var renderingComponentName=workInProgress&&getComponentNameFromFiber(workInProgress)||'Unknown';// Dedupe by the rendering component because it's the one that needs to be fixed.
var dedupeKey=renderingComponentName;if(!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)){didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);var setStateComponentName=getComponentNameFromFiber(fiber)||'Unknown';error('Cannot update a component (`%s`) while rendering a '+'different component (`%s`). To locate the bad setState() call inside `%s`, '+'follow the stack trace as described in https://reactjs.org/link/setstate-in-render',setStateComponentName,renderingComponentName,renderingComponentName);}break;}case ClassComponent:{if(!didWarnAboutUpdateInRender){error('Cannot update during an existing state transition (such as '+'within `render`). Render methods should be a pure '+'function of props and state.');didWarnAboutUpdateInRender=true;}break;}}}}}function restorePendingUpdaters(root,lanes){{if(isDevToolsPresent){var memoizedUpdaters=root.memoizedUpdaters;memoizedUpdaters.forEach(function(schedulingFiber){addFiberToLanesMap(root,schedulingFiber,lanes);});// This function intentionally does not clear memoized updaters.
// Those may still be relevant to the current commit
// and a future one (e.g. Suspense).
}}}var fakeActCallbackNode={};function scheduleCallback$1(priorityLevel,callback){{// If we're currently inside an `act` scope, bypass Scheduler and push to
// the `act` queue instead.
var actQueue=ReactCurrentActQueue$1.current;if(actQueue!==null){actQueue.push(callback);return fakeActCallbackNode;}else {return scheduleCallback(priorityLevel,callback);}}}function cancelCallback$1(callbackNode){if(callbackNode===fakeActCallbackNode){return;}// In production, always call Scheduler. This function will be stripped out.
return cancelCallback(callbackNode);}function shouldForceFlushFallbacksInDEV(){// Never force flush in production. This function should get stripped out.
return ReactCurrentActQueue$1.current!==null;}function warnIfUpdatesNotWrappedWithActDEV(fiber){{if(fiber.mode&ConcurrentMode){if(!isConcurrentActEnvironment()){// Not in an act environment. No need to warn.
return;}}else {// Legacy mode has additional cases where we suppress a warning.
if(!isLegacyActEnvironment()){// Not in an act environment. No need to warn.
return;}if(executionContext!==NoContext){// Legacy mode doesn't warn if the update is batched, i.e.
// batchedUpdates or flushSync.
return;}if(fiber.tag!==FunctionComponent&&fiber.tag!==ForwardRef&&fiber.tag!==SimpleMemoComponent){// For backwards compatibility with pre-hooks code, legacy mode only
// warns for updates that originate from a hook.
return;}}if(ReactCurrentActQueue$1.current===null){var previousFiber=current;try{setCurrentFiber(fiber);error('An update to %s inside a test was not wrapped in act(...).\n\n'+'When testing, code that causes React state updates should be '+'wrapped into act(...):\n\n'+'act(() => {\n'+'  /* fire events that update state */\n'+'});\n'+'/* assert on the output */\n\n'+"This ensures that you're testing the behavior the user would see "+'in the browser.'+' Learn more at https://reactjs.org/link/wrap-tests-with-act',getComponentNameFromFiber(fiber));}finally{if(previousFiber){setCurrentFiber(fiber);}else {resetCurrentFiber();}}}}}function warnIfSuspenseResolutionNotWrappedWithActDEV(root){{if(root.tag!==LegacyRoot&&isConcurrentActEnvironment()&&ReactCurrentActQueue$1.current===null){error('A suspended resource finished loading inside a test, but the event '+'was not wrapped in act(...).\n\n'+'When testing, code that resolves suspended data should be wrapped '+'into act(...):\n\n'+'act(() => {\n'+'  /* finish loading suspended data */\n'+'});\n'+'/* assert on the output */\n\n'+"This ensures that you're testing the behavior the user would see "+'in the browser.'+' Learn more at https://reactjs.org/link/wrap-tests-with-act');}}}function setIsRunningInsertionEffect(isRunning){{isRunningInsertionEffect=isRunning;}}/* eslint-disable react-internal/prod-error-codes */var resolveFamily=null;// $FlowFixMe Flow gets confused by a WeakSet feature check below.
var failedBoundaries=null;var setRefreshHandler=function(handler){{resolveFamily=handler;}};function resolveFunctionForHotReloading(type){{if(resolveFamily===null){// Hot reloading is disabled.
return type;}var family=resolveFamily(type);if(family===undefined){return type;}// Use the latest known implementation.
return family.current;}}function resolveClassForHotReloading(type){// No implementation differences.
return resolveFunctionForHotReloading(type);}function resolveForwardRefForHotReloading(type){{if(resolveFamily===null){// Hot reloading is disabled.
return type;}var family=resolveFamily(type);if(family===undefined){// Check if we're dealing with a real forwardRef. Don't want to crash early.
if(type!==null&&type!==undefined&&typeof type.render==='function'){// ForwardRef is special because its resolved .type is an object,
// but it's possible that we only have its inner render function in the map.
// If that inner render function is different, we'll build a new forwardRef type.
var currentRender=resolveFunctionForHotReloading(type.render);if(type.render!==currentRender){var syntheticType={$$typeof:REACT_FORWARD_REF_TYPE,render:currentRender};if(type.displayName!==undefined){syntheticType.displayName=type.displayName;}return syntheticType;}}return type;}// Use the latest known implementation.
return family.current;}}function isCompatibleFamilyForHotReloading(fiber,element){{if(resolveFamily===null){// Hot reloading is disabled.
return false;}var prevType=fiber.elementType;var nextType=element.type;// If we got here, we know types aren't === equal.
var needsCompareFamilies=false;var $$typeofNextType=typeof nextType==='object'&&nextType!==null?nextType.$$typeof:null;switch(fiber.tag){case ClassComponent:{if(typeof nextType==='function'){needsCompareFamilies=true;}break;}case FunctionComponent:{if(typeof nextType==='function'){needsCompareFamilies=true;}else if($$typeofNextType===REACT_LAZY_TYPE){// We don't know the inner type yet.
// We're going to assume that the lazy inner type is stable,
// and so it is sufficient to avoid reconciling it away.
// We're not going to unwrap or actually use the new lazy type.
needsCompareFamilies=true;}break;}case ForwardRef:{if($$typeofNextType===REACT_FORWARD_REF_TYPE){needsCompareFamilies=true;}else if($$typeofNextType===REACT_LAZY_TYPE){needsCompareFamilies=true;}break;}case MemoComponent:case SimpleMemoComponent:{if($$typeofNextType===REACT_MEMO_TYPE){// TODO: if it was but can no longer be simple,
// we shouldn't set this.
needsCompareFamilies=true;}else if($$typeofNextType===REACT_LAZY_TYPE){needsCompareFamilies=true;}break;}default:return false;}// Check if both types have a family and it's the same one.
if(needsCompareFamilies){// Note: memo() and forwardRef() we'll compare outer rather than inner type.
// This means both of them need to be registered to preserve state.
// If we unwrapped and compared the inner types for wrappers instead,
// then we would risk falsely saying two separate memo(Foo)
// calls are equivalent because they wrap the same Foo function.
var prevFamily=resolveFamily(prevType);if(prevFamily!==undefined&&prevFamily===resolveFamily(nextType)){return true;}}return false;}}function markFailedErrorBoundaryForHotReloading(fiber){{if(resolveFamily===null){// Hot reloading is disabled.
return;}if(typeof WeakSet!=='function'){return;}if(failedBoundaries===null){failedBoundaries=new WeakSet();}failedBoundaries.add(fiber);}}var scheduleRefresh=function(root,update){{if(resolveFamily===null){// Hot reloading is disabled.
return;}var staleFamilies=update.staleFamilies,updatedFamilies=update.updatedFamilies;flushPassiveEffects();flushSync(function(){scheduleFibersWithFamiliesRecursively(root.current,updatedFamilies,staleFamilies);});}};var scheduleRoot=function(root,element){{if(root.context!==emptyContextObject){// Super edge case: root has a legacy _renderSubtree context
// but we don't know the parentComponent so we can't pass it.
// Just ignore. We'll delete this with _renderSubtree code path later.
return;}flushPassiveEffects();flushSync(function(){updateContainer(element,root,null,null);});}};function scheduleFibersWithFamiliesRecursively(fiber,updatedFamilies,staleFamilies){{var alternate=fiber.alternate,child=fiber.child,sibling=fiber.sibling,tag=fiber.tag,type=fiber.type;var candidateType=null;switch(tag){case FunctionComponent:case SimpleMemoComponent:case ClassComponent:candidateType=type;break;case ForwardRef:candidateType=type.render;break;}if(resolveFamily===null){throw new Error('Expected resolveFamily to be set during hot reload.');}var needsRender=false;var needsRemount=false;if(candidateType!==null){var family=resolveFamily(candidateType);if(family!==undefined){if(staleFamilies.has(family)){needsRemount=true;}else if(updatedFamilies.has(family)){if(tag===ClassComponent){needsRemount=true;}else {needsRender=true;}}}}if(failedBoundaries!==null){if(failedBoundaries.has(fiber)||alternate!==null&&failedBoundaries.has(alternate)){needsRemount=true;}}if(needsRemount){fiber._debugNeedsRemount=true;}if(needsRemount||needsRender){var _root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(_root!==null){scheduleUpdateOnFiber(_root,fiber,SyncLane,NoTimestamp);}}if(child!==null&&!needsRemount){scheduleFibersWithFamiliesRecursively(child,updatedFamilies,staleFamilies);}if(sibling!==null){scheduleFibersWithFamiliesRecursively(sibling,updatedFamilies,staleFamilies);}}}var findHostInstancesForRefresh=function(root,families){{var hostInstances=new Set();var types=new Set(families.map(function(family){return family.current;}));findHostInstancesForMatchingFibersRecursively(root.current,types,hostInstances);return hostInstances;}};function findHostInstancesForMatchingFibersRecursively(fiber,types,hostInstances){{var child=fiber.child,sibling=fiber.sibling,tag=fiber.tag,type=fiber.type;var candidateType=null;switch(tag){case FunctionComponent:case SimpleMemoComponent:case ClassComponent:candidateType=type;break;case ForwardRef:candidateType=type.render;break;}var didMatch=false;if(candidateType!==null){if(types.has(candidateType)){didMatch=true;}}if(didMatch){// We have a match. This only drills down to the closest host components.
// There's no need to search deeper because for the purpose of giving
// visual feedback, "flashing" outermost parent rectangles is sufficient.
findHostInstancesForFiberShallowly(fiber,hostInstances);}else {// If there's no match, maybe there will be one further down in the child tree.
if(child!==null){findHostInstancesForMatchingFibersRecursively(child,types,hostInstances);}}if(sibling!==null){findHostInstancesForMatchingFibersRecursively(sibling,types,hostInstances);}}}function findHostInstancesForFiberShallowly(fiber,hostInstances){{var foundHostInstances=findChildHostInstancesForFiberShallowly(fiber,hostInstances);if(foundHostInstances){return;}// If we didn't find any host children, fallback to closest host parent.
var node=fiber;while(true){switch(node.tag){case HostComponent:hostInstances.add(node.stateNode);return;case HostPortal:hostInstances.add(node.stateNode.containerInfo);return;case HostRoot:hostInstances.add(node.stateNode.containerInfo);return;}if(node.return===null){throw new Error('Expected to reach root first.');}node=node.return;}}}function findChildHostInstancesForFiberShallowly(fiber,hostInstances){{var node=fiber;var foundHostInstances=false;while(true){if(node.tag===HostComponent){// We got a match.
foundHostInstances=true;hostInstances.add(node.stateNode);// There may still be more, so keep searching.
}else if(node.child!==null){node.child.return=node;node=node.child;continue;}if(node===fiber){return foundHostInstances;}while(node.sibling===null){if(node.return===null||node.return===fiber){return foundHostInstances;}node=node.return;}node.sibling.return=node.return;node=node.sibling;}}return false;}var hasBadMapPolyfill;{hasBadMapPolyfill=false;try{var nonExtensibleObject=Object.preventExtensions({});/* eslint-disable no-new */new Map([[nonExtensibleObject,null]]);new Set([nonExtensibleObject]);/* eslint-enable no-new */}catch(e){// TODO: Consider warning about bad polyfills
hasBadMapPolyfill=true;}}function FiberNode(tag,pendingProps,key,mode){// Instance
this.tag=tag;this.key=key;this.elementType=null;this.type=null;this.stateNode=null;// Fiber
this.return=null;this.child=null;this.sibling=null;this.index=0;this.ref=null;this.pendingProps=pendingProps;this.memoizedProps=null;this.updateQueue=null;this.memoizedState=null;this.dependencies=null;this.mode=mode;// Effects
this.flags=NoFlags;this.subtreeFlags=NoFlags;this.deletions=null;this.lanes=NoLanes;this.childLanes=NoLanes;this.alternate=null;{// Note: The following is done to avoid a v8 performance cliff.
//
// Initializing the fields below to smis and later updating them with
// double values will cause Fibers to end up having separate shapes.
// This behavior/bug has something to do with Object.preventExtension().
// Fortunately this only impacts DEV builds.
// Unfortunately it makes React unusably slow for some applications.
// To work around this, initialize the fields below with doubles.
//
// Learn more about this here:
// https://github.com/facebook/react/issues/14365
// https://bugs.chromium.org/p/v8/issues/detail?id=8538
this.actualDuration=Number.NaN;this.actualStartTime=Number.NaN;this.selfBaseDuration=Number.NaN;this.treeBaseDuration=Number.NaN;// It's okay to replace the initial doubles with smis after initialization.
// This won't trigger the performance cliff mentioned above,
// and it simplifies other profiler code (including DevTools).
this.actualDuration=0;this.actualStartTime=-1;this.selfBaseDuration=0;this.treeBaseDuration=0;}{// This isn't directly used but is handy for debugging internals:
this._debugSource=null;this._debugOwner=null;this._debugNeedsRemount=false;this._debugHookTypes=null;if(!hasBadMapPolyfill&&typeof Object.preventExtensions==='function'){Object.preventExtensions(this);}}}// This is a constructor function, rather than a POJO constructor, still
// please ensure we do the following:
// 1) Nobody should add any instance methods on this. Instance methods can be
//    more difficult to predict when they get optimized and they are almost
//    never inlined properly in static compilers.
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
//    always know when it is a fiber.
// 3) We might want to experiment with using numeric keys since they are easier
//    to optimize in a non-JIT environment.
// 4) We can easily go from a constructor to a createFiber object literal if that
//    is faster.
// 5) It should be easy to port this to a C struct and keep a C implementation
//    compatible.
var createFiber=function(tag,pendingProps,key,mode){// $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
return new FiberNode(tag,pendingProps,key,mode);};function shouldConstruct$1(Component){var prototype=Component.prototype;return !!(prototype&&prototype.isReactComponent);}function isSimpleFunctionComponent(type){return typeof type==='function'&&!shouldConstruct$1(type)&&type.defaultProps===undefined;}function resolveLazyComponentTag(Component){if(typeof Component==='function'){return shouldConstruct$1(Component)?ClassComponent:FunctionComponent;}else if(Component!==undefined&&Component!==null){var $$typeof=Component.$$typeof;if($$typeof===REACT_FORWARD_REF_TYPE){return ForwardRef;}if($$typeof===REACT_MEMO_TYPE){return MemoComponent;}}return IndeterminateComponent;}// This is used to create an alternate fiber to do work on.
function createWorkInProgress(current,pendingProps){var workInProgress=current.alternate;if(workInProgress===null){// We use a double buffering pooling technique because we know that we'll
// only ever need at most two versions of a tree. We pool the "other" unused
// node that we're free to reuse. This is lazily created to avoid allocating
// extra objects for things that are never updated. It also allow us to
// reclaim the extra memory if needed.
workInProgress=createFiber(current.tag,pendingProps,current.key,current.mode);workInProgress.elementType=current.elementType;workInProgress.type=current.type;workInProgress.stateNode=current.stateNode;{// DEV-only fields
workInProgress._debugSource=current._debugSource;workInProgress._debugOwner=current._debugOwner;workInProgress._debugHookTypes=current._debugHookTypes;}workInProgress.alternate=current;current.alternate=workInProgress;}else {workInProgress.pendingProps=pendingProps;// Needed because Blocks store data on type.
workInProgress.type=current.type;// We already have an alternate.
// Reset the effect tag.
workInProgress.flags=NoFlags;// The effects are no longer valid.
workInProgress.subtreeFlags=NoFlags;workInProgress.deletions=null;{// We intentionally reset, rather than copy, actualDuration & actualStartTime.
// This prevents time from endlessly accumulating in new commits.
// This has the downside of resetting values for different priority renders,
// But works for yielding (the common case) and should support resuming.
workInProgress.actualDuration=0;workInProgress.actualStartTime=-1;}}// Reset all effects except static ones.
// Static effects are not specific to a render.
workInProgress.flags=current.flags&StaticMask;workInProgress.childLanes=current.childLanes;workInProgress.lanes=current.lanes;workInProgress.child=current.child;workInProgress.memoizedProps=current.memoizedProps;workInProgress.memoizedState=current.memoizedState;workInProgress.updateQueue=current.updateQueue;// Clone the dependencies object. This is mutated during the render phase, so
// it cannot be shared with the current fiber.
var currentDependencies=current.dependencies;workInProgress.dependencies=currentDependencies===null?null:{lanes:currentDependencies.lanes,firstContext:currentDependencies.firstContext};// These will be overridden during the parent's reconciliation
workInProgress.sibling=current.sibling;workInProgress.index=current.index;workInProgress.ref=current.ref;{workInProgress.selfBaseDuration=current.selfBaseDuration;workInProgress.treeBaseDuration=current.treeBaseDuration;}{workInProgress._debugNeedsRemount=current._debugNeedsRemount;switch(workInProgress.tag){case IndeterminateComponent:case FunctionComponent:case SimpleMemoComponent:workInProgress.type=resolveFunctionForHotReloading(current.type);break;case ClassComponent:workInProgress.type=resolveClassForHotReloading(current.type);break;case ForwardRef:workInProgress.type=resolveForwardRefForHotReloading(current.type);break;}}return workInProgress;}// Used to reuse a Fiber for a second pass.
function resetWorkInProgress(workInProgress,renderLanes){// This resets the Fiber to what createFiber or createWorkInProgress would
// have set the values to before during the first pass. Ideally this wouldn't
// be necessary but unfortunately many code paths reads from the workInProgress
// when they should be reading from current and writing to workInProgress.
// We assume pendingProps, index, key, ref, return are still untouched to
// avoid doing another reconciliation.
// Reset the effect flags but keep any Placement tags, since that's something
// that child fiber is setting, not the reconciliation.
workInProgress.flags&=StaticMask|Placement;// The effects are no longer valid.
var current=workInProgress.alternate;if(current===null){// Reset to createFiber's initial values.
workInProgress.childLanes=NoLanes;workInProgress.lanes=renderLanes;workInProgress.child=null;workInProgress.subtreeFlags=NoFlags;workInProgress.memoizedProps=null;workInProgress.memoizedState=null;workInProgress.updateQueue=null;workInProgress.dependencies=null;workInProgress.stateNode=null;{// Note: We don't reset the actualTime counts. It's useful to accumulate
// actual time across multiple render passes.
workInProgress.selfBaseDuration=0;workInProgress.treeBaseDuration=0;}}else {// Reset to the cloned values that createWorkInProgress would've.
workInProgress.childLanes=current.childLanes;workInProgress.lanes=current.lanes;workInProgress.child=current.child;workInProgress.subtreeFlags=NoFlags;workInProgress.deletions=null;workInProgress.memoizedProps=current.memoizedProps;workInProgress.memoizedState=current.memoizedState;workInProgress.updateQueue=current.updateQueue;// Needed because Blocks store data on type.
workInProgress.type=current.type;// Clone the dependencies object. This is mutated during the render phase, so
// it cannot be shared with the current fiber.
var currentDependencies=current.dependencies;workInProgress.dependencies=currentDependencies===null?null:{lanes:currentDependencies.lanes,firstContext:currentDependencies.firstContext};{// Note: We don't reset the actualTime counts. It's useful to accumulate
// actual time across multiple render passes.
workInProgress.selfBaseDuration=current.selfBaseDuration;workInProgress.treeBaseDuration=current.treeBaseDuration;}}return workInProgress;}function createHostRootFiber(tag,isStrictMode,concurrentUpdatesByDefaultOverride){var mode;if(tag===ConcurrentRoot){mode=ConcurrentMode;if(isStrictMode===true){mode|=StrictLegacyMode;{mode|=StrictEffectsMode;}}}else {mode=NoMode;}if(isDevToolsPresent){// Always collect profile timings when DevTools are present.
// This enables DevTools to start capturing timing at any point–
// Without some nodes in the tree having empty base times.
mode|=ProfileMode;}return createFiber(HostRoot,null,null,mode);}function createFiberFromTypeAndProps(type,// React$ElementType
key,pendingProps,owner,mode,lanes){var fiberTag=IndeterminateComponent;// The resolved type is set if we know what the final type will be. I.e. it's not lazy.
var resolvedType=type;if(typeof type==='function'){if(shouldConstruct$1(type)){fiberTag=ClassComponent;{resolvedType=resolveClassForHotReloading(resolvedType);}}else {{resolvedType=resolveFunctionForHotReloading(resolvedType);}}}else if(typeof type==='string'){fiberTag=HostComponent;}else {getTag:switch(type){case REACT_FRAGMENT_TYPE:return createFiberFromFragment(pendingProps.children,mode,lanes,key);case REACT_STRICT_MODE_TYPE:fiberTag=Mode;mode|=StrictLegacyMode;if((mode&ConcurrentMode)!==NoMode){// Strict effects should never run on legacy roots
mode|=StrictEffectsMode;}break;case REACT_PROFILER_TYPE:return createFiberFromProfiler(pendingProps,mode,lanes,key);case REACT_SUSPENSE_TYPE:return createFiberFromSuspense(pendingProps,mode,lanes,key);case REACT_SUSPENSE_LIST_TYPE:return createFiberFromSuspenseList(pendingProps,mode,lanes,key);case REACT_OFFSCREEN_TYPE:return createFiberFromOffscreen(pendingProps,mode,lanes,key);case REACT_LEGACY_HIDDEN_TYPE:// eslint-disable-next-line no-fallthrough
case REACT_SCOPE_TYPE:// eslint-disable-next-line no-fallthrough
case REACT_CACHE_TYPE:// eslint-disable-next-line no-fallthrough
case REACT_TRACING_MARKER_TYPE:// eslint-disable-next-line no-fallthrough
case REACT_DEBUG_TRACING_MODE_TYPE:// eslint-disable-next-line no-fallthrough
default:{if(typeof type==='object'&&type!==null){switch(type.$$typeof){case REACT_PROVIDER_TYPE:fiberTag=ContextProvider;break getTag;case REACT_CONTEXT_TYPE:// This is a consumer
fiberTag=ContextConsumer;break getTag;case REACT_FORWARD_REF_TYPE:fiberTag=ForwardRef;{resolvedType=resolveForwardRefForHotReloading(resolvedType);}break getTag;case REACT_MEMO_TYPE:fiberTag=MemoComponent;break getTag;case REACT_LAZY_TYPE:fiberTag=LazyComponent;resolvedType=null;break getTag;}}var info='';{if(type===undefined||typeof type==='object'&&type!==null&&Object.keys(type).length===0){info+=' You likely forgot to export your component from the file '+"it's defined in, or you might have mixed up default and "+'named imports.';}var ownerName=owner?getComponentNameFromFiber(owner):null;if(ownerName){info+='\n\nCheck the render method of `'+ownerName+'`.';}}throw new Error('Element type is invalid: expected a string (for built-in '+'components) or a class/function (for composite components) '+("but got: "+(type==null?type:typeof type)+"."+info));}}}var fiber=createFiber(fiberTag,pendingProps,key,mode);fiber.elementType=type;fiber.type=resolvedType;fiber.lanes=lanes;{fiber._debugOwner=owner;}return fiber;}function createFiberFromElement(element,mode,lanes){var owner=null;{owner=element._owner;}var type=element.type;var key=element.key;var pendingProps=element.props;var fiber=createFiberFromTypeAndProps(type,key,pendingProps,owner,mode,lanes);{fiber._debugSource=element._source;fiber._debugOwner=element._owner;}return fiber;}function createFiberFromFragment(elements,mode,lanes,key){var fiber=createFiber(Fragment,elements,key,mode);fiber.lanes=lanes;return fiber;}function createFiberFromProfiler(pendingProps,mode,lanes,key){{if(typeof pendingProps.id!=='string'){error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.',typeof pendingProps.id);}}var fiber=createFiber(Profiler,pendingProps,key,mode|ProfileMode);fiber.elementType=REACT_PROFILER_TYPE;fiber.lanes=lanes;{fiber.stateNode={effectDuration:0,passiveEffectDuration:0};}return fiber;}function createFiberFromSuspense(pendingProps,mode,lanes,key){var fiber=createFiber(SuspenseComponent,pendingProps,key,mode);fiber.elementType=REACT_SUSPENSE_TYPE;fiber.lanes=lanes;return fiber;}function createFiberFromSuspenseList(pendingProps,mode,lanes,key){var fiber=createFiber(SuspenseListComponent,pendingProps,key,mode);fiber.elementType=REACT_SUSPENSE_LIST_TYPE;fiber.lanes=lanes;return fiber;}function createFiberFromOffscreen(pendingProps,mode,lanes,key){var fiber=createFiber(OffscreenComponent,pendingProps,key,mode);fiber.elementType=REACT_OFFSCREEN_TYPE;fiber.lanes=lanes;var primaryChildInstance={isHidden:false};fiber.stateNode=primaryChildInstance;return fiber;}function createFiberFromText(content,mode,lanes){var fiber=createFiber(HostText,content,null,mode);fiber.lanes=lanes;return fiber;}function createFiberFromHostInstanceForDeletion(){var fiber=createFiber(HostComponent,null,null,NoMode);fiber.elementType='DELETED';return fiber;}function createFiberFromDehydratedFragment(dehydratedNode){var fiber=createFiber(DehydratedFragment,null,null,NoMode);fiber.stateNode=dehydratedNode;return fiber;}function createFiberFromPortal(portal,mode,lanes){var pendingProps=portal.children!==null?portal.children:[];var fiber=createFiber(HostPortal,pendingProps,portal.key,mode);fiber.lanes=lanes;fiber.stateNode={containerInfo:portal.containerInfo,pendingChildren:null,// Used by persistent updates
implementation:portal.implementation};return fiber;}// Used for stashing WIP properties to replay failed work in DEV.
function assignFiberPropertiesInDEV(target,source){if(target===null){// This Fiber's initial properties will always be overwritten.
// We only use a Fiber to ensure the same hidden class so DEV isn't slow.
target=createFiber(IndeterminateComponent,null,null,NoMode);}// This is intentionally written as a list of all properties.
// We tried to use Object.assign() instead but this is called in
// the hottest path, and Object.assign() was too slow:
// https://github.com/facebook/react/issues/12502
// This code is DEV-only so size is not a concern.
target.tag=source.tag;target.key=source.key;target.elementType=source.elementType;target.type=source.type;target.stateNode=source.stateNode;target.return=source.return;target.child=source.child;target.sibling=source.sibling;target.index=source.index;target.ref=source.ref;target.pendingProps=source.pendingProps;target.memoizedProps=source.memoizedProps;target.updateQueue=source.updateQueue;target.memoizedState=source.memoizedState;target.dependencies=source.dependencies;target.mode=source.mode;target.flags=source.flags;target.subtreeFlags=source.subtreeFlags;target.deletions=source.deletions;target.lanes=source.lanes;target.childLanes=source.childLanes;target.alternate=source.alternate;{target.actualDuration=source.actualDuration;target.actualStartTime=source.actualStartTime;target.selfBaseDuration=source.selfBaseDuration;target.treeBaseDuration=source.treeBaseDuration;}target._debugSource=source._debugSource;target._debugOwner=source._debugOwner;target._debugNeedsRemount=source._debugNeedsRemount;target._debugHookTypes=source._debugHookTypes;return target;}function FiberRootNode(containerInfo,tag,hydrate,identifierPrefix,onRecoverableError){this.tag=tag;this.containerInfo=containerInfo;this.pendingChildren=null;this.current=null;this.pingCache=null;this.finishedWork=null;this.timeoutHandle=noTimeout;this.context=null;this.pendingContext=null;this.callbackNode=null;this.callbackPriority=NoLane;this.eventTimes=createLaneMap(NoLanes);this.expirationTimes=createLaneMap(NoTimestamp);this.pendingLanes=NoLanes;this.suspendedLanes=NoLanes;this.pingedLanes=NoLanes;this.expiredLanes=NoLanes;this.mutableReadLanes=NoLanes;this.finishedLanes=NoLanes;this.entangledLanes=NoLanes;this.entanglements=createLaneMap(NoLanes);this.identifierPrefix=identifierPrefix;this.onRecoverableError=onRecoverableError;{this.mutableSourceEagerHydrationData=null;}{this.effectDuration=0;this.passiveEffectDuration=0;}{this.memoizedUpdaters=new Set();var pendingUpdatersLaneMap=this.pendingUpdatersLaneMap=[];for(var _i=0;_i<TotalLanes;_i++){pendingUpdatersLaneMap.push(new Set());}}{switch(tag){case ConcurrentRoot:this._debugRootType=hydrate?'hydrateRoot()':'createRoot()';break;case LegacyRoot:this._debugRootType=hydrate?'hydrate()':'render()';break;}}}function createFiberRoot(containerInfo,tag,hydrate,initialChildren,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,// TODO: We have several of these arguments that are conceptually part of the
// host config, but because they are passed in at runtime, we have to thread
// them through the root constructor. Perhaps we should put them all into a
// single type, like a DynamicHostConfig that is defined by the renderer.
identifierPrefix,onRecoverableError,transitionCallbacks){var root=new FiberRootNode(containerInfo,tag,hydrate,identifierPrefix,onRecoverableError);// stateNode is any.
var uninitializedFiber=createHostRootFiber(tag,isStrictMode);root.current=uninitializedFiber;uninitializedFiber.stateNode=root;{var _initialState={element:initialChildren,isDehydrated:hydrate,cache:null,// not enabled yet
transitions:null,pendingSuspenseBoundaries:null};uninitializedFiber.memoizedState=_initialState;}initializeUpdateQueue(uninitializedFiber);return root;}var ReactVersion='18.2.0';function createPortal(children,containerInfo,// TODO: figure out the API for cross-renderer implementation.
implementation){var key=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;{checkKeyStringCoercion(key);}return {// This tag allow us to uniquely identify this as a React Portal
$$typeof:REACT_PORTAL_TYPE,key:key==null?null:''+key,children:children,containerInfo:containerInfo,implementation:implementation};}var didWarnAboutNestedUpdates;var didWarnAboutFindNodeInStrictMode;{didWarnAboutNestedUpdates=false;didWarnAboutFindNodeInStrictMode={};}function getContextForSubtree(parentComponent){if(!parentComponent){return emptyContextObject;}var fiber=get(parentComponent);var parentContext=findCurrentUnmaskedContext(fiber);if(fiber.tag===ClassComponent){var Component=fiber.type;if(isContextProvider(Component)){return processChildContext(fiber,Component,parentContext);}}return parentContext;}function findHostInstanceWithWarning(component,methodName){{var fiber=get(component);if(fiber===undefined){if(typeof component.render==='function'){throw new Error('Unable to find node on an unmounted component.');}else {var keys=Object.keys(component).join(',');throw new Error("Argument appears to not be a ReactComponent. Keys: "+keys);}}var hostFiber=findCurrentHostFiber(fiber);if(hostFiber===null){return null;}if(hostFiber.mode&StrictLegacyMode){var componentName=getComponentNameFromFiber(fiber)||'Component';if(!didWarnAboutFindNodeInStrictMode[componentName]){didWarnAboutFindNodeInStrictMode[componentName]=true;var previousFiber=current;try{setCurrentFiber(hostFiber);if(fiber.mode&StrictLegacyMode){error('%s is deprecated in StrictMode. '+'%s was passed an instance of %s which is inside StrictMode. '+'Instead, add a ref directly to the element you want to reference. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-find-node',methodName,methodName,componentName);}else {error('%s is deprecated in StrictMode. '+'%s was passed an instance of %s which renders StrictMode children. '+'Instead, add a ref directly to the element you want to reference. '+'Learn more about using refs safely here: '+'https://reactjs.org/link/strict-mode-find-node',methodName,methodName,componentName);}}finally{// Ideally this should reset to previous but this shouldn't be called in
// render and there's another warning for that anyway.
if(previousFiber){setCurrentFiber(previousFiber);}else {resetCurrentFiber();}}}}return hostFiber.stateNode;}}function createContainer(containerInfo,tag,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onRecoverableError,transitionCallbacks){var hydrate=false;var initialChildren=null;return createFiberRoot(containerInfo,tag,hydrate,initialChildren,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onRecoverableError);}function createHydrationContainer(initialChildren,// TODO: Remove `callback` when we delete legacy mode.
callback,containerInfo,tag,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onRecoverableError,transitionCallbacks){var hydrate=true;var root=createFiberRoot(containerInfo,tag,hydrate,initialChildren,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onRecoverableError);// TODO: Move this to FiberRoot constructor
root.context=getContextForSubtree(null);// Schedule the initial render. In a hydration root, this is different from
// a regular update because the initial render must match was was rendered
// on the server.
// NOTE: This update intentionally doesn't have a payload. We're only using
// the update to schedule work on the root fiber (and, for legacy roots, to
// enqueue the callback if one is provided).
var current=root.current;var eventTime=requestEventTime();var lane=requestUpdateLane(current);var update=createUpdate(eventTime,lane);update.callback=callback!==undefined&&callback!==null?callback:null;enqueueUpdate(current,update,lane);scheduleInitialHydrationOnRoot(root,lane,eventTime);return root;}function updateContainer(element,container,parentComponent,callback){{onScheduleRoot(container,element);}var current$1=container.current;var eventTime=requestEventTime();var lane=requestUpdateLane(current$1);{markRenderScheduled(lane);}var context=getContextForSubtree(parentComponent);if(container.context===null){container.context=context;}else {container.pendingContext=context;}{if(isRendering&&current!==null&&!didWarnAboutNestedUpdates){didWarnAboutNestedUpdates=true;error('Render methods should be a pure function of props and state; '+'triggering nested component updates from render is not allowed. '+'If necessary, trigger nested updates in componentDidUpdate.\n\n'+'Check the render method of %s.',getComponentNameFromFiber(current)||'Unknown');}}var update=createUpdate(eventTime,lane);// Caution: React DevTools currently depends on this property
// being called "element".
update.payload={element:element};callback=callback===undefined?null:callback;if(callback!==null){{if(typeof callback!=='function'){error('render(...): Expected the last optional `callback` argument to be a '+'function. Instead received: %s.',callback);}}update.callback=callback;}var root=enqueueUpdate(current$1,update,lane);if(root!==null){scheduleUpdateOnFiber(root,current$1,lane,eventTime);entangleTransitions(root,current$1,lane);}return lane;}function getPublicRootInstance(container){var containerFiber=container.current;if(!containerFiber.child){return null;}switch(containerFiber.child.tag){case HostComponent:return getPublicInstance(containerFiber.child.stateNode);default:return containerFiber.child.stateNode;}}function attemptSynchronousHydration$1(fiber){switch(fiber.tag){case HostRoot:{var root=fiber.stateNode;if(isRootDehydrated(root)){// Flush the first scheduled "update".
var lanes=getHighestPriorityPendingLanes(root);flushRoot(root,lanes);}break;}case SuspenseComponent:{flushSync(function(){var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){var eventTime=requestEventTime();scheduleUpdateOnFiber(root,fiber,SyncLane,eventTime);}});// If we're still blocked after this, we need to increase
// the priority of any promises resolving within this
// boundary so that they next attempt also has higher pri.
var retryLane=SyncLane;markRetryLaneIfNotHydrated(fiber,retryLane);break;}}}function markRetryLaneImpl(fiber,retryLane){var suspenseState=fiber.memoizedState;if(suspenseState!==null&&suspenseState.dehydrated!==null){suspenseState.retryLane=higherPriorityLane(suspenseState.retryLane,retryLane);}}// Increases the priority of thenables when they resolve within this boundary.
function markRetryLaneIfNotHydrated(fiber,retryLane){markRetryLaneImpl(fiber,retryLane);var alternate=fiber.alternate;if(alternate){markRetryLaneImpl(alternate,retryLane);}}function attemptContinuousHydration$1(fiber){if(fiber.tag!==SuspenseComponent){// We ignore HostRoots here because we can't increase
// their priority and they should not suspend on I/O,
// since you have to wrap anything that might suspend in
// Suspense.
return;}var lane=SelectiveHydrationLane;var root=enqueueConcurrentRenderForLane(fiber,lane);if(root!==null){var eventTime=requestEventTime();scheduleUpdateOnFiber(root,fiber,lane,eventTime);}markRetryLaneIfNotHydrated(fiber,lane);}function attemptHydrationAtCurrentPriority$1(fiber){if(fiber.tag!==SuspenseComponent){// We ignore HostRoots here because we can't increase
// their priority other than synchronously flush it.
return;}var lane=requestUpdateLane(fiber);var root=enqueueConcurrentRenderForLane(fiber,lane);if(root!==null){var eventTime=requestEventTime();scheduleUpdateOnFiber(root,fiber,lane,eventTime);}markRetryLaneIfNotHydrated(fiber,lane);}function findHostInstanceWithNoPortals(fiber){var hostFiber=findCurrentHostFiberWithNoPortals(fiber);if(hostFiber===null){return null;}return hostFiber.stateNode;}var shouldErrorImpl=function(fiber){return null;};function shouldError(fiber){return shouldErrorImpl(fiber);}var shouldSuspendImpl=function(fiber){return false;};function shouldSuspend(fiber){return shouldSuspendImpl(fiber);}var overrideHookState=null;var overrideHookStateDeletePath=null;var overrideHookStateRenamePath=null;var overrideProps=null;var overridePropsDeletePath=null;var overridePropsRenamePath=null;var scheduleUpdate=null;var setErrorHandler=null;var setSuspenseHandler=null;{var copyWithDeleteImpl=function(obj,path,index){var key=path[index];var updated=isArray(obj)?obj.slice():assign({},obj);if(index+1===path.length){if(isArray(updated)){updated.splice(key,1);}else {delete updated[key];}return updated;}// $FlowFixMe number or string is fine here
updated[key]=copyWithDeleteImpl(obj[key],path,index+1);return updated;};var copyWithDelete=function(obj,path){return copyWithDeleteImpl(obj,path,0);};var copyWithRenameImpl=function(obj,oldPath,newPath,index){var oldKey=oldPath[index];var updated=isArray(obj)?obj.slice():assign({},obj);if(index+1===oldPath.length){var newKey=newPath[index];// $FlowFixMe number or string is fine here
updated[newKey]=updated[oldKey];if(isArray(updated)){updated.splice(oldKey,1);}else {delete updated[oldKey];}}else {// $FlowFixMe number or string is fine here
updated[oldKey]=copyWithRenameImpl(// $FlowFixMe number or string is fine here
obj[oldKey],oldPath,newPath,index+1);}return updated;};var copyWithRename=function(obj,oldPath,newPath){if(oldPath.length!==newPath.length){warn('copyWithRename() expects paths of the same length');return;}else {for(var i=0;i<newPath.length-1;i++){if(oldPath[i]!==newPath[i]){warn('copyWithRename() expects paths to be the same except for the deepest key');return;}}}return copyWithRenameImpl(obj,oldPath,newPath,0);};var copyWithSetImpl=function(obj,path,index,value){if(index>=path.length){return value;}var key=path[index];var updated=isArray(obj)?obj.slice():assign({},obj);// $FlowFixMe number or string is fine here
updated[key]=copyWithSetImpl(obj[key],path,index+1,value);return updated;};var copyWithSet=function(obj,path,value){return copyWithSetImpl(obj,path,0,value);};var findHook=function(fiber,id){// For now, the "id" of stateful hooks is just the stateful hook index.
// This may change in the future with e.g. nested hooks.
var currentHook=fiber.memoizedState;while(currentHook!==null&&id>0){currentHook=currentHook.next;id--;}return currentHook;};// Support DevTools editable values for useState and useReducer.
overrideHookState=function(fiber,id,path,value){var hook=findHook(fiber,id);if(hook!==null){var newState=copyWithSet(hook.memoizedState,path,value);hook.memoizedState=newState;hook.baseState=newState;// We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps=assign({},fiber.memoizedProps);var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}}};overrideHookStateDeletePath=function(fiber,id,path){var hook=findHook(fiber,id);if(hook!==null){var newState=copyWithDelete(hook.memoizedState,path);hook.memoizedState=newState;hook.baseState=newState;// We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps=assign({},fiber.memoizedProps);var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}}};overrideHookStateRenamePath=function(fiber,id,oldPath,newPath){var hook=findHook(fiber,id);if(hook!==null){var newState=copyWithRename(hook.memoizedState,oldPath,newPath);hook.memoizedState=newState;hook.baseState=newState;// We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps=assign({},fiber.memoizedProps);var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}}};// Support DevTools props for function components, forwardRef, memo, host components, etc.
overrideProps=function(fiber,path,value){fiber.pendingProps=copyWithSet(fiber.memoizedProps,path,value);if(fiber.alternate){fiber.alternate.pendingProps=fiber.pendingProps;}var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}};overridePropsDeletePath=function(fiber,path){fiber.pendingProps=copyWithDelete(fiber.memoizedProps,path);if(fiber.alternate){fiber.alternate.pendingProps=fiber.pendingProps;}var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}};overridePropsRenamePath=function(fiber,oldPath,newPath){fiber.pendingProps=copyWithRename(fiber.memoizedProps,oldPath,newPath);if(fiber.alternate){fiber.alternate.pendingProps=fiber.pendingProps;}var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}};scheduleUpdate=function(fiber){var root=enqueueConcurrentRenderForLane(fiber,SyncLane);if(root!==null){scheduleUpdateOnFiber(root,fiber,SyncLane,NoTimestamp);}};setErrorHandler=function(newShouldErrorImpl){shouldErrorImpl=newShouldErrorImpl;};setSuspenseHandler=function(newShouldSuspendImpl){shouldSuspendImpl=newShouldSuspendImpl;};}function findHostInstanceByFiber(fiber){var hostFiber=findCurrentHostFiber(fiber);if(hostFiber===null){return null;}return hostFiber.stateNode;}function emptyFindFiberByHostInstance(instance){return null;}function getCurrentFiberForDevTools(){return current;}function injectIntoDevTools(devToolsConfig){var findFiberByHostInstance=devToolsConfig.findFiberByHostInstance;var ReactCurrentDispatcher=ReactSharedInternals.ReactCurrentDispatcher;return injectInternals({bundleType:devToolsConfig.bundleType,version:devToolsConfig.version,rendererPackageName:devToolsConfig.rendererPackageName,rendererConfig:devToolsConfig.rendererConfig,overrideHookState:overrideHookState,overrideHookStateDeletePath:overrideHookStateDeletePath,overrideHookStateRenamePath:overrideHookStateRenamePath,overrideProps:overrideProps,overridePropsDeletePath:overridePropsDeletePath,overridePropsRenamePath:overridePropsRenamePath,setErrorHandler:setErrorHandler,setSuspenseHandler:setSuspenseHandler,scheduleUpdate:scheduleUpdate,currentDispatcherRef:ReactCurrentDispatcher,findHostInstanceByFiber:findHostInstanceByFiber,findFiberByHostInstance:findFiberByHostInstance||emptyFindFiberByHostInstance,// React Refresh
findHostInstancesForRefresh:findHostInstancesForRefresh,scheduleRefresh:scheduleRefresh,scheduleRoot:scheduleRoot,setRefreshHandler:setRefreshHandler,// Enables DevTools to append owner stacks to error messages in DEV mode.
getCurrentFiber:getCurrentFiberForDevTools,// Enables DevTools to detect reconciler version rather than renderer version
// which may not match for third party renderers.
reconcilerVersion:ReactVersion});}/* global reportError */var defaultOnRecoverableError=typeof reportError==='function'?// In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError:function(error){// In older browsers and test environments, fallback to console.error.
// eslint-disable-next-line react-internal/no-production-logging
console['error'](error);};function ReactDOMRoot(internalRoot){this._internalRoot=internalRoot;}ReactDOMHydrationRoot.prototype.render=ReactDOMRoot.prototype.render=function(children){var root=this._internalRoot;if(root===null){throw new Error('Cannot update an unmounted root.');}{if(typeof arguments[1]==='function'){error('render(...): does not support the second callback argument. '+'To execute a side effect after rendering, declare it in a component body with useEffect().');}else if(isValidContainer(arguments[1])){error('You passed a container to the second argument of root.render(...). '+"You don't need to pass it again since you already passed it to create the root.");}else if(typeof arguments[1]!=='undefined'){error('You passed a second argument to root.render(...) but it only accepts '+'one argument.');}var container=root.containerInfo;if(container.nodeType!==COMMENT_NODE){var hostInstance=findHostInstanceWithNoPortals(root.current);if(hostInstance){if(hostInstance.parentNode!==container){error('render(...): It looks like the React-rendered content of the '+'root container was removed without using React. This is not '+'supported and will cause errors. Instead, call '+"root.unmount() to empty a root's container.");}}}}updateContainer(children,root,null,null);};ReactDOMHydrationRoot.prototype.unmount=ReactDOMRoot.prototype.unmount=function(){{if(typeof arguments[0]==='function'){error('unmount(...): does not support a callback argument. '+'To execute a side effect after rendering, declare it in a component body with useEffect().');}}var root=this._internalRoot;if(root!==null){this._internalRoot=null;var container=root.containerInfo;{if(isAlreadyRendering()){error('Attempted to synchronously unmount a root while React was already '+'rendering. React cannot finish unmounting the root until the '+'current render has completed, which may lead to a race condition.');}}flushSync(function(){updateContainer(null,root,null,null);});unmarkContainerAsRoot(container);}};function createRoot(container,options){if(!isValidContainer(container)){throw new Error('createRoot(...): Target container is not a DOM element.');}warnIfReactDOMContainerInDEV(container);var isStrictMode=false;var concurrentUpdatesByDefaultOverride=false;var identifierPrefix='';var onRecoverableError=defaultOnRecoverableError;if(options!==null&&options!==undefined){{if(options.hydrate){warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.');}else {if(typeof options==='object'&&options!==null&&options.$$typeof===REACT_ELEMENT_TYPE){error('You passed a JSX element to createRoot. You probably meant to '+'call root.render instead. '+'Example usage:\n\n'+'  let root = createRoot(domContainer);\n'+'  root.render(<App />);');}}}if(options.unstable_strictMode===true){isStrictMode=true;}if(options.identifierPrefix!==undefined){identifierPrefix=options.identifierPrefix;}if(options.onRecoverableError!==undefined){onRecoverableError=options.onRecoverableError;}if(options.transitionCallbacks!==undefined){options.transitionCallbacks;}}var root=createContainer(container,ConcurrentRoot,null,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onRecoverableError);markContainerAsRoot(root.current,container);var rootContainerElement=container.nodeType===COMMENT_NODE?container.parentNode:container;listenToAllSupportedEvents(rootContainerElement);return new ReactDOMRoot(root);}function ReactDOMHydrationRoot(internalRoot){this._internalRoot=internalRoot;}function scheduleHydration(target){if(target){queueExplicitHydrationTarget(target);}}ReactDOMHydrationRoot.prototype.unstable_scheduleHydration=scheduleHydration;function hydrateRoot(container,initialChildren,options){if(!isValidContainer(container)){throw new Error('hydrateRoot(...): Target container is not a DOM element.');}warnIfReactDOMContainerInDEV(container);{if(initialChildren===undefined){error('Must provide initial children as second argument to hydrateRoot. '+'Example usage: hydrateRoot(domContainer, <App />)');}}// For now we reuse the whole bag of options since they contain
// the hydration callbacks.
var hydrationCallbacks=options!=null?options:null;// TODO: Delete this option
var mutableSources=options!=null&&options.hydratedSources||null;var isStrictMode=false;var concurrentUpdatesByDefaultOverride=false;var identifierPrefix='';var onRecoverableError=defaultOnRecoverableError;if(options!==null&&options!==undefined){if(options.unstable_strictMode===true){isStrictMode=true;}if(options.identifierPrefix!==undefined){identifierPrefix=options.identifierPrefix;}if(options.onRecoverableError!==undefined){onRecoverableError=options.onRecoverableError;}}var root=createHydrationContainer(initialChildren,null,container,ConcurrentRoot,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onRecoverableError);markContainerAsRoot(root.current,container);// This can't be a comment node since hydration doesn't work on comment nodes anyway.
listenToAllSupportedEvents(container);if(mutableSources){for(var i=0;i<mutableSources.length;i++){var mutableSource=mutableSources[i];registerMutableSourceForHydration(root,mutableSource);}}return new ReactDOMHydrationRoot(root);}function isValidContainer(node){return !!(node&&(node.nodeType===ELEMENT_NODE||node.nodeType===DOCUMENT_NODE||node.nodeType===DOCUMENT_FRAGMENT_NODE||!disableCommentsAsDOMContainers));}// TODO: Remove this function which also includes comment nodes.
// We only use it in places that are currently more relaxed.
function isValidContainerLegacy(node){return !!(node&&(node.nodeType===ELEMENT_NODE||node.nodeType===DOCUMENT_NODE||node.nodeType===DOCUMENT_FRAGMENT_NODE||node.nodeType===COMMENT_NODE&&node.nodeValue===' react-mount-point-unstable '));}function warnIfReactDOMContainerInDEV(container){{if(container.nodeType===ELEMENT_NODE&&container.tagName&&container.tagName.toUpperCase()==='BODY'){error('createRoot(): Creating roots directly with document.body is '+'discouraged, since its children are often manipulated by third-party '+'scripts and browser extensions. This may lead to subtle '+'reconciliation issues. Try using a container element created '+'for your app.');}if(isContainerMarkedAsRoot(container)){if(container._reactRootContainer){error('You are calling ReactDOMClient.createRoot() on a container that was previously '+'passed to ReactDOM.render(). This is not supported.');}else {error('You are calling ReactDOMClient.createRoot() on a container that '+'has already been passed to createRoot() before. Instead, call '+'root.render() on the existing root instead if you want to update it.');}}}}var ReactCurrentOwner$3=ReactSharedInternals.ReactCurrentOwner;var topLevelUpdateWarnings;{topLevelUpdateWarnings=function(container){if(container._reactRootContainer&&container.nodeType!==COMMENT_NODE){var hostInstance=findHostInstanceWithNoPortals(container._reactRootContainer.current);if(hostInstance){if(hostInstance.parentNode!==container){error('render(...): It looks like the React-rendered content of this '+'container was removed without using React. This is not '+'supported and will cause errors. Instead, call '+'ReactDOM.unmountComponentAtNode to empty a container.');}}}var isRootRenderedBySomeReact=!!container._reactRootContainer;var rootEl=getReactRootElementInContainer(container);var hasNonRootReactChild=!!(rootEl&&getInstanceFromNode(rootEl));if(hasNonRootReactChild&&!isRootRenderedBySomeReact){error('render(...): Replacing React-rendered children with a new root '+'component. If you intended to update the children of this node, '+'you should instead have the existing children update their state '+'and render the new components instead of calling ReactDOM.render.');}if(container.nodeType===ELEMENT_NODE&&container.tagName&&container.tagName.toUpperCase()==='BODY'){error('render(): Rendering components directly into document.body is '+'discouraged, since its children are often manipulated by third-party '+'scripts and browser extensions. This may lead to subtle '+'reconciliation issues. Try rendering into a container element created '+'for your app.');}};}function getReactRootElementInContainer(container){if(!container){return null;}if(container.nodeType===DOCUMENT_NODE){return container.documentElement;}else {return container.firstChild;}}function noopOnRecoverableError(){// This isn't reachable because onRecoverableError isn't called in the
// legacy API.
}function legacyCreateRootFromDOMContainer(container,initialChildren,parentComponent,callback,isHydrationContainer){if(isHydrationContainer){if(typeof callback==='function'){var originalCallback=callback;callback=function(){var instance=getPublicRootInstance(root);originalCallback.call(instance);};}var root=createHydrationContainer(initialChildren,callback,container,LegacyRoot,null,// hydrationCallbacks
false,// isStrictMode
false,// concurrentUpdatesByDefaultOverride,
'',// identifierPrefix
noopOnRecoverableError);container._reactRootContainer=root;markContainerAsRoot(root.current,container);var rootContainerElement=container.nodeType===COMMENT_NODE?container.parentNode:container;listenToAllSupportedEvents(rootContainerElement);flushSync();return root;}else {// First clear any existing content.
var rootSibling;while(rootSibling=container.lastChild){container.removeChild(rootSibling);}if(typeof callback==='function'){var _originalCallback=callback;callback=function(){var instance=getPublicRootInstance(_root);_originalCallback.call(instance);};}var _root=createContainer(container,LegacyRoot,null,// hydrationCallbacks
false,// isStrictMode
false,// concurrentUpdatesByDefaultOverride,
'',// identifierPrefix
noopOnRecoverableError);container._reactRootContainer=_root;markContainerAsRoot(_root.current,container);var _rootContainerElement=container.nodeType===COMMENT_NODE?container.parentNode:container;listenToAllSupportedEvents(_rootContainerElement);// Initial mount should not be batched.
flushSync(function(){updateContainer(initialChildren,_root,parentComponent,callback);});return _root;}}function warnOnInvalidCallback$1(callback,callerName){{if(callback!==null&&typeof callback!=='function'){error('%s(...): Expected the last optional `callback` argument to be a '+'function. Instead received: %s.',callerName,callback);}}}function legacyRenderSubtreeIntoContainer(parentComponent,children,container,forceHydrate,callback){{topLevelUpdateWarnings(container);warnOnInvalidCallback$1(callback===undefined?null:callback,'render');}var maybeRoot=container._reactRootContainer;var root;if(!maybeRoot){// Initial mount
root=legacyCreateRootFromDOMContainer(container,children,parentComponent,callback,forceHydrate);}else {root=maybeRoot;if(typeof callback==='function'){var originalCallback=callback;callback=function(){var instance=getPublicRootInstance(root);originalCallback.call(instance);};}// Update
updateContainer(children,root,parentComponent,callback);}return getPublicRootInstance(root);}function findDOMNode(componentOrElement){{var owner=ReactCurrentOwner$3.current;if(owner!==null&&owner.stateNode!==null){var warnedAboutRefsInRender=owner.stateNode._warnedAboutRefsInRender;if(!warnedAboutRefsInRender){error('%s is accessing findDOMNode inside its render(). '+'render() should be a pure function of props and state. It should '+'never access something that requires stale data from the previous '+'render, such as refs. Move this logic to componentDidMount and '+'componentDidUpdate instead.',getComponentNameFromType(owner.type)||'A component');}owner.stateNode._warnedAboutRefsInRender=true;}}if(componentOrElement==null){return null;}if(componentOrElement.nodeType===ELEMENT_NODE){return componentOrElement;}{return findHostInstanceWithWarning(componentOrElement,'findDOMNode');}}function hydrate(element,container,callback){{error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot '+'instead. Until you switch to the new API, your app will behave as '+"if it's running React 17. Learn "+'more: https://reactjs.org/link/switch-to-createroot');}if(!isValidContainerLegacy(container)){throw new Error('Target container is not a DOM element.');}{var isModernRoot=isContainerMarkedAsRoot(container)&&container._reactRootContainer===undefined;if(isModernRoot){error('You are calling ReactDOM.hydrate() on a container that was previously '+'passed to ReactDOMClient.createRoot(). This is not supported. '+'Did you mean to call hydrateRoot(container, element)?');}}// TODO: throw or warn if we couldn't hydrate?
return legacyRenderSubtreeIntoContainer(null,element,container,true,callback);}function render(element,container,callback){{error('ReactDOM.render is no longer supported in React 18. Use createRoot '+'instead. Until you switch to the new API, your app will behave as '+"if it's running React 17. Learn "+'more: https://reactjs.org/link/switch-to-createroot');}if(!isValidContainerLegacy(container)){throw new Error('Target container is not a DOM element.');}{var isModernRoot=isContainerMarkedAsRoot(container)&&container._reactRootContainer===undefined;if(isModernRoot){error('You are calling ReactDOM.render() on a container that was previously '+'passed to ReactDOMClient.createRoot(). This is not supported. '+'Did you mean to call root.render(element)?');}}return legacyRenderSubtreeIntoContainer(null,element,container,false,callback);}function unstable_renderSubtreeIntoContainer(parentComponent,element,containerNode,callback){{error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported '+'in React 18. Consider using a portal instead. Until you switch to '+"the createRoot API, your app will behave as if it's running React "+'17. Learn more: https://reactjs.org/link/switch-to-createroot');}if(!isValidContainerLegacy(containerNode)){throw new Error('Target container is not a DOM element.');}if(parentComponent==null||!has(parentComponent)){throw new Error('parentComponent must be a valid React Component');}return legacyRenderSubtreeIntoContainer(parentComponent,element,containerNode,false,callback);}function unmountComponentAtNode(container){if(!isValidContainerLegacy(container)){throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.');}{var isModernRoot=isContainerMarkedAsRoot(container)&&container._reactRootContainer===undefined;if(isModernRoot){error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously '+'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?');}}if(container._reactRootContainer){{var rootEl=getReactRootElementInContainer(container);var renderedByDifferentReact=rootEl&&!getInstanceFromNode(rootEl);if(renderedByDifferentReact){error("unmountComponentAtNode(): The node you're attempting to unmount "+'was rendered by another copy of React.');}}// Unmount should not be batched.
flushSync(function(){legacyRenderSubtreeIntoContainer(null,null,container,false,function(){// $FlowFixMe This should probably use `delete container._reactRootContainer`
container._reactRootContainer=null;unmarkContainerAsRoot(container);});});// If you call unmountComponentAtNode twice in quick succession, you'll
// get `true` twice. That's probably fine?
return true;}else {{var _rootEl=getReactRootElementInContainer(container);var hasNonRootReactChild=!!(_rootEl&&getInstanceFromNode(_rootEl));// Check if the container itself is a React root node.
var isContainerReactRoot=container.nodeType===ELEMENT_NODE&&isValidContainerLegacy(container.parentNode)&&!!container.parentNode._reactRootContainer;if(hasNonRootReactChild){error("unmountComponentAtNode(): The node you're attempting to unmount "+'was rendered by React and is not a top-level container. %s',isContainerReactRoot?'You may have accidentally passed in a React root node instead '+'of its container.':'Instead, have the parent component update its state and '+'rerender in order to remove this component.');}}return false;}}setAttemptSynchronousHydration(attemptSynchronousHydration$1);setAttemptContinuousHydration(attemptContinuousHydration$1);setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);setGetCurrentUpdatePriority(getCurrentUpdatePriority);setAttemptHydrationAtPriority(runWithPriority);{if(typeof Map!=='function'||// $FlowIssue Flow incorrectly thinks Map has no prototype
Map.prototype==null||typeof Map.prototype.forEach!=='function'||typeof Set!=='function'||// $FlowIssue Flow incorrectly thinks Set has no prototype
Set.prototype==null||typeof Set.prototype.clear!=='function'||typeof Set.prototype.forEach!=='function'){error('React depends on Map and Set built-in types. Make sure that you load a '+'polyfill in older browsers. https://reactjs.org/link/react-polyfills');}}setRestoreImplementation(restoreControlledState$3);setBatchingImplementation(batchedUpdates$1,discreteUpdates,flushSync);function createPortal$1(children,container){var key=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(!isValidContainer(container)){throw new Error('Target container is not a DOM element.');}// TODO: pass ReactDOM portal implementation as third argument
// $FlowFixMe The Flow type is opaque but there's no way to actually create it.
return createPortal(children,container,null,key);}function renderSubtreeIntoContainer(parentComponent,element,containerNode,callback){return unstable_renderSubtreeIntoContainer(parentComponent,element,containerNode,callback);}var Internals={usingClientEntryPoint:false,// Keep in sync with ReactTestUtils.js.
// This is an array for better minification.
Events:[getInstanceFromNode,getNodeFromInstance,getFiberCurrentPropsFromNode,enqueueStateRestore,restoreStateIfNeeded,batchedUpdates$1]};function createRoot$1(container,options){{if(!Internals.usingClientEntryPoint&&!false){error('You are importing createRoot from "react-dom" which is not supported. '+'You should instead import it from "react-dom/client".');}}return createRoot(container,options);}function hydrateRoot$1(container,initialChildren,options){{if(!Internals.usingClientEntryPoint&&!false){error('You are importing hydrateRoot from "react-dom" which is not supported. '+'You should instead import it from "react-dom/client".');}}return hydrateRoot(container,initialChildren,options);}// Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.
// eslint-disable-next-line no-redeclare
function flushSync$1(fn){{if(isAlreadyRendering()){error('flushSync was called from inside a lifecycle method. React cannot '+'flush when React is already rendering. Consider moving this call to '+'a scheduler task or micro task.');}}return flushSync(fn);}var foundDevTools=injectIntoDevTools({findFiberByHostInstance:getClosestInstanceFromNode,bundleType:1,version:ReactVersion,rendererPackageName:'react-dom'});{if(!foundDevTools&&canUseDOM&&window.top===window.self){// If we're in Chrome or Firefox, provide a download link if not installed.
if(navigator.userAgent.indexOf('Chrome')>-1&&navigator.userAgent.indexOf('Edge')===-1||navigator.userAgent.indexOf('Firefox')>-1){var protocol=window.location.protocol;// Don't warn in exotic cases like chrome-extension://.
if(/^(https?|file):$/.test(protocol)){// eslint-disable-next-line react-internal/no-production-logging
console.info('%cDownload the React DevTools '+'for a better development experience: '+'https://reactjs.org/link/react-devtools'+(protocol==='file:'?'\nYou might need to use a local HTTP server (instead of file://): '+'https://reactjs.org/link/react-devtools-faq':''),'font-weight:bold');}}}}reactDom_development.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Internals;reactDom_development.createPortal=createPortal$1;reactDom_development.createRoot=createRoot$1;reactDom_development.findDOMNode=findDOMNode;reactDom_development.flushSync=flushSync$1;reactDom_development.hydrate=hydrate;reactDom_development.hydrateRoot=hydrateRoot$1;reactDom_development.render=render;reactDom_development.unmountComponentAtNode=unmountComponentAtNode;reactDom_development.unstable_batchedUpdates=batchedUpdates$1;reactDom_development.unstable_renderSubtreeIntoContainer=renderSubtreeIntoContainer;reactDom_development.version=ReactVersion;/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!=='undefined'&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop==='function'){__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());}})();}

{
  reactDom.exports = reactDom_development;
}

var reactDomExports = reactDom.exports;
var ReactDOM = /*@__PURE__*/getDefaultExportFromCjs(reactDomExports);

// Default to a dummy "batch" implementation that just runs the callback
function defaultNoopBatch(callback) {
  callback();
}
let batch = defaultNoopBatch; // Allow injecting another batching function later

const setBatch = newBatch => batch = newBatch; // Supply a getter just to skip dealing with ESM bindings

const getBatch = () => batch;

let realContext = null;
function getContext() {
  if (!realContext) {
    realContext = reactExports$1.createContext(null);
    {
      realContext.displayName = 'ReactRedux';
    }
  }
  return realContext;
}
const ReactReduxContext = /*#__PURE__*/new Proxy({}, /*#__PURE__*/new Proxy({}, {
  get(_, handler) {
    const target = getContext(); // @ts-ignore

    return (_target, ...args) => Reflect[handler](target, ...args);
  }
}));

/**
 * Hook factory, which creates a `useReduxContext` hook bound to a given context. This is a low-level
 * hook that you should usually not need to call directly.
 *
 * @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
 * @returns {Function} A `useReduxContext` hook bound to the specified context.
 */
function createReduxContextHook(context = ReactReduxContext) {
  return function useReduxContext() {
    const contextValue = reactExports$1.useContext(context);
    if (!contextValue) {
      throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
    }
    return contextValue;
  };
}
/**
 * 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 <div>{store.getState()}</div>
 * }
 */

const useReduxContext = /*#__PURE__*/createReduxContextHook();

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 `<Provider>`.
 * @returns {Function} A `useSelector` hook bound to the specified context.
 */

function createSelectorHook(context = ReactReduxContext) {
  const useReduxContext$1 = context === ReactReduxContext ? useReduxContext : createReduxContextHook(context);
  return function useSelector(selector, equalityFnOrOptions = {}) {
    const {
      equalityFn = refEquality,
      stabilityCheck = undefined,
      noopCheck = undefined
    } = typeof equalityFnOrOptions === 'function' ? {
      equalityFn: equalityFnOrOptions
    } : equalityFnOrOptions;
    {
      if (!selector) {
        throw new Error(`You must pass a selector to useSelector`);
      }
      if (typeof selector !== 'function') {
        throw new Error(`You must pass a function as a selector to useSelector`);
      }
      if (typeof equalityFn !== 'function') {
        throw new Error(`You must pass a function as an equality function to useSelector`);
      }
    }
    const {
      store,
      subscription,
      getServerState,
      stabilityCheck: globalStabilityCheck,
      noopCheck: globalNoopCheck
    } = useReduxContext$1();
    const firstRun = reactExports$1.useRef(true);
    const wrappedSelector = reactExports$1.useCallback({
      [selector.name](state) {
        const selected = selector(state);
        {
          const finalStabilityCheck = typeof stabilityCheck === 'undefined' ? globalStabilityCheck : stabilityCheck;
          if (finalStabilityCheck === 'always' || finalStabilityCheck === 'once' && firstRun.current) {
            const toCompare = selector(state);
            if (!equalityFn(selected, toCompare)) {
              console.warn('Selector ' + (selector.name || 'unknown') + ' returned a different result when called with the same parameters. This can lead to unnecessary rerenders.' + '\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization', {
                state,
                selected,
                selected2: toCompare
              });
            }
          }
          const finalNoopCheck = typeof noopCheck === 'undefined' ? globalNoopCheck : noopCheck;
          if (finalNoopCheck === 'always' || finalNoopCheck === 'once' && firstRun.current) {
            // @ts-ignore
            if (selected === state) {
              console.warn('Selector ' + (selector.name || 'unknown') + ' returned the root state when called. This can lead to unnecessary rerenders.' + '\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.');
            }
          }
          if (firstRun.current) firstRun.current = false;
        }
        return selected;
      }
    }[selector.name], [selector, globalStabilityCheck, stabilityCheck]);
    const selectedState = useSyncExternalStoreWithSelector(subscription.addNestedSub, store.getState, getServerState || store.getState, wrappedSelector, equalityFn);
    reactExports$1.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 <div>{counter}</div>
 * }
 */

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);
}

var reactIs$1 = {exports: {}};

var reactIs_development$1 = {};

/**
 * @license React
 * react-is.development.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 () {

    // ATTENTION
    // When adding new symbols to this file,
    // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
    // The Symbol used to tag the ReactElement-like types.
    var REACT_ELEMENT_TYPE = Symbol.for('react.element');
    var REACT_PORTAL_TYPE = Symbol.for('react.portal');
    var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
    var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
    var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
    var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
    var REACT_CONTEXT_TYPE = Symbol.for('react.context');
    var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context');
    var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
    var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
    var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
    var REACT_MEMO_TYPE = Symbol.for('react.memo');
    var REACT_LAZY_TYPE = Symbol.for('react.lazy');
    var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');

    // -----------------------------------------------------------------------------

    var enableScopeAPI = false; // Experimental Create Event Handle API.
    var enableCacheElement = false;
    var enableTransitionTracing = false; // No known bugs, but needs performance testing

    var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
    // stuff. Intended to enable React core members to more easily debug scheduling
    // issues in DEV builds.

    var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

    var REACT_MODULE_REFERENCE;
    {
      REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
    }
    function isValidElementType(type) {
      if (typeof type === 'string' || typeof type === 'function') {
        return true;
      } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).

      if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
        return true;
      }
      if (typeof type === 'object' && type !== null) {
        if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE ||
        // This needs to include all possible module reference object
        // types supported by any Flight configuration anywhere since
        // we don't know which Flight build this will end up being used
        // with.
        type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
          return true;
        }
      }
      return false;
    }
    function typeOf(object) {
      if (typeof object === 'object' && object !== null) {
        var $$typeof = object.$$typeof;
        switch ($$typeof) {
          case REACT_ELEMENT_TYPE:
            var type = object.type;
            switch (type) {
              case REACT_FRAGMENT_TYPE:
              case REACT_PROFILER_TYPE:
              case REACT_STRICT_MODE_TYPE:
              case REACT_SUSPENSE_TYPE:
              case REACT_SUSPENSE_LIST_TYPE:
                return type;
              default:
                var $$typeofType = type && type.$$typeof;
                switch ($$typeofType) {
                  case REACT_SERVER_CONTEXT_TYPE:
                  case REACT_CONTEXT_TYPE:
                  case REACT_FORWARD_REF_TYPE:
                  case REACT_LAZY_TYPE:
                  case REACT_MEMO_TYPE:
                  case REACT_PROVIDER_TYPE:
                    return $$typeofType;
                  default:
                    return $$typeof;
                }
            }
          case REACT_PORTAL_TYPE:
            return $$typeof;
        }
      }
      return undefined;
    }
    var ContextConsumer = REACT_CONTEXT_TYPE;
    var ContextProvider = REACT_PROVIDER_TYPE;
    var Element = REACT_ELEMENT_TYPE;
    var ForwardRef = REACT_FORWARD_REF_TYPE;
    var Fragment = REACT_FRAGMENT_TYPE;
    var Lazy = REACT_LAZY_TYPE;
    var Memo = REACT_MEMO_TYPE;
    var Portal = REACT_PORTAL_TYPE;
    var Profiler = REACT_PROFILER_TYPE;
    var StrictMode = REACT_STRICT_MODE_TYPE;
    var Suspense = REACT_SUSPENSE_TYPE;
    var SuspenseList = REACT_SUSPENSE_LIST_TYPE;
    var hasWarnedAboutDeprecatedIsAsyncMode = false;
    var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated

    function isAsyncMode(object) {
      {
        if (!hasWarnedAboutDeprecatedIsAsyncMode) {
          hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint

          console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.');
        }
      }
      return false;
    }
    function isConcurrentMode(object) {
      {
        if (!hasWarnedAboutDeprecatedIsConcurrentMode) {
          hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint

          console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.');
        }
      }
      return false;
    }
    function isContextConsumer(object) {
      return typeOf(object) === REACT_CONTEXT_TYPE;
    }
    function isContextProvider(object) {
      return typeOf(object) === REACT_PROVIDER_TYPE;
    }
    function isElement(object) {
      return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
    }
    function isForwardRef(object) {
      return typeOf(object) === REACT_FORWARD_REF_TYPE;
    }
    function isFragment(object) {
      return typeOf(object) === REACT_FRAGMENT_TYPE;
    }
    function isLazy(object) {
      return typeOf(object) === REACT_LAZY_TYPE;
    }
    function isMemo(object) {
      return typeOf(object) === REACT_MEMO_TYPE;
    }
    function isPortal(object) {
      return typeOf(object) === REACT_PORTAL_TYPE;
    }
    function isProfiler(object) {
      return typeOf(object) === REACT_PROFILER_TYPE;
    }
    function isStrictMode(object) {
      return typeOf(object) === REACT_STRICT_MODE_TYPE;
    }
    function isSuspense(object) {
      return typeOf(object) === REACT_SUSPENSE_TYPE;
    }
    function isSuspenseList(object) {
      return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
    }
    reactIs_development$1.ContextConsumer = ContextConsumer;
    reactIs_development$1.ContextProvider = ContextProvider;
    reactIs_development$1.Element = Element;
    reactIs_development$1.ForwardRef = ForwardRef;
    reactIs_development$1.Fragment = Fragment;
    reactIs_development$1.Lazy = Lazy;
    reactIs_development$1.Memo = Memo;
    reactIs_development$1.Portal = Portal;
    reactIs_development$1.Profiler = Profiler;
    reactIs_development$1.StrictMode = StrictMode;
    reactIs_development$1.Suspense = Suspense;
    reactIs_development$1.SuspenseList = SuspenseList;
    reactIs_development$1.isAsyncMode = isAsyncMode;
    reactIs_development$1.isConcurrentMode = isConcurrentMode;
    reactIs_development$1.isContextConsumer = isContextConsumer;
    reactIs_development$1.isContextProvider = isContextProvider;
    reactIs_development$1.isElement = isElement;
    reactIs_development$1.isForwardRef = isForwardRef;
    reactIs_development$1.isFragment = isFragment;
    reactIs_development$1.isLazy = isLazy;
    reactIs_development$1.isMemo = isMemo;
    reactIs_development$1.isPortal = isPortal;
    reactIs_development$1.isProfiler = isProfiler;
    reactIs_development$1.isStrictMode = isStrictMode;
    reactIs_development$1.isSuspense = isSuspense;
    reactIs_development$1.isSuspenseList = isSuspenseList;
    reactIs_development$1.isValidElementType = isValidElementType;
    reactIs_development$1.typeOf = typeOf;
  })();
}

{
  reactIs$1.exports = reactIs_development$1;
}

var reactIsExports$1 = reactIs$1.exports;
var ReactIs$2 = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports$1);

/**
 * Prints a warning in the console if it exists.
 *
 * @param {String} message The warning message.
 * @returns {void}
 */
function warning(message) {
  /* eslint-disable no-console */
  if (typeof console !== 'undefined' && typeof console.error === 'function') {
    console.error(message);
  }
  /* eslint-enable no-console */

  try {
    // This error was thrown as a convenience so that if you enable
    // "break on all exceptions" in your console,
    // it would pause the execution at this line.
    throw new Error(message);
    /* eslint-disable no-empty */
  } catch (e) {}
  /* eslint-enable no-empty */
}

function verify(selector, methodName) {
  if (!selector) {
    throw new Error(`Unexpected value for ${methodName} in connect.`);
  } else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {
    if (!Object.prototype.hasOwnProperty.call(selector, 'dependsOnOwnProps')) {
      warning(`The selector for ${methodName} of connect did not specify a value for dependsOnOwnProps.`);
    }
  }
}
function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps) {
  verify(mapStateToProps, 'mapStateToProps');
  verify(mapDispatchToProps, 'mapDispatchToProps');
  verify(mergeProps, 'mergeProps');
}

const _excluded$1K = ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"];
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, {
  areStatesEqual,
  areOwnPropsEqual,
  areStatePropsEqual
}) {
  let hasRunAtLeastOnce = false;
  let state;
  let ownProps;
  let stateProps;
  let dispatchProps;
  let mergedProps;
  function handleFirstCall(firstState, firstOwnProps) {
    state = firstState;
    ownProps = firstOwnProps;
    stateProps = mapStateToProps(state, ownProps);
    dispatchProps = mapDispatchToProps(dispatch, ownProps);
    mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
    hasRunAtLeastOnce = true;
    return mergedProps;
  }
  function handleNewPropsAndNewState() {
    stateProps = mapStateToProps(state, ownProps);
    if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
    mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
    return mergedProps;
  }
  function handleNewProps() {
    if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);
    if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
    mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
    return mergedProps;
  }
  function handleNewState() {
    const nextStateProps = mapStateToProps(state, ownProps);
    const statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);
    stateProps = nextStateProps;
    if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
    return mergedProps;
  }
  function handleSubsequentCalls(nextState, nextOwnProps) {
    const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
    const stateChanged = !areStatesEqual(nextState, state, nextOwnProps, ownProps);
    state = nextState;
    ownProps = nextOwnProps;
    if (propsChanged && stateChanged) return handleNewPropsAndNewState();
    if (propsChanged) return handleNewProps();
    if (stateChanged) return handleNewState();
    return mergedProps;
  }
  return function pureFinalPropsSelector(nextState, nextOwnProps) {
    return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);
  };
}
// TODO: Add more comments
// The selector returned by selectorFactory will memoize its results,
// allowing connect's shouldComponentUpdate to return false if final
// props have not changed.
function finalPropsSelectorFactory(dispatch, _ref) {
  let {
      initMapStateToProps,
      initMapDispatchToProps,
      initMergeProps
    } = _ref,
    options = _objectWithoutPropertiesLoose$2(_ref, _excluded$1K);
  const mapStateToProps = initMapStateToProps(dispatch, options);
  const mapDispatchToProps = initMapDispatchToProps(dispatch, options);
  const mergeProps = initMergeProps(dispatch, options);
  {
    verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps);
  }
  return pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}

function bindActionCreators(actionCreators, dispatch) {
  const boundActionCreators = {};
  for (const key in actionCreators) {
    const actionCreator = actionCreators[key];
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = (...args) => dispatch(actionCreator(...args));
    }
  }
  return boundActionCreators;
}

/**
 * @param {any} obj The object to inspect.
 * @returns {boolean} True if the argument appears to be a plain object.
 */
function isPlainObject$1(obj) {
  if (typeof obj !== 'object' || obj === null) return false;
  let proto = Object.getPrototypeOf(obj);
  if (proto === null) return true;
  let baseProto = proto;
  while (Object.getPrototypeOf(baseProto) !== null) {
    baseProto = Object.getPrototypeOf(baseProto);
  }
  return proto === baseProto;
}

function verifyPlainObject(value, displayName, methodName) {
  if (!isPlainObject$1(value)) {
    warning(`${methodName}() in ${displayName} must return a plain object. Instead received ${value}.`);
  }
}

function wrapMapToPropsConstant(
// * Note:
//  It seems that the dispatch argument
//  could be a dispatch function in some cases (ex: whenMapDispatchToPropsIsMissing)
//  and a state object in some others (ex: whenMapStateToPropsIsMissing)
// eslint-disable-next-line no-unused-vars
getConstant) {
  return function initConstantSelector(dispatch) {
    const constant = getConstant(dispatch);
    function constantSelector() {
      return constant;
    }
    constantSelector.dependsOnOwnProps = false;
    return constantSelector;
  };
} // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args
// to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine
// whether mapToProps needs to be invoked when props have changed.
//
// A length of one signals that mapToProps does not depend on props from the parent component.
// A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and
// therefore not reporting its length accurately..
// TODO Can this get pulled out so that we can subscribe directly to the store if we don't need ownProps?

function getDependsOnOwnProps(mapToProps) {
  return mapToProps.dependsOnOwnProps ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;
} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,
// this function wraps mapToProps in a proxy function which does several things:
//
//  * Detects whether the mapToProps function being called depends on props, which
//    is used by selectorFactory to decide if it should reinvoke on props changes.
//
//  * On first call, handles mapToProps if returns another function, and treats that
//    new function as the true mapToProps for subsequent calls.
//
//  * On first call, verifies the first result is a plain object, in order to warn
//    the developer that their mapToProps function is not returning a valid result.
//

function wrapMapToPropsFunc(mapToProps, methodName) {
  return function initProxySelector(dispatch, {
    displayName
  }) {
    const proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
      return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch, undefined);
    }; // allow detectFactoryAndVerify to get ownProps

    proxy.dependsOnOwnProps = true;
    proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
      proxy.mapToProps = mapToProps;
      proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
      let props = proxy(stateOrDispatch, ownProps);
      if (typeof props === 'function') {
        proxy.mapToProps = props;
        proxy.dependsOnOwnProps = getDependsOnOwnProps(props);
        props = proxy(stateOrDispatch, ownProps);
      }
      verifyPlainObject(props, displayName, methodName);
      return props;
    };
    return proxy;
  };
}

function createInvalidArgFactory(arg, name) {
  return (dispatch, options) => {
    throw new Error(`Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.`);
  };
}

function mapDispatchToPropsFactory(mapDispatchToProps) {
  return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(dispatch =>
  // @ts-ignore
  bindActionCreators(mapDispatchToProps, dispatch)) : !mapDispatchToProps ? wrapMapToPropsConstant(dispatch => ({
    dispatch
  })) : typeof mapDispatchToProps === 'function' ?
  // @ts-ignore
  wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : createInvalidArgFactory(mapDispatchToProps, 'mapDispatchToProps');
}

function mapStateToPropsFactory(mapStateToProps) {
  return !mapStateToProps ? wrapMapToPropsConstant(() => ({})) : typeof mapStateToProps === 'function' ?
  // @ts-ignore
  wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : createInvalidArgFactory(mapStateToProps, 'mapStateToProps');
}

function defaultMergeProps(stateProps, dispatchProps, ownProps) {
  // @ts-ignore
  return _extends({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
  return function initMergePropsProxy(dispatch, {
    displayName,
    areMergedPropsEqual
  }) {
    let hasRunOnce = false;
    let mergedProps;
    return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
      const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
      if (hasRunOnce) {
        if (!areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;
      } else {
        hasRunOnce = true;
        mergedProps = nextMergedProps;
        verifyPlainObject(mergedProps, displayName, 'mergeProps');
      }
      return mergedProps;
    };
  };
}
function mergePropsFactory(mergeProps) {
  return !mergeProps ? () => defaultMergeProps : typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : createInvalidArgFactory(mergeProps, 'mergeProps');
}

// 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$1 = canUseDOM ? reactExports$1.useLayoutEffect : reactExports$1.useEffect;

function is(x, y) {
  if (x === y) {
    return x !== 0 || y !== 0 || 1 / x === 1 / y;
  } else {
    return x !== x && y !== y;
  }
}
function shallowEqual(objA, objB) {
  if (is(objA, objB)) return true;
  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
    return false;
  }
  const keysA = Object.keys(objA);
  const keysB = Object.keys(objB);
  if (keysA.length !== keysB.length) return false;
  for (let i = 0; i < keysA.length; i++) {
    if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
      return false;
    }
  }
  return true;
}

const _excluded$1J = ["reactReduxForwardedRef"];
let useSyncExternalStore = notInitialized;
const initializeConnect = fn => {
  useSyncExternalStore = fn;
}; // Define some constant arrays just to avoid re-creating these
const NO_SUBSCRIPTION_ARRAY = [null, null]; // Attempts to stringify whatever not-really-a-component value we were given
// for logging in an error message

const stringifyComponent = Comp => {
  try {
    return JSON.stringify(Comp);
  } catch (err) {
    return String(Comp);
  }
};

// This is "just" a `useLayoutEffect`, but with two modifications:
// - we need to fall back to `useEffect` in SSR to avoid annoying warnings
// - we extract this to a separate function to avoid closing over values
//   and causing memory leaks
function useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) {
  useIsomorphicLayoutEffect$1(() => effectFunc(...effectArgs), dependencies);
} // Effect callback, extracted: assign the latest props values to refs for later usage

function captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps,
// actualChildProps: unknown,
childPropsFromStoreUpdate, notifyNestedSubs) {
  // We want to capture the wrapper props and child props we used for later comparisons
  lastWrapperProps.current = wrapperProps;
  renderIsScheduled.current = false; // If the render was from a store update, clear out that reference and cascade the subscriber update

  if (childPropsFromStoreUpdate.current) {
    childPropsFromStoreUpdate.current = null;
    notifyNestedSubs();
  }
} // Effect callback, extracted: subscribe to the Redux store or nearest connected ancestor,
// check for updates after dispatched actions, and trigger re-renders.

function subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs,
// forceComponentUpdateDispatch: React.Dispatch<any>,
additionalSubscribeListener) {
  // If we're not subscribed to the store, nothing to do here
  if (!shouldHandleStateChanges) return () => {}; // Capture values for checking if and when this component unmounts

  let didUnsubscribe = false;
  let lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component

  const checkForUpdates = () => {
    if (didUnsubscribe || !isMounted.current) {
      // Don't run stale listeners.
      // Redux doesn't guarantee unsubscriptions happen until next dispatch.
      return;
    } // TODO We're currently calling getState ourselves here, rather than letting `uSES` do it

    const latestStoreState = store.getState();
    let newChildProps, error;
    try {
      // Actually run the selector with the most recent store state and wrapper props
      // to determine what the child props should be
      newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current);
    } catch (e) {
      error = e;
      lastThrownError = e;
    }
    if (!error) {
      lastThrownError = null;
    } // If the child props haven't changed, nothing to do here - cascade the subscription update

    if (newChildProps === lastChildProps.current) {
      if (!renderIsScheduled.current) {
        notifyNestedSubs();
      }
    } else {
      // Save references to the new child props.  Note that we track the "child props from store update"
      // as a ref instead of a useState/useReducer because we need a way to determine if that value has
      // been processed.  If this went into useState/useReducer, we couldn't clear out the value without
      // forcing another re-render, which we don't want.
      lastChildProps.current = newChildProps;
      childPropsFromStoreUpdate.current = newChildProps;
      renderIsScheduled.current = true; // TODO This is hacky and not how `uSES` is meant to be used
      // Trigger the React `useSyncExternalStore` subscriber

      additionalSubscribeListener();
    }
  }; // Actually subscribe to the nearest connected ancestor (or store)

  subscription.onStateChange = checkForUpdates;
  subscription.trySubscribe(); // Pull data from the store after first render in case the store has
  // changed since we began.

  checkForUpdates();
  const unsubscribeWrapper = () => {
    didUnsubscribe = true;
    subscription.tryUnsubscribe();
    subscription.onStateChange = null;
    if (lastThrownError) {
      // It's possible that we caught an error due to a bad mapState function, but the
      // parent re-rendered without this component and we're about to unmount.
      // This shouldn't happen as long as we do top-down subscriptions correctly, but
      // if we ever do those wrong, this throw will surface the error in our tests.
      // In that case, throw the error from here so it doesn't get lost.
      throw lastThrownError;
    }
  };
  return unsubscribeWrapper;
} // Reducer initial state creation for our update reducer
function strictEqual(a, b) {
  return a === b;
}
/**
 * Infers the type of props that a connector will inject into a component.
 */

let hasWarnedAboutDeprecatedPureOption = false;
/**
 * Connects a React component to a Redux store.
 *
 * - Without arguments, just wraps the component, without changing the behavior / props
 *
 * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior
 * is to override ownProps (as stated in the docs), so what remains is everything that's
 * not a state or dispatch prop
 *
 * - When 3rd param is passed, we don't know if ownProps propagate and whether they
 * should be valid component props, because it depends on mergeProps implementation.
 * As such, it is the user's responsibility to extend ownProps interface from state or
 * dispatch props or both when applicable
 *
 * @param mapStateToProps A function that extracts values from state
 * @param mapDispatchToProps Setup for dispatching actions
 * @param mergeProps Optional callback to merge state and dispatch props together
 * @param options Options for configuring the connection
 *
 */

function connect(mapStateToProps, mapDispatchToProps, mergeProps, {
  // The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.
  // @ts-ignore
  pure,
  areStatesEqual = strictEqual,
  areOwnPropsEqual = shallowEqual,
  areStatePropsEqual = shallowEqual,
  areMergedPropsEqual = shallowEqual,
  // use React's forwardRef to expose a ref of the wrapped component
  forwardRef = false,
  // the context consumer to use
  context = ReactReduxContext
} = {}) {
  {
    if (pure !== undefined && !hasWarnedAboutDeprecatedPureOption) {
      hasWarnedAboutDeprecatedPureOption = true;
      warning('The `pure` option has been removed. `connect` is now always a "pure/memoized" component');
    }
  }
  const Context = context;
  const initMapStateToProps = mapStateToPropsFactory(mapStateToProps);
  const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps);
  const initMergeProps = mergePropsFactory(mergeProps);
  const shouldHandleStateChanges = Boolean(mapStateToProps);
  const wrapWithConnect = WrappedComponent => {
    if (!reactIsExports$1.isValidElementType(WrappedComponent)) {
      throw new Error(`You must pass a component to the function returned by connect. Instead received ${stringifyComponent(WrappedComponent)}`);
    }
    const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
    const displayName = `Connect(${wrappedComponentName})`;
    const selectorFactoryOptions = {
      shouldHandleStateChanges,
      displayName,
      wrappedComponentName,
      WrappedComponent,
      // @ts-ignore
      initMapStateToProps,
      // @ts-ignore
      initMapDispatchToProps,
      initMergeProps,
      areStatesEqual,
      areStatePropsEqual,
      areOwnPropsEqual,
      areMergedPropsEqual
    };
    function ConnectFunction(props) {
      const [propsContext, reactReduxForwardedRef, wrapperProps] = reactExports$1.useMemo(() => {
        // Distinguish between actual "data" props that were passed to the wrapper component,
        // and values needed to control behavior (forwarded refs, alternate context instances).
        // To maintain the wrapperProps object reference, memoize this destructuring.
        const {
            reactReduxForwardedRef
          } = props,
          wrapperProps = _objectWithoutPropertiesLoose$2(props, _excluded$1J);
        return [props.context, reactReduxForwardedRef, wrapperProps];
      }, [props]);
      const ContextToUse = reactExports$1.useMemo(() => {
        // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.
        // Memoize the check that determines which context instance we should use.
        return propsContext && propsContext.Consumer &&
        // @ts-ignore
        reactIsExports$1.isContextConsumer( /*#__PURE__*/React.createElement(propsContext.Consumer, null)) ? propsContext : Context;
      }, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available

      const contextValue = reactExports$1.useContext(ContextToUse); // The store _must_ exist as either a prop or in context.
      // We'll check to see if it _looks_ like a Redux store first.
      // This allows us to pass through a `store` prop that is just a plain value.

      const didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch);
      const didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);
      if (!didStoreComeFromProps && !didStoreComeFromContext) {
        throw new Error(`Could not find "store" in the context of ` + `"${displayName}". Either wrap the root component in a <Provider>, ` + `or pass a custom React context provider to <Provider> and the corresponding ` + `React context consumer to ${displayName} in connect options.`);
      } // Based on the previous check, one of these must be true

      const store = didStoreComeFromProps ? props.store : contextValue.store;
      const getServerState = didStoreComeFromContext ? contextValue.getServerState : store.getState;
      const childPropsSelector = reactExports$1.useMemo(() => {
        // The child props selector needs the store reference as an input.
        // Re-create this selector whenever the store changes.
        return finalPropsSelectorFactory(store.dispatch, selectorFactoryOptions);
      }, [store]);
      const [subscription, notifyNestedSubs] = reactExports$1.useMemo(() => {
        if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; // This Subscription's source should match where store came from: props vs. context. A component
        // connected to the store via props shouldn't use subscription from context, or vice versa.

        const subscription = createSubscription(store, didStoreComeFromProps ? undefined : contextValue.subscription); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
        // the middle of the notification loop, where `subscription` will then be null. This can
        // probably be avoided if Subscription's listeners logic is changed to not call listeners
        // that have been unsubscribed in the  middle of the notification loop.

        const notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription);
        return [subscription, notifyNestedSubs];
      }, [store, didStoreComeFromProps, contextValue]); // Determine what {store, subscription} value should be put into nested context, if necessary,
      // and memoize that value to avoid unnecessary context updates.

      const overriddenContextValue = reactExports$1.useMemo(() => {
        if (didStoreComeFromProps) {
          // This component is directly subscribed to a store from props.
          // We don't want descendants reading from this store - pass down whatever
          // the existing context value is from the nearest connected ancestor.
          return contextValue;
        } // Otherwise, put this component's subscription instance into context, so that
        // connected descendants won't update until after this component is done

        return _extends({}, contextValue, {
          subscription
        });
      }, [didStoreComeFromProps, contextValue, subscription]); // Set up refs to coordinate values between the subscription effect and the render logic

      const lastChildProps = reactExports$1.useRef();
      const lastWrapperProps = reactExports$1.useRef(wrapperProps);
      const childPropsFromStoreUpdate = reactExports$1.useRef();
      const renderIsScheduled = reactExports$1.useRef(false);
      reactExports$1.useRef(false);
      const isMounted = reactExports$1.useRef(false);
      const latestSubscriptionCallbackError = reactExports$1.useRef();
      useIsomorphicLayoutEffect$1(() => {
        isMounted.current = true;
        return () => {
          isMounted.current = false;
        };
      }, []);
      const actualChildPropsSelector = reactExports$1.useMemo(() => {
        const selector = () => {
          // Tricky logic here:
          // - This render may have been triggered by a Redux store update that produced new child props
          // - However, we may have gotten new wrapper props after that
          // If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
          // But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
          // So, we'll use the child props from store update only if the wrapper props are the same as last time.
          if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {
            return childPropsFromStoreUpdate.current;
          } // TODO We're reading the store directly in render() here. Bad idea?
          // This will likely cause Bad Things (TM) to happen in Concurrent Mode.
          // Note that we do this because on renders _not_ caused by store updates, we need the latest store state
          // to determine what the child props should be.

          return childPropsSelector(store.getState(), wrapperProps);
        };
        return selector;
      }, [store, wrapperProps]); // We need this to execute synchronously every time we re-render. However, React warns
      // about useLayoutEffect in SSR, so we try to detect environment and fall back to
      // just useEffect instead to avoid the warning, since neither will run anyway.

      const subscribeForReact = reactExports$1.useMemo(() => {
        const subscribe = reactListener => {
          if (!subscription) {
            return () => {};
          }
          return subscribeUpdates(shouldHandleStateChanges, store, subscription,
          // @ts-ignore
          childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, reactListener);
        };
        return subscribe;
      }, [subscription]);
      useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs]);
      let actualChildProps;
      try {
        actualChildProps = useSyncExternalStore(
        // TODO We're passing through a big wrapper that does a bunch of extra side effects besides subscribing
        subscribeForReact,
        // TODO This is incredibly hacky. We've already processed the store update and calculated new child props,
        // TODO and we're just passing that through so it triggers a re-render for us rather than relying on `uSES`.
        actualChildPropsSelector, getServerState ? () => childPropsSelector(getServerState(), wrapperProps) : actualChildPropsSelector);
      } catch (err) {
        if (latestSubscriptionCallbackError.current) {
          err.message += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n`;
        }
        throw err;
      }
      useIsomorphicLayoutEffect$1(() => {
        latestSubscriptionCallbackError.current = undefined;
        childPropsFromStoreUpdate.current = undefined;
        lastChildProps.current = actualChildProps;
      }); // Now that all that's done, we can finally try to actually render the child component.
      // We memoize the elements for the rendered child component as an optimization.

      const renderedWrappedComponent = reactExports$1.useMemo(() => {
        return /*#__PURE__*/(
          // @ts-ignore
          React.createElement(WrappedComponent, _extends({}, actualChildProps, {
            ref: reactReduxForwardedRef
          }))
        );
      }, [reactReduxForwardedRef, WrappedComponent, actualChildProps]); // If React sees the exact same element reference as last time, it bails out of re-rendering
      // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.

      const renderedChild = reactExports$1.useMemo(() => {
        if (shouldHandleStateChanges) {
          // If this component is subscribed to store updates, we need to pass its own
          // subscription instance down to our descendants. That means rendering the same
          // Context instance, and putting a different value into the context.
          return /*#__PURE__*/React.createElement(ContextToUse.Provider, {
            value: overriddenContextValue
          }, renderedWrappedComponent);
        }
        return renderedWrappedComponent;
      }, [ContextToUse, renderedWrappedComponent, overriddenContextValue]);
      return renderedChild;
    }
    const _Connect = React.memo(ConnectFunction);

    // Add a hacky cast to get the right output type
    const Connect = _Connect;
    Connect.WrappedComponent = WrappedComponent;
    Connect.displayName = ConnectFunction.displayName = displayName;
    if (forwardRef) {
      const _forwarded = React.forwardRef(function forwardConnectRef(props, ref) {
        // @ts-ignore
        return /*#__PURE__*/React.createElement(Connect, _extends({}, props, {
          reactReduxForwardedRef: ref
        }));
      });
      const forwarded = _forwarded;
      forwarded.displayName = displayName;
      forwarded.WrappedComponent = WrappedComponent;
      return hoistNonReactStatics$1$1(forwarded, WrappedComponent);
    }
    return hoistNonReactStatics$1$1(Connect, WrappedComponent);
  };
  return wrapWithConnect;
}

function Provider({
  store,
  context,
  children,
  serverState,
  stabilityCheck = 'once',
  noopCheck = 'once'
}) {
  const contextValue = reactExports$1.useMemo(() => {
    const subscription = createSubscription(store);
    return {
      store,
      subscription,
      getServerState: serverState ? () => serverState : undefined,
      stabilityCheck,
      noopCheck
    };
  }, [store, serverState, stabilityCheck, noopCheck]);
  const previousState = reactExports$1.useMemo(() => store.getState(), [store]);
  useIsomorphicLayoutEffect$1(() => {
    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 `<Provider>`.
 * @returns {Function} A `useStore` hook bound to the specified context.
 */

function createStoreHook(context = ReactReduxContext) {
  const useReduxContext$1 =
  // @ts-ignore
  context === ReactReduxContext ? useReduxContext :
  // @ts-ignore
  createReduxContextHook(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 <div>{store.getState()}</div>
 * }
 */

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 `<Provider>`.
 * @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 (
 *     <div>
 *       <span>{value}</span>
 *       <button onClick={increaseCounter}>Increase counter</button>
 *     </div>
 *   )
 * }
 */

const useDispatch = /*#__PURE__*/createDispatchHook();

// The primary entry point assumes we're working with standard ReactDOM/RN, but
// older versions that do not include `useSyncExternalStore` (React 16.9 - 17.x).
// Because of that, the useSyncExternalStore compat shim is needed.
initializeUseSelector(withSelectorExports.useSyncExternalStoreWithSelector);
initializeConnect(shimExports.useSyncExternalStore); // Enable batched updates in our subscriptions for use
// with standard React renderers (ReactDOM, React Native)

setBatch(reactDomExports.unstable_batchedUpdates);

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var __assign$3 = function () {
  __assign$3 = Object.assign || function __assign(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign$3.apply(this, arguments);
};

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var __assign$2 = function () {
  __assign$2 = Object.assign || function __assign(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign$2.apply(this, arguments);
};

function dotCase(input, options) {
  if (options === void 0) {
    options = {};
  }
  return noCase(input, __assign$2({
    delimiter: "."
  }, options));
}

function paramCase(input, options) {
  if (options === void 0) {
    options = {};
  }
  return dotCase(input, __assign$3({
    delimiter: "-"
  }, options));
}

var propTypes = {exports: {}};

var reactIs = {exports: {}};

var reactIs_development = {};

/** @license React v16.13.1
 * react-is.development.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 () {

    // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
    // nor polyfill, then a plain number is used for performance.
    var hasSymbol = typeof Symbol === 'function' && Symbol.for;
    var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
    var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
    var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
    var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
    var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
    var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
    var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
    // (unstable) APIs that have been removed. Can we remove the symbols?

    var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
    var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
    var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
    var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
    var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
    var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
    var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
    var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
    var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
    var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
    var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
    function isValidElementType(type) {
      return typeof type === 'string' || typeof type === 'function' ||
      // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
      type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
    }
    function typeOf(object) {
      if (typeof object === 'object' && object !== null) {
        var $$typeof = object.$$typeof;
        switch ($$typeof) {
          case REACT_ELEMENT_TYPE:
            var type = object.type;
            switch (type) {
              case REACT_ASYNC_MODE_TYPE:
              case REACT_CONCURRENT_MODE_TYPE:
              case REACT_FRAGMENT_TYPE:
              case REACT_PROFILER_TYPE:
              case REACT_STRICT_MODE_TYPE:
              case REACT_SUSPENSE_TYPE:
                return type;
              default:
                var $$typeofType = type && type.$$typeof;
                switch ($$typeofType) {
                  case REACT_CONTEXT_TYPE:
                  case REACT_FORWARD_REF_TYPE:
                  case REACT_LAZY_TYPE:
                  case REACT_MEMO_TYPE:
                  case REACT_PROVIDER_TYPE:
                    return $$typeofType;
                  default:
                    return $$typeof;
                }
            }
          case REACT_PORTAL_TYPE:
            return $$typeof;
        }
      }
      return undefined;
    } // AsyncMode is deprecated along with isAsyncMode

    var AsyncMode = REACT_ASYNC_MODE_TYPE;
    var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
    var ContextConsumer = REACT_CONTEXT_TYPE;
    var ContextProvider = REACT_PROVIDER_TYPE;
    var Element = REACT_ELEMENT_TYPE;
    var ForwardRef = REACT_FORWARD_REF_TYPE;
    var Fragment = REACT_FRAGMENT_TYPE;
    var Lazy = REACT_LAZY_TYPE;
    var Memo = REACT_MEMO_TYPE;
    var Portal = REACT_PORTAL_TYPE;
    var Profiler = REACT_PROFILER_TYPE;
    var StrictMode = REACT_STRICT_MODE_TYPE;
    var Suspense = REACT_SUSPENSE_TYPE;
    var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated

    function isAsyncMode(object) {
      {
        if (!hasWarnedAboutDeprecatedIsAsyncMode) {
          hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint

          console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
        }
      }
      return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
    }
    function isConcurrentMode(object) {
      return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
    }
    function isContextConsumer(object) {
      return typeOf(object) === REACT_CONTEXT_TYPE;
    }
    function isContextProvider(object) {
      return typeOf(object) === REACT_PROVIDER_TYPE;
    }
    function isElement(object) {
      return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
    }
    function isForwardRef(object) {
      return typeOf(object) === REACT_FORWARD_REF_TYPE;
    }
    function isFragment(object) {
      return typeOf(object) === REACT_FRAGMENT_TYPE;
    }
    function isLazy(object) {
      return typeOf(object) === REACT_LAZY_TYPE;
    }
    function isMemo(object) {
      return typeOf(object) === REACT_MEMO_TYPE;
    }
    function isPortal(object) {
      return typeOf(object) === REACT_PORTAL_TYPE;
    }
    function isProfiler(object) {
      return typeOf(object) === REACT_PROFILER_TYPE;
    }
    function isStrictMode(object) {
      return typeOf(object) === REACT_STRICT_MODE_TYPE;
    }
    function isSuspense(object) {
      return typeOf(object) === REACT_SUSPENSE_TYPE;
    }
    reactIs_development.AsyncMode = AsyncMode;
    reactIs_development.ConcurrentMode = ConcurrentMode;
    reactIs_development.ContextConsumer = ContextConsumer;
    reactIs_development.ContextProvider = ContextProvider;
    reactIs_development.Element = Element;
    reactIs_development.ForwardRef = ForwardRef;
    reactIs_development.Fragment = Fragment;
    reactIs_development.Lazy = Lazy;
    reactIs_development.Memo = Memo;
    reactIs_development.Portal = Portal;
    reactIs_development.Profiler = Profiler;
    reactIs_development.StrictMode = StrictMode;
    reactIs_development.Suspense = Suspense;
    reactIs_development.isAsyncMode = isAsyncMode;
    reactIs_development.isConcurrentMode = isConcurrentMode;
    reactIs_development.isContextConsumer = isContextConsumer;
    reactIs_development.isContextProvider = isContextProvider;
    reactIs_development.isElement = isElement;
    reactIs_development.isForwardRef = isForwardRef;
    reactIs_development.isFragment = isFragment;
    reactIs_development.isLazy = isLazy;
    reactIs_development.isMemo = isMemo;
    reactIs_development.isPortal = isPortal;
    reactIs_development.isProfiler = isProfiler;
    reactIs_development.isStrictMode = isStrictMode;
    reactIs_development.isSuspense = isSuspense;
    reactIs_development.isValidElementType = isValidElementType;
    reactIs_development.typeOf = typeOf;
  })();
}

{
  reactIs.exports = reactIs_development;
}

var reactIsExports = reactIs.exports;

/*
object-assign
(c) Sindre Sorhus
@license MIT
*/

/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
  if (val === null || val === undefined) {
    throw new TypeError('Object.assign cannot be called with null or undefined');
  }
  return Object(val);
}
function shouldUseNative() {
  try {
    if (!Object.assign) {
      return false;
    }

    // Detect buggy property enumeration order in older V8 versions.

    // https://bugs.chromium.org/p/v8/issues/detail?id=4118
    var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
    test1[5] = 'de';
    if (Object.getOwnPropertyNames(test1)[0] === '5') {
      return false;
    }

    // https://bugs.chromium.org/p/v8/issues/detail?id=3056
    var test2 = {};
    for (var i = 0; i < 10; i++) {
      test2['_' + String.fromCharCode(i)] = i;
    }
    var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
      return test2[n];
    });
    if (order2.join('') !== '0123456789') {
      return false;
    }

    // https://bugs.chromium.org/p/v8/issues/detail?id=3056
    var test3 = {};
    'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
      test3[letter] = letter;
    });
    if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
      return false;
    }
    return true;
  } catch (err) {
    // We don't expect any of the above to throw, but better to be safe.
    return false;
  }
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  var from;
  var to = toObject(target);
  var symbols;
  for (var s = 1; s < arguments.length; s++) {
    from = Object(arguments[s]);
    for (var key in from) {
      if (hasOwnProperty$1.call(from, key)) {
        to[key] = from[key];
      }
    }
    if (getOwnPropertySymbols) {
      symbols = getOwnPropertySymbols(from);
      for (var i = 0; i < symbols.length; i++) {
        if (propIsEnumerable.call(from, symbols[i])) {
          to[symbols[i]] = from[symbols[i]];
        }
      }
    }
  }
  return to;
};

/**
 * 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$2 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$2;

var has$2 = Function.call.bind(Object.prototype.hasOwnProperty);

/**
 * 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 printWarning$1 = function () {};
{
  var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
  var loggedTypeFailures = {};
  var has$1 = has$2;
  printWarning$1 = function (text) {
    var message = 'Warning: ' + text;
    if (typeof console !== 'undefined') {
      console.error(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {/**/}
  };
}

/**
 * Assert that the values match with the type specs.
 * Error messages are memorized and will only be shown once.
 *
 * @param {object} typeSpecs Map of name to a ReactPropType
 * @param {object} values Runtime values that need to be type-checked
 * @param {string} location e.g. "prop", "context", "child context"
 * @param {string} componentName Name of the component for error messages.
 * @param {?Function} getStack Returns the component stack.
 * @private
 */
function checkPropTypes$1(typeSpecs, values, location, componentName, getStack) {
  {
    for (var typeSpecName in typeSpecs) {
      if (has$1(typeSpecs, typeSpecName)) {
        var error;
        // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.
        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
            err.name = 'Invariant Violation';
            throw err;
          }
          error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
        } catch (ex) {
          error = ex;
        }
        if (error && !(error instanceof Error)) {
          printWarning$1((componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).');
        }
        if (error instanceof Error && !(error.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error.message] = true;
          var stack = getStack ? getStack() : '';
          printWarning$1('Failed ' + location + ' type: ' + error.message + (stack != null ? stack : ''));
        }
      }
    }
  }
}

/**
 * Resets warning cache when testing.
 *
 * @private
 */
checkPropTypes$1.resetWarningCache = function () {
  {
    loggedTypeFailures = {};
  }
};
var checkPropTypes_1 = checkPropTypes$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 ReactIs$1 = reactIsExports;
var assign$1 = objectAssign;
var ReactPropTypesSecret = ReactPropTypesSecret_1;
var has = has$2;
var checkPropTypes = checkPropTypes_1;
var printWarning = function () {};
{
  printWarning = function (text) {
    var message = 'Warning: ' + text;
    if (typeof console !== 'undefined') {
      console.error(message);
    }
    try {
      // --- Welcome to debugging React ---
      // This error was thrown as a convenience so that you can use this stack
      // to find the callsite that caused this warning to fire.
      throw new Error(message);
    } catch (x) {}
  };
}
function emptyFunctionThatReturnsNull() {
  return null;
}
var factoryWithTypeCheckers = function (isValidElement, throwOnDirectAccess) {
  /* global Symbol */
  var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.

  /**
   * Returns the iterator method function contained on the iterable object.
   *
   * Be sure to invoke the function with the iterable as context:
   *
   *     var iteratorFn = getIteratorFn(myIterable);
   *     if (iteratorFn) {
   *       var iterator = iteratorFn.call(myIterable);
   *       ...
   *     }
   *
   * @param {?object} maybeIterable
   * @return {?function}
   */
  function getIteratorFn(maybeIterable) {
    var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
    if (typeof iteratorFn === 'function') {
      return iteratorFn;
    }
  }

  /**
   * Collection of methods that allow declaration and validation of props that are
   * supplied to React components. Example usage:
   *
   *   var Props = require('ReactPropTypes');
   *   var MyArticle = React.createClass({
   *     propTypes: {
   *       // An optional string prop named "description".
   *       description: Props.string,
   *
   *       // A required enum prop named "category".
   *       category: Props.oneOf(['News','Photos']).isRequired,
   *
   *       // A prop named "dialog" that requires an instance of Dialog.
   *       dialog: Props.instanceOf(Dialog).isRequired
   *     },
   *     render: function() { ... }
   *   });
   *
   * A more formal specification of how these methods are used:
   *
   *   type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
   *   decl := ReactPropTypes.{type}(.isRequired)?
   *
   * Each and every declaration produces a function with the same signature. This
   * allows the creation of custom validation functions. For example:
   *
   *  var MyLink = React.createClass({
   *    propTypes: {
   *      // An optional string or URI prop named "href".
   *      href: function(props, propName, componentName) {
   *        var propValue = props[propName];
   *        if (propValue != null && typeof propValue !== 'string' &&
   *            !(propValue instanceof URI)) {
   *          return new Error(
   *            'Expected a string or an URI for ' + propName + ' in ' +
   *            componentName
   *          );
   *        }
   *      }
   *    },
   *    render: function() {...}
   *  });
   *
   * @internal
   */

  var ANONYMOUS = '<<anonymous>>';

  // Important!
  // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
  var ReactPropTypes = {
    array: createPrimitiveTypeChecker('array'),
    bigint: createPrimitiveTypeChecker('bigint'),
    bool: createPrimitiveTypeChecker('boolean'),
    func: createPrimitiveTypeChecker('function'),
    number: createPrimitiveTypeChecker('number'),
    object: createPrimitiveTypeChecker('object'),
    string: createPrimitiveTypeChecker('string'),
    symbol: createPrimitiveTypeChecker('symbol'),
    any: createAnyTypeChecker(),
    arrayOf: createArrayOfTypeChecker,
    element: createElementTypeChecker(),
    elementType: createElementTypeTypeChecker(),
    instanceOf: createInstanceTypeChecker,
    node: createNodeChecker(),
    objectOf: createObjectOfTypeChecker,
    oneOf: createEnumTypeChecker,
    oneOfType: createUnionTypeChecker,
    shape: createShapeTypeChecker,
    exact: createStrictShapeTypeChecker
  };

  /**
   * inlined Object.is polyfill to avoid requiring consumers ship their own
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
   */
  /*eslint-disable no-self-compare*/
  function is(x, y) {
    // SameValue algorithm
    if (x === y) {
      // Steps 1-5, 7-10
      // Steps 6.b-6.e: +0 != -0
      return x !== 0 || 1 / x === 1 / y;
    } else {
      // Step 6.a: NaN == NaN
      return x !== x && y !== y;
    }
  }
  /*eslint-enable no-self-compare*/

  /**
   * We use an Error-like object for backward compatibility as people may call
   * PropTypes directly and inspect their output. However, we don't use real
   * Errors anymore. We don't inspect their stack anyway, and creating them
   * is prohibitively expensive if they are created too often, such as what
   * happens in oneOfType() for any type before the one that matched.
   */
  function PropTypeError(message, data) {
    this.message = message;
    this.data = data && typeof data === 'object' ? data : {};
    this.stack = '';
  }
  // Make `instanceof Error` still work for returned errors.
  PropTypeError.prototype = Error.prototype;
  function createChainableTypeChecker(validate) {
    {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }
    function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
      componentName = componentName || ANONYMOUS;
      propFullName = propFullName || propName;
      if (secret !== ReactPropTypesSecret) {
        if (throwOnDirectAccess) {
          // New behavior only for users of `prop-types` package
          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;
        } else if (typeof console !== 'undefined') {
          // Old behavior for people using React.PropTypes
          var cacheKey = componentName + ':' + propName;
          if (!manualPropTypeCallCache[cacheKey] &&
          // Avoid spamming the console because they are often not actionable except for lib authors
          manualPropTypeWarningCount < 3) {
            printWarning('You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.');
            manualPropTypeCallCache[cacheKey] = true;
            manualPropTypeWarningCount++;
          }
        }
      }
      if (props[propName] == null) {
        if (isRequired) {
          if (props[propName] === null) {
            return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
          }
          return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
        }
        return null;
      } else {
        return validate(props, propName, componentName, location, propFullName);
      }
    }
    var chainedCheckType = checkType.bind(null, false);
    chainedCheckType.isRequired = checkType.bind(null, true);
    return chainedCheckType;
  }
  function createPrimitiveTypeChecker(expectedType) {
    function validate(props, propName, componentName, location, propFullName, secret) {
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== expectedType) {
        // `propValue` being instance of, say, date/regexp, pass the 'object'
        // check, but we can offer a more precise error message here rather than
        // 'of type `object`'.
        var preciseType = getPreciseType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'), {
          expectedType: expectedType
        });
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createAnyTypeChecker() {
    return createChainableTypeChecker(emptyFunctionThatReturnsNull);
  }
  function createArrayOfTypeChecker(typeChecker) {
    function validate(props, propName, componentName, location, propFullName) {
      if (typeof typeChecker !== 'function') {
        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
      }
      var propValue = props[propName];
      if (!Array.isArray(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
      }
      for (var i = 0; i < propValue.length; i++) {
        var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
        if (error instanceof Error) {
          return error;
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createElementTypeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      if (!isValidElement(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createElementTypeTypeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      if (!ReactIs$1.isValidElementType(propValue)) {
        var propType = getPropType(propValue);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createInstanceTypeChecker(expectedClass) {
    function validate(props, propName, componentName, location, propFullName) {
      if (!(props[propName] instanceof expectedClass)) {
        var expectedClassName = expectedClass.name || ANONYMOUS;
        var actualClassName = getClassName(props[propName]);
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createEnumTypeChecker(expectedValues) {
    if (!Array.isArray(expectedValues)) {
      {
        if (arguments.length > 1) {
          printWarning('Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).');
        } else {
          printWarning('Invalid argument supplied to oneOf, expected an array.');
        }
      }
      return emptyFunctionThatReturnsNull;
    }
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      for (var i = 0; i < expectedValues.length; i++) {
        if (is(propValue, expectedValues[i])) {
          return null;
        }
      }
      var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
        var type = getPreciseType(value);
        if (type === 'symbol') {
          return String(value);
        }
        return value;
      });
      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
    }
    return createChainableTypeChecker(validate);
  }
  function createObjectOfTypeChecker(typeChecker) {
    function validate(props, propName, componentName, location, propFullName) {
      if (typeof typeChecker !== 'function') {
        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
      }
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
      }
      for (var key in propValue) {
        if (has(propValue, key)) {
          var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
          if (error instanceof Error) {
            return error;
          }
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createUnionTypeChecker(arrayOfTypeCheckers) {
    if (!Array.isArray(arrayOfTypeCheckers)) {
      printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') ;
      return emptyFunctionThatReturnsNull;
    }
    for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
      var checker = arrayOfTypeCheckers[i];
      if (typeof checker !== 'function') {
        printWarning('Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.');
        return emptyFunctionThatReturnsNull;
      }
    }
    function validate(props, propName, componentName, location, propFullName) {
      var expectedTypes = [];
      for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
        var checker = arrayOfTypeCheckers[i];
        var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
        if (checkerResult == null) {
          return null;
        }
        if (checkerResult.data && has(checkerResult.data, 'expectedType')) {
          expectedTypes.push(checkerResult.data.expectedType);
        }
      }
      var expectedTypesMessage = expectedTypes.length > 0 ? ', expected one of type [' + expectedTypes.join(', ') + ']' : '';
      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.'));
    }
    return createChainableTypeChecker(validate);
  }
  function createNodeChecker() {
    function validate(props, propName, componentName, location, propFullName) {
      if (!isNode(props[propName])) {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function invalidValidatorError(componentName, location, propFullName, key, type) {
    return new PropTypeError((componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + type + '`.');
  }
  function createShapeTypeChecker(shapeTypes) {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
      }
      for (var key in shapeTypes) {
        var checker = shapeTypes[key];
        if (typeof checker !== 'function') {
          return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
        }
        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
        if (error) {
          return error;
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function createStrictShapeTypeChecker(shapeTypes) {
    function validate(props, propName, componentName, location, propFullName) {
      var propValue = props[propName];
      var propType = getPropType(propValue);
      if (propType !== 'object') {
        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
      }
      // We need to check all keys in case some are required but missing from props.
      var allKeys = assign$1({}, props[propName], shapeTypes);
      for (var key in allKeys) {
        var checker = shapeTypes[key];
        if (has(shapeTypes, key) && typeof checker !== 'function') {
          return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
        }
        if (!checker) {
          return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, '  ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, '  '));
        }
        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
        if (error) {
          return error;
        }
      }
      return null;
    }
    return createChainableTypeChecker(validate);
  }
  function isNode(propValue) {
    switch (typeof propValue) {
      case 'number':
      case 'string':
      case 'undefined':
        return true;
      case 'boolean':
        return !propValue;
      case 'object':
        if (Array.isArray(propValue)) {
          return propValue.every(isNode);
        }
        if (propValue === null || isValidElement(propValue)) {
          return true;
        }
        var iteratorFn = getIteratorFn(propValue);
        if (iteratorFn) {
          var iterator = iteratorFn.call(propValue);
          var step;
          if (iteratorFn !== propValue.entries) {
            while (!(step = iterator.next()).done) {
              if (!isNode(step.value)) {
                return false;
              }
            }
          } else {
            // Iterator will provide entry [k,v] tuples rather than values.
            while (!(step = iterator.next()).done) {
              var entry = step.value;
              if (entry) {
                if (!isNode(entry[1])) {
                  return false;
                }
              }
            }
          }
        } else {
          return false;
        }
        return true;
      default:
        return false;
    }
  }
  function isSymbol(propType, propValue) {
    // Native Symbol.
    if (propType === 'symbol') {
      return true;
    }

    // falsy value can't be a Symbol
    if (!propValue) {
      return false;
    }

    // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
    if (propValue['@@toStringTag'] === 'Symbol') {
      return true;
    }

    // Fallback for non-spec compliant Symbols which are polyfilled.
    if (typeof Symbol === 'function' && propValue instanceof Symbol) {
      return true;
    }
    return false;
  }

  // Equivalent of `typeof` but with special handling for array and regexp.
  function getPropType(propValue) {
    var propType = typeof propValue;
    if (Array.isArray(propValue)) {
      return 'array';
    }
    if (propValue instanceof RegExp) {
      // Old webkits (at least until Android 4.0) return 'function' rather than
      // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
      // passes PropTypes.object.
      return 'object';
    }
    if (isSymbol(propType, propValue)) {
      return 'symbol';
    }
    return propType;
  }

  // This handles more types than `getPropType`. Only used for error messages.
  // See `createPrimitiveTypeChecker`.
  function getPreciseType(propValue) {
    if (typeof propValue === 'undefined' || propValue === null) {
      return '' + propValue;
    }
    var propType = getPropType(propValue);
    if (propType === 'object') {
      if (propValue instanceof Date) {
        return 'date';
      } else if (propValue instanceof RegExp) {
        return 'regexp';
      }
    }
    return propType;
  }

  // Returns a string that is postfixed to a warning about an invalid type.
  // For example, "undefined" or "of type array"
  function getPostfixForTypeWarning(value) {
    var type = getPreciseType(value);
    switch (type) {
      case 'array':
      case 'object':
        return 'an ' + type;
      case 'boolean':
      case 'date':
      case 'regexp':
        return 'a ' + type;
      default:
        return type;
    }
  }

  // Returns class name of the object, if any.
  function getClassName(propValue) {
    if (!propValue.constructor || !propValue.constructor.name) {
      return ANONYMOUS;
    }
    return propValue.constructor.name;
  }
  ReactPropTypes.checkPropTypes = checkPropTypes;
  ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
  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.
 */

{
  var ReactIs = reactIsExports;

  // By explicitly using `prop-types` you are opting into new development behavior.
  // http://fb.me/prop-types-in-prod
  var throwOnDirectAccess = true;
  propTypes.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}

var propTypesExports = propTypes.exports;
var PropTypes = /*@__PURE__*/getDefaultExportFromCjs(propTypesExports);

const HTML5_INPUT_TYPES = {
  // Map XForm field types to <input type>
  barcode: false,
  file: "file",
  binary: "file",
  // wq.db <1.3
  date: "date",
  dateTime: "datetime-local",
  decimal: "number",
  geopoint: false,
  geoshape: false,
  geotrace: false,
  int: "number",
  select: false,
  select1: false,
  string: "text",
  time: "time",
  // String subtypes
  password: "password",
  email: "email",
  phone: "tel",
  text: false,
  note: false
};
function useHtmlInput({
  name,
  type,
  ["wq:length"]: length
}) {
  return {
    name,
    type: HTML5_INPUT_TYPES[type] || "text",
    maxLength: length && +length
  };
}
function Input$4(props) {
  const inputProps = useHtmlInput(props),
    {
      name,
      label
    } = props;
  return /*#__PURE__*/React.createElement("div", {
    style: {
      marginBottom: "0.5em"
    }
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex"
    }
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: name,
    style: {
      width: "25%"
    }
  }, label), /*#__PURE__*/React.createElement(Field, {
    style: {
      flex: 1
    },
    ...inputProps
  })), /*#__PURE__*/React.createElement(ErrorMessage, {
    name: name
  }));
}
Input$4.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  label: PropTypes.string
};

const {
  createSelector
} = ReduxORM;
const {
  pathToAction: pathToAction$1,
  getOptions: getOptions$1,
  selectLocationState: selectLocationState$1
} = ReduxFirstRouter;
const isAction$1 = path => path && path.type;
const selectors = {};
function getSelector(name) {
  if (!selectors[name]) {
    selectors[name] = state => state[name];
  }
  return selectors[name];
}
function selectRoutesMap(state) {
  return selectLocationState$1(state).routesMap;
}
function useRoutesMap() {
  return useSelector(selectRoutesMap);
}
function toNavAction(path, routesMap) {
  const {
      querySerializer
    } = getOptions$1(),
    baseUrl = routesMap.INDEX ? routesMap.INDEX.path : "/";
  return isAction$1(path) ? path : pathToAction$1(path.indexOf("/") === 0 ? path : baseUrl + path, routesMap, querySerializer);
}
function useNavAction() {
  const routesMap = useRoutesMap();
  return reactExports$1.useCallback(path => toNavAction(path, routesMap), [routesMap]);
}
function useNav(to) {
  const dispatch = useDispatch(),
    navAction = useNavAction();
  return reactExports$1.useMemo(() => {
    function nav(path) {
      dispatch(navAction(path));
    }
    return to ? nav.bind(null, to) : nav;
  }, [dispatch, navAction, to]);
}
const RouteContext = React.createContext({
  name: "@@CURRENT"
});
function useCurrentRoute() {
  return reactExports$1.useContext(RouteContext).name;
}
function useRenderContext(routeName) {
  const context = useSelector(getSelector("context")),
    currentRoute = useCurrentRoute();
  return context && context[routeName || currentRoute] || {};
}
function useRouteInfo(routeName) {
  const currentRoute = useCurrentRoute(),
    routeInfos = useSelector(getSelector("routeInfo")),
    routeInfo = routeInfos && routeInfos[routeName || currentRoute],
    context = useRenderContext(routeName),
    {
      getRouteInfo
    } = useApp().router;
  return getRouteInfo(context, routeInfo);
}
function useSiteTitle() {
  const siteTitle = useConfig().site_title,
    contextTitle = useContextTitle();
  return siteTitle || contextTitle;
}
function useContextTitle() {
  const context = useRenderContext(),
    routeInfo = useRouteInfo(),
    {
      getContextTitle
    } = useApp().router;
  return getContextTitle(context, routeInfo);
}
function useRouteTitle(routeName) {
  const app = useApp(),
    {
      getRouteTitle
    } = app.router,
    config = useConfig();
  const routeTitle = reactExports$1.useCallback(routeName => {
    const [name, mode, variant] = app.splitRoute(routeName);
    const page_config = config.pages[name] || {
      name
    };
    return getRouteTitle({
      page_config,
      mode,
      variant
    });
  }, [app, routeName, config]);
  if (routeName) {
    return routeTitle(routeName);
  } else {
    return routeTitle;
  }
}
function useReverse() {
  const routesMap = useRoutesMap();
  return reactExports$1.useCallback((name, payload, query) => {
    const action = {
      type: name.toUpperCase()
    };
    if (!routesMap[action.type]) {
      throw new Error(`Unknown route: ${action.type}`);
    }
    if (payload) {
      if (typeof payload === "object") {
        action.payload = payload;
      } else {
        action.payload = {
          slug: payload
        };
      }
    }
    if (query) {
      action.meta = {
        query
      };
    }
    return action;
  }, [routesMap]);
}
function useIndexRoute() {
  // FIXME: This should be read from the configuration
  return "index";
}
function useBreadcrumbs() {
  const title = useContextTitle(),
    {
      name,
      page,
      page_config,
      item_id,
      mode,
      full_path,
      parent_id,
      parent_label,
      parent_conf
    } = useRouteInfo(),
    reverse = useReverse(),
    index = useIndexRoute(),
    {
      getRouteTitle
    } = useApp().router;
  if (name === index) {
    return null;
  }
  const links = [],
    addLink = (url, label) => links.push({
      url,
      label
    }),
    addCurrentPage = label => addLink(full_path, label);
  addLink(reverse(index), "Home");
  if (parent_id && parent_conf) {
    addLink(reverse(`${parent_conf.page}_list`), getRouteTitle({
      page_config: parent_conf,
      mode: "list"
    }));
    addLink(reverse(`${parent_conf.page}_detail`, parent_id), parent_label);
  }
  if (item_id) {
    addLink(reverse(`${page_config.name}_list`), getRouteTitle({
      page_config,
      mode: "list"
    }));
    if (mode !== "detail") {
      const currentTitle = getRouteTitle({
          page_config,
          mode
        }),
        detailTitle = getRouteTitle({
          page_config,
          mode: "detail"
        });
      addLink(reverse(`${page}_detail`, item_id), title === currentTitle ? detailTitle : title);
      addCurrentPage(mode);
    } else {
      addCurrentPage(title);
    }
  } else {
    addCurrentPage(title);
  }
  return links;
}
function useSitemap() {
  const config = useConfig(),
    {
      user,
      config: authConfig
    } = usePluginState("auth"),
    messages = useMessages();
  return reactExports$1.useMemo(() => {
    const pages = Object.values(config.pages).filter(page => showInIndex(page, user, authConfig)).sort(orderSort),
      sections = [],
      sectionPages = {};
    for (const page of pages) {
      const section = getPageSection(page, messages),
        route = getPageRoute(page);
      if (!sectionPages[section]) {
        sectionPages[section] = [];
        sections.push({
          name: section,
          pages: sectionPages[section]
        });
      }
      sectionPages[section].push({
        ...page,
        route
      });
    }
    return sections;
  }, [config, user, authConfig, messages]);
}
function showInIndex(page, user, authConfig) {
  if (page.show_in_index === false) {
    return false;
  } else if (page.show_in_index === true || !page.show_in_index) {
    return true;
  } else if (page.show_in_index === "is_authenticated") {
    return Boolean(user);
  } else if (page.show_in_index === "not_authenticated") {
    return !user;
  } else if (page.show_in_index.startsWith("is_")) {
    return Boolean(user && user[page.show_in_index]);
  } else if (page.show_in_index.startsWith("not_")) {
    return Boolean(user && !user[page.show_in_index]);
  } else if (page.show_in_index.startsWith("can_")) {
    return Boolean(user && authConfig.pages && authConfig.pages[page.name] && authConfig.pages[page.name][page.show_in_index]);
  } else {
    return true;
  }
}
function orderSort(page1, page2) {
  const order1 = page1.order || 0,
    order2 = page2.order || 0;
  if (order1 < order2) {
    return -1;
  } else if (order1 > order2) {
    return 1;
  } else if (page1.list && !page2.list) {
    return -1;
  } else if (!page2.list && page2.list) {
    return 1;
  } else if (page1.name < page2.name) {
    return -1;
  } else if (page1.name > page2.name) {
    return 1;
  } else {
    return 0;
  }
}
function getPageSection(page, messages) {
  if (page.section) {
    return page.section;
  } else if (page.list) {
    return messages.MODEL_PAGES;
  } else {
    return messages.OTHER_PAGES;
  }
}
function getPageRoute(page) {
  if (page.list) {
    return `${page.name}_list`;
  } else {
    return page.name;
  }
}
function useSpinner() {
  const spinner = useSelector(getSelector("spinner"));
  return spinner;
}
const AppContext = React.createContext({
  app: {
    plugins: {},
    models: {}
  }
});
function useComponents() {
  return usePluginComponentMap("react", "components");
}
function useInputComponents() {
  return usePluginComponentMap("react", "inputs");
}
function useIconComponents() {
  return usePluginComponentMap("react", "icons");
}
function useIcon(icon) {
  const icons = useIconComponents();
  if (typeof icon === "string") {
    if (icons[icon]) {
      return icons[icon];
    } else {
      return null;
    }
  } else if (typeof icon === "function") {
    return icon;
  } else {
    return null;
  }
}
function useViewComponents() {
  return usePluginComponentMap("react", "views");
}
function useApp() {
  return reactExports$1.useContext(AppContext).app;
}
function useConfig() {
  const app = useApp();
  return app.config;
}
function useModel(name, filter) {
  const app = useApp(),
    model = app.models[name];
  if (!model) {
    throw new Error(`Unknown model name ${name}`);
  }
  const selector = reactExports$1.useMemo(() => {
    let selector;
    if (typeof filter === "function" || typeof filter === "object" && !Array.isArray(filter)) {
      // Filter by query
      selector = createSelector(model.orm, session => model.getQuerySet(session).filter(filter).toRefArray());
    } else if (filter) {
      // Filter by id (default ModelSelectorSpec behavior)
      selector = state => createSelector(model.orm[name])(state, filter);
    } else {
      // All objects (use getQuerySet() to leverage config.ordering)
      selector = createSelector(model.orm, session => model.getQuerySet(session).toRefArray());
    }
    return selector;
  }, [model, filter]);
  return useSelector(selector);
}
function selectOutbox(state) {
  return state.offline.outbox;
}
function useOutbox() {
  const outbox = useSelector(selectOutbox),
    {
      outbox: {
        parseOutbox
      }
    } = useApp();
  return reactExports$1.useMemo(() => {
    if (outbox) {
      return parseOutbox(outbox);
    } else {
      return [];
    }
  }, [outbox, parseOutbox]);
}
function useUnsynced(modelNameOrConf) {
  const outbox = useOutbox(),
    {
      outbox: {
        filterUnsynced
      },
      models
    } = useApp(),
    modelConf = typeof modelNameOrConf === "string" ? models[modelNameOrConf].config : modelNameOrConf;
  return reactExports$1.useMemo(() => {
    return filterUnsynced(outbox, modelConf);
  }, [outbox, modelConf]);
}
function useList(routeName) {
  const {
      list: contextList,
      show_unsynced
    } = useRenderContext(routeName),
    {
      page_config
    } = useRouteInfo(routeName),
    modelList = useModel(page_config.page),
    unsynced = useUnsynced(page_config);
  return reactExports$1.useMemo(() => {
    let list;
    if (show_unsynced) {
      // Context list should generally already equal model list, unless
      // there has been a sync or other model update since last RENDER.
      const seen = {};
      modelList.forEach(row => seen[row.id] = true);
      list = modelList.concat((contextList || []).filter(row => !seen[row.id]));
    } else {
      // Context list probably came directly from server, ignore local model
      list = contextList || [];
    }
    const empty = !list || !list.length;
    return {
      page_config,
      list,
      unsynced: show_unsynced ? unsynced : [],
      empty
    };
  }, [contextList, show_unsynced, page_config, modelList, unsynced]);
}
function usePlugin(name) {
  const {
    plugins
  } = useApp();
  return plugins[name];
}
function usePluginComponentMap(pluginName, mapName, paramCaseOnly) {
  const plugin = usePlugin(pluginName) || {},
    {
      registry = {}
    } = plugin,
    {
      [mapName]: componentMap = {}
    } = registry;
  const result = paramCaseOnly ? {} : componentMap;
  Object.entries(componentMap).forEach(([key, val]) => {
    result[paramCase(key)] = val;
  });
  return result;
}
function usePluginState(name) {
  const plugin = usePlugin(name),
    pluginState = useSelector(getSelector(name));
  if (plugin) {
    return pluginState;
  } else {
    return null;
  }
}
function usePluginReducer(name) {
  const plugin = usePlugin(name),
    pluginState = useSelector(getSelector(name));
  if (plugin) {
    return [pluginState, plugin];
  } else {
    return [null, null];
  }
}
function usePluginContent() {
  const app = useApp(),
    components = useComponents();
  const content = reactExports$1.useMemo(() => Object.values(app.plugins).map(plugin => plugin.runComponent).map(name => name ? components[name] : null).filter(component => !!component), [app]);
  return reactExports$1.useCallback(function PluginContent() {
    if (!content.length) {
      return null;
    } else {
      return /*#__PURE__*/React.createElement(React.Fragment, null, content.map((Component, i) => /*#__PURE__*/React.createElement(Component, {
        key: i
      })));
    }
  }, [content]);
}
function useMessages() {
  const {
    config
  } = usePlugin("react");
  return config.messages;
}
function useValidate() {
  const app = useApp();
  return reactExports$1.useCallback((values, modelConf) => app.outbox.validate(values, modelConf), [app]);
}

var messages = {
  // Index
  OTHER_PAGES: "Options",
  MODEL_PAGES: "Content",
  // AutoForm, Login
  CANCEL: "Cancel",
  SUBMIT: "Submit",
  // DefaultList
  LIST_IS_EMPTY: "Empty list.",
  SYNCED_ITEMS: "Synced Items",
  // DeleteForm
  CONFIRM_DELETE: "Are you sure you want to delete this record?",
  // DeleteForm.native
  CONFIRM_DELETE_TITLE: "Confirm Deletion",
  CONFIRM_DELETE_OK: "Yes, Delete",
  CONFIRM_DELETE_CANCEL: "Cancel",
  // OutboxList
  EMPTY_OUTBOX: "Empty Outbox",
  RETRY_ALL: "Retry All",
  OUTBOX_IS_EMPTY: "No items in outbox.",
  SYNC_ERROR: "One or more errors found.",
  SYNC_SUCCESS: "Successfully synced.",
  UNSYNCED_ITEMS: "Unsynced Items",
  // Logout
  LOGGED_OUT: "Logged out.",
  LOGGING_OUT: "Logging out...",
  // Loading
  LOADING: "Loading...",
  // Geo
  GEO_POINT_NEW: "Click the {POINT_ICON} tool to draw a new point.",
  GEO_POINT_EDIT: "Select the existing point to move it, or click the {POINT_ICON} tool to draw a new point.",
  GEO_LINE_STRING_NEW: "Click the {LINE_ICON} tool to draw a new line.",
  GEO_LINE_STRING_EDIT: "Select the existing line to move it or its vertices.",
  GEO_POLYGON_NEW: "Click the {LINE_ICON} tool to draw a new polygon.",
  GEO_POLYGON_EDIT: "Select the existing polygon to move it or its vertices."
};

function Container$1({
  children
}) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, children);
}
Container$1.propTypes = {
  children: PropTypes.node
};

function Header$1() {
  const title = useSiteTitle(),
    links = useBreadcrumbs(),
    {
      Breadcrumbs
    } = useComponents();
  return /*#__PURE__*/React.createElement("header", null, /*#__PURE__*/React.createElement("h1", null, title), /*#__PURE__*/React.createElement(Breadcrumbs, {
    links: links
  }));
}

function Logo({
  edge
}) {
  const {
      logo,
      site_title
    } = useConfig(),
    {
      Img
    } = useComponents();
  if (!logo) {
    return null;
  }
  const style = {
    height: 64
  };
  if (edge === "start") {
    style.marginLeft = -12;
    style.marginRight = 16;
  } else if (edge === "end") {
    style.marginLeft = 16;
    style.marginRight = -12;
  }
  return /*#__PURE__*/React.createElement(Img, {
    src: logo,
    style: style,
    alt: site_title
  });
}

function NavMenuPopup$1() {
  return null;
}

function NavMenuFixed$1() {
  return null;
}

function Main$1({
  children
}) {
  return /*#__PURE__*/React.createElement("main", null, children);
}
Main$1.propTypes = {
  children: PropTypes.node
};

function Footer$1() {
  const {
    FooterContent
  } = useComponents();
  return /*#__PURE__*/React.createElement("center", null, /*#__PURE__*/React.createElement("small", null, /*#__PURE__*/React.createElement(FooterContent, null)));
}

function FooterContent$1() {
  return /*#__PURE__*/React.createElement(React.Fragment, null, "Powered by", " ", /*#__PURE__*/React.createElement("a", {
    href: "https://wq.io/"
  }, /*#__PURE__*/React.createElement("b", null, "wq")));
}

function View$1(props) {
  return /*#__PURE__*/React.createElement("div", {
    ...props
  });
}

function ScrollView$1({
  children
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      overflowX: "hidden",
      overflowY: "auto"
    }
  }, children);
}
ScrollView$1.propTypes = {
  children: PropTypes.node
};

function HorizontalView$1({
  children,
  style,
  ...rest
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex",
      justifyContent: "space-between",
      ...style
    },
    ...rest
  }, children);
}
HorizontalView$1.propTypes = {
  children: PropTypes.node,
  style: PropTypes.object
};

var Fragment$3 = reactExports$1.Fragment;

function Img(props) {
  return /*#__PURE__*/React.createElement("img", {
    ...props
  });
}

const variants = {
  default: "p",
  h1: "h1",
  h2: "h2",
  h3: "h3",
  h4: "h4",
  h5: "h5",
  h6: "h6",
  subtitle1: "h6",
  subtitle2: "h6",
  body1: "p",
  body2: "p",
  caption: "small"
};
function Typography$2({
  variant,
  ...rest
}) {
  const Component = variants[variant] || variants.default;
  return /*#__PURE__*/React.createElement(Component, {
    ...rest
  });
}
Typography$2.propTypes = {
  variant: PropTypes.string
};

function FormatJson$1({
  json
}) {
  return /*#__PURE__*/React.createElement("pre", null, /*#__PURE__*/React.createElement("code", null, JSON.stringify(json, null, 4)));
}
FormatJson$1.propTypes = {
  json: PropTypes.object
};

function Message$1({
  id
}) {
  const messages = useMessages(),
    message = messages[id] || id;
  return /*#__PURE__*/React.createElement(React.Fragment, null, message);
}
Message$1.propTypes = {
  id: PropTypes.string
};

const {
  getOptions,
  history,
  actionToPath,
  pathToAction,
  redirect,
  selectLocationState
} = ReduxFirstRouter;
const {
  stripBasename
} = PathUtils;
const matchPath = _default$9.default || _default$9;

var toUrl = (to, routesMap) => {
  const {
    querySerializer,
    basename
  } = getOptions();
  if (to && typeof to === "string") {
    return history().createHref({
      pathname: to
    });
  } else if (Array.isArray(to)) {
    const path = `/${to.join("/")}`;
    return history().createHref({
      pathname: path
    });
  } else if (typeof to === "object") {
    const action = to;
    try {
      const path = actionToPath(action, routesMap, querySerializer);
      return history().createHref({
        pathname: path
      });
    } catch (e) {
      {
        console.warn("[redux-first-router-link] could not create path from action:", action, "For reference, here are your current routes:", routesMap);
      }
      return "#";
    }
  }
  {
    console.warn("[redux-first-router-link] `to` prop must be a string, array or action object. You provided:", to);
  }
  return "#";
};
var handlePress = (url, routesMap, onClick, shouldDispatch, target, dispatch, to, dispatchRedirect, e) => {
  let shouldGo = true;
  if (onClick) {
    shouldGo = onClick(e); // onClick can return false to prevent dispatch
    shouldGo = typeof shouldGo === "undefined" ? true : shouldGo;
  }
  const prevented = e.defaultPrevented;
  if (e.button !== 1 && !target && e && e.preventDefault && !isModified(e)) {
    e.preventDefault();
  }
  if (shouldGo && shouldDispatch && !target && !prevented && e.button === 0 && !isModified(e)) {
    const {
      querySerializer: serializer
    } = getOptions();
    let action = to;
    if (!isAction(to)) {
      url = url.indexOf("#") > -1 ? url.substring(url.indexOf("#") + 1, url.length) : url;
      action = pathToAction(url, routesMap, serializer);
    }
    action = dispatchRedirect ? redirect(action) : action;
    dispatch(action);
  }
};
const isAction = to => typeof to === "object" && !Array.isArray(to);
const isModified = e => !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
var preventDefault = e => e && e.preventDefault && e.preventDefault();
const Link$4 = React.forwardRef(({
  to,
  href,
  redirect,
  replace,
  tagName = "a",
  children,
  onPress,
  onClick,
  down = false,
  shouldDispatch = true,
  target,
  dispatch,
  routesMap,
  ...props
}, ref) => {
  to = href || to; // href is deprecated and will be removed in next major version

  const url = toUrl(to, routesMap);
  const handler = handlePress.bind(null, url, routesMap, onPress || onClick, shouldDispatch, target, dispatch, to, replace || redirect);
  const Root = tagName;
  const localProps = {};
  if (tagName === "a" && url) {
    localProps.href = url;
  }
  if (down && handler) {
    localProps.onMouseDown = handler;
    localProps.onTouchStart = handler;
  }
  if (target) {
    localProps.target = target;
  }
  return /*#__PURE__*/React.createElement(Root, {
    onClick: !down && handler || preventDefault,
    ...localProps,
    ...props,
    ref
  }, children);
});
const mapState$1 = state => ({
  routesMap: selectLocationState(state).routesMap
});
const connector$1 = connect(mapState$1, undefined, undefined, {
  forwardRef: true
});

// $FlowIgnore
connector$1(Link$4);
const NavLink = reactExports$1.forwardRef(({
  to,
  href,
  location,
  className,
  style,
  activeClassName = "active",
  activeStyle,
  ariaCurrent = "true",
  exact,
  strict,
  isActive,
  ...props
}, ref) => {
  to = href || to;
  const options = getOptions();
  const basename = options.basename ? options.basename : "";
  const path = toUrl(to, location.routesMap).split("?")[0];
  const match = matchPath(location.pathname, {
    path: stripBasename(path, basename),
    exact,
    strict
  });
  const active = !!(isActive ? isActive(match, location) : match);
  const combinedClassName = active ? [className, activeClassName].filter(i => i).join(" ") : className;
  const combinedStyle = active ? {
    ...style,
    ...activeStyle
  } : style;
  return /*#__PURE__*/React.createElement(Link$4, {
    className: combinedClassName,
    style: combinedStyle,
    "aria-current": active && ariaCurrent,
    routesMap: location.routesMap,
    ref,
    to,
    ...props
  });
});
const mapState = state => ({
  location: selectLocationState(state)
});
const connector = connect(mapState, undefined, undefined, {
  forwardRef: true
});

// $FlowIgnore
var NavLink$1 = connector(NavLink);

function Button$3({
  type = "button",
  ...rest
}) {
  return /*#__PURE__*/React.createElement("button", {
    type: type,
    ...rest
  });
}
Button$3.propTypes = {
  type: PropTypes.string
};

function ButtonLink$1(props) {
  return /*#__PURE__*/React.createElement(NavLink$1, {
    style: {
      textDecoration: "none",
      border: "1px solid #eee",
      borderRadius: "0.2em",
      padding: "0.2em"
    },
    ...props
  });
}

function IconButton$3({
  icon,
  type = "button",
  ...rest
}) {
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement("button", {
    type: type,
    ...rest
  }, /*#__PURE__*/React.createElement(Icon, null));
}
IconButton$3.propTypes = {
  icon: PropTypes.string,
  type: PropTypes.string
};

function Fab$3({
  icon,
  to,
  ...rest
}) {
  const {
      Link
    } = useComponents(),
    Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement(Link, {
    to: to,
    ...rest
  }, /*#__PURE__*/React.createElement(Icon, null));
}
Fab$3.propTypes = {
  icon: PropTypes.string,
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
};

var Fragment$2 = reactExports$1.Fragment;

function TabItem$1({
  label,
  children
}) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h3", null, label), /*#__PURE__*/React.createElement("div", null, children));
}

function BottomNavigation$2({
  children,
  style,
  ...rest
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex",
      justifyContent: "space-between",
      ...style
    },
    ...rest
  }, children);
}
BottomNavigation$2.propTypes = {
  children: PropTypes.node,
  style: PropTypes.object
};

function Chip$3({
  label,
  icon,
  onDelete,
  ...rest
}) {
  const {
      IconButton
    } = useComponents(),
    Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement("span", {
    style: {
      border: "1px solid blue",
      "border-radius": "1em",
      padding: "0.25em"
    },
    ...rest
  }, Icon && /*#__PURE__*/React.createElement(Icon, null), label, onDelete && /*#__PURE__*/React.createElement(IconButton, {
    icon: "delete",
    onClick: onDelete
  }));
}
Chip$3.propTypes = {
  label: PropTypes.node,
  icon: PropTypes.string,
  onDelete: PropTypes.func
};

function Switch$2() {
  return null;
}

function CheckboxButton() {
  return null;
}

function RadioButton() {
  return null;
}

function List$4(props) {
  return /*#__PURE__*/React.createElement("ul", {
    ...props
  });
}

function ListItem$3({
  children,
  description,
  icon,
  ...rest
}) {
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement("li", {
    ...rest
  }, Icon && /*#__PURE__*/React.createElement(Icon, null), children, description && /*#__PURE__*/React.createElement("small", null, description));
}
ListItem$3.propTypes = {
  children: PropTypes.node,
  description: PropTypes.node,
  icon: PropTypes.oneOfType([PropTypes.string, PropTypes.func])
};

function ListItemLink$1({
  children,
  icon,
  description,
  ...rest
}) {
  const {
    ListItem,
    Link
  } = useComponents();
  return /*#__PURE__*/React.createElement(ListItem, {
    icon: icon,
    description: description
  }, /*#__PURE__*/React.createElement(Link, {
    ...rest
  }, children));
}
ListItemLink$1.propTypes = {
  children: PropTypes.node,
  description: PropTypes.node,
  icon: PropTypes.string
};

function ListSubheader$2(props) {
  return /*#__PURE__*/React.createElement("li", {
    style: {
      marginTop: 8,
      borderBottom: "1px solid #999",
      color: "#999",
      listStyleType: "none"
    },
    ...props
  });
}

function ExpansionPanel({
  summary,
  children,
  open,
  onToggle
}) {
  let handleToggle;
  if (onToggle) {
    handleToggle = evt => onToggle(evt.target.open);
  }
  return /*#__PURE__*/React.createElement("details", {
    open: open,
    onToggle: handleToggle
  }, /*#__PURE__*/React.createElement("summary", null, summary), children);
}
ExpansionPanel.propTypes = {
  summary: PropTypes.node,
  children: PropTypes.node,
  open: PropTypes.bool,
  onToggle: PropTypes.func
};

function ExpandableListItem$1({
  children,
  open,
  onToggle
}) {
  const [summary, ...details] = React.Children.toArray(children);
  let handleToggle;
  if (onToggle) {
    handleToggle = evt => onToggle(evt.target.open);
  }
  return /*#__PURE__*/React.createElement("details", {
    open: open,
    onToggle: handleToggle
  }, /*#__PURE__*/React.createElement("summary", null, summary), details);
}
ExpandableListItem$1.propTypes = {
  children: PropTypes.node,
  open: PropTypes.bool,
  onToggle: PropTypes.func
};

function Divider$2() {
  return /*#__PURE__*/React.createElement("hr", null);
}

function Table$2(props) {
  return /*#__PURE__*/React.createElement("table", {
    ...props
  });
}

function TableHead$2(props) {
  return /*#__PURE__*/React.createElement("thead", {
    ...props
  });
}

function TableBody$2(props) {
  return /*#__PURE__*/React.createElement("tbody", {
    ...props
  });
}

function TableRow$2(props) {
  return /*#__PURE__*/React.createElement("tr", {
    ...props
  });
}

function TableTitle(props) {
  return /*#__PURE__*/React.createElement("th", {
    ...props
  });
}

function TableCell$2(props) {
  return /*#__PURE__*/React.createElement("td", {
    ...props
  });
}

var Fragment$1 = reactExports$1.Fragment;

function TablePagination$2() {
  return null;
}

function AutoForm$1({
  action,
  cancel,
  method,
  onSubmit,
  storage,
  backgroundSync,
  outboxId,
  form = [],
  modelConf,
  data,
  error,
  FormRoot,
  children
}) {
  const {
    Message,
    AutoInput,
    Form,
    FormError,
    HorizontalView,
    View,
    CancelButton,
    SubmitButton
  } = useComponents();
  const formData = initData(form, data);
  if (!modelConf) {
    modelConf = {
      form
    };
  }
  return /*#__PURE__*/React.createElement(Form, {
    action: action,
    method: method,
    onSubmit: onSubmit,
    data: formData,
    modelConf: modelConf,
    error: error,
    storage: storage,
    backgroundSync: backgroundSync,
    outboxId: outboxId,
    FormRoot: FormRoot
  }, children, (form || []).map(({
    name,
    children: subform,
    ...rest
  }) => /*#__PURE__*/React.createElement(AutoInput, {
    key: name,
    name: name,
    subform: subform,
    ...rest
  })), /*#__PURE__*/React.createElement(FormError, null), /*#__PURE__*/React.createElement(HorizontalView, null, cancel ? /*#__PURE__*/React.createElement(CancelButton, {
    to: cancel
  }, /*#__PURE__*/React.createElement(Message, {
    id: "CANCEL"
  })) : /*#__PURE__*/React.createElement(View, null), /*#__PURE__*/React.createElement(SubmitButton, null, /*#__PURE__*/React.createElement(Message, {
    id: "SUBMIT"
  }))));
}
AutoForm$1.propTypes = {
  action: PropTypes.string,
  cancel: PropTypes.object,
  method: PropTypes.string,
  onSubmit: PropTypes.func,
  storage: PropTypes.string,
  backgroundSync: PropTypes.bool,
  outboxId: PropTypes.number,
  form: PropTypes.arrayOf(PropTypes.object),
  modelConf: PropTypes.object,
  data: PropTypes.object,
  error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  FormRoot: PropTypes.func,
  children: PropTypes.node
};
function initData(form, data) {
  if (!data) {
    data = {};
  }
  const formData = {};
  if (data.id) {
    formData.id = data.id;
  }
  form.forEach(field => {
    const fieldName = field["wq:ForeignKey"] ? `${field.name}_id` : field.name;
    let value;
    if (field.type === "repeat") {
      value = (data[fieldName] || []).map(row => initData(field.children, row));
    } else if (field.type === "group") {
      if (fieldName) {
        value = initData(field.children, data[fieldName] || {});
      } else {
        value = initData(field.children, data);
      }
    } else if (fieldName in data) {
      value = data[fieldName];
    } else {
      value = defaultValue(field);
    }
    if (fieldName) {
      formData[fieldName] = value;
    } else {
      Object.assign(formData, value);
    }
  });
  return formData;
  function defaultValue(field) {
    if (field.type === "select") {
      return [];
    } else if (NULL_FIELDS.includes(field.type)) {
      return null;
    } else {
      return "";
    }
  }
}
const NULL_FIELDS = ["date", "time", "dateTime", "int", "integer", "decimal"];
AutoForm$1.initData = initData;

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var __assign$1 = function () {
  __assign$1 = Object.assign || function __assign(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign$1.apply(this, arguments);
};

function pascalCaseTransform(input, index) {
  var firstChar = input.charAt(0);
  var lowerChars = input.substr(1).toLowerCase();
  if (index > 0 && firstChar >= "0" && firstChar <= "9") {
    return "_" + firstChar + lowerChars;
  }
  return "" + firstChar.toUpperCase() + lowerChars;
}
function pascalCase(input, options) {
  if (options === void 0) {
    options = {};
  }
  return noCase(input, __assign$1({
    delimiter: "",
    transform: pascalCaseTransform
  }, options));
}

function AutoInput$1({
  name,
  choices,
  type,
  bind = {},
  ...rest
}) {
  const inputs = useInputComponents(),
    {
      AutoSubform,
      AutoSubformArray,
      Text
    } = useComponents();
  if (type === "group") {
    return /*#__PURE__*/React.createElement(AutoSubform, {
      name: name,
      ...rest
    });
  } else if (type === "repeat") {
    return /*#__PURE__*/React.createElement(AutoSubformArray, {
      name: name,
      ...rest
    });
  }
  let inputType,
    required = bind.required;
  if (rest["wq:ForeignKey"]) {
    name = `${name}_id`;
    inputType = "foreign-key";
  } else if (type === "select1" || type === "select one") {
    if (!choices) {
      choices = [];
    }
    if (choices.length < 5) {
      inputType = "toggle";
    } else if (choices.length < 10) {
      inputType = "radio";
    } else {
      inputType = "select";
    }
  } else if (inputs[type]) {
    inputType = type;
  } else {
    if (type === "picture" || type === "photo") {
      inputType = "image";
    } else if (type === "video" || type === "audio") {
      inputType = "file";
    } else if (type === "binary") {
      // wq.db <1.3
      inputType = "file";
    } else {
      inputType = "input";
    }
  }
  if (rest.control && rest.control.appearance) {
    inputType = rest.control.appearance;
  }
  const Input = inputs[inputType];
  if (!Input) {
    return /*#__PURE__*/React.createElement(Text, null, "Unknown input type \"", inputType, "\". Perhaps you need to define inputs.", pascalCase(inputType), " in a plugin?");
  }
  return /*#__PURE__*/React.createElement(Input, {
    name: name,
    choices: choices,
    type: type,
    required: required,
    ...rest
  });
}
AutoInput$1.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  bind: PropTypes.object,
  "wq:ForeignKey": PropTypes.string,
  choices: PropTypes.arrayOf(PropTypes.object)
};

function AutoSubform$1({
  name,
  label,
  subform,
  component,
  ...rest
}) {
  const components = useComponents(),
    inputs = useInputComponents(),
    {
      AutoInput
    } = components,
    componentName = rest.control && rest.control.appearance;
  let Fieldset;
  if (component) {
    // Passed in from parent AutoSubformArray
    Fieldset = component;
  } else if (componentName) {
    // Defined in XLSForm config
    Fieldset = inputs[componentName];
    if (!Fieldset) {
      // eslint-disable-next-line
      Fieldset = ({
        children,
        ...rest
      }) => {
        const {
            Text
          } = components,
          {
            Fieldset
          } = inputs,
          name = pascalCase(componentName);
        return /*#__PURE__*/React.createElement(Fieldset, {
          ...rest
        }, /*#__PURE__*/React.createElement(Text, null, "Unknown fieldset type \"", componentName, "\".", " ", components[componentName] ? /*#__PURE__*/React.createElement(React.Fragment, null, "Move or copy components.", name, " to inputs.", name, "?") : /*#__PURE__*/React.createElement(React.Fragment, null, "Perhaps you need to define inputs.", name, " in a plugin?")), children);
      };
    }
  } else {
    // Default (or global default override)
    Fieldset = inputs.Fieldset;
  }
  const prefix = name ? `${name}.` : "";
  return /*#__PURE__*/React.createElement(Fieldset, {
    name: name,
    label: label,
    ...rest
  }, subform.map(({
    name: fieldName,
    children: subform,
    ...rest
  }) => /*#__PURE__*/React.createElement(AutoInput, {
    key: fieldName,
    name: `${prefix}${fieldName}`,
    subform: subform,
    ...rest
  })));
}
AutoSubform$1.propTypes = {
  name: PropTypes.string,
  label: PropTypes.string,
  subform: PropTypes.arrayOf(PropTypes.object),
  component: PropTypes.elementType
};

function AutoSubformArray$1({
  name,
  label,
  subform,
  ...rest
}) {
  const components = useComponents(),
    inputs = useInputComponents(),
    {
      AutoSubform
    } = components,
    componentName = rest.control && rest.control.appearance;
  let FieldsetArray;
  if (componentName) {
    // Defined in XLSForm config
    FieldsetArray = inputs[componentName];
    if (!FieldsetArray) {
      // eslint-disable-next-line
      FieldsetArray = ({
        children,
        ...rest
      }) => {
        const {
            Text
          } = components,
          {
            FieldsetArray
          } = inputs,
          name = pascalCase(componentName);
        return /*#__PURE__*/React.createElement(FieldsetArray, {
          ...rest
        }, /*#__PURE__*/React.createElement(Text, null, "Unknown fieldset array type \"", componentName, "\".", " ", components[componentName] ? /*#__PURE__*/React.createElement(React.Fragment, null, "Move or copy components.", name, " to inputs.", name, "?") : /*#__PURE__*/React.createElement(React.Fragment, null, "Perhaps you need to define inputs.", name, " in a plugin?")), children);
      };
    }
  } else if (subform.length === 1 && (subform[0].type === "file" || subform[0].type === "image")) {
    // Special case for subforms containing only a single file field
    FieldsetArray = components.FileArray;
  } else {
    // Default (or global default override)
    FieldsetArray = components.FieldsetArray;
  }
  const SubformArray = reactExports$1.useCallback(({
    form: formikContext,
    push,
    remove,
    pop
  }) => {
    const {
        values
      } = formikContext,
      list = getIn(values, name) || [];
    function addRow(vals) {
      const row = initData(subform, vals || {});
      push(row);
    }
    const removeRow = remove,
      removeLastRow = pop;
    return /*#__PURE__*/React.createElement(FieldsetArray, {
      name: name,
      label: label,
      subform: subform,
      addRow: addRow,
      removeRow: removeRow,
      removeLastRow: removeLastRow,
      ...rest
    }, list.map((row, i) => /*#__PURE__*/React.createElement(AutoSubform, {
      key: i,
      label: `${label} ${i + 1}`,
      name: `${name}[${i}]`,
      subform: subform,
      component: FieldsetArray.Fieldset
    })));
  }, [name, label, subform, FieldsetArray, AutoSubform]);
  SubformArray.displayName = "SubformArray";
  return /*#__PURE__*/React.createElement(FieldArray, {
    name: name,
    component: SubformArray,
    label: label,
    subform: subform
  });
}
AutoSubformArray$1.propTypes = {
  name: PropTypes.string,
  label: PropTypes.string,
  subform: PropTypes.arrayOf(PropTypes.object)
};

const Value = ({
  values,
  field
}) => {
  const {
      FormatJson,
      ImagePreview,
      FileLink
    } = useComponents(),
    value = values[field.name];
  if (field.children && values[field.name]) {
    if (field.type === "repeat") {
      return /*#__PURE__*/React.createElement(PropertyTableList, {
        form: field.children,
        values: values[field.name]
      });
    } else {
      return /*#__PURE__*/React.createElement(PropertyTable$1, {
        form: field.children,
        values: values[field.name]
      });
    }
  } else if (field["wq:ForeignKey"]) {
    if (value && typeof value === "object" && value.label) {
      return value.label;
    } else {
      return values[field.name + "_label"] || values[field.name + "_id"] || value + "";
    }
  } else if (field.choices) {
    const choice = field.choices.find(c => c.name === value);
    if (choice && choice.label) {
      return choice.label;
    } else {
      return values[field.name + "_label"] || value + "";
    }
  } else if (field.type === "image") {
    return /*#__PURE__*/React.createElement(ImagePreview, {
      value: value,
      field: field
    });
  } else if (field.type === "file") {
    return /*#__PURE__*/React.createElement(FileLink, {
      value: value,
      field: field
    });
  } else if (typeof value === "object") {
    return /*#__PURE__*/React.createElement(FormatJson, {
      json: value,
      field: field
    });
  } else {
    return value + "";
  }
};
const isInteractive = (values, field) => {
  const result = Value({
    values,
    field
  });
  if (result && typeof result !== "string") {
    return true;
  } else {
    return false;
  }
};
function PropertyTable$1({
  form,
  values
}) {
  const {
      Table,
      TableBody,
      TableRow,
      TableCell
    } = useComponents(),
    rootFieldset = form.find(field => field.name === "" && field.type === "group"),
    fields = rootFieldset ? rootFieldset.children.concat(form.filter(field => field !== rootFieldset)) : form;
  return /*#__PURE__*/React.createElement(Table, null, /*#__PURE__*/React.createElement(TableBody, null, fields.map(field => /*#__PURE__*/React.createElement(TableRow, {
    key: field.name
  }, /*#__PURE__*/React.createElement(TableCell, null, field.label || field.name), /*#__PURE__*/React.createElement(TableCell, {
    interactive: isInteractive(values, field)
  }, /*#__PURE__*/React.createElement(Value, {
    values: values,
    field: field
  }))))));
}
PropertyTable$1.propTypes = {
  form: PropTypes.arrayOf(PropTypes.object),
  values: PropTypes.object
};
function PropertyTableList({
  form,
  values
}) {
  const {
    Divider
  } = useComponents();
  if (!Array.isArray(values)) {
    return null;
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, values.map((vals, i) => /*#__PURE__*/React.createElement(React.Fragment, {
    key: vals && vals.id || i
  }, i > 0 && /*#__PURE__*/React.createElement(Divider, null), /*#__PURE__*/React.createElement(PropertyTable$1, {
    form: form,
    values: vals
  }))));
}
PropertyTableList.propTypes = {
  form: PropTypes.arrayOf(PropTypes.object),
  values: PropTypes.object
};

function ImagePreview$1({
  value
}) {
  const [open, setOpen] = reactExports$1.useState(false),
    {
      View,
      Popup,
      Img
    } = useComponents();
  if (!value) {
    return null;
  }
  const label = value.split("/").reverse()[0];
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Img, {
    src: value,
    alt: label,
    style: {
      maxHeight: 200,
      maxWidth: "66vw",
      cursor: "pointer"
    },
    onClick: () => setOpen(true)
  }), /*#__PURE__*/React.createElement(Popup, {
    open: open,
    onClose: () => setOpen(false)
  }, /*#__PURE__*/React.createElement(View, {
    style: {
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      padding: 8
    }
  }, /*#__PURE__*/React.createElement(Img, {
    src: value,
    alt: label,
    onClick: () => setOpen(false),
    style: {
      maxWidth: "95vw",
      maxHeight: "90vh"
    }
  }))));
}
ImagePreview$1.propTypes = {
  value: PropTypes.string
};

function FileLink$1({
  value
}) {
  const {
    Link
  } = useComponents();
  if (!value) {
    return null;
  }
  const label = value.split("/").reverse()[0];
  return /*#__PURE__*/React.createElement(Link, {
    component: "a",
    href: value,
    target: "_blank"
  }, label);
}
FileLink$1.propTypes = {
  value: PropTypes.string
};

function Form$1({
  action,
  method,
  onSubmit,
  storage,
  backgroundSync,
  outboxId,
  preserve,
  modelConf,
  data = {},
  error,
  FormRoot,
  children
}) {
  const app = useApp(),
    validate = useValidate(),
    {
      FormRoot: DefaultRoot
    } = useComponents();
  if (backgroundSync === undefined) {
    backgroundSync = app.config.backgroundSync;
  }
  if (!FormRoot) {
    FormRoot = DefaultRoot;
  }
  async function handleSubmit(values, {
    setSubmitting,
    setTouched,
    setErrors
  }) {
    if (onSubmit) {
      const result = await onSubmit(values);
      if (!result) {
        setSubmitting(false);
        return;
      }
    }
    const has_files = checkForFiles(values);
    const [item, error] = await app.submitForm({
      url: action,
      storage,
      backgroundSync,
      has_files,
      outboxId,
      preserve,
      data: {
        _method: method,
        ...values
      }
    });
    if (error) {
      const errors = parseApiError(item.error, values);
      setErrors(errors);
      setTouched(errors, false);
    }
    setSubmitting(false);
    return item;
  }
  const errors = parseApiError(error, data);
  return /*#__PURE__*/React.createElement(Formik, {
    initialValues: data,
    initialErrors: errors,
    initialTouched: errors,
    validate: values => validate(values, modelConf),
    validateOnBlur: true,
    validateOnChange: false,
    onSubmit: handleSubmit,
    enableReinitialize: true
  }, /*#__PURE__*/React.createElement(FormRoot, null, children));
}
Form$1.propTypes = {
  action: PropTypes.string,
  method: PropTypes.string,
  onSubmit: PropTypes.func,
  storage: PropTypes.string,
  backgroundSync: PropTypes.bool,
  outboxId: PropTypes.number,
  preserve: PropTypes.arrayOf(PropTypes.string),
  modelConf: PropTypes.object,
  data: PropTypes.object,
  error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  FormRoot: PropTypes.func,
  children: PropTypes.node
};
function parseApiError(error, values) {
  if (!error) {
    return;
  }
  const errors = {};
  if (typeof error === "string") {
    errors["__other__"] = error;
  } else {
    Object.entries(error).map(([key, error]) => {
      if (!(key in values)) {
        key = "__other__";
      }
      if (Array.isArray(error)) {
        if (typeof error[0] === "object") {
          errors[key] = error.map((err, i) => parseApiError(err, (values[key] || [])[i] || {}));
          return;
        }
      } else if (typeof error === "object") {
        errors[key] = parseApiError(error, values[key] || {});
        return;
      } else {
        error = [error];
      }
      if (errors[key]) {
        error = [errors[key], ...error];
      }
      errors[key] = error.join("; ");
    });
  }
  return errors;
}
function checkForFiles(values) {
  if (!values || typeof values !== "object") {
    return false;
  }
  if (values.name && values.type && (values.body || values.uri)) {
    return true;
  }
  if (Array.isArray(values)) {
    return values.some(checkForFiles);
  }
  return Object.values(values).some(checkForFiles);
}

function FormRoot$1({
  children
}) {
  return /*#__PURE__*/React.createElement(Form$2, {
    style: {
      padding: "1em"
    }
  }, children);
}
FormRoot$1.propTypes = {
  children: PropTypes.node
};

function FormError$2() {
  const [, {
    error
  }] = useField("__other__");
  if (!error) {
    return null;
  }
  return error;
}

function SubmitButton$1(props) {
  const {
      Button
    } = useComponents(),
    {
      isSubmitting
    } = useFormikContext();
  return /*#__PURE__*/React.createElement(Button, {
    type: "submit",
    disabled: isSubmitting,
    ...props
  });
}

function IconSubmitButton$1(props) {
  const {
      IconButton
    } = useComponents(),
    {
      isSubmitting
    } = useFormikContext();
  return /*#__PURE__*/React.createElement(IconButton, {
    type: "submit",
    disabled: isSubmitting,
    ...props
  });
}

function DeleteForm$1({
  action
}) {
  const {
      Form,
      SubmitButton,
      View,
      HorizontalView
    } = useComponents(),
    {
      CONFIRM_DELETE
    } = useMessages();
  function confirmSubmit() {
    return window.confirm(CONFIRM_DELETE);
  }
  return /*#__PURE__*/React.createElement(Form, {
    action: action,
    method: "DELETE",
    backgroundSync: false,
    onSubmit: confirmSubmit
  }, /*#__PURE__*/React.createElement(HorizontalView, null, /*#__PURE__*/React.createElement(View, null), /*#__PURE__*/React.createElement(SubmitButton, null, "Delete")));
}
DeleteForm$1.propTypes = {
  action: PropTypes.string
};

const style$2 = {
  position: "absolute",
  top: "1em",
  right: "1em",
  color: "gray"
};
function Spinner$1() {
  const {
    active
  } = useSpinner();
  if (!active) {
    return null;
  }
  // FIXME: text, type
  return /*#__PURE__*/React.createElement("div", {
    style: style$2
  }, "(Working...)");
}

function Popup$3({
  open,
  children
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      display: open ? "block" : "none",
      position: "fixed",
      border: "1px solid black",
      backgroundColor: "white",
      zIndex: 100,
      margin: "1em",
      padding: "1em",
      bottom: 0,
      left: "10%",
      right: "10%",
      maxHeight: "50%"
    }
  }, children);
}
Popup$3.propTypes = {
  open: PropTypes.bool,
  children: PropTypes.node
};

function SidePanel$1({
  children
}) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, children);
}
SidePanel$1.propTypes = {
  children: PropTypes.node
};

function Breadcrumbs$3({
  links
}) {
  const {
    Link
  } = useComponents();
  if (!links) {
    return null;
  }
  links[links.length - 1].last = true;
  return /*#__PURE__*/React.createElement("div", null, links.map(({
    url,
    label,
    last
  }, i) => /*#__PURE__*/React.createElement(React.Fragment, {
    key: i
  }, /*#__PURE__*/React.createElement(Link, {
    key: i,
    to: url
  }, label), !last && /*#__PURE__*/React.createElement(React.Fragment, null, " > "))));
}
Breadcrumbs$3.propTypes = {
  links: PropTypes.arrayOf(PropTypes.object)
};

function Pagination$1() {
  const {
      Link
    } = useComponents(),
    {
      multiple,
      page: pageNum,
      pages,
      per_page,
      previous,
      next,
      previous_is_local,
      current_is_local
    } = useRenderContext();
  if (!(multiple && pages && per_page)) {
    return null;
  }
  return /*#__PURE__*/React.createElement("p", null, previous && /*#__PURE__*/React.createElement(Link, {
    to: previous
  }, "<", " ", previous_is_local ? "Local Cache" : `Previous ${per_page}`), !current_is_local && /*#__PURE__*/React.createElement(React.Fragment, null, "Page ", pageNum, " of ", pages), next && /*#__PURE__*/React.createElement(Link, {
    to: next
  }, current_is_local ? "All Data" : `Next ${per_page}`, " >"));
}

const SKIP = ["app_config", "router_info", "rt", "svc", "user", "is_authenticated", "csrf_token", "native", "unsynced", "local", "_refreshCount"];
function DebugContext$1() {
  const context = useRenderContext(),
    routeInfo = useRouteInfo(),
    {
      List,
      ListSubheader,
      FormatJson
    } = useComponents();
  const main = {
      ...context
    },
    other = {};
  SKIP.forEach(skip => {
    other[skip] = main[skip];
    delete main[skip];
  });
  return /*#__PURE__*/React.createElement(List, null, /*#__PURE__*/React.createElement(ListSubheader, null, "Context"), /*#__PURE__*/React.createElement(FormatJson, {
    json: main
  }), /*#__PURE__*/React.createElement(ListSubheader, null, "Route Info"), /*#__PURE__*/React.createElement(FormatJson, {
    json: routeInfo
  }), /*#__PURE__*/React.createElement(ListSubheader, null, "Additional Context"), /*#__PURE__*/React.createElement(FormatJson, {
    json: other
  }));
}

var components$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Accordion: ExpansionPanel,
  AutoForm: AutoForm$1,
  AutoInput: AutoInput$1,
  AutoSubform: AutoSubform$1,
  AutoSubformArray: AutoSubformArray$1,
  BottomNavigation: BottomNavigation$2,
  BottomNavigationAction: ButtonLink$1,
  Breadcrumbs: Breadcrumbs$3,
  Button: Button$3,
  ButtonLink: ButtonLink$1,
  CancelButton: ButtonLink$1,
  CheckboxButton: CheckboxButton,
  Chip: Chip$3,
  Container: Container$1,
  DebugContext: DebugContext$1,
  DeleteForm: DeleteForm$1,
  Divider: Divider$2,
  ExpandableListItem: ExpandableListItem$1,
  ExpansionPanel: ExpansionPanel,
  Fab: Fab$3,
  FileLink: FileLink$1,
  Footer: Footer$1,
  FooterContent: FooterContent$1,
  Form: Form$1,
  FormError: FormError$2,
  FormRoot: FormRoot$1,
  FormatJson: FormatJson$1,
  Header: Header$1,
  HomeLink: ButtonLink$1,
  HorizontalView: HorizontalView$1,
  IconButton: IconButton$3,
  IconSubmitButton: IconSubmitButton$1,
  ImagePreview: ImagePreview$1,
  Img: Img,
  Link: NavLink$1,
  List: List$4,
  ListItem: ListItem$3,
  ListItemLink: ListItemLink$1,
  ListSubheader: ListSubheader$2,
  Logo: Logo,
  Main: Main$1,
  Message: Message$1,
  NavMenuFixed: NavMenuFixed$1,
  NavMenuPopup: NavMenuPopup$1,
  Pagination: Pagination$1,
  Popup: Popup$3,
  PropertyTable: PropertyTable$1,
  RadioButton: RadioButton,
  ScrollView: ScrollView$1,
  SidePanel: SidePanel$1,
  Spinner: Spinner$1,
  SubmitButton: SubmitButton$1,
  Switch: Switch$2,
  TabGroup: Fragment$2,
  TabItem: TabItem$1,
  Table: Table$2,
  TableBody: TableBody$2,
  TableCell: TableCell$2,
  TableContainer: Fragment$1,
  TableHead: TableHead$2,
  TablePagination: TablePagination$2,
  TableRow: TableRow$2,
  TableTitle: TableTitle,
  Text: Fragment$3,
  Typography: Typography$2,
  View: View$1
});

function File$2({
  name,
  label,
  ...rest
}) {
  const [, {
    value,
    initialValue
  }, {
    setValue
  }] = useField(name);
  function setFile(evt) {
    if (evt.target.files) {
      const {
        name,
        type
      } = evt.target.files[0];
      setValue({
        name,
        type,
        body: evt.target.files[0]
      });
    } else {
      setValue(initialValue || null);
    }
  }
  const hasValue = value && value !== "__clear__";
  return /*#__PURE__*/React.createElement("div", {
    style: {
      marginBottom: "0.5em"
    }
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex"
    }
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: name,
    style: {
      width: "25%"
    }
  }, label), /*#__PURE__*/React.createElement("input", {
    style: {
      flex: 1
    },
    name: name,
    onChange: setFile,
    ...rest,
    type: "file"
  })), hasValue && /*#__PURE__*/React.createElement("p", null, "Current: ", value.name ? value.name : value, /*#__PURE__*/React.createElement("button", {
    onClick: () => setValue(initialValue ? "__clear__" : null)
  }, "Clear")), /*#__PURE__*/React.createElement(ErrorMessage, {
    name: name
  }));
}
File$2.propTypes = {
  name: PropTypes.string,
  label: PropTypes.string
};

function Image$1(props) {
  return /*#__PURE__*/React.createElement(File$2, {
    accept: "image/*",
    ...props
  });
}

function Select$4({
  name,
  type,
  label,
  choices
}) {
  const multiple = type === "select";
  return /*#__PURE__*/React.createElement("div", {
    style: {
      marginBottom: "0.5em"
    }
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex"
    }
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: name,
    style: {
      width: "25%"
    }
  }, label), /*#__PURE__*/React.createElement(Field, {
    as: "select",
    style: {
      flex: 1
    },
    name: name,
    multiple: multiple
  }, !multiple && /*#__PURE__*/React.createElement("option", {
    value: ""
  }, "Select one..."), choices.map(({
    name,
    label
  }) => /*#__PURE__*/React.createElement("option", {
    key: name,
    value: name
  }, label)))), /*#__PURE__*/React.createElement(ErrorMessage, {
    name: name
  }));
}
Select$4.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  label: PropTypes.string,
  choices: PropTypes.arrayOf(PropTypes.object)
};

function useChoices(modelName, group_by) {
  const records = useModel(modelName),
    unsyncedItems = useUnsynced(modelName),
    getGroup = record => group_by && record[group_by] || null;
  return unsyncedItems.map(item => ({
    name: "outbox-" + item.id,
    label: `* ${item.label}`,
    group: getGroup(item.data),
    data: item.data
  })).concat(records.map(record => ({
    name: record.id,
    label: record.label,
    group: getGroup(record),
    data: record
  })));
}
function useFilteredChoices(modelName, group_by, filterConf) {
  const choices = useChoices(modelName, group_by),
    {
      values
    } = useFormikContext(),
    filter = {};
  Object.entries(filterConf).forEach(([key, value]) => {
    filter[key] = getIn(values, value);
  });
  return choices.filter(choice => Object.entries(filter).every(([key, value]) => {
    return choice.data[key] == value;
  }));
}
function useSelectInput(component) {
  const inputs = useInputComponents(),
    {
      Select
    } = inputs;
  let Component;
  if (typeof component === "string") {
    Component = inputs[component];
    if (!Component) {
      Component = function UnknownInput(props) {
        return /*#__PURE__*/React.createElement(Select, {
          ...props,
          hint: `Unknown input type "${component}"`
        });
      };
    }
  } else if (component) {
    Component = component;
  } else {
    Component = Select;
  }
  return Component;
}
function ForeignKey$1({
  filter,
  ...rest
}) {
  if (filter) {
    return /*#__PURE__*/React.createElement(FilteredForeignKey, {
      filter: filter,
      ...rest
    });
  } else {
    return /*#__PURE__*/React.createElement(UnfilteredForeignKey, {
      ...rest
    });
  }
}
function FilteredForeignKey({
  ["wq:ForeignKey"]: modelName,
  group_by,
  filter,
  component,
  ...rest
}) {
  const choices = useFilteredChoices(modelName, group_by, filter),
    Select = useSelectInput(component);
  return /*#__PURE__*/React.createElement(Select, {
    ...rest,
    choices: choices
  });
}
function UnfilteredForeignKey({
  ["wq:ForeignKey"]: modelName,
  group_by,
  component,
  ...rest
}) {
  const choices = useChoices(modelName, group_by),
    Select = useSelectInput(component);
  return /*#__PURE__*/React.createElement(Select, {
    ...rest,
    choices: choices
  });
}

function Radio$3({
  name,
  label,
  choices,
  horizontal
}) {
  const style = {
    display: "flex",
    flexDirection: horizontal ? "row" : "column"
  };
  return /*#__PURE__*/React.createElement("div", {
    style: {
      marginBottom: "0.5em"
    }
  }, /*#__PURE__*/React.createElement("fieldset", null, /*#__PURE__*/React.createElement("legend", null, label), /*#__PURE__*/React.createElement("div", {
    style: style
  }, choices.map(({
    name: value,
    label
  }) => /*#__PURE__*/React.createElement("label", {
    key: value
  }, /*#__PURE__*/React.createElement(Field, {
    name: name,
    type: "radio",
    value: value
  }), label)))), /*#__PURE__*/React.createElement(ErrorMessage, {
    name: name
  }));
}
Radio$3.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  label: PropTypes.string,
  horizontal: PropTypes.bool,
  choices: PropTypes.arrayOf(PropTypes.object)
};

function Toggle$1(props) {
  return /*#__PURE__*/React.createElement(Radio$3, {
    horizontal: true,
    ...props
  });
}

function Hidden$2(props) {
  const {
    name
  } = props;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Field, {
    ...props,
    type: "hidden"
  }), /*#__PURE__*/React.createElement(ErrorMessage, {
    name: name
  }));
}
Hidden$2.propTypes = {
  name: PropTypes.string
};

function HelperText$1({
  name,
  hint
}) {
  const {
      errors,
      touched
    } = useFormikContext(),
    error = getIn(errors, name),
    showError = !!error && !!getIn(touched, name);
  if (showError) {
    hint = error;
  }
  if (!hint) {
    return null;
  }
  return /*#__PURE__*/React.createElement("p", {
    style: showError && {
      color: "red"
    }
  }, hint);
}
HelperText$1.propTypes = {
  name: PropTypes.string,
  hint: PropTypes.string
};

function Fieldset$1({
  label,
  children
}) {
  return /*#__PURE__*/React.createElement("fieldset", null, /*#__PURE__*/React.createElement("legend", null, label), children);
}
Fieldset$1.propTypes = {
  label: PropTypes.string,
  children: PropTypes.node
};

function FlatFieldset$1({
  label,
  children
}) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h6", null, label), children);
}
FlatFieldset$1.propTypes = {
  label: PropTypes.string,
  children: PropTypes.node
};

function FieldsetArray$1({
  label,
  children,
  addRow
}) {
  const {
    View,
    Button
  } = useComponents();
  return /*#__PURE__*/React.createElement(View, null, children, addRow && /*#__PURE__*/React.createElement(Button, {
    onClick: () => addRow()
  }, `Add ${label}`));
}
FieldsetArray$1.propTypes = {
  label: PropTypes.string,
  children: PropTypes.node,
  addRow: PropTypes.func
};

const Date$2 = Input$4;
const Time$1 = Input$4;
const dateTime$1 = Input$4;

var inputs$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Checkbox: Input$4,
  Date: Date$2,
  DateTime: Input$4,
  Fieldset: Fieldset$1,
  FieldsetArray: FieldsetArray$1,
  File: File$2,
  FileArray: FieldsetArray$1,
  FlatFieldset: FlatFieldset$1,
  ForeignKey: ForeignKey$1,
  HelperText: HelperText$1,
  Hidden: Hidden$2,
  Image: Image$1,
  Input: Input$4,
  Radio: Radio$3,
  Select: Select$4,
  Time: Time$1,
  Toggle: Toggle$1,
  dateTime: dateTime$1
});

function Add$1() {
  return "\u2795"; // Plus
}

function Edit$1() {
  return "\u270f"; // Pencil
}

function Delete$2() {
  return "\u{1f5d1}"; // Wastebasket
}

function Success() {
  return "\u2714"; // Check Mark
}

function Error$2() {
  return "\u274c"; // Cross Mark
}

function Pending() {
  return "\u23f3"; // Hourglass Not Done
}

function GpsStart() {
  return "\u{1f6f0}\u{fe0f}"; // Satellite
}

function GpsStop() {
  return "\u{1f6d1}"; // Stop Sign
}

function Search$1() {
  return "\u{1f50d}"; // Magnifying Glass
}

function List$3() {
  return "\u{1f9fe}"; // Reciept
}

function Detail() {
  return "\u2139"; // Info
}

function Map$5() {
  return "\u{1f5fa}"; // World Map
}

function Home$1() {
  return "\u{1f3e0}";
}
function Expand() {
  return "\u2b07";
}
function BreadcrumbSeparator() {
  return "\u27a1";
}
function Menu$3() {
  return "\u{1f4c2}"; // Open File Folder
}

function Login$2() {
  return "\u{1f511}"; // Key
}

function Logout$2() {
  return "\u274c"; // Cross Mark
}

function Config() {
  return "\u{1f6e0}"; // Hammer and Wrench
}

function External() {
  return "\u{1f517}"; // Link
}

var icons$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Add: Add$1,
  BreadcrumbSeparator: BreadcrumbSeparator,
  Config: Config,
  Delete: Delete$2,
  Detail: Detail,
  Edit: Edit$1,
  Error: Error$2,
  Expand: Expand,
  External: External,
  GpsStart: GpsStart,
  GpsStop: GpsStop,
  Home: Home$1,
  List: List$3,
  Login: Login$2,
  Logout: Logout$2,
  Map: Map$5,
  Menu: Menu$3,
  Pending: Pending,
  Search: Search$1,
  Success: Success
});

function Default() {
  const {
      template
    } = useRouteInfo(),
    {
      View,
      Text,
      DebugContext
    } = useComponents();
  return /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, null, "To customize this view, define views.", pascalCase(template), " in a plugin."), /*#__PURE__*/React.createElement(DebugContext, null));
}

function DefaultList() {
  const reverse = useReverse(),
    {
      list,
      unsynced,
      empty,
      page_config
    } = useList(),
    {
      Message,
      ScrollView,
      List,
      ListSubheader,
      ListItem,
      ListItemLink,
      Pagination,
      Fab
    } = useComponents(),
    {
      OutboxList
    } = useViewComponents(),
    {
      page,
      can_add,
      can_view
    } = page_config,
    hasUnsynced = unsynced.length > 0;
  function Row({
    id,
    label
  }) {
    if (can_view === false) {
      return /*#__PURE__*/React.createElement(ListItem, null, label);
    } else {
      return /*#__PURE__*/React.createElement(ListItemLink, {
        to: reverse(`${page}_detail`, id)
      }, label);
    }
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ScrollView, null, hasUnsynced ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(OutboxList, {
    modelConf: page_config
  }), !empty && /*#__PURE__*/React.createElement(List, null, /*#__PURE__*/React.createElement(ListSubheader, null, /*#__PURE__*/React.createElement(Message, {
    id: "SYNCED_ITEMS"
  })), list.map(row => /*#__PURE__*/React.createElement(Row, {
    key: row.id,
    ...row
  })))) : /*#__PURE__*/React.createElement(List, null, empty ? /*#__PURE__*/React.createElement(ListItem, null, /*#__PURE__*/React.createElement(Message, {
    id: "LIST_IS_EMPTY"
  })) : list.map(row => /*#__PURE__*/React.createElement(Row, {
    key: row.id,
    ...row
  }))), /*#__PURE__*/React.createElement(Pagination, null)), can_add !== false && /*#__PURE__*/React.createElement(Fab, {
    icon: "add",
    to: reverse(`${page}_edit:new`)
  }));
}

function DefaultDetail() {
  const reverse = useReverse(),
    context = useRenderContext(),
    {
      page,
      item_id,
      page_config
    } = useRouteInfo(),
    {
      ScrollView,
      PropertyTable,
      Fab
    } = useComponents(),
    form = page_config.form || [{
      name: "label"
    }],
    editUrl = reverse(`${page}_edit`, item_id);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ScrollView, null, /*#__PURE__*/React.createElement(PropertyTable, {
    form: form,
    values: context
  })), page_config.can_change !== false && /*#__PURE__*/React.createElement(Fab, {
    icon: "edit",
    to: editUrl
  }));
}

function DefaultEdit() {
  const reverse = useReverse(),
    context = useRenderContext(),
    {
      page,
      variant,
      page_config,
      outbox_id
    } = useRouteInfo(),
    {
      form
    } = page_config,
    {
      ScrollView,
      AutoForm,
      DeleteForm
    } = useComponents();
  let backUrl;
  if (outbox_id || variant === "new") {
    backUrl = reverse(`${page_config.name}_list`);
  } else {
    backUrl = reverse(`${page}_detail`, context.id);
  }
  let submitUrl, method;
  if (context.id) {
    submitUrl = `${page_config.url}/${context.id}`;
    method = "PUT";
  } else {
    submitUrl = `${page_config.url}/`;
    method = "POST";
  }
  return /*#__PURE__*/React.createElement(ScrollView, null, context.id && page_config.can_delete !== false && /*#__PURE__*/React.createElement(DeleteForm, {
    action: submitUrl
  }), /*#__PURE__*/React.createElement(AutoForm, {
    action: submitUrl,
    cancel: backUrl,
    method: method,
    backgroundSync: page_config.background_sync,
    outboxId: outbox_id,
    data: context,
    error: outbox_id ? context.error : null,
    form: form,
    modelConf: page_config
  }));
}

function Index({
  onNavigate
}) {
  const reverse = useReverse(),
    routeTitle = useRouteTitle(),
    {
      name: currentRoute
    } = useRouteInfo(),
    sections = useSitemap(),
    {
      ScrollView,
      List,
      ListSubheader,
      ListItemLink
    } = useComponents();
  function PageLink({
    route,
    config: {
      icon = null,
      external = false,
      description = null,
      url = "/"
    } = {}
  }) {
    const title = routeTitle(route),
      props = {};
    if (external) {
      props.component = "a";
      props.href = url;
      props.icon = icon || "external";
    } else {
      props.to = reverse(route);
      props.selected = currentRoute.split("_")[0] === route.split("_")[0];
      props.icon = icon || (route.endsWith("_list") ? "list" : "config");
    }
    if (description) {
      props.description = description;
    }
    if (onNavigate) {
      props.onClick = () => onNavigate(route);
    }
    return /*#__PURE__*/React.createElement(ListItemLink, {
      ...props
    }, title);
  }
  PageLink.propTypes = {
    route: PropTypes.string,
    config: PropTypes.object
  };
  return /*#__PURE__*/React.createElement(ScrollView, null, /*#__PURE__*/React.createElement(List, null, sections.map(({
    name,
    pages
  }) => /*#__PURE__*/React.createElement(React.Fragment, null, name && /*#__PURE__*/React.createElement(ListSubheader, null, name), pages.map(page => /*#__PURE__*/React.createElement(PageLink, {
    key: page.name,
    route: page.route,
    config: page
  }))))));
}
Index.propTypes = {
  onNavigate: PropTypes.func
};

function Login$1() {
  const reverse = useReverse(),
    {
      Message,
      Form,
      FormError,
      HorizontalView,
      CancelButton,
      SubmitButton,
      View,
      Text,
      ButtonLink
    } = useComponents(),
    {
      Input
    } = useInputComponents(),
    {
      is_authenticated,
      user
    } = useRenderContext();
  if (is_authenticated) {
    return /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, null, "Logged in as ", user.label || user.username), /*#__PURE__*/React.createElement(HorizontalView, null, /*#__PURE__*/React.createElement(ButtonLink, {
      to: reverse("logout")
    }, "Log Out"), /*#__PURE__*/React.createElement(ButtonLink, {
      to: reverse("index")
    }, "Return to Home")));
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Form, {
    action: "login",
    method: "POST",
    storage: "temporary",
    backgroundSync: false
  }, /*#__PURE__*/React.createElement(Input, {
    name: "username",
    label: "Username"
  }), /*#__PURE__*/React.createElement(Input, {
    name: "password",
    type: "password",
    label: "Password"
  }), /*#__PURE__*/React.createElement(FormError, null), /*#__PURE__*/React.createElement(HorizontalView, null, /*#__PURE__*/React.createElement(CancelButton, {
    to: reverse("index")
  }, /*#__PURE__*/React.createElement(Message, {
    id: "CANCEL"
  })), /*#__PURE__*/React.createElement(SubmitButton, null, /*#__PURE__*/React.createElement(Message, {
    id: "SUBMIT"
  })))));
}

function Logout$1() {
  const {
      is_authenticated
    } = useRenderContext(),
    {
      Message,
      View,
      Text
    } = useComponents();
  return /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, null, /*#__PURE__*/React.createElement(Message, {
    id: is_authenticated ? "LOGGING_OUT" : "LOGGED_OUT"
  })));
}

function OutboxList({
  modelConf
}) {
  const app = useApp(),
    reverse = useReverse(),
    routeTitle = useRouteTitle(),
    allItems = useOutbox(),
    items = modelConf ? app.outbox.filterUnsynced(allItems, modelConf) : allItems,
    {
      Message,
      List,
      ListItem,
      ListItemLink,
      ListSubheader,
      View,
      ScrollView,
      HorizontalView,
      Button
    } = useComponents();
  const empty = !items.length;
  function getLink(item) {
    if (item.synced) {
      // TODO: Link to model detail or edit page?
      return null;
    } else {
      return reverse("outbox_edit", item.id);
    }
  }
  function getIcon(item) {
    if (item.synced) {
      return "success";
    } else if (item.error) {
      return "error";
    } else {
      return "pending";
    }
  }
  function getTitle(item) {
    if (item.options.modelConf && !modelConf) {
      const pageName = routeTitle(`${item.options.modelConf.name}_detail`);
      return `${pageName}: ${item.label}`;
    } else {
      return item.label;
    }
  }
  function getStatus(item) {
    if (item.synced) {
      return "SYNC_SUCCESS";
    } else if (item.error) {
      if (typeof item.error === "string") {
        return item.error;
      } else {
        return "SYNC_ERROR";
      }
    } else {
      return null;
    }
  }
  function OutboxItems() {
    return /*#__PURE__*/React.createElement(React.Fragment, null, empty && /*#__PURE__*/React.createElement(ListItem, null, /*#__PURE__*/React.createElement(Message, {
      id: "OUTBOX_IS_EMPTY"
    })), items.map(item => {
      const link = getLink(item),
        ListItemOrLink = link ? ListItemLink : ListItem;
      return /*#__PURE__*/React.createElement(ListItemOrLink, {
        key: item.id,
        to: link,
        icon: getIcon(item),
        description: /*#__PURE__*/React.createElement(Message, {
          id: getStatus(item)
        })
      }, getTitle(item));
    }));
  }
  if (modelConf) {
    return /*#__PURE__*/React.createElement(List, null, /*#__PURE__*/React.createElement(ListSubheader, null, /*#__PURE__*/React.createElement(Message, {
      id: "UNSYNCED_ITEMS"
    })), /*#__PURE__*/React.createElement(OutboxItems, null));
  } else {
    return /*#__PURE__*/React.createElement(View, {
      style: {
        flex: 1,
        display: "flex",
        flexDirection: "column"
      }
    }, /*#__PURE__*/React.createElement(ScrollView, null, /*#__PURE__*/React.createElement(List, null, /*#__PURE__*/React.createElement(OutboxItems, null))), !empty && /*#__PURE__*/React.createElement(HorizontalView, null, /*#__PURE__*/React.createElement(Button, {
      onClick: () => app.emptyOutbox(true)
    }, /*#__PURE__*/React.createElement(Message, {
      id: "EMPTY_OUTBOX"
    })), /*#__PURE__*/React.createElement(Button, {
      onClick: () => app.retryAll()
    }, /*#__PURE__*/React.createElement(Message, {
      id: "RETRY_ALL"
    }))));
  }
}
OutboxList.propTypes = {
  modelConf: PropTypes.object
};

function Loading() {
  const {
    Message,
    Text
  } = useComponents();
  return /*#__PURE__*/React.createElement(Text, null, /*#__PURE__*/React.createElement(Message, {
    id: "LOADING"
  }));
}

function NotFound() {
  const {
    url
  } = useRenderContext();
  return /*#__PURE__*/React.createElement(React.Fragment, null, "Page ", url, " not found.");
}

const HTML$1 = "@@HTML";
function Server() {
  const html = useRenderContext()[HTML$1];
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", null, "This renderer does not (yet) support server-rendered HTML."), /*#__PURE__*/React.createElement("pre", null, /*#__PURE__*/React.createElement("code", null, html)));
}

var views = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Default: Default,
  DefaultDetail: DefaultDetail,
  DefaultEdit: DefaultEdit,
  DefaultList: DefaultList,
  Index: Index,
  Loading: Loading,
  Login: Login$1,
  Logout: Logout$1,
  NavMenu: Index,
  NotFound: NotFound,
  OutboxList: OutboxList,
  Server: Server
});

function validate(values, modelConf) {
  const labels = [],
    errors = validateRequired(values, modelConf && modelConf.form, labels);
  if (errors && labels.length) {
    errors["__other__"] = "The following fields are required: " + labels.filter((label, i) => labels.indexOf(label) === i).join(", ");
  }
  return errors || {};
}
function validateRequired(values, form, labels = null) {
  if (!values || !form) {
    return null;
  }
  const errors = {};
  form.forEach(field => {
    const name = field["wq:ForeignKey"] ? `${field.name}_id` : field.name,
      value = values[name];
    if (isMissing(value, field)) {
      errors[name] = "This field is required.";
      if (labels) {
        labels.push(field.label);
      }
    } else if (value && field.type === "repeat") {
      const nestedErrors = value.map(row => validateRequired(row, field.children, labels));
      if (nestedErrors.some(row => row)) {
        errors[name] = nestedErrors;
      }
    } else if (field.type === "group") {
      if (name === "") {
        Object.assign(errors, validateRequired(values, field.children, labels));
      } else if (value) {
        const nestedErrors = validateRequired(value, field.children, labels);
        if (nestedErrors) {
          errors[name] = nestedErrors;
        }
      }
    }
  });
  return Object.keys(errors).length > 0 ? errors : null;
}
function isMissing(value, field) {
  if (field.required || field.bind && field.bind.required) {
    return value === undefined || value === null || value === "";
  } else {
    return false;
  }
}

var react = {
  name: "react",
  type: "renderer",
  dependencies: [orm],
  config: {
    messages: {
      ...messages
    }
  },
  registry: {
    components: {
      ...components$1
    },
    inputs: {
      ...inputs$1
    },
    icons: {
      ...icons$1
    },
    views: {
      ...views
    }
  },
  setEngine({
    init,
    start,
    unmount,
    App
  }) {
    this.engine = {
      init,
      start,
      unmount
    };
    this.registry.components.App = App;
  },
  init(config) {
    if (!this.engine) {
      throw new Error("Missing react engine!");
    }
    if (config) {
      Object.assign(this.config, config);
    }
    Object.values(this.app.plugins).forEach(plugin => {
      if (plugin.messages) {
        Object.assign(this.config.messages, plugin.messages);
      }
      if (plugin.components) {
        Object.assign(this.registry.components, plugin.components);
      }
      if (plugin.inputs) {
        Object.assign(this.registry.inputs, plugin.inputs);
      }
      if (plugin.icons) {
        Object.assign(this.registry.icons, plugin.icons);
      }
      if (plugin.views) {
        Object.assign(this.registry.views, plugin.views);
      }
    });
    this.engine.init.call(this);
  },
  getRootComponent() {
    const {
        app,
        registry
      } = this,
      {
        components
      } = registry,
      {
        App
      } = components;
    const AppRoot = () => /*#__PURE__*/React.createElement(Provider, {
      store: this.app.store._store
    }, /*#__PURE__*/React.createElement(AppContext.Provider, {
      value: {
        app
      }
    }, /*#__PURE__*/React.createElement(App, null)));
    AppRoot.displayName = "AppRoot";
    return AppRoot;
  },
  start() {
    this.engine.start.call(this);
  },
  validate,
  createInstance(component, root, app) {
    if (!app) {
      app = this.app;
    }
    const tempPlugin = {
      app: {
        ...app,
        plugins: {
          ...app.plugins
        }
      },
      config: {
        messages: {}
      },
      engine: this.engine,
      registry: {
        components: {},
        inputs: {},
        icons: {},
        views: {}
      },
      root,
      getRootComponent: this.getRootComponent
    };
    this.init.call(tempPlugin);
    tempPlugin.app.plugins.react = tempPlugin;
    tempPlugin.registry.components.App = component;
    return {
      start: () => this.start.call(tempPlugin),
      getRootComponent: () => tempPlugin.getRootComponent(),
      stop: () => this.engine.unmount.call(tempPlugin)
    };
  },
  attach(component, root, app) {
    const instance = this.createInstance(component, root, app);
    instance.start();
    return () => instance.stop();
  },
  wrap(component, app) {
    const emptyRoot = {},
      instance = this.createInstance(component, emptyRoot, app);
    return instance.getRootComponent();
  }
};
const {
  Link: Link$3,
  Message,
  Form,
  FormError: FormError$1,
  AutoForm,
  AutoInput,
  AutoSubform,
  AutoSubformArray,
  PropertyTable,
  ImagePreview,
  FileLink,
  DebugContext
} = components$1;
const autoFormData = AutoForm.initData;
const {
  ForeignKey
} = inputs$1;

const HTML = "@@HTML",
  // @wq/router
  CURRENT = "@@CURRENT"; // @wq/router

function App$1({
  route
}) {
  if (!route) {
    route = CURRENT;
  }
  return /*#__PURE__*/React.createElement(RouteContext.Provider, {
    value: {
      name: route
    }
  }, /*#__PURE__*/React.createElement(AppLayout, {
    showHeader: route === CURRENT
  }));
}
App$1.propTypes = {
  route: PropTypes.string
};
function AppLayout({
  showHeader
}) {
  const context = useRenderContext(),
    routeInfo = useRouteInfo(),
    views = useViewComponents(),
    PluginContent = usePluginContent(),
    {
      Container,
      Header,
      NavMenuFixed,
      Footer,
      Main,
      Spinner
    } = useComponents();
  let name;
  if (routeInfo.pending) {
    name = "loading";
  } else if (context[HTML]) {
    name = "server";
  } else if (views[routeInfo.template]) {
    name = routeInfo.template;
  } else if (typeof routeInfo.template === "string" && views[routeInfo.template.replace("_", "-")]) {
    name = routeInfo.template.replace("_", "-");
  } else if (views[routeInfo.name]) {
    name = routeInfo.name;
  } else if (routeInfo.mode) {
    const {
        page,
        mode
      } = routeInfo,
      names = [`${page}_${mode}`, `${page}-${mode}`, `default-${mode}`, "default"];
    name = names.find(name => views[name]);
  } else {
    name = "default";
  }
  const View = views[name];
  if (!View) {
    return /*#__PURE__*/React.createElement(Container, null, `Missing ${name} view!`, /*#__PURE__*/React.createElement(Spinner, null));
  }
  if (View.fullscreen) {
    return /*#__PURE__*/React.createElement(Container, null, /*#__PURE__*/React.createElement(View, null), /*#__PURE__*/React.createElement(PluginContent, null), /*#__PURE__*/React.createElement(Spinner, null));
  } else {
    return /*#__PURE__*/React.createElement(Container, null, showHeader && /*#__PURE__*/React.createElement(Header, null), /*#__PURE__*/React.createElement(Main, null, /*#__PURE__*/React.createElement(NavMenuFixed, null), /*#__PURE__*/React.createElement(View, null), /*#__PURE__*/React.createElement(PluginContent, null)), /*#__PURE__*/React.createElement(Footer, null), /*#__PURE__*/React.createElement(Spinner, null));
  }
}
AppLayout.propTypes = {
  showHeader: PropTypes.bool
};

var createRoot;

var m = reactDomExports;
{
  var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  createRoot = function (c, o) {
    i.usingClientEntryPoint = true;
    try {
      return m.createRoot(c, o);
    } finally {
      i.usingClientEntryPoint = false;
    }
  };
}

function init() {
  if (!this.root) {
    this.root = document.body.appendChild(document.createElement("div"));
    this.root.id = "wq-app-root";
  }
}
function start$1() {
  const RootComponent = this.getRootComponent();
  this._reactRoot = createRoot(this.root);
  this._reactRoot.render( /*#__PURE__*/React.createElement(RootComponent, null));
}
function unmount() {
  if (this._reactRoot) {
    this._reactRoot.unmount();
  }
}

react.setEngine({
  init,
  start: start$1,
  unmount,
  App: App$1
});

var reactExports = /*#__PURE__*/Object.freeze({
  __proto__: null,
  App: App$1,
  AppContext: AppContext,
  AutoForm: AutoForm,
  AutoInput: AutoInput,
  AutoSubform: AutoSubform,
  AutoSubformArray: AutoSubformArray,
  DebugContext: DebugContext,
  Default: Default,
  DefaultDetail: DefaultDetail,
  DefaultEdit: DefaultEdit,
  DefaultList: DefaultList,
  FileLink: FileLink,
  ForeignKey: ForeignKey,
  Form: Form,
  FormError: FormError$1,
  ImagePreview: ImagePreview,
  Index: Index,
  Link: Link$3,
  Loading: Loading,
  Login: Login$1,
  Logout: Logout$1,
  Message: Message,
  NavMenu: Index,
  NotFound: NotFound,
  OutboxList: OutboxList,
  PropertyTable: PropertyTable,
  RouteContext: RouteContext,
  Server: Server,
  autoFormData: autoFormData,
  default: react,
  getPageRoute: getPageRoute,
  getPageSection: getPageSection,
  orderSort: orderSort,
  showInIndex: showInIndex,
  toNavAction: toNavAction,
  useApp: useApp,
  useBreadcrumbs: useBreadcrumbs,
  useComponents: useComponents,
  useConfig: useConfig,
  useContextTitle: useContextTitle,
  useCurrentRoute: useCurrentRoute,
  useHtmlInput: useHtmlInput,
  useIcon: useIcon,
  useIconComponents: useIconComponents,
  useIndexRoute: useIndexRoute,
  useInputComponents: useInputComponents,
  useList: useList,
  useMessages: useMessages,
  useModel: useModel,
  useNav: useNav,
  useNavAction: useNavAction,
  useOutbox: useOutbox,
  usePlugin: usePlugin,
  usePluginComponentMap: usePluginComponentMap,
  usePluginContent: usePluginContent,
  usePluginReducer: usePluginReducer,
  usePluginState: usePluginState,
  useRenderContext: useRenderContext,
  useReverse: useReverse,
  useRouteInfo: useRouteInfo,
  useRouteTitle: useRouteTitle,
  useRoutesMap: useRoutesMap,
  useSiteTitle: useSiteTitle,
  useSitemap: useSitemap,
  useSpinner: useSpinner,
  useUnsynced: useUnsynced,
  useValidate: useValidate,
  useViewComponents: useViewComponents
});

function chainPropTypes(propType1, propType2) {
  return function validate(...args) {
    return propType1(...args) || propType2(...args);
  };
}

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 ? {
    ...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;
}

function isClassComponent$1(elementType) {
  // elementType.prototype?.isReactComponent
  const {
    prototype = {}
  } = elementType;
  return Boolean(prototype.isReactComponent);
}
function acceptingRef(props, propName, componentName, location, propFullName) {
  const element = props[propName];
  const safePropName = propFullName || propName;
  if (element == null ||
  // When server-side rendering React doesn't warn either.
  // This is not an accurate check for SSR.
  // This is only in place for Emotion compat.
  // TODO: Revisit once https://github.com/facebook/react/issues/20047 is resolved.
  typeof window === 'undefined') {
    return null;
  }
  let warningHint;
  const elementType = element.type;
  /**
   * Blacklisting instead of whitelisting
   *
   * Blacklisting will miss some components, such as React.Fragment. Those will at least
   * trigger a warning in React.
   * We can't whitelist because there is no safe way to detect React.forwardRef
   * or class components. "Safe" means there's no public API.
   *
   */
  if (typeof elementType === 'function' && !isClassComponent$1(elementType)) {
    warningHint = 'Did you accidentally use a plain function component for an element instead?';
  }
  if (warningHint !== undefined) {
    return new Error(`Invalid ${location} \`${safePropName}\` supplied to \`${componentName}\`. ` + `Expected an element that can hold a ref. ${warningHint} ` + 'For more information see https://mui.com/r/caveat-with-refs-guide');
  }
  return null;
}
const elementAcceptingRef = chainPropTypes(PropTypes.element, acceptingRef);
elementAcceptingRef.isRequired = chainPropTypes(PropTypes.element.isRequired, acceptingRef);
var elementAcceptingRef$1 = elementAcceptingRef;

function isClassComponent(elementType) {
  // elementType.prototype?.isReactComponent
  const {
    prototype = {}
  } = elementType;
  return Boolean(prototype.isReactComponent);
}
function elementTypeAcceptingRef(props, propName, componentName, location, propFullName) {
  const propValue = props[propName];
  const safePropName = propFullName || propName;
  if (propValue == null ||
  // When server-side rendering React doesn't warn either.
  // This is not an accurate check for SSR.
  // This is only in place for emotion compat.
  // TODO: Revisit once https://github.com/facebook/react/issues/20047 is resolved.
  typeof window === 'undefined') {
    return null;
  }
  let warningHint;

  /**
   * Blacklisting instead of whitelisting
   *
   * Blacklisting will miss some components, such as React.Fragment. Those will at least
   * trigger a warning in React.
   * We can't whitelist because there is no safe way to detect React.forwardRef
   * or class components. "Safe" means there's no public API.
   *
   */
  if (typeof propValue === 'function' && !isClassComponent(propValue)) {
    warningHint = 'Did you accidentally provide a plain function component instead?';
  }
  if (warningHint !== undefined) {
    return new Error(`Invalid ${location} \`${safePropName}\` supplied to \`${componentName}\`. ` + `Expected an element type that can hold a ref. ${warningHint} ` + 'For more information see https://mui.com/r/caveat-with-refs-guide');
  }
  return null;
}
var elementTypeAcceptingRef$1 = chainPropTypes(PropTypes.elementType, elementTypeAcceptingRef);

// This module is based on https://github.com/airbnb/prop-types-exact repository.
// However, in order to reduce the number of dependencies and to remove some extra safe checks
// the module was forked.
const specialProperty = 'exact-prop: \u200b';
function exactProp(propTypes) {
  return {
    ...propTypes,
    [specialProperty]: props => {
      const unsupportedProps = Object.keys(props).filter(prop => !propTypes.hasOwnProperty(prop));
      if (unsupportedProps.length > 0) {
        return new Error(`The following props are not supported: ${unsupportedProps.map(prop => `\`${prop}\``).join(', ')}. Please remove them.`);
      }
      return null;
    }
  };
}

/**
 * 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 */
}

// Simplified polyfill for IE11 support
// https://github.com/JamesMGreene/Function.name/blob/58b314d4a983110c3682f1228f845d39ccca1817/Function.name.js#L3
const fnNameMatchRegex = /^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/;
function getFunctionName(fn) {
  const match = `${fn}`.match(fnNameMatchRegex);
  const name = match && match[1];
  return name || '';
}
function getFunctionComponentName(Component, fallback = '') {
  return Component.displayName || Component.name || getFunctionName(Component) || fallback;
}
function getWrappedName(outerType, innerType, wrapperName) {
  const functionName = getFunctionComponentName(innerType);
  return outerType.displayName || (functionName !== '' ? `${wrapperName}(${functionName})` : wrapperName);
}

/**
 * cherry-pick from
 * https://github.com/facebook/react/blob/769b1f270e1251d9dbdce0fcbd9e92e502d059b8/packages/shared/getComponentName.js
 * originally forked from recompose/getDisplayName with added IE11 support
 */
function getDisplayName(Component) {
  if (Component == null) {
    return undefined;
  }
  if (typeof Component === 'string') {
    return Component;
  }
  if (typeof Component === 'function') {
    return getFunctionComponentName(Component, 'Component');
  }

  // TypeScript can't have components as objects but they exist in the form of `memo` or `Suspense`
  if (typeof Component === 'object') {
    switch (Component.$$typeof) {
      case reactIsExports$1.ForwardRef:
        return getWrappedName(Component, Component.render, 'ForwardRef');
      case reactIsExports$1.Memo:
        return getWrappedName(Component, Component.type, 'memo');
      default:
        return undefined;
    }
  }
  return undefined;
}

function HTMLElementType(props, propName, componentName, location, propFullName) {
  const propValue = props[propName];
  const safePropName = propFullName || propName;
  if (propValue == null) {
    return null;
  }
  if (propValue && propValue.nodeType !== 1) {
    return new Error(`Invalid ${location} \`${safePropName}\` supplied to \`${componentName}\`. ` + `Expected an HTMLElement.`);
  }
  return null;
}

/* eslint-disable */
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var ponyfillGlobal = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();

const refType = PropTypes.oneOfType([PropTypes.func, PropTypes.object]);
var refType$1 = refType;

// 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(`MUI: \`capitalize(string)\` expects a string argument.` );
  }
  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 (props, propName, componentName, location, propFullName) => {
    const componentNameSafe = componentName || '<<anonymous>>';
    const propFullNameSafe = propFullName || propName;
    if (typeof props[propName] !== 'undefined') {
      return new Error(`The ${location} \`${propFullNameSafe}\` of ` + `\`${componentNameSafe}\` is deprecated. ${reason}`);
    }
    return null;
  };
}

function isMuiElement(element, muiNames) {
  return /*#__PURE__*/reactExports$1.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) {

  // eslint-disable-next-line react/forbid-foreign-prop-types
  const prevPropTypes = Component ? {
    ...Component.propTypes
  } : null;
  const requireProp = requiredProp => (props, propName, componentName, location, propFullName, ...args) => {
    const propFullNameSafe = propFullName || propName;
    const defaultTypeChecker = prevPropTypes == null ? void 0 : prevPropTypes[propFullNameSafe];
    if (defaultTypeChecker) {
      const typeCheckerResult = defaultTypeChecker(props, propName, componentName, location, propFullName, ...args);
      if (typeCheckerResult) {
        return typeCheckerResult;
      }
    }
    if (typeof props[propName] !== 'undefined' && !props[requiredProp]) {
      return new Error(`The prop \`${propFullNameSafe}\` of ` + `\`${componentNameInError}\` can only be used together with the \`${requiredProp}\` prop.`);
    }
    return null;
  };
  return requireProp;
}

/**
 * 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$1.useLayoutEffect : reactExports$1.useEffect;
var useEnhancedEffect$1 = useEnhancedEffect;

let globalId = 0;
function useGlobalId(idOverride) {
  const [defaultId, setDefaultId] = reactExports$1.useState(idOverride);
  const id = idOverride || defaultId;
  reactExports$1.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;
}

// downstream bundlers may remove unnecessary concatenation, but won't remove toString call -- Workaround for https://github.com/webpack/webpack/issues/14814
const maybeReactUseId = React$1['useId'.toString()];
/**
 *
 * @example <div id={useId()} />
 * @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) {
  const propFullNameSafe = propFullName || propName;
  if (typeof props[propName] !== 'undefined') {
    return new Error(`The prop \`${propFullNameSafe}\` is not supported. Please remove it.`);
  }
  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$1.useRef(controlled !== undefined);
  const [valueState, setValue] = reactExports$1.useState(defaultProp);
  const value = isControlled ? controlled : valueState;
  {
    reactExports$1.useEffect(() => {
      if (isControlled !== (controlled !== undefined)) {
        console.error([`MUI: A component is changing the ${isControlled ? '' : 'un'}controlled ${state} state of ${name} to be ${isControlled ? 'un' : ''}controlled.`, 'Elements should not switch from uncontrolled to controlled (or vice versa).', `Decide between using a controlled or uncontrolled ${name} ` + 'element for the lifetime of the component.', "The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.", 'More info: https://fb.me/react-controlled-components'].join('\n'));
      }
    }, [state, name, controlled]);
    const {
      current: defaultValue
    } = reactExports$1.useRef(defaultProp);
    reactExports$1.useEffect(() => {
      if (!isControlled && defaultValue !== defaultProp) {
        console.error([`MUI: A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. ` + `To suppress this warning opt to use a controlled ${name}.`].join('\n'));
      }
    }, [JSON.stringify(defaultProp)]);
  }
  const setValueIfUncontrolled = reactExports$1.useCallback(newValue => {
    if (!isControlled) {
      setValue(newValue);
    }
  }, []);
  return [value, setValueIfUncontrolled];
}

/**
 * https://github.com/facebook/react/issues/14099#issuecomment-440013892
 */
function useEventCallback(fn) {
  const ref = reactExports$1.useRef(fn);
  useEnhancedEffect$1(() => {
    ref.current = fn;
  });
  return reactExports$1.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$1.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$1.useCallback(node => {
    if (node != null) {
      prepare(node.ownerDocument);
    }
  }, []);
  const isFocusVisibleRef = reactExports$1.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);
}

// Source from https://github.com/alitaheri/normalize-scroll-left
let cachedType;

/**
 * Based on the jquery plugin https://github.com/othree/jquery.rtl-scroll-type
 *
 * Types of scrollLeft, assuming scrollWidth=100 and direction is rtl.
 *
 * Type             | <- Most Left | Most Right -> | Initial
 * ---------------- | ------------ | ------------- | -------
 * default          | 0            | 100           | 100
 * negative (spec*) | -100         | 0             | 0
 * reverse          | 100          | 0             | 0
 *
 * Edge 85: default
 * Safari 14: negative
 * Chrome 85: negative
 * Firefox 81: negative
 * IE11: reverse
 *
 * spec* https://drafts.csswg.org/cssom-view/#dom-window-scroll
 */
function detectScrollType() {
  if (cachedType) {
    return cachedType;
  }
  const dummy = document.createElement('div');
  const container = document.createElement('div');
  container.style.width = '10px';
  container.style.height = '1px';
  dummy.appendChild(container);
  dummy.dir = 'rtl';
  dummy.style.fontSize = '14px';
  dummy.style.width = '4px';
  dummy.style.height = '1px';
  dummy.style.position = 'absolute';
  dummy.style.top = '-1000px';
  dummy.style.overflow = 'scroll';
  document.body.appendChild(dummy);
  cachedType = 'reverse';
  if (dummy.scrollLeft > 0) {
    cachedType = 'default';
  } else {
    dummy.scrollLeft = 1;
    if (dummy.scrollLeft === 0) {
      cachedType = 'negative';
    }
  }
  document.body.removeChild(dummy);
  return cachedType;
}

// Based on https://stackoverflow.com/a/24394376
function getNormalizedScrollLeft(element, direction) {
  const scrollLeft = element.scrollLeft;

  // Perform the calculations only when direction is rtl to avoid messing up the ltr behavior
  if (direction !== 'rtl') {
    return scrollLeft;
  }
  const type = detectScrollType();
  switch (type) {
    case 'negative':
      return element.scrollWidth - element.clientWidth + scrollLeft;
    case 'reverse':
      return element.scrollWidth - element.clientWidth - scrollLeft;
    default:
      return scrollLeft;
  }
}

const usePreviousProps = value => {
  const ref = reactExports$1.useRef({});
  reactExports$1.useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};
var usePreviousProps$1 = usePreviousProps;

const visuallyHidden = {
  border: 0,
  clip: 'rect(0 0 0 0)',
  height: '1px',
  margin: -1,
  overflow: 'hidden',
  padding: 0,
  position: 'absolute',
  whiteSpace: 'nowrap',
  width: '1px'
};
var visuallyHidden$1 = visuallyHidden;

function getTypeByValue(value) {
  const valueType = typeof value;
  switch (valueType) {
    case 'number':
      if (Number.isNaN(value)) {
        return 'NaN';
      }
      if (!Number.isFinite(value)) {
        return 'Infinity';
      }
      if (value !== Math.floor(value)) {
        return 'float';
      }
      return 'number';
    case 'object':
      if (value === null) {
        return 'null';
      }
      return value.constructor.name;
    default:
      return valueType;
  }
}

// IE 11 support
function ponyfillIsInteger(x) {
  // eslint-disable-next-line no-restricted-globals
  return typeof x === 'number' && isFinite(x) && Math.floor(x) === x;
}
const isInteger = Number.isInteger || ponyfillIsInteger;
function requiredInteger(props, propName, componentName, location) {
  const propValue = props[propName];
  if (propValue == null || !isInteger(propValue)) {
    const propType = getTypeByValue(propValue);
    return new RangeError(`Invalid ${location} \`${propName}\` of type \`${propType}\` supplied to \`${componentName}\`, expected \`integer\`.`);
  }
  return null;
}
function validator(props, propName, ...other) {
  const propValue = props[propName];
  if (propValue === undefined) {
    return null;
  }
  return requiredInteger(props, propName, ...other);
}
function validatorNoop() {
  return null;
}
validator.isRequired = requiredInteger;
validatorNoop.isRequired = validatorNoop;
var integerPropType = validator;

/**
 * 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 = {
    ...props
  };
  Object.keys(defaultProps).forEach(propName => {
    if (propName.toString().match(/^(components|slots)$/)) {
      output[propName] = {
        ...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] = {
          ...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 = undefined) {
  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) {
        const utilityClass = getUtilityClass(key);
        if (utilityClass !== '') {
          acc.push(utilityClass);
        }
        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();
var ClassNameGenerator$1 = ClassNameGenerator;

const globalStateClassesMapping = {
  active: 'active',
  checked: 'checked',
  completed: 'completed',
  disabled: 'disabled',
  readOnly: 'readOnly',
  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 muiUtils = /*#__PURE__*/Object.freeze({
  __proto__: null,
  HTMLElementType: HTMLElementType,
  chainPropTypes: chainPropTypes,
  deepmerge: deepmerge,
  elementAcceptingRef: elementAcceptingRef$1,
  elementTypeAcceptingRef: elementTypeAcceptingRef$1,
  exactProp: exactProp,
  formatMuiErrorMessage: formatMuiErrorMessage,
  getDisplayName: getDisplayName,
  integerPropType: integerPropType,
  internal_resolveProps: resolveProps,
  isPlainObject: isPlainObject,
  ponyfillGlobal: ponyfillGlobal,
  refType: refType$1,
  unstable_ClassNameGenerator: ClassNameGenerator$1,
  unstable_capitalize: capitalize,
  unstable_composeClasses: composeClasses,
  unstable_createChainedFunction: createChainedFunction,
  unstable_debounce: debounce$1,
  unstable_deprecatedPropType: deprecatedPropType,
  unstable_detectScrollType: detectScrollType,
  unstable_generateUtilityClass: generateUtilityClass,
  unstable_generateUtilityClasses: generateUtilityClasses,
  unstable_getNormalizedScrollLeft: getNormalizedScrollLeft,
  unstable_getScrollbarSize: getScrollbarSize,
  unstable_isMuiElement: isMuiElement,
  unstable_ownerDocument: ownerDocument,
  unstable_ownerWindow: ownerWindow,
  unstable_requirePropFactory: requirePropFactory,
  unstable_setRef: setRef,
  unstable_unsupportedProp: unsupportedProp,
  unstable_useControlled: useControlled,
  unstable_useEnhancedEffect: useEnhancedEffect$1,
  unstable_useEventCallback: useEventCallback,
  unstable_useForkRef: useForkRef,
  unstable_useId: useId,
  unstable_useIsFocusVisible: useIsFocusVisible,
  usePreviousProps: usePreviousProps$1,
  visuallyHidden: visuallyHidden$1
});

const _excluded$1I = ["values", "unit", "step"];
const sortBreakpointsValues = values => {
  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$1I);
  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
};
var shape$1 = shape;

const responsivePropType = PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object, PropTypes.array]) ;
var responsivePropType$1 = responsivePropType;

function merge$1(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);
}

// compute base for responsive values; e.g.,
// [1,2,3] => {xs: true, sm: true, md: true}
// {xs: 1, sm: 2, md: 3} => {xs: true, sm: true, md: true}
function computeBreakpointsBase(breakpointValues, themeBreakpoints) {
  // fixed value
  if (typeof breakpointValues !== 'object') {
    return {};
  }
  const base = {};
  const breakpointsKeys = Object.keys(themeBreakpoints);
  if (Array.isArray(breakpointValues)) {
    breakpointsKeys.forEach((breakpoint, i) => {
      if (i < breakpointValues.length) {
        base[breakpoint] = true;
      }
    });
  } else {
    breakpointsKeys.forEach(breakpoint => {
      if (breakpointValues[breakpoint] != null) {
        base[breakpoint] = true;
      }
    });
  }
  return base;
}
function resolveBreakpointValues({
  values: breakpointValues,
  breakpoints: themeBreakpoints,
  base: customBase
}) {
  const base = customBase || computeBreakpointsBase(breakpointValues, themeBreakpoints);
  const keys = Object.keys(base);
  if (keys.length === 0) {
    return breakpointValues;
  }
  let previous;
  return keys.reduce((acc, breakpoint, i) => {
    if (Array.isArray(breakpointValues)) {
      acc[breakpoint] = breakpointValues[i] != null ? breakpointValues[i] : breakpointValues[previous];
      previous = i;
    } else if (typeof breakpointValues === 'object') {
      acc[breakpoint] = breakpointValues[breakpoint] != null ? breakpointValues[breakpoint] : breakpointValues[previous];
      previous = breakpoint;
    } else {
      acc[breakpoint] = breakpointValues;
    }
    return acc;
  }, {});
}

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 = {
    [prop]: responsivePropType$1
  } ;
  fn.filterProps = [prop];
  return fn;
}

function memoize$1(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$1(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'];
const spacingKeys = [...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;
      }
      {
        if (typeof abs !== 'number') {
          console.error(`MUI: Expected ${propName} argument to be a number or a string, got ${abs}.`);
        }
      }
      return themeSpacing * abs;
    };
  }
  if (Array.isArray(themeSpacing)) {
    return abs => {
      if (typeof abs === 'string') {
        return abs;
      }
      {
        if (!Number.isInteger(abs)) {
          console.error([`MUI: The \`theme.${themeKey}\` array type cannot be combined with non integer values.` + `You should either use an integer value that can be used as index, or define the \`theme.${themeKey}\` as a number.`].join('\n'));
        } else if (abs > themeSpacing.length - 1) {
          console.error([`MUI: The value provided (${abs}) overflows.`, `The supported values are: ${JSON.stringify(themeSpacing)}.`, `${abs} > ${themeSpacing.length - 1}, you need to add the missing values.`].join('\n'));
        }
      }
      return themeSpacing[abs];
    };
  }
  if (typeof themeSpacing === 'function') {
    return themeSpacing;
  }
  {
    console.error([`MUI: The \`theme.${themeKey}\` value (${themeSpacing}) is invalid.`, 'It should be a number, an array or a function.'].join('\n'));
  }
  return () => undefined;
}
function createUnarySpacing(theme) {
  return createUnaryUnit(theme, 'spacing', 8, 'spacing');
}
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$1, {});
}
function margin(props) {
  return style(props, marginKeys);
}
margin.propTypes = marginKeys.reduce((obj, key) => {
  obj[key] = responsivePropType$1;
  return obj;
}, {}) ;
margin.filterProps = marginKeys;
function padding(props) {
  return style(props, paddingKeys);
}
padding.propTypes = paddingKeys.reduce((obj, key) => {
  obj[key] = responsivePropType$1;
  return obj;
}, {}) ;
padding.filterProps = paddingKeys;
spacingKeys.reduce((obj, key) => {
  obj[key] = responsivePropType$1;
  return obj;
}, {}) ;

// The different signatures imply different meaning for their arguments that can't be expressed structurally.
// We express the difference with variable names.
/* tslint:disable:unified-signatures */
/* 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) => {
    {
      if (!(argsInput.length <= 4)) {
        console.error(`MUI: Too many arguments provided, expected between 0 and 4, got ${argsInput.length}`);
      }
    }
    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;
}

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$1(acc, handlers[prop](props));
      }
      return acc;
    }, {});
  };
  fn.propTypes = styles.reduce((acc, style) => Object.assign(acc, style.propTypes), {}) ;
  fn.filterProps = styles.reduce((acc, style) => acc.concat(style.filterProps), []);
  return fn;
}

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, 'borderRadius');
    const styleFromPropValue = propValue => ({
      borderRadius: getValue(transformer, propValue)
    });
    return handleBreakpoints(props, props.borderRadius, styleFromPropValue);
  }
  return null;
};
borderRadius.propTypes = {
  borderRadius: responsivePropType$1
} ;
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, 'gap');
    const styleFromPropValue = propValue => ({
      gap: getValue(transformer, propValue)
    });
    return handleBreakpoints(props, props.gap, styleFromPropValue);
  }
  return null;
};
gap.propTypes = {
  gap: responsivePropType$1
} ;
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, 'columnGap');
    const styleFromPropValue = propValue => ({
      columnGap: getValue(transformer, propValue)
    });
    return handleBreakpoints(props, props.columnGap, styleFromPropValue);
  }
  return null;
};
columnGap.propTypes = {
  columnGap: responsivePropType$1
} ;
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, 'rowGap');
    const styleFromPropValue = propValue => ({
      rowGap: getValue(transformer, propValue)
    });
    return handleBreakpoints(props, props.rowGap, styleFromPropValue);
  }
  return null;
};
rowGap.propTypes = {
  rowGap: responsivePropType$1
} ;
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'
  }
};
var 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;
    }
    if (themeKey === 'typography' && val === 'inherit') {
      return {
        [prop]: val
      };
    }
    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$1(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$1(css, breakpointsValues);
              }
            }
          } else {
            css = merge$1(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'];
var styleFunctionSx$1 = styleFunctionSx;

const _excluded$1H = ["breakpoints", "palette", "spacing", "shape"];
function createTheme$2(options = {}, ...args) {
  const {
      breakpoints: breakpointsInput = {},
      palette: paletteInput = {},
      spacing: spacingInput,
      shape: shapeInput = {}
    } = options,
    other = _objectWithoutPropertiesLoose$2(options, _excluded$1H);
  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;
}

function createMixins(breakpoints, mixins) {
  return _extends({
    toolbar: {
      minHeight: 56,
      [breakpoints.up('xs')]: {
        '@media (orientation: landscape)': {
          minHeight: 48
        }
      },
      [breakpoints.up('sm')]: {
        minHeight: 64
      }
    }
  }, mixins);
}

/* eslint-disable @typescript-eslint/naming-convention */
/**
 * 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(value, min = 0, max = 1) {
  {
    if (value < min || value > max) {
      console.error(`MUI: The value provided ${value} is out of range [${min}, ${max}].`);
    }
  }
  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(`MUI: Unsupported \`${color}\` color.
The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), 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(`MUI: unsupported \`${colorSpace}\` color space.
The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.` );
    }
  } 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(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(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(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);
}

/**
 * Darken or lighten a color, depending on its luminance.
 * Light colors are darkened, dark colors are lightened.
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
 * @param {number} coefficient=0.15 - multiplier in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */
function emphasize(color, coefficient = 0.15) {
  return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}

const common = {
  black: '#000',
  white: '#fff'
};
var common$1 = common;

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'
};
var grey$1 = grey;

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'
};
var purple$1 = purple;

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'
};
var red$1 = red;

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'
};
var orange$1 = orange;

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'
};
var 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'
};
var 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'
};
var green$1 = green;

const _excluded$1G = ["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$1G);
  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;
    {
      const contrast = getContrastRatio(background, contrastText);
      if (contrast < 3) {
        console.error([`MUI: The contrast ratio of ${contrast}:1 for ${contrastText} on ${background}`, 'falls below the WCAG recommended absolute minimum contrast ratio of 3:1.', 'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast'].join('\n'));
      }
    }
    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(`MUI: The color${name ? ` (${name})` : ''} provided to augmentColor(color) is invalid.
The color object needs to have a \`main\` property or a \`${mainShade}\` property.` );
    }
    if (typeof color.main !== 'string') {
      throw new Error(`MUI: The color${name ? ` (${name})` : ''} provided to augmentColor(color) is invalid.
\`color.main\` should be a string, but \`${JSON.stringify(color.main)}\` was provided instead.

Did you intend to use one of the following approaches?

import { green } from "@mui/material/colors";

const theme1 = createTheme({ palette: {
  primary: green,
} });

const theme2 = createTheme({ palette: {
  primary: { main: green[500] },
} });` );
    }
    addLightOrDark(color, 'light', lightShade, tonalOffset);
    addLightOrDark(color, 'dark', darkShade, tonalOffset);
    if (!color.contrastText) {
      color.contrastText = getContrastText(color.main);
    }
    return color;
  };
  const modes = {
    dark,
    light
  };
  {
    if (!modes[mode]) {
      console.error(`MUI: The palette mode \`${mode}\` is not supported.`);
    }
  }
  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$1F = ["fontFamily", "fontSize", "fontWeightLight", "fontWeightRegular", "fontWeightMedium", "fontWeightBold", "htmlFontSize", "allVariants", "pxToRem"];
function round$1(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$1F);
  {
    if (typeof fontSize !== 'number') {
      console.error('MUI: `fontSize` is required to be a number.');
    }
    if (typeof htmlFontSize !== 'number') {
      console.error('MUI: `htmlFontSize` is required to be a number.');
    }
  }
  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$1(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),
    inherit: {
      fontFamily: 'inherit',
      fontWeight: 'inherit',
      fontSize: 'inherit',
      lineHeight: 'inherit',
      letterSpacing: 'inherit'
    }
  };
  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)];
var shadows$1 = shadows;

const _excluded$1E = ["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,
      other = _objectWithoutPropertiesLoose$2(options, _excluded$1E);
    {
      const isString = value => typeof value === 'string';
      // IE11 support, replace with Number.isNaN
      // eslint-disable-next-line no-restricted-globals
      const isNumber = value => !isNaN(parseFloat(value));
      if (!isString(props) && !Array.isArray(props)) {
        console.error('MUI: Argument "props" must be a string or Array.');
      }
      if (!isNumber(durationOption) && !isString(durationOption)) {
        console.error(`MUI: Argument "duration" must be a number or a string but found ${durationOption}.`);
      }
      if (!isString(easingOption)) {
        console.error('MUI: Argument "easing" must be a string.');
      }
      if (!isNumber(delay) && !isString(delay)) {
        console.error('MUI: Argument "delay" must be a number or a string.');
      }
      if (Object.keys(other).length !== 0) {
        console.error(`MUI: Unrecognized argument(s) [${Object.keys(other).join(',')}].`);
      }
    }
    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
};
var zIndex$1 = zIndex;

const _excluded$1D = ["breakpoints", "mixins", "spacing", "palette", "transitions", "typography", "shape"];
function createTheme$1(options = {}, ...args) {
  const {
      mixins: mixinsInput = {},
      palette: paletteInput = {},
      transitions: transitionsInput = {},
      typography: typographyInput = {}
    } = options,
    other = _objectWithoutPropertiesLoose$2(options, _excluded$1D);
  if (options.vars) {
    throw new Error(`MUI: \`vars\` is a private field used for CSS variables support.
Please use another name.` );
  }
  const palette = createPalette(paletteInput);
  const systemTheme = createTheme$2(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);
  {
    // TODO v6: Refactor to use globalStateClassesMapping from @mui/utils once `readOnly` state class is used in Rating component.
    const stateClasses = ['active', 'checked', 'completed', 'disabled', 'error', 'expanded', 'focused', 'focusVisible', 'required', 'selected'];
    const traverse = (node, component) => {
      let key;

      // eslint-disable-next-line guard-for-in, no-restricted-syntax
      for (key in node) {
        const child = node[key];
        if (stateClasses.indexOf(key) !== -1 && Object.keys(child).length > 0) {
          {
            const stateClass = generateUtilityClass('', key);
            console.error([`MUI: The \`${component}\` component increases ` + `the CSS specificity of the \`${key}\` internal state.`, 'You can not override it like this: ', JSON.stringify(node, null, 2), '', `Instead, you need to use the '&.${stateClass}' syntax:`, JSON.stringify({
              root: {
                [`&.${stateClass}`]: child
              }
            }, null, 2), '', 'https://mui.com/r/state-classes-guide'].join('\n'));
          }
          // Remove the style to prevent global conflicts.
          node[key] = {};
        }
      }
    };
    Object.keys(muiTheme.components).forEach(component => {
      const styleOverrides = muiTheme.components[component].styleOverrides;
      if (styleOverrides && component.indexOf('Mui') === 0) {
        traverse(styleOverrides, component);
      }
    });
  }
  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$1 = /*#__PURE__*/reactExports$1.createContext(null);
{
  ThemeContext$1.displayName = 'ThemeContext';
}
var ThemeContext$2 = ThemeContext$1;

function useTheme$4() {
  const theme = reactExports$1.useContext(ThemeContext$2);
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useDebugValue(theme);
  }
  return theme;
}

const hasSymbol = typeof Symbol === 'function' && Symbol.for;
var nested = hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__';

var jsxRuntime$1 = {exports: {}};

var reactJsxRuntime_development = {};

/**
 * @license React
 * react-jsx-runtime.development.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 () {

    var React = reactExports$1;

    // ATTENTION
    // When adding new symbols to this file,
    // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
    // The Symbol used to tag the ReactElement-like types.
    var REACT_ELEMENT_TYPE = Symbol.for('react.element');
    var REACT_PORTAL_TYPE = Symbol.for('react.portal');
    var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
    var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
    var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
    var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
    var REACT_CONTEXT_TYPE = Symbol.for('react.context');
    var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
    var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
    var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
    var REACT_MEMO_TYPE = Symbol.for('react.memo');
    var REACT_LAZY_TYPE = Symbol.for('react.lazy');
    var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
    var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
    var FAUX_ITERATOR_SYMBOL = '@@iterator';
    function getIteratorFn(maybeIterable) {
      if (maybeIterable === null || typeof maybeIterable !== 'object') {
        return null;
      }
      var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
      if (typeof maybeIterator === 'function') {
        return maybeIterator;
      }
      return null;
    }
    var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
    function error(format) {
      {
        {
          for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
            args[_key2 - 1] = arguments[_key2];
          }
          printWarning('error', format, args);
        }
      }
    }
    function printWarning(level, format, args) {
      // When changing this logic, you might want to also
      // update consoleWithStackDev.www.js as well.
      {
        var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
        var stack = ReactDebugCurrentFrame.getStackAddendum();
        if (stack !== '') {
          format += '%s';
          args = args.concat([stack]);
        } // eslint-disable-next-line react-internal/safe-string-coercion

        var argsWithFormat = args.map(function (item) {
          return String(item);
        }); // Careful: RN currently depends on this prefix

        argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
        // breaks IE9: https://github.com/facebook/react/issues/13610
        // eslint-disable-next-line react-internal/no-production-logging

        Function.prototype.apply.call(console[level], console, argsWithFormat);
      }
    }

    // -----------------------------------------------------------------------------

    var enableScopeAPI = false; // Experimental Create Event Handle API.
    var enableCacheElement = false;
    var enableTransitionTracing = false; // No known bugs, but needs performance testing

    var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
    // stuff. Intended to enable React core members to more easily debug scheduling
    // issues in DEV builds.

    var enableDebugTracing = false; // Track which Fiber(s) schedule render work.

    var REACT_MODULE_REFERENCE;
    {
      REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
    }
    function isValidElementType(type) {
      if (typeof type === 'string' || typeof type === 'function') {
        return true;
      } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).

      if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
        return true;
      }
      if (typeof type === 'object' && type !== null) {
        if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE ||
        // This needs to include all possible module reference object
        // types supported by any Flight configuration anywhere since
        // we don't know which Flight build this will end up being used
        // with.
        type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
          return true;
        }
      }
      return false;
    }
    function getWrappedName(outerType, innerType, wrapperName) {
      var displayName = outerType.displayName;
      if (displayName) {
        return displayName;
      }
      var functionName = innerType.displayName || innerType.name || '';
      return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
    } // Keep in sync with react-reconciler/getComponentNameFromFiber

    function getContextName(type) {
      return type.displayName || 'Context';
    } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.

    function getComponentNameFromType(type) {
      if (type == null) {
        // Host root, text node or just invalid type.
        return null;
      }
      {
        if (typeof type.tag === 'number') {
          error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
        }
      }
      if (typeof type === 'function') {
        return type.displayName || type.name || null;
      }
      if (typeof type === 'string') {
        return type;
      }
      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return 'Fragment';
        case REACT_PORTAL_TYPE:
          return 'Portal';
        case REACT_PROFILER_TYPE:
          return 'Profiler';
        case REACT_STRICT_MODE_TYPE:
          return 'StrictMode';
        case REACT_SUSPENSE_TYPE:
          return 'Suspense';
        case REACT_SUSPENSE_LIST_TYPE:
          return 'SuspenseList';
      }
      if (typeof type === 'object') {
        switch (type.$$typeof) {
          case REACT_CONTEXT_TYPE:
            var context = type;
            return getContextName(context) + '.Consumer';
          case REACT_PROVIDER_TYPE:
            var provider = type;
            return getContextName(provider._context) + '.Provider';
          case REACT_FORWARD_REF_TYPE:
            return getWrappedName(type, type.render, 'ForwardRef');
          case REACT_MEMO_TYPE:
            var outerName = type.displayName || null;
            if (outerName !== null) {
              return outerName;
            }
            return getComponentNameFromType(type.type) || 'Memo';
          case REACT_LAZY_TYPE:
            {
              var lazyComponent = type;
              var payload = lazyComponent._payload;
              var init = lazyComponent._init;
              try {
                return getComponentNameFromType(init(payload));
              } catch (x) {
                return null;
              }
            }

          // eslint-disable-next-line no-fallthrough
        }
      }

      return null;
    }
    var assign = Object.assign;

    // Helpers to patch console.logs to avoid logging during side-effect free
    // replaying on render function. This currently only patches the object
    // lazily which won't cover if the log function was extracted eagerly.
    // We could also eagerly patch the method.
    var disabledDepth = 0;
    var prevLog;
    var prevInfo;
    var prevWarn;
    var prevError;
    var prevGroup;
    var prevGroupCollapsed;
    var prevGroupEnd;
    function disabledLog() {}
    disabledLog.__reactDisabledLog = true;
    function disableLogs() {
      {
        if (disabledDepth === 0) {
          /* eslint-disable react-internal/no-production-logging */
          prevLog = console.log;
          prevInfo = console.info;
          prevWarn = console.warn;
          prevError = console.error;
          prevGroup = console.group;
          prevGroupCollapsed = console.groupCollapsed;
          prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099

          var props = {
            configurable: true,
            enumerable: true,
            value: disabledLog,
            writable: true
          }; // $FlowFixMe Flow thinks console is immutable.

          Object.defineProperties(console, {
            info: props,
            log: props,
            warn: props,
            error: props,
            group: props,
            groupCollapsed: props,
            groupEnd: props
          });
          /* eslint-enable react-internal/no-production-logging */
        }

        disabledDepth++;
      }
    }
    function reenableLogs() {
      {
        disabledDepth--;
        if (disabledDepth === 0) {
          /* eslint-disable react-internal/no-production-logging */
          var props = {
            configurable: true,
            enumerable: true,
            writable: true
          }; // $FlowFixMe Flow thinks console is immutable.

          Object.defineProperties(console, {
            log: assign({}, props, {
              value: prevLog
            }),
            info: assign({}, props, {
              value: prevInfo
            }),
            warn: assign({}, props, {
              value: prevWarn
            }),
            error: assign({}, props, {
              value: prevError
            }),
            group: assign({}, props, {
              value: prevGroup
            }),
            groupCollapsed: assign({}, props, {
              value: prevGroupCollapsed
            }),
            groupEnd: assign({}, props, {
              value: prevGroupEnd
            })
          });
          /* eslint-enable react-internal/no-production-logging */
        }

        if (disabledDepth < 0) {
          error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
        }
      }
    }
    var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
    var prefix;
    function describeBuiltInComponentFrame(name, source, ownerFn) {
      {
        if (prefix === undefined) {
          // Extract the VM specific prefix used by each line.
          try {
            throw Error();
          } catch (x) {
            var match = x.stack.trim().match(/\n( *(at )?)/);
            prefix = match && match[1] || '';
          }
        } // We use the prefix to ensure our stacks line up with native stack frames.

        return '\n' + prefix + name;
      }
    }
    var reentry = false;
    var componentFrameCache;
    {
      var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
      componentFrameCache = new PossiblyWeakMap();
    }
    function describeNativeComponentFrame(fn, construct) {
      // If something asked for a stack inside a fake render, it should get ignored.
      if (!fn || reentry) {
        return '';
      }
      {
        var frame = componentFrameCache.get(fn);
        if (frame !== undefined) {
          return frame;
        }
      }
      var control;
      reentry = true;
      var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.

      Error.prepareStackTrace = undefined;
      var previousDispatcher;
      {
        previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
        // for warnings.

        ReactCurrentDispatcher.current = null;
        disableLogs();
      }
      try {
        // This should throw.
        if (construct) {
          // Something should be setting the props in the constructor.
          var Fake = function () {
            throw Error();
          }; // $FlowFixMe

          Object.defineProperty(Fake.prototype, 'props', {
            set: function () {
              // We use a throwing setter instead of frozen or non-writable props
              // because that won't throw in a non-strict mode function.
              throw Error();
            }
          });
          if (typeof Reflect === 'object' && Reflect.construct) {
            // We construct a different control for this case to include any extra
            // frames added by the construct call.
            try {
              Reflect.construct(Fake, []);
            } catch (x) {
              control = x;
            }
            Reflect.construct(fn, [], Fake);
          } else {
            try {
              Fake.call();
            } catch (x) {
              control = x;
            }
            fn.call(Fake.prototype);
          }
        } else {
          try {
            throw Error();
          } catch (x) {
            control = x;
          }
          fn();
        }
      } catch (sample) {
        // This is inlined manually because closure doesn't do it for us.
        if (sample && control && typeof sample.stack === 'string') {
          // This extracts the first frame from the sample that isn't also in the control.
          // Skipping one frame that we assume is the frame that calls the two.
          var sampleLines = sample.stack.split('\n');
          var controlLines = control.stack.split('\n');
          var s = sampleLines.length - 1;
          var c = controlLines.length - 1;
          while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
            // We expect at least one stack frame to be shared.
            // Typically this will be the root most one. However, stack frames may be
            // cut off due to maximum stack limits. In this case, one maybe cut off
            // earlier than the other. We assume that the sample is longer or the same
            // and there for cut off earlier. So we should find the root most frame in
            // the sample somewhere in the control.
            c--;
          }
          for (; s >= 1 && c >= 0; s--, c--) {
            // Next we find the first one that isn't the same which should be the
            // frame that called our sample function and the control.
            if (sampleLines[s] !== controlLines[c]) {
              // In V8, the first line is describing the message but other VMs don't.
              // If we're about to return the first line, and the control is also on the same
              // line, that's a pretty good indicator that our sample threw at same line as
              // the control. I.e. before we entered the sample frame. So we ignore this result.
              // This can happen if you passed a class to function component, or non-function.
              if (s !== 1 || c !== 1) {
                do {
                  s--;
                  c--; // We may still have similar intermediate frames from the construct call.
                  // The next one that isn't the same should be our match though.

                  if (c < 0 || sampleLines[s] !== controlLines[c]) {
                    // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
                    var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
                    // but we have a user-provided "displayName"
                    // splice it in to make the stack more readable.

                    if (fn.displayName && _frame.includes('<anonymous>')) {
                      _frame = _frame.replace('<anonymous>', fn.displayName);
                    }
                    {
                      if (typeof fn === 'function') {
                        componentFrameCache.set(fn, _frame);
                      }
                    } // Return the line we found.

                    return _frame;
                  }
                } while (s >= 1 && c >= 0);
              }
              break;
            }
          }
        }
      } finally {
        reentry = false;
        {
          ReactCurrentDispatcher.current = previousDispatcher;
          reenableLogs();
        }
        Error.prepareStackTrace = previousPrepareStackTrace;
      } // Fallback to just using the name if we couldn't make it throw.

      var name = fn ? fn.displayName || fn.name : '';
      var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
      {
        if (typeof fn === 'function') {
          componentFrameCache.set(fn, syntheticFrame);
        }
      }
      return syntheticFrame;
    }
    function describeFunctionComponentFrame(fn, source, ownerFn) {
      {
        return describeNativeComponentFrame(fn, false);
      }
    }
    function shouldConstruct(Component) {
      var prototype = Component.prototype;
      return !!(prototype && prototype.isReactComponent);
    }
    function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
      if (type == null) {
        return '';
      }
      if (typeof type === 'function') {
        {
          return describeNativeComponentFrame(type, shouldConstruct(type));
        }
      }
      if (typeof type === 'string') {
        return describeBuiltInComponentFrame(type);
      }
      switch (type) {
        case REACT_SUSPENSE_TYPE:
          return describeBuiltInComponentFrame('Suspense');
        case REACT_SUSPENSE_LIST_TYPE:
          return describeBuiltInComponentFrame('SuspenseList');
      }
      if (typeof type === 'object') {
        switch (type.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            return describeFunctionComponentFrame(type.render);
          case REACT_MEMO_TYPE:
            // Memo may contain any component type so we recursively resolve it.
            return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
          case REACT_LAZY_TYPE:
            {
              var lazyComponent = type;
              var payload = lazyComponent._payload;
              var init = lazyComponent._init;
              try {
                // Lazy may contain any component type so we recursively resolve it.
                return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
              } catch (x) {}
            }
        }
      }
      return '';
    }
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var loggedTypeFailures = {};
    var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
    function setCurrentlyValidatingElement(element) {
      {
        if (element) {
          var owner = element._owner;
          var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
          ReactDebugCurrentFrame.setExtraStackFrame(stack);
        } else {
          ReactDebugCurrentFrame.setExtraStackFrame(null);
        }
      }
    }
    function checkPropTypes(typeSpecs, values, location, componentName, element) {
      {
        // $FlowFixMe This is okay but Flow doesn't know it.
        var has = Function.call.bind(hasOwnProperty);
        for (var typeSpecName in typeSpecs) {
          if (has(typeSpecs, typeSpecName)) {
            var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
            // fail the render phase where it didn't fail before. So we log it.
            // After these have been cleaned up, we'll let them throw.

            try {
              // This is intentionally an invariant that gets caught. It's the same
              // behavior as without this statement except with a better message.
              if (typeof typeSpecs[typeSpecName] !== 'function') {
                // eslint-disable-next-line react-internal/prod-error-codes
                var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
                err.name = 'Invariant Violation';
                throw err;
              }
              error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
            } catch (ex) {
              error$1 = ex;
            }
            if (error$1 && !(error$1 instanceof Error)) {
              setCurrentlyValidatingElement(element);
              error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
              setCurrentlyValidatingElement(null);
            }
            if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
              // Only monitor this failure once because there tends to be a lot of the
              // same error.
              loggedTypeFailures[error$1.message] = true;
              setCurrentlyValidatingElement(element);
              error('Failed %s type: %s', location, error$1.message);
              setCurrentlyValidatingElement(null);
            }
          }
        }
      }
    }
    var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare

    function isArray(a) {
      return isArrayImpl(a);
    }

    /*
     * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
     * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
     *
     * The functions in this module will throw an easier-to-understand,
     * easier-to-debug exception with a clear errors message message explaining the
     * problem. (Instead of a confusing exception thrown inside the implementation
     * of the `value` object).
     */
    // $FlowFixMe only called in DEV, so void return is not possible.
    function typeName(value) {
      {
        // toStringTag is needed for namespaced types like Temporal.Instant
        var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
        var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
        return type;
      }
    } // $FlowFixMe only called in DEV, so void return is not possible.

    function willCoercionThrow(value) {
      {
        try {
          testStringCoercion(value);
          return false;
        } catch (e) {
          return true;
        }
      }
    }
    function testStringCoercion(value) {
      // If you ended up here by following an exception call stack, here's what's
      // happened: you supplied an object or symbol value to React (as a prop, key,
      // DOM attribute, CSS property, string ref, etc.) and when React tried to
      // coerce it to a string using `'' + value`, an exception was thrown.
      //
      // The most common types that will cause this exception are `Symbol` instances
      // and Temporal objects like `Temporal.Instant`. But any object that has a
      // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
      // exception. (Library authors do this to prevent users from using built-in
      // numeric operators like `+` or comparison operators like `>=` because custom
      // methods are needed to perform accurate arithmetic or comparison.)
      //
      // To fix the problem, coerce this object or symbol value to a string before
      // passing it to React. The most reliable way is usually `String(value)`.
      //
      // To find which value is throwing, check the browser or debugger console.
      // Before this exception was thrown, there should be `console.error` output
      // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
      // problem and how that type was used: key, atrribute, input value prop, etc.
      // In most cases, this console output also shows the component and its
      // ancestor components where the exception happened.
      //
      // eslint-disable-next-line react-internal/safe-string-coercion
      return '' + value;
    }
    function checkKeyStringCoercion(value) {
      {
        if (willCoercionThrow(value)) {
          error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
          return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
        }
      }
    }

    var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
    var RESERVED_PROPS = {
      key: true,
      ref: true,
      __self: true,
      __source: true
    };
    var specialPropKeyWarningShown;
    var specialPropRefWarningShown;
    var didWarnAboutStringRefs;
    {
      didWarnAboutStringRefs = {};
    }
    function hasValidRef(config) {
      {
        if (hasOwnProperty.call(config, 'ref')) {
          var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
          if (getter && getter.isReactWarning) {
            return false;
          }
        }
      }
      return config.ref !== undefined;
    }
    function hasValidKey(config) {
      {
        if (hasOwnProperty.call(config, 'key')) {
          var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
          if (getter && getter.isReactWarning) {
            return false;
          }
        }
      }
      return config.key !== undefined;
    }
    function warnIfStringRefCannotBeAutoConverted(config, self) {
      {
        if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
          var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
          if (!didWarnAboutStringRefs[componentName]) {
            error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
            didWarnAboutStringRefs[componentName] = true;
          }
        }
      }
    }
    function defineKeyPropWarningGetter(props, displayName) {
      {
        var warnAboutAccessingKey = function () {
          if (!specialPropKeyWarningShown) {
            specialPropKeyWarningShown = true;
            error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
          }
        };
        warnAboutAccessingKey.isReactWarning = true;
        Object.defineProperty(props, 'key', {
          get: warnAboutAccessingKey,
          configurable: true
        });
      }
    }
    function defineRefPropWarningGetter(props, displayName) {
      {
        var warnAboutAccessingRef = function () {
          if (!specialPropRefWarningShown) {
            specialPropRefWarningShown = true;
            error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
          }
        };
        warnAboutAccessingRef.isReactWarning = true;
        Object.defineProperty(props, 'ref', {
          get: warnAboutAccessingRef,
          configurable: true
        });
      }
    }
    /**
     * Factory method to create a new React element. This no longer adheres to
     * the class pattern, so do not use new to call it. Also, instanceof check
     * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
     * if something is a React Element.
     *
     * @param {*} type
     * @param {*} props
     * @param {*} key
     * @param {string|object} ref
     * @param {*} owner
     * @param {*} self A *temporary* helper to detect places where `this` is
     * different from the `owner` when React.createElement is called, so that we
     * can warn. We want to get rid of owner and replace string `ref`s with arrow
     * functions, and as long as `this` and owner are the same, there will be no
     * change in behavior.
     * @param {*} source An annotation object (added by a transpiler or otherwise)
     * indicating filename, line number, and/or other information.
     * @internal
     */

    var ReactElement = function (type, key, ref, self, source, owner, props) {
      var element = {
        // This tag allows us to uniquely identify this as a React Element
        $$typeof: REACT_ELEMENT_TYPE,
        // Built-in properties that belong on the element
        type: type,
        key: key,
        ref: ref,
        props: props,
        // Record the component responsible for creating this element.
        _owner: owner
      };
      {
        // The validation flag is currently mutative. We put it on
        // an external backing store so that we can freeze the whole object.
        // This can be replaced with a WeakMap once they are implemented in
        // commonly used development environments.
        element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
        // the validation flag non-enumerable (where possible, which should
        // include every environment we run tests in), so the test framework
        // ignores it.

        Object.defineProperty(element._store, 'validated', {
          configurable: false,
          enumerable: false,
          writable: true,
          value: false
        }); // self and source are DEV only properties.

        Object.defineProperty(element, '_self', {
          configurable: false,
          enumerable: false,
          writable: false,
          value: self
        }); // Two elements created in two different places should be considered
        // equal for testing purposes and therefore we hide it from enumeration.

        Object.defineProperty(element, '_source', {
          configurable: false,
          enumerable: false,
          writable: false,
          value: source
        });
        if (Object.freeze) {
          Object.freeze(element.props);
          Object.freeze(element);
        }
      }
      return element;
    };
    /**
     * https://github.com/reactjs/rfcs/pull/107
     * @param {*} type
     * @param {object} props
     * @param {string} key
     */

    function jsxDEV(type, config, maybeKey, source, self) {
      {
        var propName; // Reserved names are extracted

        var props = {};
        var key = null;
        var ref = null; // Currently, key can be spread in as a prop. This causes a potential
        // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
        // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
        // but as an intermediary step, we will use jsxDEV for everything except
        // <div {...props} key="Hi" />, because we aren't currently able to tell if
        // key is explicitly declared to be undefined or not.

        if (maybeKey !== undefined) {
          {
            checkKeyStringCoercion(maybeKey);
          }
          key = '' + maybeKey;
        }
        if (hasValidKey(config)) {
          {
            checkKeyStringCoercion(config.key);
          }
          key = '' + config.key;
        }
        if (hasValidRef(config)) {
          ref = config.ref;
          warnIfStringRefCannotBeAutoConverted(config, self);
        } // Remaining properties are added to a new props object

        for (propName in config) {
          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
            props[propName] = config[propName];
          }
        } // Resolve default props

        if (type && type.defaultProps) {
          var defaultProps = type.defaultProps;
          for (propName in defaultProps) {
            if (props[propName] === undefined) {
              props[propName] = defaultProps[propName];
            }
          }
        }
        if (key || ref) {
          var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
          if (key) {
            defineKeyPropWarningGetter(props, displayName);
          }
          if (ref) {
            defineRefPropWarningGetter(props, displayName);
          }
        }
        return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
      }
    }
    var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
    var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
    function setCurrentlyValidatingElement$1(element) {
      {
        if (element) {
          var owner = element._owner;
          var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
          ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
        } else {
          ReactDebugCurrentFrame$1.setExtraStackFrame(null);
        }
      }
    }
    var propTypesMisspellWarningShown;
    {
      propTypesMisspellWarningShown = false;
    }
    /**
     * Verifies the object is a ReactElement.
     * See https://reactjs.org/docs/react-api.html#isvalidelement
     * @param {?object} object
     * @return {boolean} True if `object` is a ReactElement.
     * @final
     */

    function isValidElement(object) {
      {
        return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
      }
    }
    function getDeclarationErrorAddendum() {
      {
        if (ReactCurrentOwner$1.current) {
          var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
          if (name) {
            return '\n\nCheck the render method of `' + name + '`.';
          }
        }
        return '';
      }
    }
    function getSourceInfoErrorAddendum(source) {
      {
        if (source !== undefined) {
          var fileName = source.fileName.replace(/^.*[\\\/]/, '');
          var lineNumber = source.lineNumber;
          return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
        }
        return '';
      }
    }
    /**
     * Warn if there's no key explicitly set on dynamic arrays of children or
     * object keys are not valid. This allows us to keep track of children between
     * updates.
     */

    var ownerHasKeyUseWarning = {};
    function getCurrentComponentErrorInfo(parentType) {
      {
        var info = getDeclarationErrorAddendum();
        if (!info) {
          var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
          if (parentName) {
            info = "\n\nCheck the top-level render call using <" + parentName + ">.";
          }
        }
        return info;
      }
    }
    /**
     * Warn if the element doesn't have an explicit key assigned to it.
     * This element is in an array. The array could grow and shrink or be
     * reordered. All children that haven't already been validated are required to
     * have a "key" property assigned to it. Error statuses are cached so a warning
     * will only be shown once.
     *
     * @internal
     * @param {ReactElement} element Element that requires a key.
     * @param {*} parentType element's parent's type.
     */

    function validateExplicitKey(element, parentType) {
      {
        if (!element._store || element._store.validated || element.key != null) {
          return;
        }
        element._store.validated = true;
        var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
        if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
          return;
        }
        ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
        // property, it may be the creator of the child that's responsible for
        // assigning it a key.

        var childOwner = '';
        if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
          // Give the component that originally created this child.
          childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
        }
        setCurrentlyValidatingElement$1(element);
        error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
        setCurrentlyValidatingElement$1(null);
      }
    }
    /**
     * Ensure that every element either is passed in a static location, in an
     * array with an explicit keys property defined, or in an object literal
     * with valid key property.
     *
     * @internal
     * @param {ReactNode} node Statically passed child of any type.
     * @param {*} parentType node's parent's type.
     */

    function validateChildKeys(node, parentType) {
      {
        if (typeof node !== 'object') {
          return;
        }
        if (isArray(node)) {
          for (var i = 0; i < node.length; i++) {
            var child = node[i];
            if (isValidElement(child)) {
              validateExplicitKey(child, parentType);
            }
          }
        } else if (isValidElement(node)) {
          // This element was passed in a valid location.
          if (node._store) {
            node._store.validated = true;
          }
        } else if (node) {
          var iteratorFn = getIteratorFn(node);
          if (typeof iteratorFn === 'function') {
            // Entry iterators used to provide implicit keys,
            // but now we print a separate warning for them later.
            if (iteratorFn !== node.entries) {
              var iterator = iteratorFn.call(node);
              var step;
              while (!(step = iterator.next()).done) {
                if (isValidElement(step.value)) {
                  validateExplicitKey(step.value, parentType);
                }
              }
            }
          }
        }
      }
    }
    /**
     * Given an element, validate that its props follow the propTypes definition,
     * provided by the type.
     *
     * @param {ReactElement} element
     */

    function validatePropTypes(element) {
      {
        var type = element.type;
        if (type === null || type === undefined || typeof type === 'string') {
          return;
        }
        var propTypes;
        if (typeof type === 'function') {
          propTypes = type.propTypes;
        } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE ||
        // Note: Memo only checks outer props here.
        // Inner props are checked in the reconciler.
        type.$$typeof === REACT_MEMO_TYPE)) {
          propTypes = type.propTypes;
        } else {
          return;
        }
        if (propTypes) {
          // Intentionally inside to avoid triggering lazy initializers:
          var name = getComponentNameFromType(type);
          checkPropTypes(propTypes, element.props, 'prop', name, element);
        } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
          propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:

          var _name = getComponentNameFromType(type);
          error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
        }
        if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
          error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
        }
      }
    }
    /**
     * Given a fragment, validate that it can only be provided with fragment props
     * @param {ReactElement} fragment
     */

    function validateFragmentProps(fragment) {
      {
        var keys = Object.keys(fragment.props);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          if (key !== 'children' && key !== 'key') {
            setCurrentlyValidatingElement$1(fragment);
            error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
            setCurrentlyValidatingElement$1(null);
            break;
          }
        }
        if (fragment.ref !== null) {
          setCurrentlyValidatingElement$1(fragment);
          error('Invalid attribute `ref` supplied to `React.Fragment`.');
          setCurrentlyValidatingElement$1(null);
        }
      }
    }
    function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
      {
        var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
        // succeed and there will likely be errors in render.

        if (!validType) {
          var info = '';
          if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
            info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
          }
          var sourceInfo = getSourceInfoErrorAddendum(source);
          if (sourceInfo) {
            info += sourceInfo;
          } else {
            info += getDeclarationErrorAddendum();
          }
          var typeString;
          if (type === null) {
            typeString = 'null';
          } else if (isArray(type)) {
            typeString = 'array';
          } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
            typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
            info = ' Did you accidentally export a JSX literal instead of a component?';
          } else {
            typeString = typeof type;
          }
          error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
        }
        var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
        // TODO: Drop this when these are no longer allowed as the type argument.

        if (element == null) {
          return element;
        } // Skip key warning if the type isn't valid since our key validation logic
        // doesn't expect a non-string/function type and can throw confusing errors.
        // We don't want exception behavior to differ between dev and prod.
        // (Rendering will throw with a helpful message and as soon as the type is
        // fixed, the key warnings will appear.)

        if (validType) {
          var children = props.children;
          if (children !== undefined) {
            if (isStaticChildren) {
              if (isArray(children)) {
                for (var i = 0; i < children.length; i++) {
                  validateChildKeys(children[i], type);
                }
                if (Object.freeze) {
                  Object.freeze(children);
                }
              } else {
                error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
              }
            } else {
              validateChildKeys(children, type);
            }
          }
        }
        if (type === REACT_FRAGMENT_TYPE) {
          validateFragmentProps(element);
        } else {
          validatePropTypes(element);
        }
        return element;
      }
    } // These two functions exist to still get child warnings in dev
    // even with the prod transform. This means that jsxDEV is purely
    // opt-in behavior for better messages but that we won't stop
    // giving you warnings if you use production apis.

    function jsxWithValidationStatic(type, props, key) {
      {
        return jsxWithValidation(type, props, key, true);
      }
    }
    function jsxWithValidationDynamic(type, props, key) {
      {
        return jsxWithValidation(type, props, key, false);
      }
    }
    var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children.
    // for now we can ship identical prod functions

    var jsxs = jsxWithValidationStatic;
    reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
    reactJsxRuntime_development.jsx = jsx;
    reactJsxRuntime_development.jsxs = jsxs;
  })();
}

{
  jsxRuntime$1.exports = reactJsxRuntime_development;
}

var jsxRuntimeExports = jsxRuntime$1.exports;
var jsxRuntime = /*@__PURE__*/getDefaultExportFromCjs(jsxRuntimeExports);

function mergeOuterLocalTheme(outerTheme, localTheme) {
  if (typeof localTheme === 'function') {
    const mergedTheme = localTheme(outerTheme);
    {
      if (!mergedTheme) {
        console.error(['MUI: You should return an object from your theme function, i.e.', '<ThemeProvider theme={() => ({})} />'].join('\n'));
      }
    }
    return mergedTheme;
  }
  return {
    ...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$3(props) {
  const {
    children,
    theme: localTheme
  } = props;
  const outerTheme = useTheme$4();
  {
    if (outerTheme === null && typeof localTheme === 'function') {
      console.error(['MUI: You are providing a theme function prop to the ThemeProvider component:', '<ThemeProvider theme={outerTheme => outerTheme} />', '', 'However, no outer theme is present.', 'Make sure a theme is already injected higher in the React tree ' + 'or provide a theme object.'].join('\n'));
    }
  }
  const theme = reactExports$1.useMemo(() => {
    const output = outerTheme === null ? localTheme : mergeOuterLocalTheme(outerTheme, localTheme);
    if (output != null) {
      output[nested] = outerTheme !== null;
    }
    return output;
  }, [localTheme, outerTheme]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeContext$2.Provider, {
    value: theme,
    children: children
  });
}
ThemeProvider$3.propTypes = {
  /**
   * Your component tree.
   */
  children: PropTypes.node,
  /**
   * A theme object. You can provide a function to extend the outer theme.
   */
  theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired
} ;
{
  ThemeProvider$3.propTypes = exactProp(ThemeProvider$3.propTypes) ;
}

function memoize(fn) {
  var cache = Object.create(null);
  return function (arg) {
    if (cache[arg] === undefined) cache[arg] = fn(arg);
    return cache[arg];
  };
}

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(function (prop) {
  return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
  /* o */ && prop.charCodeAt(1) === 110
  /* n */ && prop.charCodeAt(2) < 91;
}
/* Z+1 */);

/*

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 ? "development" === '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];
    {
      var isImportRule = rule.charCodeAt(0) === 64 && rule.charCodeAt(1) === 105;
      if (isImportRule && this._alreadyInsertedOrderInsensitiveRule) {
        // this would only cause problem in speedy mode
        // but we don't want enabling speedy to affect the observable behavior
        // so we report this error at all times
        console.error("You're attempting to insert the following rule:\n" + rule + '\n\n`@import` rules must be before all other types of rules in a stylesheet but other rules have already been inserted. Please ensure that `@import` rules are before all other rules.');
      }
      this._alreadyInsertedOrderInsensitiveRule = this._alreadyInsertedOrderInsensitiveRule || !isImportRule;
    }
    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) {
        if (!/:(-moz-placeholder|-moz-focus-inner|-moz-focusring|-ms-input-placeholder|-moz-read-write|-moz-read-only|-ms-clear|-ms-expand|-ms-reveal){/.test(rule)) {
          console.error("There was a problem inserting the following rule: \"" + rule + "\"", 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;
    {
      this._alreadyInsertedOrderInsensitiveRule = false;
    }
  };
  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';
var LAYER = '@layer';

/**
 * @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(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(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(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(index, position - 1) + '*' + from(type === 47 ? type : next());
}

/**
 * @param {number} index
 * @return {string}
 */
function identifier(index) {
  while (!token(peek())) next();
  return slice(index, position);
}

/**
 * @param {string} value
 * @return {object[]}
 */
function compile(value) {
  return dealloc(parse$1('', 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$1(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 (ampersand == -1) characters = replace(characters, /\f/g, '');
          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$1(characters, root, reference, reference, props, rulesets, length, points, children);else switch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) {
            // d l m s
            case 100:
            case 108:
            case 109:
            case 115:
              parse$1(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$1(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 LAYER:
      if (element.children.length) break;
    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;
  };
}

var weakMemoize = function weakMemoize(func) {
  // $FlowFixMe flow doesn't include all non-primitive types as allowed for weakmaps
  var cache = new WeakMap();
  return function (arg) {
    if (cache.has(arg)) {
      // $FlowFixMe
      return cache.get(arg);
    }
    var ret = func(arg);
    cache.set(arg, ret);
    return ret;
  };
};

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(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 = '';
    }
  }
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
  return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
  return function (element, index, children) {
    if (element.type !== 'rule' || cache.compat) return;
    var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
    if (unsafePseudoClasses) {
      var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
      //
      // considering this input:
      // .a {
      //   .b /* comm */ {}
      //   color: hotpink;
      // }
      // we get output corresponding to this:
      // .a {
      //   & {
      //     /* comm */
      //     color: hotpink;
      //   }
      //   .b {}
      // }

      var commentContainer = isNested ? element.parent.children :
      // global rule at the root level
      children;
      for (var i = commentContainer.length - 1; i >= 0; i--) {
        var node = commentContainer[i];
        if (node.line < element.line) {
          break;
        } // it is quite weird but comments are *usually* put at `column: element.column - 1`
        // so we seek *from the end* for the node that is earlier than the rule's `element` and check that
        // this will also match inputs like this:
        // .a {
        //   /* comm */
        //   .b {}
        // }
        //
        // but that is fine
        //
        // it would be the easiest to change the placement of the comment to be the first child of the rule:
        // .a {
        //   .b { /* comm */ }
        // }
        // with such inputs we wouldn't have to search for the comment at all
        // TODO: consider changing this comment placement in the next major version

        if (node.column < element.column) {
          if (isIgnoringComment(node)) {
            return;
          }
          break;
        }
      }
      unsafePseudoClasses.forEach(function (unsafePseudoClass) {
        console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
      });
    }
  };
};
var isImportRule = function isImportRule(element) {
  return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
  for (var i = index - 1; i >= 0; i--) {
    if (!isImportRule(children[i])) {
      return true;
    }
  }
  return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user

var nullifyElement = function nullifyElement(element) {
  element.type = '';
  element.value = '';
  element["return"] = '';
  element.children = '';
  element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
  if (!isImportRule(element)) {
    return;
  }
  if (element.parent) {
    console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
    nullifyElement(element);
  } else if (isPrependedWithRegularRules(index, children)) {
    console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
    nullifyElement(element);
  }
};

/* 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 isBrowser$5 = typeof document !== 'undefined';
var getServerStylisCache = isBrowser$5 ? undefined : weakMemoize(function () {
  return memoize(function () {
    var cache = {};
    return function (name) {
      return cache[name];
    };
  });
});
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
  var key = options.key;
  if (!key) {
    throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\n" + "If multiple caches share the same key they might \"fight\" for each other's style elements.");
  }
  if (isBrowser$5 && 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;
  {
    // $FlowFixMe
    if (/[^a-z-]/.test(key)) {
      throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed");
    }
  }
  var inserted = {};
  var container;
  var nodesToHydrate = [];
  if (isBrowser$5) {
    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];
  {
    omnipresentPlugins.push(createUnsafeSelectorsAlarm({
      get compat() {
        return cache.compat;
      }
    }), incorrectImportAlarm);
  }
  if (isBrowser$5) {
    var currentSheet;
    var finalizingPlugins = [stringify, function (element) {
      if (!element.root) {
        if (element["return"]) {
          currentSheet.insert(element["return"]);
        } else if (element.value && element.type !== COMMENT) {
          // insert empty rule in non-production environments
          // so @emotion/jest can grab `key` from the (JS)DOM for caches without any rules inserted yet
          currentSheet.insert(element.value + "{}");
        }
      }
    } ];
    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;
      if (serialized.map !== undefined) {
        currentSheet = {
          insert: function insert(rule) {
            sheet.insert(rule + serialized.map);
          }
        };
      }
      stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
      if (shouldCache) {
        cache.inserted[serialized.name] = true;
      }
    };
  } else {
    var _finalizingPlugins = [stringify];
    var _serializer = middleware(omnipresentPlugins.concat(stylisPlugins, _finalizingPlugins));
    var _stylis = function _stylis(styles) {
      return serialize(compile(styles), _serializer);
    }; // $FlowFixMe

    var serverStylisCache = getServerStylisCache(stylisPlugins)(key);
    var getRules = function getRules(selector, serialized) {
      var name = serialized.name;
      if (serverStylisCache[name] === undefined) {
        serverStylisCache[name] = _stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
      }
      return serverStylisCache[name];
    };
    _insert = function _insert(selector, serialized, sheet, shouldCache) {
      var name = serialized.name;
      var rules = getRules(selector, serialized);
      if (cache.compat === undefined) {
        // in regular mode, we don't set the styles on the inserted cache
        // since we don't need to and that would be wasting memory
        // we return them so that they are rendered in a style tag
        if (shouldCache) {
          cache.inserted[name] = true;
        }
        if (
        // using === development instead of !== production
        // because if people do ssr in tests, the source maps showing up would be annoying
        serialized.map !== undefined) {
          return rules + serialized.map;
        }
        return rules;
      } else {
        // in compat mode, we put the styles on the inserted cache so
        // that emotion-server can pull out the styles
        // except when we don't want to cache it which was in Global but now
        // is nowhere but we don't want to do a major right now
        // and just in case we're going to leave the case here
        // it's also not affecting client side bundle size
        // so it's really not a big deal
        if (shouldCache) {
          cache.inserted[name] = rules;
        } else {
          return rules;
        }
      }
    };
  }
  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;
};

// this file isolates this package that is not tree-shakeable
// and if this module doesn't actually contain any logic of its own
// then Rollup just use 'hoist-non-react-statics' directly in other chunks

var hoistNonReactStatics = function (targetComponent, sourceComponent) {
  return hoistNonReactStatics$1$1(targetComponent, sourceComponent);
};

var isBrowser$4 = typeof document !== '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$4 === false && cache.compat !== undefined) && 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 stylesForSSR = '';
    var current = serialized;
    do {
      var maybeStyles = cache.insert(serialized === current ? "." + className : '', current, cache.sheet, true);
      if (!isBrowser$4 && maybeStyles !== undefined) {
        stylesForSSR += maybeStyles;
      }
      current = current.next;
    } while (current !== undefined);
    if (!isBrowser$4 && stylesForSSR.length !== 0) {
      return stylesForSSR;
    }
  }
};

/* 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,
  aspectRatio: 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
};

var ILLEGAL_ESCAPE_SEQUENCE_ERROR$1 = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var UNDEFINED_AS_OBJECT_KEY_ERROR = "You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).";
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(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 contentValuePattern = /(var|attr|counters?|url|element|(((repeating-)?(linear|radial))|conic)-gradient)\(|(no-)?(open|close)-quote/;
  var contentValues = ['normal', 'none', 'initial', 'inherit', 'unset'];
  var oldProcessStyleValue = processStyleValue;
  var msPattern = /^-ms-/;
  var hyphenPattern = /-(.)/g;
  var hyphenatedCache = {};
  processStyleValue = function processStyleValue(key, value) {
    if (key === 'content') {
      if (typeof value !== 'string' || contentValues.indexOf(value) === -1 && !contentValuePattern.test(value) && (value.charAt(0) !== value.charAt(value.length - 1) || value.charAt(0) !== '"' && value.charAt(0) !== "'")) {
        throw new Error("You seem to be using a value for 'content' without quotes, try replacing it with `content: '\"" + value + "\"'`");
      }
    }
    var processed = oldProcessStyleValue(key, value);
    if (processed !== '' && !isCustomProperty(key) && key.indexOf('-') !== -1 && hyphenatedCache[key] === undefined) {
      hyphenatedCache[key] = true;
      console.error("Using kebab-case for css properties in objects is not supported. Did you mean " + key.replace(msPattern, 'ms-').replace(hyphenPattern, function (str, _char) {
        return _char.toUpperCase();
      }) + "?");
    }
    return processed;
  };
}
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) {
    if (interpolation.toString() === 'NO_COMPONENT_SELECTOR') {
      throw new Error(noComponentSelectorMessage);
    }
    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 + ";";
          if (interpolation.map !== undefined) {
            styles += interpolation.map;
          }
          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);
        } else {
          console.error('Functions that are interpolated in css calls will be stringified.\n' + 'If you want to have a css call based on props, create a function that returns a css call like this\n' + 'let dynamicStyle = (props) => css`color: ${props.color}`\n' + 'It can be called directly with props or interpolated in a styled call like this\n' + "let SomeComponent = styled('div')`${dynamicStyle}`");
        }
        break;
      }
    case 'string':
      {
        var matched = [];
        var replaced = interpolation.replace(animationRegex, function (match, p1, p2) {
          var fakeVarName = "animation" + matched.length;
          matched.push("const " + fakeVarName + " = keyframes`" + p2.replace(/^@keyframes animation-\w+/, '') + "`");
          return "${" + fakeVarName + "}";
        });
        if (matched.length) {
          console.error('`keyframes` output got interpolated into plain string, please wrap it with `css`.\n\n' + 'Instead of doing this:\n\n' + [].concat(matched, ["`" + replaced + "`"]).join('\n') + '\n\nYou should wrap it with `css` like this:\n\n' + ("css`" + replaced + "`"));
        }
      }
      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' && "development" !== '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:
              {
                if (_key === 'undefined') {
                  console.error(UNDEFINED_AS_OBJECT_KEY_ERROR);
                }
                string += _key + "{" + interpolated + "}";
              }
          }
        }
      }
    }
  }
  return string;
}
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
var sourceMapPattern;
{
  sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g;
} // this is the cursor for keyframes
// 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 {
    if (strings[0] === undefined) {
      console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR$1);
    }
    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) {
      if (strings[i] === undefined) {
        console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR$1);
      }
      styles += strings[i];
    }
  }
  var sourceMap;
  {
    styles = styles.replace(sourceMapPattern, function (match) {
      sourceMap = match;
      return '';
    });
  } // using a global regex with .exec is stateful so lastIndex has to be reset each time

  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;
  {
    // $FlowFixMe SerializedStyles type doesn't have toString property (and we don't want to add it)
    return {
      name: name,
      styles: styles,
      map: sourceMap,
      next: cursor,
      toString: function toString() {
        return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).";
      }
    };
  }
};

var isBrowser$3 = typeof document !== 'undefined';
var syncFallback = function syncFallback(create) {
  return create();
};
var useInsertionEffect = React$1['useInsertion' + 'Effect'] ? React$1['useInsertion' + 'Effect'] : false;
var useInsertionEffectAlwaysWithSyncFallback = !isBrowser$3 ? syncFallback : useInsertionEffect || syncFallback;
var useInsertionEffectWithLayoutFallback = useInsertionEffect || reactExports$1.useLayoutEffect;

var isBrowser$2 = typeof document !== 'undefined';
var hasOwnProperty = {}.hasOwnProperty;
var EmotionCacheContext = /* #__PURE__ */reactExports$1.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.displayName = 'EmotionCacheContext';
}
var CacheProvider = EmotionCacheContext.Provider;
var __unsafe_useEmotionCache = function useEmotionCache() {
  return reactExports$1.useContext(EmotionCacheContext);
};
var withEmotionCache = function withEmotionCache(func) {
  // $FlowFixMe
  return /*#__PURE__*/reactExports$1.forwardRef(function (props, ref) {
    // the cache will never be null in the browser
    var cache = reactExports$1.useContext(EmotionCacheContext);
    return func(props, cache, ref);
  });
};
if (!isBrowser$2) {
  withEmotionCache = function withEmotionCache(func) {
    return function (props) {
      var cache = reactExports$1.useContext(EmotionCacheContext);
      if (cache === null) {
        // yes, we're potentially creating this on every render
        // it doesn't actually matter though since it's only on the server
        // so there will only every be a single render
        // that could change in the future because of suspense and etc. but for now,
        // this works and i don't want to optimise for a future thing that we aren't sure about
        cache = createCache({
          key: 'css'
        });
        return /*#__PURE__*/reactExports$1.createElement(EmotionCacheContext.Provider, {
          value: cache
        }, func(props, cache));
      } else {
        return func(props, cache);
      }
    };
  };
}
var ThemeContext = /* #__PURE__ */reactExports$1.createContext({});
{
  ThemeContext.displayName = 'EmotionThemeContext';
}
var useTheme$3 = function useTheme() {
  return reactExports$1.useContext(ThemeContext);
};
var getTheme = function getTheme(outerTheme, theme) {
  if (typeof theme === 'function') {
    var mergedTheme = theme(outerTheme);
    if ((mergedTheme == null || typeof mergedTheme !== 'object' || Array.isArray(mergedTheme))) {
      throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!');
    }
    return mergedTheme;
  }
  if ((theme == null || typeof theme !== 'object' || Array.isArray(theme))) {
    throw new Error('[ThemeProvider] Please make your theme prop a plain object');
  }
  return _extends({}, outerTheme, theme);
};
var createCacheWithTheme = /* #__PURE__ */weakMemoize(function (outerTheme) {
  return weakMemoize(function (theme) {
    return getTheme(outerTheme, theme);
  });
});
var ThemeProvider$2 = function ThemeProvider(props) {
  var theme = reactExports$1.useContext(ThemeContext);
  if (props.theme !== theme) {
    theme = createCacheWithTheme(theme)(props.theme);
  }
  return /*#__PURE__*/reactExports$1.createElement(ThemeContext.Provider, {
    value: theme
  }, props.children);
};
function withTheme$1(Component) {
  var componentName = Component.displayName || Component.name || 'Component';
  var render = function render(props, ref) {
    var theme = reactExports$1.useContext(ThemeContext);
    return /*#__PURE__*/reactExports$1.createElement(Component, _extends({
      theme: theme,
      ref: ref
    }, props));
  }; // $FlowFixMe

  var WithTheme = /*#__PURE__*/reactExports$1.forwardRef(render);
  WithTheme.displayName = "WithTheme(" + componentName + ")";
  return hoistNonReactStatics(WithTheme, Component);
}
var getLastPart = function getLastPart(functionName) {
  // The match may be something like 'Object.createEmotionProps' or
  // 'Loader.prototype.render'
  var parts = functionName.split('.');
  return parts[parts.length - 1];
};
var getFunctionNameFromStackTraceLine = function getFunctionNameFromStackTraceLine(line) {
  // V8
  var match = /^\s+at\s+([A-Za-z0-9$.]+)\s/.exec(line);
  if (match) return getLastPart(match[1]); // Safari / Firefox

  match = /^([A-Za-z0-9$.]+)@/.exec(line);
  if (match) return getLastPart(match[1]);
  return undefined;
};
var internalReactFunctionNames = /* #__PURE__ */new Set(['renderWithHooks', 'processChild', 'finishClassComponent', 'renderToString']); // These identifiers come from error stacks, so they have to be valid JS
// identifiers, thus we only need to replace what is a valid character for JS,
// but not for CSS.

var sanitizeIdentifier = function sanitizeIdentifier(identifier) {
  return identifier.replace(/\$/g, '-');
};
var getLabelFromStackTrace = function getLabelFromStackTrace(stackTrace) {
  if (!stackTrace) return undefined;
  var lines = stackTrace.split('\n');
  for (var i = 0; i < lines.length; i++) {
    var functionName = getFunctionNameFromStackTraceLine(lines[i]); // The first line of V8 stack traces is just "Error"

    if (!functionName) continue; // If we reach one of these, we have gone too far and should quit

    if (internalReactFunctionNames.has(functionName)) break; // The component name is the first function in the stack that starts with an
    // uppercase letter

    if (/^[A-Z]/.test(functionName)) return sanitizeIdentifier(functionName);
  }
  return undefined;
};
var typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';
var labelPropName = '__EMOTION_LABEL_PLEASE_DO_NOT_USE__';
var createEmotionProps = function createEmotionProps(type, props) {
  if (typeof props.css === 'string' &&
  // check if there is a css declaration
  props.css.indexOf(':') !== -1) {
    throw new Error("Strings are not allowed as css prop values, please wrap it in a css template literal from '@emotion/react' like this: css`" + props.css + "`");
  }
  var newProps = {};
  for (var key in props) {
    if (hasOwnProperty.call(props, key)) {
      newProps[key] = props[key];
    }
  }
  newProps[typePropName] = type; // For performance, only call getLabelFromStackTrace in development and when
  // the label hasn't already been computed

  if (!!props.css && (typeof props.css !== 'object' || typeof props.css.name !== 'string' || props.css.name.indexOf('-') === -1)) {
    var label = getLabelFromStackTrace(new Error().stack);
    if (label) newProps[labelPropName] = label;
  }
  return newProps;
};
var Insertion$2 = function Insertion(_ref) {
  var cache = _ref.cache,
    serialized = _ref.serialized,
    isStringTag = _ref.isStringTag;
  registerStyles(cache, serialized, isStringTag);
  var rules = useInsertionEffectAlwaysWithSyncFallback(function () {
    return insertStyles(cache, serialized, isStringTag);
  });
  if (!isBrowser$2 && rules !== undefined) {
    var _ref2;
    var serializedNames = serialized.name;
    var next = serialized.next;
    while (next !== undefined) {
      serializedNames += ' ' + next.name;
      next = next.next;
    }
    return /*#__PURE__*/reactExports$1.createElement("style", (_ref2 = {}, _ref2["data-emotion"] = cache.key + " " + serializedNames, _ref2.dangerouslySetInnerHTML = {
      __html: rules
    }, _ref2.nonce = cache.sheet.nonce, _ref2));
  }
  return null;
};
var Emotion = /* #__PURE__ */withEmotionCache(function (props, cache, ref) {
  var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works
  // not passing the registered cache to serializeStyles because it would
  // make certain babel optimisations not possible

  if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {
    cssProp = cache.registered[cssProp];
  }
  var WrappedComponent = props[typePropName];
  var registeredStyles = [cssProp];
  var className = '';
  if (typeof props.className === 'string') {
    className = getRegisteredStyles(cache.registered, registeredStyles, props.className);
  } else if (props.className != null) {
    className = props.className + " ";
  }
  var serialized = serializeStyles(registeredStyles, undefined, reactExports$1.useContext(ThemeContext));
  if (serialized.name.indexOf('-') === -1) {
    var labelFromStack = props[labelPropName];
    if (labelFromStack) {
      serialized = serializeStyles([serialized, 'label:' + labelFromStack + ';']);
    }
  }
  className += cache.key + "-" + serialized.name;
  var newProps = {};
  for (var key in props) {
    if (hasOwnProperty.call(props, key) && key !== 'css' && key !== typePropName && (key !== labelPropName)) {
      newProps[key] = props[key];
    }
  }
  newProps.ref = ref;
  newProps.className = className;
  return /*#__PURE__*/reactExports$1.createElement(reactExports$1.Fragment, null, /*#__PURE__*/reactExports$1.createElement(Insertion$2, {
    cache: cache,
    serialized: serialized,
    isStringTag: typeof WrappedComponent === 'string'
  }), /*#__PURE__*/reactExports$1.createElement(WrappedComponent, newProps));
});
{
  Emotion.displayName = 'EmotionCssPropInternal';
}
var Emotion$1 = Emotion;

var pkg = {
  name: "@emotion/react",
  version: "11.11.1",
  main: "dist/emotion-react.cjs.js",
  module: "dist/emotion-react.esm.js",
  browser: {
    "./dist/emotion-react.esm.js": "./dist/emotion-react.browser.esm.js"
  },
  exports: {
    ".": {
      module: {
        worker: "./dist/emotion-react.worker.esm.js",
        browser: "./dist/emotion-react.browser.esm.js",
        "default": "./dist/emotion-react.esm.js"
      },
      "import": "./dist/emotion-react.cjs.mjs",
      "default": "./dist/emotion-react.cjs.js"
    },
    "./jsx-runtime": {
      module: {
        worker: "./jsx-runtime/dist/emotion-react-jsx-runtime.worker.esm.js",
        browser: "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js",
        "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.esm.js"
      },
      "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.mjs",
      "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.js"
    },
    "./_isolated-hnrs": {
      module: {
        worker: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.worker.esm.js",
        browser: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js",
        "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.esm.js"
      },
      "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.mjs",
      "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.js"
    },
    "./jsx-dev-runtime": {
      module: {
        worker: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.worker.esm.js",
        browser: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js",
        "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.esm.js"
      },
      "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.mjs",
      "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.js"
    },
    "./package.json": "./package.json",
    "./types/css-prop": "./types/css-prop.d.ts",
    "./macro": {
      types: {
        "import": "./macro.d.mts",
        "default": "./macro.d.ts"
      },
      "default": "./macro.js"
    }
  },
  types: "types/index.d.ts",
  files: ["src", "dist", "jsx-runtime", "jsx-dev-runtime", "_isolated-hnrs", "types/*.d.ts", "macro.*"],
  sideEffects: false,
  author: "Emotion Contributors",
  license: "MIT",
  scripts: {
    "test:typescript": "dtslint types"
  },
  dependencies: {
    "@babel/runtime": "^7.18.3",
    "@emotion/babel-plugin": "^11.11.0",
    "@emotion/cache": "^11.11.0",
    "@emotion/serialize": "^1.1.2",
    "@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",
    "@emotion/utils": "^1.2.1",
    "@emotion/weak-memoize": "^0.3.1",
    "hoist-non-react-statics": "^3.3.1"
  },
  peerDependencies: {
    react: ">=16.8.0"
  },
  peerDependenciesMeta: {
    "@types/react": {
      optional: true
    }
  },
  devDependencies: {
    "@definitelytyped/dtslint": "0.0.112",
    "@emotion/css": "11.11.0",
    "@emotion/css-prettifier": "1.1.3",
    "@emotion/server": "11.11.0",
    "@emotion/styled": "11.11.0",
    "html-tag-names": "^1.1.2",
    react: "16.14.0",
    "svg-tag-names": "^1.1.1",
    typescript: "^4.5.5"
  },
  repository: "https://github.com/emotion-js/emotion/tree/main/packages/react",
  publishConfig: {
    access: "public"
  },
  "umd:main": "dist/emotion-react.umd.min.js",
  preconstruct: {
    entrypoints: ["./index.js", "./jsx-runtime.js", "./jsx-dev-runtime.js", "./_isolated-hnrs.js"],
    umdName: "emotionReact",
    exports: {
      envConditions: ["browser", "worker"],
      extra: {
        "./types/css-prop": "./types/css-prop.d.ts",
        "./macro": {
          types: {
            "import": "./macro.d.mts",
            "default": "./macro.d.ts"
          },
          "default": "./macro.js"
        }
      }
    }
  }
};
var jsx = function jsx(type, props) {
  var args = arguments;
  if (props == null || !hasOwnProperty.call(props, 'css')) {
    // $FlowFixMe
    return reactExports$1.createElement.apply(undefined, args);
  }
  var argsLength = args.length;
  var createElementArgArray = new Array(argsLength);
  createElementArgArray[0] = Emotion$1;
  createElementArgArray[1] = createEmotionProps(type, props);
  for (var i = 2; i < argsLength; i++) {
    createElementArgArray[i] = args[i];
  } // $FlowFixMe

  return reactExports$1.createElement.apply(null, createElementArgArray);
};
var warnedAboutCssPropForGlobal = false; // maintain place over rerenders.
// 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) {
  if (!warnedAboutCssPropForGlobal && (
  // check for className as well since the user is
  // probably using the custom createElement which
  // means it will be turned into a className prop
  // $FlowFixMe I don't really want to add it to the type since it shouldn't be used
  props.className || props.css)) {
    console.error("It looks like you're using the css prop on Global, did you mean to use the styles prop instead?");
    warnedAboutCssPropForGlobal = true;
  }
  var styles = props.styles;
  var serialized = serializeStyles([styles], undefined, reactExports$1.useContext(ThemeContext));
  if (!isBrowser$2) {
    var _ref;
    var serializedNames = serialized.name;
    var serializedStyles = serialized.styles;
    var next = serialized.next;
    while (next !== undefined) {
      serializedNames += ' ' + next.name;
      serializedStyles += next.styles;
      next = next.next;
    }
    var shouldCache = cache.compat === true;
    var rules = cache.insert("", {
      name: serializedNames,
      styles: serializedStyles
    }, cache.sheet, shouldCache);
    if (shouldCache) {
      return null;
    }
    return /*#__PURE__*/reactExports$1.createElement("style", (_ref = {}, _ref["data-emotion"] = cache.key + "-global " + serializedNames, _ref.dangerouslySetInnerHTML = {
      __html: rules
    }, _ref.nonce = cache.sheet.nonce, _ref));
  } // yes, i know these hooks are used conditionally
  // 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$1.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 <Global/>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;
});
{
  Global.displayName = 'EmotionGlobal';
}
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_";
    }
  };
};
var classnames = function classnames(args) {
  var len = args.length;
  var i = 0;
  var cls = '';
  for (; i < len; i++) {
    var arg = args[i];
    if (arg == null) continue;
    var toAdd = void 0;
    switch (typeof arg) {
      case 'boolean':
        break;
      case 'object':
        {
          if (Array.isArray(arg)) {
            toAdd = classnames(arg);
          } else {
            if (arg.styles !== undefined && arg.name !== undefined) {
              console.error('You have passed styles created with `css` from `@emotion/react` package to the `cx`.\n' + '`cx` is meant to compose class names (strings) so you should convert those styles to a class name by passing them to the `css` received from <ClassNames/> component.');
            }
            toAdd = '';
            for (var k in arg) {
              if (arg[k] && k) {
                toAdd && (toAdd += ' ');
                toAdd += k;
              }
            }
          }
          break;
        }
      default:
        {
          toAdd = arg;
        }
    }
    if (toAdd) {
      cls && (cls += ' ');
      cls += toAdd;
    }
  }
  return cls;
};
function merge(registered, css, className) {
  var registeredStyles = [];
  var rawClassName = getRegisteredStyles(registered, registeredStyles, className);
  if (registeredStyles.length < 2) {
    return className;
  }
  return rawClassName + css(registeredStyles);
}
var Insertion$1 = function Insertion(_ref) {
  var cache = _ref.cache,
    serializedArr = _ref.serializedArr;
  var rules = useInsertionEffectAlwaysWithSyncFallback(function () {
    var rules = '';
    for (var i = 0; i < serializedArr.length; i++) {
      var res = insertStyles(cache, serializedArr[i], false);
      if (!isBrowser$2 && res !== undefined) {
        rules += res;
      }
    }
    if (!isBrowser$2) {
      return rules;
    }
  });
  if (!isBrowser$2 && rules.length !== 0) {
    var _ref2;
    return /*#__PURE__*/reactExports$1.createElement("style", (_ref2 = {}, _ref2["data-emotion"] = cache.key + " " + serializedArr.map(function (serialized) {
      return serialized.name;
    }).join(' '), _ref2.dangerouslySetInnerHTML = {
      __html: rules
    }, _ref2.nonce = cache.sheet.nonce, _ref2));
  }
  return null;
};
var ClassNames = /* #__PURE__ */withEmotionCache(function (props, cache) {
  var hasRendered = false;
  var serializedArr = [];
  var css = function css() {
    if (hasRendered && "development" !== 'production') {
      throw new Error('css can only be used during render');
    }
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    var serialized = serializeStyles(args, cache.registered);
    serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`

    registerStyles(cache, serialized, false);
    return cache.key + "-" + serialized.name;
  };
  var cx = function cx() {
    if (hasRendered && "development" !== 'production') {
      throw new Error('cx can only be used during render');
    }
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    return merge(cache.registered, css, classnames(args));
  };
  var content = {
    css: css,
    cx: cx,
    theme: reactExports$1.useContext(ThemeContext)
  };
  var ele = props.children(content);
  hasRendered = true;
  return /*#__PURE__*/reactExports$1.createElement(reactExports$1.Fragment, null, /*#__PURE__*/reactExports$1.createElement(Insertion$1, {
    cache: cache,
    serializedArr: serializedArr
  }), ele);
});
{
  ClassNames.displayName = 'EmotionClassNames';
}
{
  var isBrowser$1 = typeof document !== 'undefined'; // #1727, #2905 for some reason Jest and Vitest evaluate modules twice if some consuming module gets mocked

  var isTestEnv = typeof jest !== 'undefined' || typeof vi !== 'undefined';
  if (isBrowser$1 && !isTestEnv) {
    // globalThis has wide browser support - https://caniuse.com/?search=globalThis, Node.js 12 and later
    var globalContext =
    // $FlowIgnore
    typeof globalThis !== 'undefined' ? globalThis // eslint-disable-line no-undef
    : isBrowser$1 ? window : global;
    var globalKey = "__EMOTION_REACT_" + pkg.version.split('.')[0] + "__";
    if (globalContext[globalKey]) {
      console.warn('You are loading @emotion/react when it is already loaded. Running ' + 'multiple instances may cause problems. This can happen if multiple ' + 'versions are used, or if multiple builds of the same version are ' + 'used.');
    }
    globalContext[globalKey] = true;
  }
}

var emReact = /*#__PURE__*/Object.freeze({
  __proto__: null,
  CacheProvider: CacheProvider,
  ClassNames: ClassNames,
  Global: Global,
  ThemeContext: ThemeContext,
  ThemeProvider: ThemeProvider$2,
  __unsafe_useEmotionCache: __unsafe_useEmotionCache,
  createElement: jsx,
  css: css,
  jsx: jsx,
  keyframes: keyframes,
  useTheme: useTheme$3,
  get withEmotionCache () { return withEmotionCache; },
  withTheme: withTheme$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 ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var isBrowser = typeof document !== 'undefined';
var Insertion = function Insertion(_ref) {
  var cache = _ref.cache,
    serialized = _ref.serialized,
    isStringTag = _ref.isStringTag;
  registerStyles(cache, serialized, isStringTag);
  var rules = useInsertionEffectAlwaysWithSyncFallback(function () {
    return insertStyles(cache, serialized, isStringTag);
  });
  if (!isBrowser && rules !== undefined) {
    var _ref2;
    var serializedNames = serialized.name;
    var next = serialized.next;
    while (next !== undefined) {
      serializedNames += ' ' + next.name;
      next = next.next;
    }
    return /*#__PURE__*/reactExports$1.createElement("style", (_ref2 = {}, _ref2["data-emotion"] = cache.key + " " + serializedNames, _ref2.dangerouslySetInnerHTML = {
      __html: rules
    }, _ref2.nonce = cache.sheet.nonce, _ref2));
  }
  return null;
};
var createStyled$1 = function createStyled(tag, options) {
  {
    if (tag === undefined) {
      throw new Error('You are trying to create a styled element with an undefined component.\nYou may have forgotten to import it.');
    }
  }
  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 {
      if (args[0][0] === undefined) {
        console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);
      }
      styles.push(args[0][0]);
      var len = args.length;
      var i = 1;
      for (; i < len; i++) {
        if (args[0][i] === undefined) {
          console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR);
        }
        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$1.useContext(ThemeContext);
      }
      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$1.createElement(reactExports$1.Fragment, null, /*#__PURE__*/reactExports$1.createElement(Insertion, {
        cache: cache,
        serialized: serialized,
        isStringTag: typeof FinalTag === 'string'
      }), /*#__PURE__*/reactExports$1.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 && "development" !== '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);
});

function isEmpty$4(obj) {
  return obj === undefined || obj === null || Object.keys(obj).length === 0;
}
function GlobalStyles$2(props) {
  const {
    styles,
    defaultTheme = {}
  } = props;
  const globalStyles = typeof styles === 'function' ? themeInput => styles(isEmpty$4(themeInput) ? defaultTheme : themeInput) : styles;
  return /*#__PURE__*/jsxRuntimeExports.jsx(Global, {
    styles: globalStyles
  });
}
GlobalStyles$2.propTypes = {
  defaultTheme: PropTypes.object,
  styles: PropTypes.oneOfType([PropTypes.array, PropTypes.string, PropTypes.object, PropTypes.func])
} ;

/**
 * @mui/styled-engine v5.13.2
 *
 * @license MIT
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
/* eslint-disable no-underscore-dangle */
function styled$2(tag, options) {
  const stylesFactory = newStyled(tag, options);
  {
    return (...styles) => {
      const component = typeof tag === 'string' ? `"${tag}"` : 'component';
      if (styles.length === 0) {
        console.error([`MUI: Seems like you called \`styled(${component})()\` without a \`style\` argument.`, 'You must provide a `styles` argument: `styled("div")(styleYouForgotToPass)`.'].join('\n'));
      } else if (styles.some(style => style === undefined)) {
        console.error(`MUI: the styled(${component})(...args) API requires all its args to be defined.`);
      }
      return stylesFactory(...styles);
    };
  }
}

// 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 isObjectEmpty(obj) {
  return Object.keys(obj).length === 0;
}
function useTheme$2(defaultTheme = null) {
  const contextTheme = reactExports$1.useContext(ThemeContext);
  return !contextTheme || isObjectEmpty(contextTheme) ? defaultTheme : contextTheme;
}

const EMPTY_THEME = {};
function useThemeScoping(themeId, upperTheme, localTheme, isPrivate = false) {
  return reactExports$1.useMemo(() => {
    const resolvedTheme = themeId ? upperTheme[themeId] || upperTheme : upperTheme;
    if (typeof localTheme === 'function') {
      const mergedTheme = localTheme(resolvedTheme);
      const result = themeId ? _extends({}, upperTheme, {
        [themeId]: mergedTheme
      }) : mergedTheme;
      // must return a function for the private theme to NOT merge with the upper theme.
      // see the test case "use provided theme from a callback" in ThemeProvider.test.js
      if (isPrivate) {
        return () => result;
      }
      return result;
    }
    return themeId ? _extends({}, upperTheme, {
      [themeId]: localTheme
    }) : _extends({}, upperTheme, localTheme);
  }, [themeId, upperTheme, localTheme, isPrivate]);
}

/**
 * This component makes the `theme` available down the React tree.
 * It should preferably be used at **the root of your component tree**.
 *
 * <ThemeProvider theme={theme}> // existing use case
 * <ThemeProvider theme={{ id: theme }}> // theme scoping
 */
function ThemeProvider$1(props) {
  const {
    children,
    theme: localTheme,
    themeId
  } = props;
  const upperTheme = useTheme$2(EMPTY_THEME);
  const upperPrivateTheme = useTheme$4() || EMPTY_THEME;
  {
    if (upperTheme === null && typeof localTheme === 'function' || themeId && upperTheme && !upperTheme[themeId] && typeof localTheme === 'function') {
      console.error(['MUI: You are providing a theme function prop to the ThemeProvider component:', '<ThemeProvider theme={outerTheme => outerTheme} />', '', 'However, no outer theme is present.', 'Make sure a theme is already injected higher in the React tree ' + 'or provide a theme object.'].join('\n'));
    }
  }
  const engineTheme = useThemeScoping(themeId, upperTheme, localTheme);
  const privateTheme = useThemeScoping(themeId, upperPrivateTheme, localTheme, true);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeProvider$3, {
    theme: privateTheme,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(ThemeContext.Provider, {
      value: engineTheme,
      children: children
    })
  });
}
ThemeProvider$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Your component tree.
   */
  children: PropTypes.node,
  /**
   * A theme object. You can provide a function to extend the outer theme.
   */
  theme: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,
  /**
   * The design system's unique id for getting the corresponded theme when there are multiple design systems.
   */
  themeId: PropTypes.string
} ;
{
  ThemeProvider$1.propTypes = exactProp(ThemeProvider$1.propTypes) ;
}

var THEME_ID = '$$material';

const _excluded$1C = ["theme"];
function ThemeProvider(_ref) {
  let {
      theme: themeInput
    } = _ref,
    props = _objectWithoutPropertiesLoose$2(_ref, _excluded$1C);
  const scopedTheme = themeInput[THEME_ID];
  return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeProvider$1, _extends({}, props, {
    themeId: scopedTheme ? THEME_ID : undefined,
    theme: scopedTheme || themeInput
  }));
}
ThemeProvider.propTypes = {
  /**
   * Your component tree.
   */
  children: PropTypes.node,
  /**
   * A theme object. You can provide a function to extend the outer theme.
   */
  theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired
} ;

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);
}

const systemDefaultTheme$1 = createTheme$2();
function useTheme$1(defaultTheme = systemDefaultTheme$1) {
  return useTheme$2(defaultTheme);
}

function useThemeProps$1({
  props,
  name,
  defaultTheme,
  themeId
}) {
  let theme = useTheme$1(defaultTheme);
  if (themeId) {
    theme = theme[themeId] || theme;
  }
  const mergedProps = getThemeProps({
    theme,
    name,
    props
  });
  return mergedProps;
}

const defaultTheme$1 = createTheme$1();
var defaultTheme$2 = defaultTheme$1;

function useThemeProps({
  props,
  name
}) {
  return useThemeProps$1({
    props,
    name,
    defaultTheme: defaultTheme$2,
    themeId: THEME_ID
  });
}

function GlobalStyles$1({
  styles,
  themeId,
  defaultTheme = {}
}) {
  const upperTheme = useTheme$1(defaultTheme);
  const globalStyles = typeof styles === 'function' ? styles(themeId ? upperTheme[themeId] || upperTheme : upperTheme) : styles;
  return /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles$2, {
    styles: globalStyles
  });
}
GlobalStyles$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * @ignore
   */
  defaultTheme: PropTypes.object,
  /**
   * @ignore
   */
  styles: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.array, PropTypes.func, PropTypes.number, PropTypes.object, PropTypes.string, PropTypes.bool]),
  /**
   * @ignore
   */
  themeId: PropTypes.string
} ;

function GlobalStyles(props) {
  return /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles$1, _extends({}, props, {
    defaultTheme: defaultTheme$2,
    themeId: THEME_ID
  }));
}
GlobalStyles.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The styles you want to apply globally.
   */
  styles: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.array, PropTypes.func, PropTypes.number, PropTypes.object, PropTypes.string, PropTypes.bool])
} ;

const html = (theme, enableColorScheme) => _extends({
  WebkitFontSmoothing: 'antialiased',
  // Antialiasing.
  MozOsxFontSmoothing: 'grayscale',
  // Antialiasing.
  // Change from `box-sizing: content-box` so that `width`
  // is not affected by `padding` or `border`.
  boxSizing: 'border-box',
  // Fix font resize problem in iOS
  WebkitTextSizeAdjust: '100%'
}, enableColorScheme && !theme.vars && {
  colorScheme: theme.palette.mode
});
const body = theme => _extends({
  color: (theme.vars || theme).palette.text.primary
}, theme.typography.body1, {
  backgroundColor: (theme.vars || theme).palette.background.default,
  '@media print': {
    // Save printer ink.
    backgroundColor: (theme.vars || theme).palette.common.white
  }
});
const styles$5 = (theme, enableColorScheme = false) => {
  var _theme$components, _theme$components$Mui;
  const colorSchemeStyles = {};
  if (enableColorScheme && theme.colorSchemes) {
    Object.entries(theme.colorSchemes).forEach(([key, scheme]) => {
      var _scheme$palette;
      colorSchemeStyles[theme.getColorSchemeSelector(key).replace(/\s*&/, '')] = {
        colorScheme: (_scheme$palette = scheme.palette) == null ? void 0 : _scheme$palette.mode
      };
    });
  }
  let defaultStyles = _extends({
    html: html(theme, enableColorScheme),
    '*, *::before, *::after': {
      boxSizing: 'inherit'
    },
    'strong, b': {
      fontWeight: theme.typography.fontWeightBold
    },
    body: _extends({
      margin: 0
    }, body(theme), {
      // Add support for document.body.requestFullScreen().
      // Other elements, if background transparent, are not supported.
      '&::backdrop': {
        backgroundColor: (theme.vars || theme).palette.background.default
      }
    })
  }, colorSchemeStyles);
  const themeOverrides = (_theme$components = theme.components) == null ? void 0 : (_theme$components$Mui = _theme$components.MuiCssBaseline) == null ? void 0 : _theme$components$Mui.styleOverrides;
  if (themeOverrides) {
    defaultStyles = [defaultStyles, themeOverrides];
  }
  return defaultStyles;
};

/**
 * Kickstart an elegant, consistent, and simple baseline to build upon.
 */
function CssBaseline(inProps) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiCssBaseline'
  });
  const {
    children,
    enableColorScheme = false
  } = props;
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles, {
      styles: theme => styles$5(theme, enableColorScheme)
    }), children]
  });
}
CssBaseline.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * You can wrap a node.
   */
  children: PropTypes.node,
  /**
   * Enable `color-scheme` CSS property to use `theme.palette.mode`.
   * For more details, check out https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme
   * For browser support, check out https://caniuse.com/?search=color-scheme
   * @default false
   */
  enableColorScheme: PropTypes.bool
} ;

function App() {
  const {
      theme
    } = usePlugin("material").config,
    muiTheme = reactExports$1.useMemo(() => createTheme(theme), [theme]);
  return /*#__PURE__*/React.createElement(ThemeProvider, {
    theme: muiTheme
  }, /*#__PURE__*/React.createElement(CssBaseline, null), /*#__PURE__*/React.createElement(App$1, null));
}
function createTheme(theme) {
  const {
    type,
    primary,
    secondary,
    background
  } = theme;
  const palette = theme.palette || {};
  if (type) {
    palette.mode = type;
  }
  if (primary) {
    palette.primary = {
      main: primary
    };
  }
  if (secondary) {
    palette.secondary = {
      main: secondary
    };
  }
  if (background) {
    palette.background = {
      paper: background
    };
  }
  return createTheme$1({
    palette
  });
}

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 < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);else for (t in e) e[t] && (n && (n += " "), n += t);
  return n;
}
function clsx() {
  for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t);
  return n;
}

const _excluded$1B = ["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$1B);
  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
  });
}

const _excluded$1A = ["className", "component"];
function createBox(options = {}) {
  const {
    themeId,
    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$1.forwardRef(function Box(inProps, ref) {
    const theme = useTheme$1(defaultTheme);
    const _extendSxProp = extendSxProp(inProps),
      {
        className,
        component = 'div'
      } = _extendSxProp,
      other = _objectWithoutPropertiesLoose$2(_extendSxProp, _excluded$1A);
    return /*#__PURE__*/jsxRuntimeExports.jsx(BoxRoot, _extends({
      as: component,
      ref: ref,
      className: clsx(className, generateClassName ? generateClassName(defaultClassName) : defaultClassName),
      theme: themeId ? theme[themeId] || theme : theme
    }, other));
  });
  return Box;
}

const _excluded$1z = ["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$1z);
  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$1y = ["name", "slot", "skipVariantsResolver", "skipSx", "overridesResolver"];
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$2();
const lowercaseFirstLetter = string => {
  return string.charAt(0).toLowerCase() + string.slice(1);
};
function resolveTheme({
  defaultTheme,
  theme,
  themeId
}) {
  return isEmpty$2(theme) ? defaultTheme : theme[themeId] || theme;
}
function createStyled(input = {}) {
  const {
    themeId,
    defaultTheme = systemDefaultTheme,
    rootShouldForwardProp = shouldForwardProp,
    slotShouldForwardProp = shouldForwardProp
  } = input;
  const systemSx = props => {
    return styleFunctionSx$1(_extends({}, props, {
      theme: resolveTheme(_extends({}, props, {
        defaultTheme,
        themeId
      }))
    }));
  };
  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$1y);

    // 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;
    {
      if (componentName) {
        label = `${componentName}-${lowercaseFirstLetter(componentSlot || 'Root')}`;
      }
    }
    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 ? props => {
          return stylesArg(_extends({}, props, {
            theme: resolveTheme(_extends({}, props, {
              defaultTheme,
              themeId
            }))
          }));
        } : stylesArg;
      }) : [];
      let transformedStyleArg = styleArg;
      if (componentName && overridesResolver) {
        expressionsWithDefaultTheme.push(props => {
          const theme = resolveTheme(_extends({}, props, {
            defaultTheme,
            themeId
          }));
          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 = resolveTheme(_extends({}, props, {
            defaultTheme,
            themeId
          }));
          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 = props => styleArg(_extends({}, props, {
          theme: resolveTheme(_extends({}, props, {
            defaultTheme,
            themeId
          }))
        }));
      }
      const Component = defaultStyledResolver(transformedStyleArg, ...expressionsWithDefaultTheme);
      {
        let displayName;
        if (componentName) {
          displayName = `${componentName}${componentSlot || ''}`;
        }
        if (displayName === undefined) {
          displayName = `Styled(${getDisplayName(tag)})`;
        }
        Component.displayName = displayName;
      }
      if (tag.muiName) {
        Component.muiName = tag.muiName;
      }
      return Component;
    };
    if (defaultStyledResolver.withConfig) {
      muiStyledResolver.withConfig = defaultStyledResolver.withConfig;
    }
    return muiStyledResolver;
  };
}

function useTheme() {
  const theme = useTheme$1(defaultTheme$2);
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useDebugValue(theme);
  }
  return theme[THEME_ID] || theme;
}

const rootShouldForwardProp = prop => shouldForwardProp(prop) && prop !== 'classes';
const slotShouldForwardProp = shouldForwardProp;
const styled = createStyled({
  themeId: THEME_ID,
  defaultTheme: defaultTheme$2,
  rootShouldForwardProp
});
var 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);
};
var getOverlayAlpha$1 = getOverlayAlpha;

const defaultTheme = createTheme$1();
const Box = createBox({
  themeId: THEME_ID,
  defaultTheme,
  defaultClassName: 'MuiBox-root',
  generateClassName: ClassNameGenerator$1.generate
});
Box.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * @ignore
   */
  children: PropTypes.node,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var Box$1 = Box;

function Container({
  children
}) {
  return /*#__PURE__*/React.createElement(Box$1, {
    sx: {
      display: "flex",
      flexDirection: "column",
      height: "100vh"
    }
  }, children);
}
Container.propTypes = {
  children: PropTypes.node
};

/**
 * 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)
  });
}

const defaultContextValue = {
  disableDefaultClasses: false
};
const ClassNameConfiguratorContext = /*#__PURE__*/reactExports$1.createContext(defaultContextValue);
/**
 * @ignore - internal hook.
 *
 * Wraps the `generateUtilityClass` function and controls how the classes are generated.
 * Currently it only affects whether the classes are applied or not.
 *
 * @returns Function to be called with the `generateUtilityClass` function specific to a component to generate the classes.
 */
function useClassNamesOverride(generateUtilityClass) {
  const {
    disableDefaultClasses
  } = reactExports$1.useContext(ClassNameConfiguratorContext);
  return slot => {
    if (disableDefaultClasses) {
      return '';
    }
    return generateUtilityClass(slot);
  };
}

/**
 * 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 a Base UI 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 Base UI) 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$1x = ["elementType", "externalSlotProps", "ownerState"];
/**
 * @ignore - do not document.
 * 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$1x);
  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;
}

/**
 *
 * Demos:
 *
 * - [Badge](https://mui.com/base/react-badge/#hook)
 *
 * API:
 *
 * - [useBadge API](https://mui.com/base/react-badge/hooks-api/#use-badge)
 */
function useBadge(parameters) {
  const {
    badgeContent: badgeContentProp,
    invisible: invisibleProp = false,
    max: maxProp = 99,
    showZero = false
  } = parameters;
  const prevProps = usePreviousProps$1({
    badgeContent: badgeContentProp,
    max: maxProp
  });
  let invisible = invisibleProp;
  if (invisibleProp === false && badgeContentProp === 0 && !showZero) {
    invisible = true;
  }
  const {
    badgeContent,
    max = maxProp
  } = invisible ? prevProps : parameters;
  const displayValue = badgeContent && Number(badgeContent) > max ? `${max}+` : badgeContent;
  return {
    badgeContent,
    invisible,
    max,
    displayValue
  };
}

function mapEventPropToEvent(eventProp) {
  return eventProp.substring(2).toLowerCase();
}
function clickedRootScrollbar(event, doc) {
  return doc.documentElement.clientWidth < event.clientX || doc.documentElement.clientHeight < event.clientY;
}
/**
 * Listen for click events that occur somewhere in the document, outside of the element itself.
 * For instance, if you need to hide a menu when people click anywhere else on your page.
 *
 * Demos:
 *
 * - [Click-Away Listener](https://mui.com/base/react-click-away-listener/)
 *
 * API:
 *
 * - [ClickAwayListener API](https://mui.com/base/react-click-away-listener/components-api/#click-away-listener)
 */
function ClickAwayListener(props) {
  const {
    children,
    disableReactTree = false,
    mouseEvent = 'onClick',
    onClickAway,
    touchEvent = 'onTouchEnd'
  } = props;
  const movedRef = reactExports$1.useRef(false);
  const nodeRef = reactExports$1.useRef(null);
  const activatedRef = reactExports$1.useRef(false);
  const syntheticEventRef = reactExports$1.useRef(false);
  reactExports$1.useEffect(() => {
    // Ensure that this component is not "activated" synchronously.
    // https://github.com/facebook/react/issues/20074
    setTimeout(() => {
      activatedRef.current = true;
    }, 0);
    return () => {
      activatedRef.current = false;
    };
  }, []);
  const handleRef = useForkRef(
  // @ts-expect-error TODO upstream fix
  children.ref, nodeRef);

  // The handler doesn't take event.defaultPrevented into account:
  //
  // event.preventDefault() is meant to stop default behaviors like
  // clicking a checkbox to check it, hitting a button to submit a form,
  // and hitting left arrow to move the cursor in a text input etc.
  // Only special HTML elements have these default behaviors.
  const handleClickAway = useEventCallback(event => {
    // Given developers can stop the propagation of the synthetic event,
    // we can only be confident with a positive value.
    const insideReactTree = syntheticEventRef.current;
    syntheticEventRef.current = false;
    const doc = ownerDocument(nodeRef.current);

    // 1. IE11 support, which trigger the handleClickAway even after the unbind
    // 2. The child might render null.
    // 3. Behave like a blur listener.
    if (!activatedRef.current || !nodeRef.current || 'clientX' in event && clickedRootScrollbar(event, doc)) {
      return;
    }

    // Do not act if user performed touchmove
    if (movedRef.current) {
      movedRef.current = false;
      return;
    }
    let insideDOM;

    // If not enough, can use https://github.com/DieterHolvoet/event-propagation-path/blob/master/propagationPath.js
    if (event.composedPath) {
      insideDOM = event.composedPath().indexOf(nodeRef.current) > -1;
    } else {
      insideDOM = !doc.documentElement.contains(
      // @ts-expect-error returns `false` as intended when not dispatched from a Node
      event.target) || nodeRef.current.contains(
      // @ts-expect-error returns `false` as intended when not dispatched from a Node
      event.target);
    }
    if (!insideDOM && (disableReactTree || !insideReactTree)) {
      onClickAway(event);
    }
  });

  // Keep track of mouse/touch events that bubbled up through the portal.
  const createHandleSynthetic = handlerName => event => {
    syntheticEventRef.current = true;
    const childrenPropsHandler = children.props[handlerName];
    if (childrenPropsHandler) {
      childrenPropsHandler(event);
    }
  };
  const childrenProps = {
    ref: handleRef
  };
  if (touchEvent !== false) {
    childrenProps[touchEvent] = createHandleSynthetic(touchEvent);
  }
  reactExports$1.useEffect(() => {
    if (touchEvent !== false) {
      const mappedTouchEvent = mapEventPropToEvent(touchEvent);
      const doc = ownerDocument(nodeRef.current);
      const handleTouchMove = () => {
        movedRef.current = true;
      };
      doc.addEventListener(mappedTouchEvent, handleClickAway);
      doc.addEventListener('touchmove', handleTouchMove);
      return () => {
        doc.removeEventListener(mappedTouchEvent, handleClickAway);
        doc.removeEventListener('touchmove', handleTouchMove);
      };
    }
    return undefined;
  }, [handleClickAway, touchEvent]);
  if (mouseEvent !== false) {
    childrenProps[mouseEvent] = createHandleSynthetic(mouseEvent);
  }
  reactExports$1.useEffect(() => {
    if (mouseEvent !== false) {
      const mappedMouseEvent = mapEventPropToEvent(mouseEvent);
      const doc = ownerDocument(nodeRef.current);
      doc.addEventListener(mappedMouseEvent, handleClickAway);
      return () => {
        doc.removeEventListener(mappedMouseEvent, handleClickAway);
      };
    }
    return undefined;
  }, [handleClickAway, mouseEvent]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(reactExports$1.Fragment, {
    children: /*#__PURE__*/reactExports$1.cloneElement(children, childrenProps)
  });
}
ClickAwayListener.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * The wrapped element.
   */
  children: elementAcceptingRef$1.isRequired,
  /**
   * If `true`, the React tree is ignored and only the DOM tree is considered.
   * This prop changes how portaled elements are handled.
   * @default false
   */
  disableReactTree: PropTypes.bool,
  /**
   * The mouse event to listen to. You can disable the listener by providing `false`.
   * @default 'onClick'
   */
  mouseEvent: PropTypes.oneOf(['onClick', 'onMouseDown', 'onMouseUp', 'onPointerDown', 'onPointerUp', false]),
  /**
   * Callback fired when a "click away" event is detected.
   */
  onClickAway: PropTypes.func.isRequired,
  /**
   * The touch event to listen to. You can disable the listener by providing `false`.
   * @default 'onTouchEnd'
   */
  touchEvent: PropTypes.oneOf(['onTouchEnd', 'onTouchStart', false])
} ;
{
  // eslint-disable-next-line
  ClickAwayListener['propTypes' + ''] = exactProp(ClickAwayListener.propTypes);
}

/* 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, <details/>, <audio controls/> and <video controls/> elements get a default
  //  `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
  //  yet they are still part of the regular tab order; in FF, they get a default
  //  `tabIndex` of 0; since Chrome still puts those elements in the regular tab
  //  order, consider their tab index to be 0.
  if (node.contentEditable === 'true' || (node.nodeName === 'AUDIO' || node.nodeName === 'VIDEO' || node.nodeName === 'DETAILS') && node.getAttribute('tabindex') === null) {
    return 0;
  }
  return node.tabIndex;
}
function isNonTabbableRadio(node) {
  if (node.tagName !== 'INPUT' || node.type !== 'radio') {
    return false;
  }
  if (!node.name) {
    return false;
  }
  const getRadio = selector => node.ownerDocument.querySelector(`input[type="radio"]${selector}`);
  let roving = getRadio(`[name="${node.name}"]:checked`);
  if (!roving) {
    roving = getRadio(`[name="${node.name}"]`);
  }
  return roving !== node;
}
function isNodeMatchingSelectorFocusable(node) {
  if (node.disabled || node.tagName === 'INPUT' && node.type === 'hidden' || isNonTabbableRadio(node)) {
    return false;
  }
  return true;
}
function defaultGetTabbable(root) {
  const regularTabNodes = [];
  const orderedTabNodes = [];
  Array.from(root.querySelectorAll(candidatesSelector)).forEach((node, i) => {
    const nodeTabIndex = getTabIndex(node);
    if (nodeTabIndex === -1 || !isNodeMatchingSelectorFocusable(node)) {
      return;
    }
    if (nodeTabIndex === 0) {
      regularTabNodes.push(node);
    } else {
      orderedTabNodes.push({
        documentOrder: i,
        tabIndex: nodeTabIndex,
        node: node
      });
    }
  });
  return orderedTabNodes.sort((a, b) => a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex).map(a => a.node).concat(regularTabNodes);
}
function defaultIsEnabled() {
  return true;
}

/**
 * Utility component that locks focus inside the component.
 *
 * Demos:
 *
 * - [Focus Trap](https://mui.com/base/react-focus-trap/)
 *
 * API:
 *
 * - [FocusTrap API](https://mui.com/base/react-focus-trap/components-api/#focus-trap)
 */
function FocusTrap(props) {
  const {
    children,
    disableAutoFocus = false,
    disableEnforceFocus = false,
    disableRestoreFocus = false,
    getTabbable = defaultGetTabbable,
    isEnabled = defaultIsEnabled,
    open
  } = props;
  const ignoreNextEnforceFocus = reactExports$1.useRef(false);
  const sentinelStart = reactExports$1.useRef(null);
  const sentinelEnd = reactExports$1.useRef(null);
  const nodeToRestore = reactExports$1.useRef(null);
  const reactFocusEventTarget = reactExports$1.useRef(null);
  // This variable is useful when disableAutoFocus is true.
  // It waits for the active element to move into the component to activate.
  const activated = reactExports$1.useRef(false);
  const rootRef = reactExports$1.useRef(null);
  // @ts-expect-error TODO upstream fix
  const handleRef = useForkRef(children.ref, rootRef);
  const lastKeydown = reactExports$1.useRef(null);
  reactExports$1.useEffect(() => {
    // We might render an empty child.
    if (!open || !rootRef.current) {
      return;
    }
    activated.current = !disableAutoFocus;
  }, [disableAutoFocus, open]);
  reactExports$1.useEffect(() => {
    // We might render an empty child.
    if (!open || !rootRef.current) {
      return;
    }
    const doc = ownerDocument(rootRef.current);
    if (!rootRef.current.contains(doc.activeElement)) {
      if (!rootRef.current.hasAttribute('tabIndex')) {
        {
          console.error(['MUI: The modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to "-1".'].join('\n'));
        }
        rootRef.current.setAttribute('tabIndex', '-1');
      }
      if (activated.current) {
        rootRef.current.focus();
      }
    }
    return () => {
      // restoreLastFocus()
      if (!disableRestoreFocus) {
        // In IE11 it is possible for document.activeElement to be null resulting
        // in nodeToRestore.current being null.
        // Not all elements in IE11 have a focus method.
        // Once IE11 support is dropped the focus() call can be unconditional.
        if (nodeToRestore.current && nodeToRestore.current.focus) {
          ignoreNextEnforceFocus.current = true;
          nodeToRestore.current.focus();
        }
        nodeToRestore.current = null;
      }
    };
    // Missing `disableRestoreFocus` which is fine.
    // We don't support changing that prop on an open FocusTrap
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);
  reactExports$1.useEffect(() => {
    // We might render an empty child.
    if (!open || !rootRef.current) {
      return;
    }
    const doc = ownerDocument(rootRef.current);
    const contain = nativeEvent => {
      const {
        current: rootElement
      } = rootRef;

      // Cleanup functions are executed lazily in React 17.
      // Contain can be called between the component being unmounted and its cleanup function being run.
      if (rootElement === null) {
        return;
      }
      if (!doc.hasFocus() || disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) {
        ignoreNextEnforceFocus.current = false;
        return;
      }
      if (!rootElement.contains(doc.activeElement)) {
        // if the focus event is not coming from inside the children's react tree, reset the refs
        if (nativeEvent && reactFocusEventTarget.current !== nativeEvent.target || doc.activeElement !== reactFocusEventTarget.current) {
          reactFocusEventTarget.current = null;
        } else if (reactFocusEventTarget.current !== null) {
          return;
        }
        if (!activated.current) {
          return;
        }
        let tabbable = [];
        if (doc.activeElement === sentinelStart.current || doc.activeElement === sentinelEnd.current) {
          tabbable = getTabbable(rootRef.current);
        }
        if (tabbable.length > 0) {
          var _lastKeydown$current, _lastKeydown$current2;
          const isShiftTab = Boolean(((_lastKeydown$current = lastKeydown.current) == null ? void 0 : _lastKeydown$current.shiftKey) && ((_lastKeydown$current2 = lastKeydown.current) == null ? void 0 : _lastKeydown$current2.key) === 'Tab');
          const focusNext = tabbable[0];
          const focusPrevious = tabbable[tabbable.length - 1];
          if (typeof focusNext !== 'string' && typeof focusPrevious !== 'string') {
            if (isShiftTab) {
              focusPrevious.focus();
            } else {
              focusNext.focus();
            }
          }
        } else {
          rootElement.focus();
        }
      }
    };
    const loopFocus = nativeEvent => {
      lastKeydown.current = nativeEvent;
      if (disableEnforceFocus || !isEnabled() || nativeEvent.key !== 'Tab') {
        return;
      }

      // Make sure the next tab starts from the right place.
      // doc.activeElement refers to the origin.
      if (doc.activeElement === rootRef.current && nativeEvent.shiftKey) {
        // We need to ignore the next contain as
        // it will try to move the focus back to the rootRef element.
        ignoreNextEnforceFocus.current = true;
        if (sentinelEnd.current) {
          sentinelEnd.current.focus();
        }
      }
    };
    doc.addEventListener('focusin', contain);
    doc.addEventListener('keydown', loopFocus, true);

    // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area.
    // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.
    // Instead, we can look if the active element was restored on the BODY element.
    //
    // The whatwg spec defines how the browser should behave but does not explicitly mention any events:
    // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.
    const interval = setInterval(() => {
      if (doc.activeElement && doc.activeElement.tagName === 'BODY') {
        contain(null);
      }
    }, 50);
    return () => {
      clearInterval(interval);
      doc.removeEventListener('focusin', contain);
      doc.removeEventListener('keydown', loopFocus, true);
    };
  }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open, getTabbable]);
  const onFocus = event => {
    if (nodeToRestore.current === null) {
      nodeToRestore.current = event.relatedTarget;
    }
    activated.current = true;
    reactFocusEventTarget.current = event.target;
    const childrenPropsHandler = children.props.onFocus;
    if (childrenPropsHandler) {
      childrenPropsHandler(event);
    }
  };
  const handleFocusSentinel = event => {
    if (nodeToRestore.current === null) {
      nodeToRestore.current = event.relatedTarget;
    }
    activated.current = true;
  };
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx("div", {
      tabIndex: open ? 0 : -1,
      onFocus: handleFocusSentinel,
      ref: sentinelStart,
      "data-testid": "sentinelStart"
    }), /*#__PURE__*/reactExports$1.cloneElement(children, {
      ref: handleRef,
      onFocus
    }), /*#__PURE__*/jsxRuntimeExports.jsx("div", {
      tabIndex: open ? 0 : -1,
      onFocus: handleFocusSentinel,
      ref: sentinelEnd,
      "data-testid": "sentinelEnd"
    })]
  });
}
FocusTrap.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * A single child content element.
   */
  children: elementAcceptingRef$1,
  /**
   * If `true`, the focus trap will not automatically shift focus to itself when it opens, and
   * replace it to the last focused element when it closes.
   * This also works correctly with any focus trap children that have the `disableAutoFocus` prop.
   *
   * Generally this should never be set to `true` as it makes the focus trap less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableAutoFocus: PropTypes.bool,
  /**
   * If `true`, the focus trap will not prevent focus from leaving the focus trap while open.
   *
   * Generally this should never be set to `true` as it makes the focus trap less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableEnforceFocus: PropTypes.bool,
  /**
   * If `true`, the focus trap will not restore focus to previously focused element once
   * focus trap is hidden or unmounted.
   * @default false
   */
  disableRestoreFocus: PropTypes.bool,
  /**
   * Returns an array of ordered tabbable nodes (i.e. in tab order) within the root.
   * For instance, you can provide the "tabbable" npm dependency.
   * @param {HTMLElement} root
   */
  getTabbable: PropTypes.func,
  /**
   * This prop extends the `open` prop.
   * It allows to toggle the open state without having to wait for a rerender when changing the `open` prop.
   * This prop should be memoized.
   * It can be used to support multiple focus trap mounted at the same time.
   * @default function defaultIsEnabled(): boolean {
   *   return true;
   * }
   */
  isEnabled: PropTypes.func,
  /**
   * If `true`, focus is locked.
   */
  open: PropTypes.bool.isRequired
} ;
{
  // eslint-disable-next-line
  FocusTrap['propTypes' + ''] = exactProp(FocusTrap.propTypes);
}

var top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var auto = 'auto';
var basePlacements = [top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
  return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
  return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM

var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers

var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)

var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];

function getNodeName(element) {
  return element ? (element.nodeName || '').toLowerCase() : null;
}

function getWindow(node) {
  if (node == null) {
    return window;
  }
  if (node.toString() !== '[object Window]') {
    var ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }
  return node;
}

function isElement(node) {
  var OwnElement = getWindow(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement$1(node) {
  var OwnElement = getWindow(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
  // IE 11 has no ShadowRoot
  if (typeof ShadowRoot === 'undefined') {
    return false;
  }
  var OwnElement = getWindow(node).ShadowRoot;
  return node instanceof OwnElement || node instanceof ShadowRoot;
}

// and applies them to the HTMLElements such as popper and arrow

function applyStyles(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function (name) {
    var style = state.styles[name] || {};
    var attributes = state.attributes[name] || {};
    var element = state.elements[name]; // arrow is optional + virtual elements

    if (!isHTMLElement$1(element) || !getNodeName(element)) {
      return;
    } // Flow doesn't support to extend this property, but it's the most
    // effective way to apply styles to an HTMLElement
    // $FlowFixMe[cannot-write]

    Object.assign(element.style, style);
    Object.keys(attributes).forEach(function (name) {
      var value = attributes[name];
      if (value === false) {
        element.removeAttribute(name);
      } else {
        element.setAttribute(name, value === true ? '' : value);
      }
    });
  });
}
function effect$2(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: '0',
      top: '0',
      margin: '0'
    },
    arrow: {
      position: 'absolute'
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;
  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }
  return function () {
    Object.keys(state.elements).forEach(function (name) {
      var element = state.elements[name];
      var attributes = state.attributes[name] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them

      var style = styleProperties.reduce(function (style, property) {
        style[property] = '';
        return style;
      }, {}); // arrow is optional + virtual elements

      if (!isHTMLElement$1(element) || !getNodeName(element)) {
        return;
      }
      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function (attribute) {
        element.removeAttribute(attribute);
      });
    });
  };
} // eslint-disable-next-line import/no-unused-modules

var applyStyles$1 = {
  name: 'applyStyles',
  enabled: true,
  phase: 'write',
  fn: applyStyles,
  effect: effect$2,
  requires: ['computeStyles']
};

function getBasePlacement(placement) {
  return placement.split('-')[0];
}

var max = Math.max;
var min = Math.min;
var round = Math.round;

function getUAString() {
  var uaData = navigator.userAgentData;
  if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
    return uaData.brands.map(function (item) {
      return item.brand + "/" + item.version;
    }).join(' ');
  }
  return navigator.userAgent;
}

function isLayoutViewport() {
  return !/^((?!chrome|android).)*safari/i.test(getUAString());
}

function getBoundingClientRect(element, includeScale, isFixedStrategy) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  var clientRect = element.getBoundingClientRect();
  var scaleX = 1;
  var scaleY = 1;
  if (includeScale && isHTMLElement$1(element)) {
    scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
    scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
  }
  var _ref = isElement(element) ? getWindow(element) : window,
    visualViewport = _ref.visualViewport;
  var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
  var width = clientRect.width / scaleX;
  var height = clientRect.height / scaleY;
  return {
    width: width,
    height: height,
    top: y,
    right: x + width,
    bottom: y + height,
    left: x,
    x: x,
    y: y
  };
}

// means it doesn't take into account transforms.

function getLayoutRect(element) {
  var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
  // Fixes https://github.com/popperjs/popper-core/issues/1223

  var width = element.offsetWidth;
  var height = element.offsetHeight;
  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }
  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }
  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width: width,
    height: height
  };
}

function contains(parent, child) {
  var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method

  if (parent.contains(child)) {
    return true;
  } // then fallback to custom implementation with Shadow DOM support
  else if (rootNode && isShadowRoot(rootNode)) {
    var next = child;
    do {
      if (next && parent.isSameNode(next)) {
        return true;
      } // $FlowFixMe[prop-missing]: need a better way to handle this...

      next = next.parentNode || next.host;
    } while (next);
  } // Give up, the result is false

  return false;
}

function getComputedStyle(element) {
  return getWindow(element).getComputedStyle(element);
}

function isTableElement(element) {
  return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}

function getDocumentElement(element) {
  // $FlowFixMe[incompatible-return]: assume body is always available
  return ((isElement(element) ? element.ownerDocument :
  // $FlowFixMe[prop-missing]
  element.document) || window.document).documentElement;
}

function getParentNode(element) {
  if (getNodeName(element) === 'html') {
    return element;
  }
  return (
    // this is a quicker (but less type safe) way to save quite some bytes from the bundle
    // $FlowFixMe[incompatible-return]
    // $FlowFixMe[prop-missing]
    element.assignedSlot ||
    // step into the shadow DOM of the parent of a slotted node
    element.parentNode || (
    // DOM Element detected
    isShadowRoot(element) ? element.host : null) ||
    // ShadowRoot detected
    // $FlowFixMe[incompatible-call]: HTMLElement is a Node
    getDocumentElement(element) // fallback
  );
}

function getTrueOffsetParent(element) {
  if (!isHTMLElement$1(element) ||
  // https://github.com/popperjs/popper-core/issues/837
  getComputedStyle(element).position === 'fixed') {
    return null;
  }
  return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block

function getContainingBlock(element) {
  var isFirefox = /firefox/i.test(getUAString());
  var isIE = /Trident/i.test(getUAString());
  if (isIE && isHTMLElement$1(element)) {
    // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
    var elementCss = getComputedStyle(element);
    if (elementCss.position === 'fixed') {
      return null;
    }
  }
  var currentNode = getParentNode(element);
  if (isShadowRoot(currentNode)) {
    currentNode = currentNode.host;
  }
  while (isHTMLElement$1(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
    var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that
    // create a containing block.
    // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block

    if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.

function getOffsetParent(element) {
  var window = getWindow(element);
  var offsetParent = getTrueOffsetParent(element);
  while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {
    offsetParent = getTrueOffsetParent(offsetParent);
  }
  if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {
    return window;
  }
  return offsetParent || getContainingBlock(element) || window;
}

function getMainAxisFromPlacement(placement) {
  return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}

function within(min$1, value, max$1) {
  return max(min$1, min(value, max$1));
}
function withinMaxClamp(min, value, max) {
  var v = within(min, value, max);
  return v > max ? max : v;
}

function getFreshSideObject() {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
}

function mergePaddingObject(paddingObject) {
  return Object.assign({}, getFreshSideObject(), paddingObject);
}

function expandToHashMap(value, keys) {
  return keys.reduce(function (hashMap, key) {
    hashMap[key] = value;
    return hashMap;
  }, {});
}

var toPaddingObject = function toPaddingObject(padding, state) {
  padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
    placement: state.placement
  })) : padding;
  return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
  var _state$modifiersData$;
  var state = _ref.state,
    name = _ref.name,
    options = _ref.options;
  var arrowElement = state.elements.arrow;
  var popperOffsets = state.modifiersData.popperOffsets;
  var basePlacement = getBasePlacement(state.placement);
  var axis = getMainAxisFromPlacement(basePlacement);
  var isVertical = [left, right].indexOf(basePlacement) >= 0;
  var len = isVertical ? 'height' : 'width';
  if (!arrowElement || !popperOffsets) {
    return;
  }
  var paddingObject = toPaddingObject(options.padding, state);
  var arrowRect = getLayoutRect(arrowElement);
  var minProp = axis === 'y' ? top : left;
  var maxProp = axis === 'y' ? bottom : right;
  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
  var startDiff = popperOffsets[axis] - state.rects.reference[axis];
  var arrowOffsetParent = getOffsetParent(arrowElement);
  var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
  // outside of the popper bounds

  var min = paddingObject[minProp];
  var max = clientSize - arrowRect[len] - paddingObject[maxProp];
  var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  var offset = within(min, center, max); // Prevents breaking syntax highlighting...

  var axisProp = axis;
  state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function effect$1(_ref2) {
  var state = _ref2.state,
    options = _ref2.options;
  var _options$element = options.element,
    arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
  if (arrowElement == null) {
    return;
  } // CSS selector

  if (typeof arrowElement === 'string') {
    arrowElement = state.elements.popper.querySelector(arrowElement);
    if (!arrowElement) {
      return;
    }
  }
  if (!contains(state.elements.popper, arrowElement)) {
    return;
  }
  state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules

var arrow$1 = {
  name: 'arrow',
  enabled: true,
  phase: 'main',
  fn: arrow,
  effect: effect$1,
  requires: ['popperOffsets'],
  requiresIfExists: ['preventOverflow']
};

function getVariation(placement) {
  return placement.split('-')[1];
}

var unsetSides = {
  top: 'auto',
  right: 'auto',
  bottom: 'auto',
  left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.

function roundOffsetsByDPR(_ref, win) {
  var x = _ref.x,
    y = _ref.y;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round(x * dpr) / dpr || 0,
    y: round(y * dpr) / dpr || 0
  };
}
function mapToStyles(_ref2) {
  var _Object$assign2;
  var popper = _ref2.popper,
    popperRect = _ref2.popperRect,
    placement = _ref2.placement,
    variation = _ref2.variation,
    offsets = _ref2.offsets,
    position = _ref2.position,
    gpuAcceleration = _ref2.gpuAcceleration,
    adaptive = _ref2.adaptive,
    roundOffsets = _ref2.roundOffsets,
    isFixed = _ref2.isFixed;
  var _offsets$x = offsets.x,
    x = _offsets$x === void 0 ? 0 : _offsets$x,
    _offsets$y = offsets.y,
    y = _offsets$y === void 0 ? 0 : _offsets$y;
  var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
    x: x,
    y: y
  }) : {
    x: x,
    y: y
  };
  x = _ref3.x;
  y = _ref3.y;
  var hasX = offsets.hasOwnProperty('x');
  var hasY = offsets.hasOwnProperty('y');
  var sideX = left;
  var sideY = top;
  var win = window;
  if (adaptive) {
    var offsetParent = getOffsetParent(popper);
    var heightProp = 'clientHeight';
    var widthProp = 'clientWidth';
    if (offsetParent === getWindow(popper)) {
      offsetParent = getDocumentElement(popper);
      if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {
        heightProp = 'scrollHeight';
        widthProp = 'scrollWidth';
      }
    } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it

    offsetParent = offsetParent;
    if (placement === top || (placement === left || placement === right) && variation === end) {
      sideY = bottom;
      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height :
      // $FlowFixMe[prop-missing]
      offsetParent[heightProp];
      y -= offsetY - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }
    if (placement === left || (placement === top || placement === bottom) && variation === end) {
      sideX = right;
      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width :
      // $FlowFixMe[prop-missing]
      offsetParent[widthProp];
      x -= offsetX - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }
  var commonStyles = Object.assign({
    position: position
  }, adaptive && unsetSides);
  var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
    x: x,
    y: y
  }, getWindow(popper)) : {
    x: x,
    y: y
  };
  x = _ref4.x;
  y = _ref4.y;
  if (gpuAcceleration) {
    var _Object$assign;
    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }
  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref5) {
  var state = _ref5.state,
    options = _ref5.options;
  var _options$gpuAccelerat = options.gpuAcceleration,
    gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
    _options$adaptive = options.adaptive,
    adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
    _options$roundOffsets = options.roundOffsets,
    roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  var commonStyles = {
    placement: getBasePlacement(state.placement),
    variation: getVariation(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration: gpuAcceleration,
    isFixed: state.options.strategy === 'fixed'
  };
  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive: adaptive,
      roundOffsets: roundOffsets
    })));
  }
  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: 'absolute',
      adaptive: false,
      roundOffsets: roundOffsets
    })));
  }
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-placement': state.placement
  });
} // eslint-disable-next-line import/no-unused-modules

var computeStyles$1 = {
  name: 'computeStyles',
  enabled: true,
  phase: 'beforeWrite',
  fn: computeStyles,
  data: {}
};

var passive = {
  passive: true
};
function effect(_ref) {
  var state = _ref.state,
    instance = _ref.instance,
    options = _ref.options;
  var _options$scroll = options.scroll,
    scroll = _options$scroll === void 0 ? true : _options$scroll,
    _options$resize = options.resize,
    resize = _options$resize === void 0 ? true : _options$resize;
  var window = getWindow(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
  if (scroll) {
    scrollParents.forEach(function (scrollParent) {
      scrollParent.addEventListener('scroll', instance.update, passive);
    });
  }
  if (resize) {
    window.addEventListener('resize', instance.update, passive);
  }
  return function () {
    if (scroll) {
      scrollParents.forEach(function (scrollParent) {
        scrollParent.removeEventListener('scroll', instance.update, passive);
      });
    }
    if (resize) {
      window.removeEventListener('resize', instance.update, passive);
    }
  };
} // eslint-disable-next-line import/no-unused-modules

var eventListeners = {
  name: 'eventListeners',
  enabled: true,
  phase: 'write',
  fn: function fn() {},
  effect: effect,
  data: {}
};

var hash$1 = {
  left: 'right',
  right: 'left',
  bottom: 'top',
  top: 'bottom'
};
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, function (matched) {
    return hash$1[matched];
  });
}

var hash = {
  start: 'end',
  end: 'start'
};
function getOppositeVariationPlacement(placement) {
  return placement.replace(/start|end/g, function (matched) {
    return hash[matched];
  });
}

function getWindowScroll(node) {
  var win = getWindow(node);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft: scrollLeft,
    scrollTop: scrollTop
  };
}

function getWindowScrollBarX(element) {
  // If <html> has a CSS width greater than the viewport, then this will be
  // incorrect for RTL.
  // Popper 1 is broken in this case and never had a bug report so let's assume
  // it's not an issue. I don't think anyone ever specifies width on <html>
  // anyway.
  // Browsers where the left scrollbar doesn't cause an issue report `0` for
  // this (e.g. Edge 2019, IE11, Safari)
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}

function getViewportRect(element, strategy) {
  var win = getWindow(element);
  var html = getDocumentElement(element);
  var visualViewport = win.visualViewport;
  var width = html.clientWidth;
  var height = html.clientHeight;
  var x = 0;
  var y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    var layoutViewport = isLayoutViewport();
    if (layoutViewport || !layoutViewport && strategy === 'fixed') {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  return {
    width: width,
    height: height,
    x: x + getWindowScrollBarX(element),
    y: y
  };
}

// of the `<html>` and `<body>` rect bounds if horizontally scrollable

function getDocumentRect(element) {
  var _element$ownerDocumen;
  var html = getDocumentElement(element);
  var winScroll = getWindowScroll(element);
  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  var y = -winScroll.scrollTop;
  if (getComputedStyle(body || html).direction === 'rtl') {
    x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  }
  return {
    width: width,
    height: height,
    x: x,
    y: y
  };
}

function isScrollParent(element) {
  // Firefox wants us to check `-x` and `-y` variations as well
  var _getComputedStyle = getComputedStyle(element),
    overflow = _getComputedStyle.overflow,
    overflowX = _getComputedStyle.overflowX,
    overflowY = _getComputedStyle.overflowY;
  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}

function getScrollParent(node) {
  if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
    // $FlowFixMe[incompatible-return]: assume body is always available
    return node.ownerDocument.body;
  }
  if (isHTMLElement$1(node) && isScrollParent(node)) {
    return node;
  }
  return getScrollParent(getParentNode(node));
}

/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/

function listScrollParents(element, list) {
  var _element$ownerDocumen;
  if (list === void 0) {
    list = [];
  }
  var scrollParent = getScrollParent(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list.concat(target);
  return isBody ? updatedList :
  // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
  updatedList.concat(listScrollParents(getParentNode(target)));
}

function rectToClientRect(rect) {
  return Object.assign({}, rect, {
    left: rect.x,
    top: rect.y,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  });
}

function getInnerBoundingClientRect(element, strategy) {
  var rect = getBoundingClientRect(element, false, strategy === 'fixed');
  rect.top = rect.top + element.clientTop;
  rect.left = rect.left + element.clientLeft;
  rect.bottom = rect.top + element.clientHeight;
  rect.right = rect.left + element.clientWidth;
  rect.width = element.clientWidth;
  rect.height = element.clientHeight;
  rect.x = rect.left;
  rect.y = rect.top;
  return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`

function getClippingParents(element) {
  var clippingParents = listScrollParents(getParentNode(element));
  var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;
  var clipperElement = canEscapeClipping && isHTMLElement$1(element) ? getOffsetParent(element) : element;
  if (!isElement(clipperElement)) {
    return [];
  } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414

  return clippingParents.filter(function (clippingParent) {
    return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
  });
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents

function getClippingRect(element, boundary, rootBoundary, strategy) {
  var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
  var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
  var firstClippingParent = clippingParents[0];
  var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
    var rect = getClientRectFromMixedType(element, clippingParent, strategy);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromMixedType(element, firstClippingParent, strategy));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}

function computeOffsets(_ref) {
  var reference = _ref.reference,
    element = _ref.element,
    placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement(placement) : null;
  var variation = placement ? getVariation(placement) : null;
  var commonX = reference.x + reference.width / 2 - element.width / 2;
  var commonY = reference.y + reference.height / 2 - element.height / 2;
  var offsets;
  switch (basePlacement) {
    case top:
      offsets = {
        x: commonX,
        y: reference.y - element.height
      };
      break;
    case bottom:
      offsets = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case right:
      offsets = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case left:
      offsets = {
        x: reference.x - element.width,
        y: commonY
      };
      break;
    default:
      offsets = {
        x: reference.x,
        y: reference.y
      };
  }
  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
  if (mainAxis != null) {
    var len = mainAxis === 'y' ? 'height' : 'width';
    switch (variation) {
      case start:
        offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
        break;
      case end:
        offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
        break;
    }
  }
  return offsets;
}

function detectOverflow(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options,
    _options$placement = _options.placement,
    placement = _options$placement === void 0 ? state.placement : _options$placement,
    _options$strategy = _options.strategy,
    strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
    _options$boundary = _options.boundary,
    boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
    _options$rootBoundary = _options.rootBoundary,
    rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
    _options$elementConte = _options.elementContext,
    elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
    _options$altBoundary = _options.altBoundary,
    altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
    _options$padding = _options.padding,
    padding = _options$padding === void 0 ? 0 : _options$padding;
  var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
  var altContext = elementContext === popper ? reference : popper;
  var popperRect = state.rects.popper;
  var element = state.elements[altBoundary ? altContext : elementContext];
  var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
  var referenceClientRect = getBoundingClientRect(state.elements.reference);
  var popperOffsets = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    strategy: 'absolute',
    placement: placement
  });
  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
  var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
  // 0 or negative = within the clipping rect

  var overflowOffsets = {
    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
    right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  };
  var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element

  if (elementContext === popper && offsetData) {
    var offset = offsetData[placement];
    Object.keys(overflowOffsets).forEach(function (key) {
      var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
      var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
      overflowOffsets[key] += offset[axis] * multiply;
    });
  }
  return overflowOffsets;
}

function computeAutoPlacement(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options,
    placement = _options.placement,
    boundary = _options.boundary,
    rootBoundary = _options.rootBoundary,
    padding = _options.padding,
    flipVariations = _options.flipVariations,
    _options$allowedAutoP = _options.allowedAutoPlacements,
    allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
  var variation = getVariation(placement);
  var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
    return getVariation(placement) === variation;
  }) : basePlacements;
  var allowedPlacements = placements$1.filter(function (placement) {
    return allowedAutoPlacements.indexOf(placement) >= 0;
  });
  if (allowedPlacements.length === 0) {
    allowedPlacements = placements$1;
  } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...

  var overflows = allowedPlacements.reduce(function (acc, placement) {
    acc[placement] = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding
    })[getBasePlacement(placement)];
    return acc;
  }, {});
  return Object.keys(overflows).sort(function (a, b) {
    return overflows[a] - overflows[b];
  });
}

function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement(placement) === auto) {
    return [];
  }
  var oppositePlacement = getOppositePlacement(placement);
  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
  var state = _ref.state,
    options = _ref.options,
    name = _ref.name;
  if (state.modifiersData[name]._skip) {
    return;
  }
  var _options$mainAxis = options.mainAxis,
    checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
    _options$altAxis = options.altAxis,
    checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
    specifiedFallbackPlacements = options.fallbackPlacements,
    padding = options.padding,
    boundary = options.boundary,
    rootBoundary = options.rootBoundary,
    altBoundary = options.altBoundary,
    _options$flipVariatio = options.flipVariations,
    flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
    allowedAutoPlacements = options.allowedAutoPlacements;
  var preferredPlacement = state.options.placement;
  var basePlacement = getBasePlacement(preferredPlacement);
  var isBasePlacement = basePlacement === preferredPlacement;
  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
    return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      padding: padding,
      flipVariations: flipVariations,
      allowedAutoPlacements: allowedAutoPlacements
    }) : placement);
  }, []);
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var checksMap = new Map();
  var makeFallbackChecks = true;
  var firstFittingPlacement = placements[0];
  for (var i = 0; i < placements.length; i++) {
    var placement = placements[i];
    var _basePlacement = getBasePlacement(placement);
    var isStartVariation = getVariation(placement) === start;
    var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
    var len = isVertical ? 'width' : 'height';
    var overflow = detectOverflow(state, {
      placement: placement,
      boundary: boundary,
      rootBoundary: rootBoundary,
      altBoundary: altBoundary,
      padding: padding
    });
    var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }
    var altVariationSide = getOppositePlacement(mainVariationSide);
    var checks = [];
    if (checkMainAxis) {
      checks.push(overflow[_basePlacement] <= 0);
    }
    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }
    if (checks.every(function (check) {
      return check;
    })) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }
    checksMap.set(placement, checks);
  }
  if (makeFallbackChecks) {
    // `2` may be desired in some cases – research later
    var numberOfChecks = flipVariations ? 3 : 1;
    var _loop = function _loop(_i) {
      var fittingPlacement = placements.find(function (placement) {
        var checks = checksMap.get(placement);
        if (checks) {
          return checks.slice(0, _i).every(function (check) {
            return check;
          });
        }
      });
      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        return "break";
      }
    };
    for (var _i = numberOfChecks; _i > 0; _i--) {
      var _ret = _loop(_i);
      if (_ret === "break") break;
    }
  }
  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
} // eslint-disable-next-line import/no-unused-modules

var flip$1 = {
  name: 'flip',
  enabled: true,
  phase: 'main',
  fn: flip,
  requiresIfExists: ['offset'],
  data: {
    _skip: false
  }
};

function getSideOffsets(overflow, rect, preventedOffsets) {
  if (preventedOffsets === void 0) {
    preventedOffsets = {
      x: 0,
      y: 0
    };
  }
  return {
    top: overflow.top - rect.height - preventedOffsets.y,
    right: overflow.right - rect.width + preventedOffsets.x,
    bottom: overflow.bottom - rect.height + preventedOffsets.y,
    left: overflow.left - rect.width - preventedOffsets.x
  };
}
function isAnySideFullyClipped(overflow) {
  return [top, right, bottom, left].some(function (side) {
    return overflow[side] >= 0;
  });
}
function hide(_ref) {
  var state = _ref.state,
    name = _ref.name;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var preventedOffsets = state.modifiersData.preventOverflow;
  var referenceOverflow = detectOverflow(state, {
    elementContext: 'reference'
  });
  var popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name] = {
    referenceClippingOffsets: referenceClippingOffsets,
    popperEscapeOffsets: popperEscapeOffsets,
    isReferenceHidden: isReferenceHidden,
    hasPopperEscaped: hasPopperEscaped
  };
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    'data-popper-reference-hidden': isReferenceHidden,
    'data-popper-escaped': hasPopperEscaped
  });
} // eslint-disable-next-line import/no-unused-modules

var hide$1 = {
  name: 'hide',
  enabled: true,
  phase: 'main',
  requiresIfExists: ['preventOverflow'],
  fn: hide
};

function distanceAndSkiddingToXY(placement, rects, offset) {
  var basePlacement = getBasePlacement(placement);
  var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
  var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
      placement: placement
    })) : offset,
    skidding = _ref[0],
    distance = _ref[1];
  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left, right].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}
function offset(_ref2) {
  var state = _ref2.state,
    options = _ref2.options,
    name = _ref2.name;
  var _options$offset = options.offset,
    offset = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data = placements.reduce(function (acc, placement) {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
    return acc;
  }, {});
  var _data$state$placement = data[state.placement],
    x = _data$state$placement.x,
    y = _data$state$placement.y;
  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }
  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules

var offset$1 = {
  name: 'offset',
  enabled: true,
  phase: 'main',
  requires: ['popperOffsets'],
  fn: offset
};

function popperOffsets(_ref) {
  var state = _ref.state,
    name = _ref.name;
  // Offsets are the actual position the popper needs to have to be
  // properly positioned near its reference element
  // This is the most basic placement, and will be adjusted by
  // the modifiers in the next step
  state.modifiersData[name] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: 'absolute',
    placement: state.placement
  });
} // eslint-disable-next-line import/no-unused-modules

var popperOffsets$1 = {
  name: 'popperOffsets',
  enabled: true,
  phase: 'read',
  fn: popperOffsets,
  data: {}
};

function getAltAxis(axis) {
  return axis === 'x' ? 'y' : 'x';
}

function preventOverflow(_ref) {
  var state = _ref.state,
    options = _ref.options,
    name = _ref.name;
  var _options$mainAxis = options.mainAxis,
    checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
    _options$altAxis = options.altAxis,
    checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
    boundary = options.boundary,
    rootBoundary = options.rootBoundary,
    altBoundary = options.altBoundary,
    padding = options.padding,
    _options$tether = options.tether,
    tether = _options$tether === void 0 ? true : _options$tether,
    _options$tetherOffset = options.tetherOffset,
    tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  var overflow = detectOverflow(state, {
    boundary: boundary,
    rootBoundary: rootBoundary,
    padding: padding,
    altBoundary: altBoundary
  });
  var basePlacement = getBasePlacement(state.placement);
  var variation = getVariation(state.placement);
  var isBasePlacement = !variation;
  var mainAxis = getMainAxisFromPlacement(basePlacement);
  var altAxis = getAltAxis(mainAxis);
  var popperOffsets = state.modifiersData.popperOffsets;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
    placement: state.placement
  })) : tetherOffset;
  var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
    mainAxis: tetherOffsetValue,
    altAxis: tetherOffsetValue
  } : Object.assign({
    mainAxis: 0,
    altAxis: 0
  }, tetherOffsetValue);
  var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
  var data = {
    x: 0,
    y: 0
  };
  if (!popperOffsets) {
    return;
  }
  if (checkMainAxis) {
    var _offsetModifierState$;
    var mainSide = mainAxis === 'y' ? top : left;
    var altSide = mainAxis === 'y' ? bottom : right;
    var len = mainAxis === 'y' ? 'height' : 'width';
    var offset = popperOffsets[mainAxis];
    var min$1 = offset + overflow[mainSide];
    var max$1 = offset - overflow[altSide];
    var additive = tether ? -popperRect[len] / 2 : 0;
    var minLen = variation === start ? referenceRect[len] : popperRect[len];
    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
    // outside the reference bounds

    var arrowElement = state.elements.arrow;
    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
      width: 0,
      height: 0
    };
    var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
    var arrowPaddingMin = arrowPaddingObject[mainSide];
    var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
    // to include its full size in the calculation. If the reference is small
    // and near the edge of a boundary, the popper can overflow even if the
    // reference is not overflowing as well (e.g. virtual elements with no
    // width or height)

    var arrowLen = within(0, referenceRect[len], arrowRect[len]);
    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
    var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
    var tetherMax = offset + maxOffset - offsetModifierValue;
    var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
    popperOffsets[mainAxis] = preventedOffset;
    data[mainAxis] = preventedOffset - offset;
  }
  if (checkAltAxis) {
    var _offsetModifierState$2;
    var _mainSide = mainAxis === 'x' ? top : left;
    var _altSide = mainAxis === 'x' ? bottom : right;
    var _offset = popperOffsets[altAxis];
    var _len = altAxis === 'y' ? 'height' : 'width';
    var _min = _offset + overflow[_mainSide];
    var _max = _offset - overflow[_altSide];
    var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
    var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
    var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
    var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
    var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
    popperOffsets[altAxis] = _preventedOffset;
    data[altAxis] = _preventedOffset - _offset;
  }
  state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules

var preventOverflow$1 = {
  name: 'preventOverflow',
  enabled: true,
  phase: 'main',
  fn: preventOverflow,
  requiresIfExists: ['offset']
};

function getHTMLElementScroll(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}

function getNodeScroll(node) {
  if (node === getWindow(node) || !isHTMLElement$1(node)) {
    return getWindowScroll(node);
  } else {
    return getHTMLElementScroll(node);
  }
}

function isElementScaled(element) {
  var rect = element.getBoundingClientRect();
  var scaleX = round(rect.width) / element.offsetWidth || 1;
  var scaleY = round(rect.height) / element.offsetHeight || 1;
  return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.

function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  var isOffsetParentAnElement = isHTMLElement$1(offsetParent);
  var offsetParentIsScaled = isHTMLElement$1(offsetParent) && isElementScaled(offsetParent);
  var documentElement = getDocumentElement(offsetParent);
  var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== 'body' ||
    // https://github.com/popperjs/popper-core/issues/1078
    isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement$1(offsetParent)) {
      offsets = getBoundingClientRect(offsetParent, true);
      offsets.x += offsetParent.clientLeft;
      offsets.y += offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}

function order(modifiers) {
  var map = new Map();
  var visited = new Set();
  var result = [];
  modifiers.forEach(function (modifier) {
    map.set(modifier.name, modifier);
  }); // On visiting object, check for its dependencies and visit them recursively

  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function (dep) {
      if (!visited.has(dep)) {
        var depModifier = map.get(dep);
        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result.push(modifier);
  }
  modifiers.forEach(function (modifier) {
    if (!visited.has(modifier.name)) {
      // check for visited object
      sort(modifier);
    }
  });
  return result;
}
function orderModifiers(modifiers) {
  // order based on dependencies
  var orderedModifiers = order(modifiers); // order based on phase

  return modifierPhases.reduce(function (acc, phase) {
    return acc.concat(orderedModifiers.filter(function (modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}

function debounce(fn) {
  var pending;
  return function () {
    if (!pending) {
      pending = new Promise(function (resolve) {
        Promise.resolve().then(function () {
          pending = undefined;
          resolve(fn());
        });
      });
    }
    return pending;
  };
}

function mergeByName(modifiers) {
  var merged = modifiers.reduce(function (merged, current) {
    var existing = merged[current.name];
    merged[current.name] = existing ? Object.assign({}, existing, current, {
      options: Object.assign({}, existing.options, current.options),
      data: Object.assign({}, existing.data, current.data)
    }) : current;
    return merged;
  }, {}); // IE11 does not support Object.values

  return Object.keys(merged).map(function (key) {
    return merged[key];
  });
}

var DEFAULT_OPTIONS = {
  placement: 'bottom',
  modifiers: [],
  strategy: 'absolute'
};
function areValidElements() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return !args.some(function (element) {
    return !(element && typeof element.getBoundingClientRect === 'function');
  });
}
function popperGenerator(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }
  var _generatorOptions = generatorOptions,
    _generatorOptions$def = _generatorOptions.defaultModifiers,
    defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
    _generatorOptions$def2 = _generatorOptions.defaultOptions,
    defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  return function createPopper(reference, popper, options) {
    if (options === void 0) {
      options = defaultOptions;
    }
    var state = {
      placement: 'bottom',
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
      modifiersData: {},
      elements: {
        reference: reference,
        popper: popper
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed = false;
    var instance = {
      state: state,
      setOptions: function setOptions(setOptionsAction) {
        var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions, state.options, options);
        state.scrollParents = {
          reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
          popper: listScrollParents(popper)
        }; // Orders the modifiers based on their dependencies and `phase`
        // properties

        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers

        state.orderedModifiers = orderedModifiers.filter(function (m) {
          return m.enabled;
        });
        runModifierEffects();
        return instance.update();
      },
      // Sync update – it will always be executed, even if not necessary. This
      // is useful for low frequency updates where sync behavior simplifies the
      // logic.
      // For high frequency updates (e.g. `resize` and `scroll` events), always
      // prefer the async Popper#update method
      forceUpdate: function forceUpdate() {
        if (isDestroyed) {
          return;
        }
        var _state$elements = state.elements,
          reference = _state$elements.reference,
          popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
        // anymore

        if (!areValidElements(reference, popper)) {
          return;
        } // Store the reference and popper rects to be read by modifiers

        state.rects = {
          reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
          popper: getLayoutRect(popper)
        }; // Modifiers have the ability to reset the current update cycle. The
        // most common use case for this is the `flip` modifier changing the
        // placement, which then needs to re-run all the modifiers, because the
        // logic was previously ran for the previous placement and is therefore
        // stale/incorrect

        state.reset = false;
        state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
        // is filled with the initial data specified by the modifier. This means
        // it doesn't persist and is fresh on each update.
        // To ensure persistent data, use `${name}#persistent`

        state.orderedModifiers.forEach(function (modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });
        for (var index = 0; index < state.orderedModifiers.length; index++) {
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }
          var _state$orderedModifie = state.orderedModifiers[index],
            fn = _state$orderedModifie.fn,
            _state$orderedModifie2 = _state$orderedModifie.options,
            _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
            name = _state$orderedModifie.name;
          if (typeof fn === 'function') {
            state = fn({
              state: state,
              options: _options,
              name: name,
              instance: instance
            }) || state;
          }
        }
      },
      // Async and optimistically optimized update – it will not be executed if
      // not necessary (debounced to run at most once-per-tick)
      update: debounce(function () {
        return new Promise(function (resolve) {
          instance.forceUpdate();
          resolve(state);
        });
      }),
      destroy: function destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };
    if (!areValidElements(reference, popper)) {
      return instance;
    }
    instance.setOptions(options).then(function (state) {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state);
      }
    }); // Modifiers have the ability to execute arbitrary code before the first
    // update cycle runs. They will be executed in the same order as the update
    // cycle. This is useful when a modifier adds some persistent data that
    // other modifiers need to use, but the modifier is run after the dependent
    // one.

    function runModifierEffects() {
      state.orderedModifiers.forEach(function (_ref) {
        var name = _ref.name,
          _ref$options = _ref.options,
          options = _ref$options === void 0 ? {} : _ref$options,
          effect = _ref.effect;
        if (typeof effect === 'function') {
          var cleanupFn = effect({
            state: state,
            name: name,
            instance: instance,
            options: options
          });
          var noopFn = function noopFn() {};
          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }
    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function (fn) {
        return fn();
      });
      effectCleanupFns = [];
    }
    return instance;
  };
}

var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
var createPopper = /*#__PURE__*/popperGenerator({
  defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules

function getContainer$1(container) {
  return typeof container === 'function' ? container() : container;
}

/**
 * Portals provide a first-class way to render children into a DOM node
 * that exists outside the DOM hierarchy of the parent component.
 *
 * Demos:
 *
 * - [Portal](https://mui.com/base/react-portal/)
 *
 * API:
 *
 * - [Portal API](https://mui.com/base/react-portal/components-api/#portal)
 */
const Portal = /*#__PURE__*/reactExports$1.forwardRef(function Portal(props, forwardedRef) {
  const {
    children,
    container,
    disablePortal = false
  } = props;
  const [mountNode, setMountNode] = reactExports$1.useState(null);
  // @ts-expect-error TODO upstream fix
  const handleRef = useForkRef( /*#__PURE__*/reactExports$1.isValidElement(children) ? children.ref : null, forwardedRef);
  useEnhancedEffect$1(() => {
    if (!disablePortal) {
      setMountNode(getContainer$1(container) || document.body);
    }
  }, [container, disablePortal]);
  useEnhancedEffect$1(() => {
    if (mountNode && !disablePortal) {
      setRef(forwardedRef, mountNode);
      return () => {
        setRef(forwardedRef, null);
      };
    }
    return undefined;
  }, [forwardedRef, mountNode, disablePortal]);
  if (disablePortal) {
    if ( /*#__PURE__*/reactExports$1.isValidElement(children)) {
      const newProps = {
        ref: handleRef
      };
      return /*#__PURE__*/reactExports$1.cloneElement(children, newProps);
    }
    return /*#__PURE__*/jsxRuntimeExports.jsx(reactExports$1.Fragment, {
      children: children
    });
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(reactExports$1.Fragment, {
    children: mountNode ? /*#__PURE__*/reactDomExports.createPortal(children, mountNode) : mountNode
  });
});
Portal.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * The children to render into the `container`.
   */
  children: PropTypes.node,
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: PropTypes.bool
} ;
{
  // eslint-disable-next-line
  Portal['propTypes' + ''] = exactProp(Portal.propTypes);
}
var Portal$1 = Portal;

function getPopperUtilityClass(slot) {
  return generateUtilityClass('MuiPopper', slot);
}
generateUtilityClasses('MuiPopper', ['root']);

const _excluded$1w = ["anchorEl", "children", "direction", "disablePortal", "modifiers", "open", "placement", "popperOptions", "popperRef", "slotProps", "slots", "TransitionProps", "ownerState"],
  _excluded2$6 = ["anchorEl", "children", "container", "direction", "disablePortal", "keepMounted", "modifiers", "open", "placement", "popperOptions", "popperRef", "style", "transition", "slotProps", "slots"];
function flipPlacement(placement, direction) {
  if (direction === 'ltr') {
    return placement;
  }
  switch (placement) {
    case 'bottom-end':
      return 'bottom-start';
    case 'bottom-start':
      return 'bottom-end';
    case 'top-end':
      return 'top-start';
    case 'top-start':
      return 'top-end';
    default:
      return placement;
  }
}
function resolveAnchorEl$1(anchorEl) {
  return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
function isHTMLElement(element) {
  return element.nodeType !== undefined;
}
function isVirtualElement(element) {
  return !isHTMLElement(element);
}
const useUtilityClasses$1h = () => {
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, useClassNamesOverride(getPopperUtilityClass));
};
const defaultPopperOptions = {};
const PopperTooltip = /*#__PURE__*/reactExports$1.forwardRef(function PopperTooltip(props, forwardedRef) {
  var _slots$root;
  const {
      anchorEl,
      children,
      direction,
      disablePortal,
      modifiers,
      open,
      placement: initialPlacement,
      popperOptions,
      popperRef: popperRefProp,
      slotProps = {},
      slots = {},
      TransitionProps
      // @ts-ignore internal logic
      // prevent from spreading to DOM, it can come from the parent component e.g. Select.
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1w);
  const tooltipRef = reactExports$1.useRef(null);
  const ownRef = useForkRef(tooltipRef, forwardedRef);
  const popperRef = reactExports$1.useRef(null);
  const handlePopperRef = useForkRef(popperRef, popperRefProp);
  const handlePopperRefRef = reactExports$1.useRef(handlePopperRef);
  useEnhancedEffect$1(() => {
    handlePopperRefRef.current = handlePopperRef;
  }, [handlePopperRef]);
  reactExports$1.useImperativeHandle(popperRefProp, () => popperRef.current, []);
  const rtlPlacement = flipPlacement(initialPlacement, direction);
  /**
   * placement initialized from prop but can change during lifetime if modifiers.flip.
   * modifiers.flip is essentially a flip for controlled/uncontrolled behavior
   */
  const [placement, setPlacement] = reactExports$1.useState(rtlPlacement);
  const [resolvedAnchorElement, setResolvedAnchorElement] = reactExports$1.useState(resolveAnchorEl$1(anchorEl));
  reactExports$1.useEffect(() => {
    if (popperRef.current) {
      popperRef.current.forceUpdate();
    }
  });
  reactExports$1.useEffect(() => {
    if (anchorEl) {
      setResolvedAnchorElement(resolveAnchorEl$1(anchorEl));
    }
  }, [anchorEl]);
  useEnhancedEffect$1(() => {
    if (!resolvedAnchorElement || !open) {
      return undefined;
    }
    const handlePopperUpdate = data => {
      setPlacement(data.placement);
    };
    {
      if (resolvedAnchorElement && isHTMLElement(resolvedAnchorElement) && resolvedAnchorElement.nodeType === 1) {
        const box = resolvedAnchorElement.getBoundingClientRect();
        if (box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
          console.warn(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
        }
      }
    }
    let popperModifiers = [{
      name: 'preventOverflow',
      options: {
        altBoundary: disablePortal
      }
    }, {
      name: 'flip',
      options: {
        altBoundary: disablePortal
      }
    }, {
      name: 'onUpdate',
      enabled: true,
      phase: 'afterWrite',
      fn: ({
        state
      }) => {
        handlePopperUpdate(state);
      }
    }];
    if (modifiers != null) {
      popperModifiers = popperModifiers.concat(modifiers);
    }
    if (popperOptions && popperOptions.modifiers != null) {
      popperModifiers = popperModifiers.concat(popperOptions.modifiers);
    }
    const popper = createPopper(resolvedAnchorElement, tooltipRef.current, _extends({
      placement: rtlPlacement
    }, popperOptions, {
      modifiers: popperModifiers
    }));
    handlePopperRefRef.current(popper);
    return () => {
      popper.destroy();
      handlePopperRefRef.current(null);
    };
  }, [resolvedAnchorElement, disablePortal, modifiers, open, popperOptions, rtlPlacement]);
  const childProps = {
    placement: placement
  };
  if (TransitionProps !== null) {
    childProps.TransitionProps = TransitionProps;
  }
  const classes = useUtilityClasses$1h();
  const Root = (_slots$root = slots.root) != null ? _slots$root : 'div';
  const rootProps = useSlotProps({
    elementType: Root,
    externalSlotProps: slotProps.root,
    externalForwardedProps: other,
    additionalProps: {
      role: 'tooltip',
      ref: ownRef
    },
    ownerState: props,
    className: classes.root
  });
  return /*#__PURE__*/jsxRuntimeExports.jsx(Root, _extends({}, rootProps, {
    children: typeof children === 'function' ? children(childProps) : children
  }));
});

/**
 * Poppers rely on the 3rd party library [Popper.js](https://popper.js.org/docs/v2/) for positioning.
 *
 * Demos:
 *
 * - [Popper](https://mui.com/base/react-popper/)
 *
 * API:
 *
 * - [Popper API](https://mui.com/base/react-popper/components-api/#popper)
 */
const Popper$2 = /*#__PURE__*/reactExports$1.forwardRef(function Popper(props, forwardedRef) {
  const {
      anchorEl,
      children,
      container: containerProp,
      direction = 'ltr',
      disablePortal = false,
      keepMounted = false,
      modifiers,
      open,
      placement = 'bottom',
      popperOptions = defaultPopperOptions,
      popperRef,
      style,
      transition = false,
      slotProps = {},
      slots = {}
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded2$6);
  const [exited, setExited] = reactExports$1.useState(true);
  const handleEnter = () => {
    setExited(false);
  };
  const handleExited = () => {
    setExited(true);
  };
  if (!keepMounted && !open && (!transition || exited)) {
    return null;
  }

  // If the container prop is provided, use that
  // If the anchorEl prop is provided, use its parent body element as the container
  // If neither are provided let the Modal take care of choosing the container
  let container;
  if (containerProp) {
    container = containerProp;
  } else if (anchorEl) {
    const resolvedAnchorEl = resolveAnchorEl$1(anchorEl);
    container = resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) ? ownerDocument(resolvedAnchorEl).body : ownerDocument(null).body;
  }
  const display = !open && keepMounted && (!transition || exited) ? 'none' : undefined;
  const transitionProps = transition ? {
    in: open,
    onEnter: handleEnter,
    onExited: handleExited
  } : undefined;
  return /*#__PURE__*/jsxRuntimeExports.jsx(Portal$1, {
    disablePortal: disablePortal,
    container: container,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(PopperTooltip, _extends({
      anchorEl: anchorEl,
      direction: direction,
      disablePortal: disablePortal,
      modifiers: modifiers,
      ref: forwardedRef,
      open: transition ? !exited : open,
      placement: placement,
      popperOptions: popperOptions,
      popperRef: popperRef,
      slotProps: slotProps,
      slots: slots
    }, other, {
      style: _extends({
        // Prevents scroll issue, waiting for Popper.js to add this style once initiated.
        position: 'fixed',
        // Fix Popper.js display issue
        top: 0,
        left: 0,
        display
      }, style),
      TransitionProps: transitionProps,
      children: children
    }))
  });
});
Popper$2.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),
   * or a function that returns either.
   * It's used to set the position of the popper.
   * The return value will passed as the reference object of the Popper instance.
   */
  anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]), props => {
    if (props.open) {
      const resolvedAnchorEl = resolveAnchorEl$1(props.anchorEl);
      if (resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) && resolvedAnchorEl.nodeType === 1) {
        const box = resolvedAnchorEl.getBoundingClientRect();
        if (box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
          return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
        }
      } else if (!resolvedAnchorEl || typeof resolvedAnchorEl.getBoundingClientRect !== 'function' || isVirtualElement(resolvedAnchorEl) && resolvedAnchorEl.contextElement != null && resolvedAnchorEl.contextElement.nodeType !== 1) {
        return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'It should be an HTML element instance or a virtualElement ', '(https://popper.js.org/docs/v2/virtual-elements/).'].join('\n'));
      }
    }
    return null;
  }),
  /**
   * Popper render function or node.
   */
  children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.node, PropTypes.func]),
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * Direction of the text.
   * @default 'ltr'
   */
  direction: PropTypes.oneOf(['ltr', 'rtl']),
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: PropTypes.bool,
  /**
   * Always keep the children in the DOM.
   * This prop can be useful in SEO situation or
   * when you want to maximize the responsiveness of the Popper.
   * @default false
   */
  keepMounted: PropTypes.bool,
  /**
   * Popper.js is based on a "plugin-like" architecture,
   * most of its features are fully encapsulated "modifiers".
   *
   * A modifier is a function that is called each time Popper.js needs to
   * compute the position of the popper.
   * For this reason, modifiers should be very performant to avoid bottlenecks.
   * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).
   */
  modifiers: PropTypes.arrayOf(PropTypes.shape({
    data: PropTypes.object,
    effect: PropTypes.func,
    enabled: PropTypes.bool,
    fn: PropTypes.func,
    name: PropTypes.any,
    options: PropTypes.object,
    phase: PropTypes.oneOf(['afterMain', 'afterRead', 'afterWrite', 'beforeMain', 'beforeRead', 'beforeWrite', 'main', 'read', 'write']),
    requires: PropTypes.arrayOf(PropTypes.string),
    requiresIfExists: PropTypes.arrayOf(PropTypes.string)
  })),
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * Popper placement.
   * @default 'bottom'
   */
  placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
  /**
   * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.
   * @default {}
   */
  popperOptions: PropTypes.shape({
    modifiers: PropTypes.array,
    onFirstUpdate: PropTypes.func,
    placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
    strategy: PropTypes.oneOf(['absolute', 'fixed'])
  }),
  /**
   * A ref that points to the used popper instance.
   */
  popperRef: refType$1,
  /**
   * The props used for each slot inside the Popper.
   * @default {}
   */
  slotProps: PropTypes.shape({
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the Popper.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    root: PropTypes.elementType
  }),
  /**
   * Help supporting a react-transition-group/Transition component.
   * @default false
   */
  transition: PropTypes.bool
} ;
var BasePopper = Popper$2;

// Is a vertical scrollbar displayed?
function isOverflowing(container) {
  const doc = ownerDocument(container);
  if (doc.body === container) {
    return ownerWindow(container).innerWidth > doc.documentElement.clientWidth;
  }
  return container.scrollHeight > container.clientHeight;
}
function ariaHidden(element, show) {
  if (show) {
    element.setAttribute('aria-hidden', 'true');
  } else {
    element.removeAttribute('aria-hidden');
  }
}
function getPaddingRight(element) {
  return parseInt(ownerWindow(element).getComputedStyle(element).paddingRight, 10) || 0;
}
function isAriaHiddenForbiddenOnElement(element) {
  // The forbidden HTML tags are the ones from ARIA specification that
  // can be children of body and can't have aria-hidden attribute.
  // cf. https://www.w3.org/TR/html-aria/#docconformance
  const forbiddenTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE', 'LINK', 'MAP', 'META', 'NOSCRIPT', 'PICTURE', 'COL', 'COLGROUP', 'PARAM', 'SLOT', 'SOURCE', 'TRACK'];
  const isForbiddenTagName = forbiddenTagNames.indexOf(element.tagName) !== -1;
  const isInputHidden = element.tagName === 'INPUT' && element.getAttribute('type') === 'hidden';
  return isForbiddenTagName || isInputHidden;
}
function ariaHiddenSiblings(container, mountElement, currentElement, elementsToExclude, show) {
  const blacklist = [mountElement, currentElement, ...elementsToExclude];
  [].forEach.call(container.children, element => {
    const isNotExcludedElement = blacklist.indexOf(element) === -1;
    const isNotForbiddenElement = !isAriaHiddenForbiddenOnElement(element);
    if (isNotExcludedElement && isNotForbiddenElement) {
      ariaHidden(element, show);
    }
  });
}
function findIndexOf(items, callback) {
  let idx = -1;
  items.some((item, index) => {
    if (callback(item)) {
      idx = index;
      return true;
    }
    return false;
  });
  return idx;
}
function handleContainer(containerInfo, props) {
  const restoreStyle = [];
  const container = containerInfo.container;
  if (!props.disableScrollLock) {
    if (isOverflowing(container)) {
      // Compute the size before applying overflow hidden to avoid any scroll jumps.
      const scrollbarSize = getScrollbarSize(ownerDocument(container));
      restoreStyle.push({
        value: container.style.paddingRight,
        property: 'padding-right',
        el: container
      });
      // Use computed style, here to get the real padding to add our scrollbar width.
      container.style.paddingRight = `${getPaddingRight(container) + scrollbarSize}px`;

      // .mui-fixed is a global helper.
      const fixedElements = ownerDocument(container).querySelectorAll('.mui-fixed');
      [].forEach.call(fixedElements, element => {
        restoreStyle.push({
          value: element.style.paddingRight,
          property: 'padding-right',
          el: element
        });
        element.style.paddingRight = `${getPaddingRight(element) + scrollbarSize}px`;
      });
    }
    let scrollContainer;
    if (container.parentNode instanceof DocumentFragment) {
      scrollContainer = ownerDocument(container).body;
    } else {
      // Improve Gatsby support
      // https://css-tricks.com/snippets/css/force-vertical-scrollbar/
      const parent = container.parentElement;
      const containerWindow = ownerWindow(container);
      scrollContainer = (parent == null ? void 0 : parent.nodeName) === 'HTML' && containerWindow.getComputedStyle(parent).overflowY === 'scroll' ? parent : container;
    }

    // Block the scroll even if no scrollbar is visible to account for mobile keyboard
    // screensize shrink.
    restoreStyle.push({
      value: scrollContainer.style.overflow,
      property: 'overflow',
      el: scrollContainer
    }, {
      value: scrollContainer.style.overflowX,
      property: 'overflow-x',
      el: scrollContainer
    }, {
      value: scrollContainer.style.overflowY,
      property: 'overflow-y',
      el: scrollContainer
    });
    scrollContainer.style.overflow = 'hidden';
  }
  const restore = () => {
    restoreStyle.forEach(({
      value,
      el,
      property
    }) => {
      if (value) {
        el.style.setProperty(property, value);
      } else {
        el.style.removeProperty(property);
      }
    });
  };
  return restore;
}
function getHiddenSiblings(container) {
  const hiddenSiblings = [];
  [].forEach.call(container.children, element => {
    if (element.getAttribute('aria-hidden') === 'true') {
      hiddenSiblings.push(element);
    }
  });
  return hiddenSiblings;
}
/**
 * @ignore - do not document.
 *
 * Proper state management for containers and the modals in those containers.
 * Simplified, but inspired by react-overlay's ModalManager class.
 * Used by the Modal to ensure proper styling of containers.
 */
class ModalManager {
  constructor() {
    this.containers = void 0;
    this.modals = void 0;
    this.modals = [];
    this.containers = [];
  }
  add(modal, container) {
    let modalIndex = this.modals.indexOf(modal);
    if (modalIndex !== -1) {
      return modalIndex;
    }
    modalIndex = this.modals.length;
    this.modals.push(modal);

    // If the modal we are adding is already in the DOM.
    if (modal.modalRef) {
      ariaHidden(modal.modalRef, false);
    }
    const hiddenSiblings = getHiddenSiblings(container);
    ariaHiddenSiblings(container, modal.mount, modal.modalRef, hiddenSiblings, true);
    const containerIndex = findIndexOf(this.containers, item => item.container === container);
    if (containerIndex !== -1) {
      this.containers[containerIndex].modals.push(modal);
      return modalIndex;
    }
    this.containers.push({
      modals: [modal],
      container,
      restore: null,
      hiddenSiblings
    });
    return modalIndex;
  }
  mount(modal, props) {
    const containerIndex = findIndexOf(this.containers, item => item.modals.indexOf(modal) !== -1);
    const containerInfo = this.containers[containerIndex];
    if (!containerInfo.restore) {
      containerInfo.restore = handleContainer(containerInfo, props);
    }
  }
  remove(modal, ariaHiddenState = true) {
    const modalIndex = this.modals.indexOf(modal);
    if (modalIndex === -1) {
      return modalIndex;
    }
    const containerIndex = findIndexOf(this.containers, item => item.modals.indexOf(modal) !== -1);
    const containerInfo = this.containers[containerIndex];
    containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);
    this.modals.splice(modalIndex, 1);

    // If that was the last modal in a container, clean up the container.
    if (containerInfo.modals.length === 0) {
      // The modal might be closed before it had the chance to be mounted in the DOM.
      if (containerInfo.restore) {
        containerInfo.restore();
      }
      if (modal.modalRef) {
        // In case the modal wasn't in the DOM yet.
        ariaHidden(modal.modalRef, ariaHiddenState);
      }
      ariaHiddenSiblings(containerInfo.container, modal.mount, modal.modalRef, containerInfo.hiddenSiblings, false);
      this.containers.splice(containerIndex, 1);
    } else {
      // Otherwise make sure the next top modal is visible to a screen reader.
      const nextTop = containerInfo.modals[containerInfo.modals.length - 1];
      // as soon as a modal is adding its modalRef is undefined. it can't set
      // aria-hidden because the dom element doesn't exist either
      // when modal was unmounted before modalRef gets null
      if (nextTop.modalRef) {
        ariaHidden(nextTop.modalRef, false);
      }
    }
    return modalIndex;
  }
  isTopModal(modal) {
    return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;
  }
}

function getModalUtilityClass(slot) {
  return generateUtilityClass('MuiModal', slot);
}
generateUtilityClasses('MuiModal', ['root', 'hidden', 'backdrop']);

const _excluded$1v = ["children", "closeAfterTransition", "container", "disableAutoFocus", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "manager", "onBackdropClick", "onClose", "onKeyDown", "open", "onTransitionEnter", "onTransitionExited", "slotProps", "slots"];
const useUtilityClasses$1g = ownerState => {
  const {
    open,
    exited
  } = ownerState;
  const slots = {
    root: ['root', !open && exited && 'hidden'],
    backdrop: ['backdrop']
  };
  return composeClasses(slots, useClassNamesOverride(getModalUtilityClass));
};
function getContainer(container) {
  return typeof container === 'function' ? container() : container;
}
function getHasTransition(children) {
  return children ? children.props.hasOwnProperty('in') : false;
}

// A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
const defaultManager = new ModalManager();

/**
 * Modal is a lower-level construct that is leveraged by the following components:
 *
 * *   [Dialog](https://mui.com/material-ui/api/dialog/)
 * *   [Drawer](https://mui.com/material-ui/api/drawer/)
 * *   [Menu](https://mui.com/material-ui/api/menu/)
 * *   [Popover](https://mui.com/material-ui/api/popover/)
 *
 * If you are creating a modal dialog, you probably want to use the [Dialog](https://mui.com/material-ui/api/dialog/) component
 * rather than directly using Modal.
 *
 * This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
 *
 * Demos:
 *
 * - [Modal](https://mui.com/base/react-modal/)
 *
 * API:
 *
 * - [Modal API](https://mui.com/base/react-modal/components-api/#modal)
 */
const Modal$2 = /*#__PURE__*/reactExports$1.forwardRef(function Modal(props, forwardedRef) {
  var _props$ariaHidden, _slots$root;
  const {
      children,
      closeAfterTransition = false,
      container,
      disableAutoFocus = false,
      disableEnforceFocus = false,
      disableEscapeKeyDown = false,
      disablePortal = false,
      disableRestoreFocus = false,
      disableScrollLock = false,
      hideBackdrop = false,
      keepMounted = false,
      // private
      manager: managerProp = defaultManager,
      onBackdropClick,
      onClose,
      onKeyDown,
      open,
      onTransitionEnter,
      onTransitionExited,
      slotProps = {},
      slots = {}
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1v);
  // TODO: `modal`` must change its type in this file to match the type of methods
  // provided by `ModalManager`
  const manager = managerProp;
  const [exited, setExited] = reactExports$1.useState(!open);
  const modal = reactExports$1.useRef({});
  const mountNodeRef = reactExports$1.useRef(null);
  const modalRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(modalRef, forwardedRef);
  const hasTransition = getHasTransition(children);
  const ariaHiddenProp = (_props$ariaHidden = props['aria-hidden']) != null ? _props$ariaHidden : true;
  const getDoc = () => ownerDocument(mountNodeRef.current);
  const getModal = () => {
    modal.current.modalRef = modalRef.current;
    modal.current.mountNode = mountNodeRef.current;
    return modal.current;
  };
  const handleMounted = () => {
    manager.mount(getModal(), {
      disableScrollLock
    });

    // Fix a bug on Chrome where the scroll isn't initially 0.
    if (modalRef.current) {
      modalRef.current.scrollTop = 0;
    }
  };
  const handleOpen = useEventCallback(() => {
    const resolvedContainer = getContainer(container) || getDoc().body;
    manager.add(getModal(), resolvedContainer);

    // The element was already mounted.
    if (modalRef.current) {
      handleMounted();
    }
  });
  const isTopModal = reactExports$1.useCallback(() => manager.isTopModal(getModal()), [manager]);
  const handlePortalRef = useEventCallback(node => {
    mountNodeRef.current = node;
    if (!node || !modalRef.current) {
      return;
    }
    if (open && isTopModal()) {
      handleMounted();
    } else {
      ariaHidden(modalRef.current, ariaHiddenProp);
    }
  });
  const handleClose = reactExports$1.useCallback(() => {
    manager.remove(getModal(), ariaHiddenProp);
  }, [manager, ariaHiddenProp]);
  reactExports$1.useEffect(() => {
    return () => {
      handleClose();
    };
  }, [handleClose]);
  reactExports$1.useEffect(() => {
    if (open) {
      handleOpen();
    } else if (!hasTransition || !closeAfterTransition) {
      handleClose();
    }
  }, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
  const ownerState = _extends({}, props, {
    closeAfterTransition,
    disableAutoFocus,
    disableEnforceFocus,
    disableEscapeKeyDown,
    disablePortal,
    disableRestoreFocus,
    disableScrollLock,
    exited,
    hideBackdrop,
    keepMounted
  });
  const classes = useUtilityClasses$1g(ownerState);
  const handleEnter = () => {
    setExited(false);
    if (onTransitionEnter) {
      onTransitionEnter();
    }
  };
  const handleExited = () => {
    setExited(true);
    if (onTransitionExited) {
      onTransitionExited();
    }
    if (closeAfterTransition) {
      handleClose();
    }
  };
  const handleBackdropClick = event => {
    if (event.target !== event.currentTarget) {
      return;
    }
    if (onBackdropClick) {
      onBackdropClick(event);
    }
    if (onClose) {
      onClose(event, 'backdropClick');
    }
  };
  const handleKeyDown = event => {
    if (onKeyDown) {
      onKeyDown(event);
    }

    // The handler doesn't take event.defaultPrevented into account:
    //
    // event.preventDefault() is meant to stop default behaviors like
    // clicking a checkbox to check it, hitting a button to submit a form,
    // and hitting left arrow to move the cursor in a text input etc.
    // Only special HTML elements have these default behaviors.
    if (event.key !== 'Escape' || !isTopModal()) {
      return;
    }
    if (!disableEscapeKeyDown) {
      // Swallow the event, in case someone is listening for the escape key on the body.
      event.stopPropagation();
      if (onClose) {
        onClose(event, 'escapeKeyDown');
      }
    }
  };
  const childProps = {};
  if (children.props.tabIndex === undefined) {
    childProps.tabIndex = '-1';
  }

  // It's a Transition like component
  if (hasTransition) {
    childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);
    childProps.onExited = createChainedFunction(handleExited, children.props.onExited);
  }
  const Root = (_slots$root = slots.root) != null ? _slots$root : 'div';
  const rootProps = useSlotProps({
    elementType: Root,
    externalSlotProps: slotProps.root,
    externalForwardedProps: other,
    additionalProps: {
      ref: handleRef,
      role: 'presentation',
      onKeyDown: handleKeyDown
    },
    className: classes.root,
    ownerState
  });
  const BackdropComponent = slots.backdrop;
  const backdropProps = useSlotProps({
    elementType: BackdropComponent,
    externalSlotProps: slotProps.backdrop,
    additionalProps: {
      'aria-hidden': true,
      onClick: handleBackdropClick,
      open
    },
    className: classes.backdrop,
    ownerState
  });
  if (!keepMounted && !open && (!hasTransition || exited)) {
    return null;
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(Portal$1
  // @ts-expect-error TODO: include ref to Base UI Portal props
  , {
    ref: handlePortalRef,
    container: container,
    disablePortal: disablePortal,
    children: /*#__PURE__*/jsxRuntimeExports.jsxs(Root, _extends({}, rootProps, {
      children: [!hideBackdrop && BackdropComponent ? /*#__PURE__*/jsxRuntimeExports.jsx(BackdropComponent, _extends({}, backdropProps)) : null, /*#__PURE__*/jsxRuntimeExports.jsx(FocusTrap, {
        disableEnforceFocus: disableEnforceFocus,
        disableAutoFocus: disableAutoFocus,
        disableRestoreFocus: disableRestoreFocus,
        isEnabled: isTopModal,
        open: open,
        children: /*#__PURE__*/reactExports$1.cloneElement(children, childProps)
      })]
    }))
  });
});
Modal$2.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * A single child content element.
   */
  children: elementAcceptingRef$1.isRequired,
  /**
   * When set to true the Modal waits until a nested Transition is completed before closing.
   * @default false
   */
  closeAfterTransition: PropTypes.bool,
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * If `true`, the modal will not automatically shift focus to itself when it opens, and
   * replace it to the last focused element when it closes.
   * This also works correctly with any modal children that have the `disableAutoFocus` prop.
   *
   * Generally this should never be set to `true` as it makes the modal less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableAutoFocus: PropTypes.bool,
  /**
   * If `true`, the modal will not prevent focus from leaving the modal while open.
   *
   * Generally this should never be set to `true` as it makes the modal less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableEnforceFocus: PropTypes.bool,
  /**
   * If `true`, hitting escape will not fire the `onClose` callback.
   * @default false
   */
  disableEscapeKeyDown: PropTypes.bool,
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: PropTypes.bool,
  /**
   * If `true`, the modal will not restore focus to previously focused element once
   * modal is hidden or unmounted.
   * @default false
   */
  disableRestoreFocus: PropTypes.bool,
  /**
   * Disable the scroll lock behavior.
   * @default false
   */
  disableScrollLock: PropTypes.bool,
  /**
   * If `true`, the backdrop is not rendered.
   * @default false
   */
  hideBackdrop: PropTypes.bool,
  /**
   * Always keep the children in the DOM.
   * This prop can be useful in SEO situation or
   * when you want to maximize the responsiveness of the Modal.
   * @default false
   */
  keepMounted: PropTypes.bool,
  /**
   * Callback fired when the backdrop is clicked.
   * @deprecated Use the `onClose` prop with the `reason` argument to handle the `backdropClick` events.
   */
  onBackdropClick: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   * The `reason` parameter can optionally be used to control the response to `onClose`.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
   */
  onClose: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * The props used for each slot inside the Modal.
   * @default {}
   */
  slotProps: PropTypes.shape({
    backdrop: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the Modal.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    backdrop: PropTypes.elementType,
    root: PropTypes.elementType
  })
} ;
var ModalUnstyled = Modal$2;

/**
 * The basic building block for creating custom snackbar.
 *
 * Demos:
 *
 * - [Snackbar](https://mui.com/base/react-snackbar/#hook)
 *
 * API:
 *
 * - [useSnackbar API](https://mui.com/base/react-snackbar/hooks-api/#use-snackbar)
 */
function useSnackbar(parameters) {
  const {
    autoHideDuration = null,
    disableWindowBlurListener = false,
    onClose,
    open,
    resumeHideDuration
  } = parameters;
  const timerAutoHide = reactExports$1.useRef();
  reactExports$1.useEffect(() => {
    if (!open) {
      return undefined;
    }

    /**
     * @param {KeyboardEvent} nativeEvent
     */
    function handleKeyDown(nativeEvent) {
      if (!nativeEvent.defaultPrevented) {
        // IE11, Edge (prior to using Blink?) use 'Esc'
        if (nativeEvent.key === 'Escape' || nativeEvent.key === 'Esc') {
          // not calling `preventDefault` since we don't know if people may ignore this event e.g. a permanently open snackbar
          onClose == null ? void 0 : onClose(nativeEvent, 'escapeKeyDown');
        }
      }
    }
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [open, onClose]);
  const handleClose = useEventCallback((event, reason) => {
    onClose == null ? void 0 : onClose(event, reason);
  });
  const setAutoHideTimer = useEventCallback(autoHideDurationParam => {
    if (!onClose || autoHideDurationParam == null) {
      return;
    }
    clearTimeout(timerAutoHide.current);
    timerAutoHide.current = setTimeout(() => {
      handleClose(null, 'timeout');
    }, autoHideDurationParam);
  });
  reactExports$1.useEffect(() => {
    if (open) {
      setAutoHideTimer(autoHideDuration);
    }
    return () => {
      clearTimeout(timerAutoHide.current);
    };
  }, [open, autoHideDuration, setAutoHideTimer]);
  const handleClickAway = event => {
    onClose == null ? void 0 : onClose(event, 'clickaway');
  };

  // Pause the timer when the user is interacting with the Snackbar
  // or when the user hide the window.
  const handlePause = () => {
    clearTimeout(timerAutoHide.current);
  };

  // Restart the timer when the user is no longer interacting with the Snackbar
  // or when the window is shown back.
  const handleResume = reactExports$1.useCallback(() => {
    if (autoHideDuration != null) {
      setAutoHideTimer(resumeHideDuration != null ? resumeHideDuration : autoHideDuration * 0.5);
    }
  }, [autoHideDuration, resumeHideDuration, setAutoHideTimer]);
  const createHandleBlur = otherHandlers => event => {
    const onBlurCallback = otherHandlers.onBlur;
    onBlurCallback == null ? void 0 : onBlurCallback(event);
    handleResume();
  };
  const createHandleFocus = otherHandlers => event => {
    const onFocusCallback = otherHandlers.onFocus;
    onFocusCallback == null ? void 0 : onFocusCallback(event);
    handlePause();
  };
  const createMouseEnter = otherHandlers => event => {
    const onMouseEnterCallback = otherHandlers.onMouseEnter;
    onMouseEnterCallback == null ? void 0 : onMouseEnterCallback(event);
    handlePause();
  };
  const createMouseLeave = otherHandlers => event => {
    const onMouseLeaveCallback = otherHandlers.onMouseLeave;
    onMouseLeaveCallback == null ? void 0 : onMouseLeaveCallback(event);
    handleResume();
  };
  reactExports$1.useEffect(() => {
    // TODO: window global should be refactored here
    if (!disableWindowBlurListener && open) {
      window.addEventListener('focus', handleResume);
      window.addEventListener('blur', handlePause);
      return () => {
        window.removeEventListener('focus', handleResume);
        window.removeEventListener('blur', handlePause);
      };
    }
    return undefined;
  }, [disableWindowBlurListener, handleResume, open]);
  const getRootProps = (otherHandlers = {}) => {
    const propsEventHandlers = extractEventHandlers(parameters);
    const externalEventHandlers = _extends({}, propsEventHandlers, otherHandlers);
    return _extends({
      // ClickAwayListener adds an `onClick` prop which results in the alert not being announced.
      // See https://github.com/mui/material-ui/issues/29080
      role: 'presentation'
    }, externalEventHandlers, {
      onBlur: createHandleBlur(externalEventHandlers),
      onFocus: createHandleFocus(externalEventHandlers),
      onMouseEnter: createMouseEnter(externalEventHandlers),
      onMouseLeave: createMouseLeave(externalEventHandlers)
    });
  };
  return {
    getRootProps,
    onClickAway: handleClickAway
  };
}

const _excluded$1u = ["onChange", "maxRows", "minRows", "style", "value"];
function getStyleValue(value) {
  return parseInt(value, 10) || 0;
}
const styles$4 = {
  shadow: {
    // Visibility needed to hide the extra text area on iPads
    visibility: 'hidden',
    // Remove from the content flow
    position: 'absolute',
    // Ignore the scrollbar width
    overflow: 'hidden',
    height: 0,
    top: 0,
    left: 0,
    // Create a new layer, increase the isolation of the computed values
    transform: 'translateZ(0)'
  }
};
function isEmpty$1(obj) {
  return obj === undefined || obj === null || Object.keys(obj).length === 0 || obj.outerHeightStyle === 0 && !obj.overflow;
}

/**
 *
 * Demos:
 *
 * - [Textarea Autosize](https://mui.com/base/react-textarea-autosize/)
 * - [Textarea Autosize](https://mui.com/material-ui/react-textarea-autosize/)
 *
 * API:
 *
 * - [TextareaAutosize API](https://mui.com/base/react-textarea-autosize/components-api/#textarea-autosize)
 */
const TextareaAutosize = /*#__PURE__*/reactExports$1.forwardRef(function TextareaAutosize(props, forwardedRef) {
  const {
      onChange,
      maxRows,
      minRows = 1,
      style,
      value
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1u);
  const {
    current: isControlled
  } = reactExports$1.useRef(value != null);
  const inputRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(forwardedRef, inputRef);
  const shadowRef = reactExports$1.useRef(null);
  const renders = reactExports$1.useRef(0);
  const [state, setState] = reactExports$1.useState({
    outerHeightStyle: 0
  });
  const getUpdatedState = reactExports$1.useCallback(() => {
    const input = inputRef.current;
    const containerWindow = ownerWindow(input);
    const computedStyle = containerWindow.getComputedStyle(input);

    // If input's width is shrunk and it's not visible, don't sync height.
    if (computedStyle.width === '0px') {
      return {
        outerHeightStyle: 0
      };
    }
    const inputShallow = shadowRef.current;
    inputShallow.style.width = computedStyle.width;
    inputShallow.value = input.value || props.placeholder || 'x';
    if (inputShallow.value.slice(-1) === '\n') {
      // Certain fonts which overflow the line height will cause the textarea
      // to report a different scrollHeight depending on whether the last line
      // is empty. Make it non-empty to avoid this issue.
      inputShallow.value += ' ';
    }
    const boxSizing = computedStyle.boxSizing;
    const padding = getStyleValue(computedStyle.paddingBottom) + getStyleValue(computedStyle.paddingTop);
    const border = getStyleValue(computedStyle.borderBottomWidth) + getStyleValue(computedStyle.borderTopWidth);

    // The height of the inner content
    const innerHeight = inputShallow.scrollHeight;

    // Measure height of a textarea with a single row
    inputShallow.value = 'x';
    const singleRowHeight = inputShallow.scrollHeight;

    // The height of the outer content
    let outerHeight = innerHeight;
    if (minRows) {
      outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight);
    }
    if (maxRows) {
      outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight);
    }
    outerHeight = Math.max(outerHeight, singleRowHeight);

    // Take the box sizing into account for applying this value as a style.
    const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);
    const overflow = Math.abs(outerHeight - innerHeight) <= 1;
    return {
      outerHeightStyle,
      overflow
    };
  }, [maxRows, minRows, props.placeholder]);
  const updateState = (prevState, newState) => {
    const {
      outerHeightStyle,
      overflow
    } = newState;
    // Need a large enough difference to update the height.
    // This prevents infinite rendering loop.
    if (renders.current < 20 && (outerHeightStyle > 0 && Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1 || prevState.overflow !== overflow)) {
      renders.current += 1;
      return {
        overflow,
        outerHeightStyle
      };
    }
    {
      if (renders.current === 20) {
        console.error(['MUI: Too many re-renders. The layout is unstable.', 'TextareaAutosize limits the number of renders to prevent an infinite loop.'].join('\n'));
      }
    }
    return prevState;
  };
  const syncHeight = reactExports$1.useCallback(() => {
    const newState = getUpdatedState();
    if (isEmpty$1(newState)) {
      return;
    }
    setState(prevState => {
      return updateState(prevState, newState);
    });
  }, [getUpdatedState]);
  const syncHeightWithFlushSync = () => {
    const newState = getUpdatedState();
    if (isEmpty$1(newState)) {
      return;
    }

    // In React 18, state updates in a ResizeObserver's callback are happening after the paint which causes flickering
    // when doing some visual updates in it. Using flushSync ensures that the dom will be painted after the states updates happen
    // Related issue - https://github.com/facebook/react/issues/24331
    reactDomExports.flushSync(() => {
      setState(prevState => {
        return updateState(prevState, newState);
      });
    });
  };
  reactExports$1.useEffect(() => {
    const handleResize = debounce$1(() => {
      renders.current = 0;

      // If the TextareaAutosize component is replaced by Suspense with a fallback, the last
      // ResizeObserver's handler that runs because of the change in the layout is trying to
      // access a dom node that is no longer there (as the fallback component is being shown instead).
      // See https://github.com/mui/material-ui/issues/32640
      if (inputRef.current) {
        syncHeightWithFlushSync();
      }
    });
    let resizeObserver;
    const input = inputRef.current;
    const containerWindow = ownerWindow(input);
    containerWindow.addEventListener('resize', handleResize);
    if (typeof ResizeObserver !== 'undefined') {
      resizeObserver = new ResizeObserver(handleResize);
      resizeObserver.observe(input);
    }
    return () => {
      handleResize.clear();
      containerWindow.removeEventListener('resize', handleResize);
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  });
  useEnhancedEffect$1(() => {
    syncHeight();
  });
  reactExports$1.useEffect(() => {
    renders.current = 0;
  }, [value]);
  const handleChange = event => {
    renders.current = 0;
    if (!isControlled) {
      syncHeight();
    }
    if (onChange) {
      onChange(event);
    }
  };
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx("textarea", _extends({
      value: value,
      onChange: handleChange,
      ref: handleRef
      // Apply the rows prop to get a "correct" first SSR paint
      ,

      rows: minRows,
      style: _extends({
        height: state.outerHeightStyle,
        // Need a large enough difference to allow scrolling.
        // This prevents infinite rendering loop.
        overflow: state.overflow ? 'hidden' : undefined
      }, style)
    }, other)), /*#__PURE__*/jsxRuntimeExports.jsx("textarea", {
      "aria-hidden": true,
      className: props.className,
      readOnly: true,
      ref: shadowRef,
      tabIndex: -1,
      style: _extends({}, styles$4.shadow, style, {
        padding: 0
      })
    })]
  });
});
TextareaAutosize.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Maximum number of rows to display.
   */
  maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Minimum number of rows to display.
   * @default 1
   */
  minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * @ignore
   */
  onChange: PropTypes.func,
  /**
   * @ignore
   */
  placeholder: PropTypes.string,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * @ignore
   */
  value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.string), PropTypes.number, PropTypes.string])
} ;
var TextareaAutosize$1 = TextareaAutosize;

// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
// Give up on IE11 support for this feature
function stripDiacritics(string) {
  return typeof string.normalize !== 'undefined' ? string.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : string;
}
function createFilterOptions(config = {}) {
  const {
    ignoreAccents = true,
    ignoreCase = true,
    limit,
    matchFrom = 'any',
    stringify,
    trim = false
  } = config;
  return (options, {
    inputValue,
    getOptionLabel
  }) => {
    let input = trim ? inputValue.trim() : inputValue;
    if (ignoreCase) {
      input = input.toLowerCase();
    }
    if (ignoreAccents) {
      input = stripDiacritics(input);
    }
    const filteredOptions = !input ? options : options.filter(option => {
      let candidate = (stringify || getOptionLabel)(option);
      if (ignoreCase) {
        candidate = candidate.toLowerCase();
      }
      if (ignoreAccents) {
        candidate = stripDiacritics(candidate);
      }
      return matchFrom === 'start' ? candidate.indexOf(input) === 0 : candidate.indexOf(input) > -1;
    });
    return typeof limit === 'number' ? filteredOptions.slice(0, limit) : filteredOptions;
  };
}

// To replace with .findIndex() once we stop IE11 support.
function findIndex(array, comp) {
  for (let i = 0; i < array.length; i += 1) {
    if (comp(array[i])) {
      return i;
    }
  }
  return -1;
}
const defaultFilterOptions = createFilterOptions();

// Number of options to jump in list box when `Page Up` and `Page Down` keys are used.
const pageSize = 5;
const defaultIsActiveElementInListbox = listboxRef => {
  var _listboxRef$current$p;
  return listboxRef.current !== null && ((_listboxRef$current$p = listboxRef.current.parentElement) == null ? void 0 : _listboxRef$current$p.contains(document.activeElement));
};
function useAutocomplete(props) {
  const {
    // eslint-disable-next-line @typescript-eslint/naming-convention
    unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,
    // eslint-disable-next-line @typescript-eslint/naming-convention
    unstable_classNamePrefix = 'Mui',
    autoComplete = false,
    autoHighlight = false,
    autoSelect = false,
    blurOnSelect = false,
    clearOnBlur = !props.freeSolo,
    clearOnEscape = false,
    componentName = 'useAutocomplete',
    defaultValue = props.multiple ? [] : null,
    disableClearable = false,
    disableCloseOnSelect = false,
    disabled: disabledProp,
    disabledItemsFocusable = false,
    disableListWrap = false,
    filterOptions = defaultFilterOptions,
    filterSelectedOptions = false,
    freeSolo = false,
    getOptionDisabled,
    getOptionLabel: getOptionLabelProp = option => {
      var _option$label;
      return (_option$label = option.label) != null ? _option$label : option;
    },
    groupBy,
    handleHomeEndKeys = !props.freeSolo,
    id: idProp,
    includeInputInList = false,
    inputValue: inputValueProp,
    isOptionEqualToValue = (option, value) => option === value,
    multiple = false,
    onChange,
    onClose,
    onHighlightChange,
    onInputChange,
    onOpen,
    open: openProp,
    openOnFocus = false,
    options,
    readOnly = false,
    selectOnFocus = !props.freeSolo,
    value: valueProp
  } = props;
  const id = useId(idProp);
  let getOptionLabel = getOptionLabelProp;
  getOptionLabel = option => {
    const optionLabel = getOptionLabelProp(option);
    if (typeof optionLabel !== 'string') {
      {
        const erroneousReturn = optionLabel === undefined ? 'undefined' : `${typeof optionLabel} (${optionLabel})`;
        console.error(`MUI: The \`getOptionLabel\` method of ${componentName} returned ${erroneousReturn} instead of a string for ${JSON.stringify(option)}.`);
      }
      return String(optionLabel);
    }
    return optionLabel;
  };
  const ignoreFocus = reactExports$1.useRef(false);
  const firstFocus = reactExports$1.useRef(true);
  const inputRef = reactExports$1.useRef(null);
  const listboxRef = reactExports$1.useRef(null);
  const [anchorEl, setAnchorEl] = reactExports$1.useState(null);
  const [focusedTag, setFocusedTag] = reactExports$1.useState(-1);
  const defaultHighlighted = autoHighlight ? 0 : -1;
  const highlightedIndexRef = reactExports$1.useRef(defaultHighlighted);
  const [value, setValueState] = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: componentName
  });
  const [inputValue, setInputValueState] = useControlled({
    controlled: inputValueProp,
    default: '',
    name: componentName,
    state: 'inputValue'
  });
  const [focused, setFocused] = reactExports$1.useState(false);
  const resetInputValue = reactExports$1.useCallback((event, newValue) => {
    // retain current `inputValue` if new option isn't selected and `clearOnBlur` is false
    // When `multiple` is enabled, `newValue` is an array of all selected items including the newly selected item
    const isOptionSelected = multiple ? value.length < newValue.length : newValue !== null;
    if (!isOptionSelected && !clearOnBlur) {
      return;
    }
    let newInputValue;
    if (multiple) {
      newInputValue = '';
    } else if (newValue == null) {
      newInputValue = '';
    } else {
      const optionLabel = getOptionLabel(newValue);
      newInputValue = typeof optionLabel === 'string' ? optionLabel : '';
    }
    if (inputValue === newInputValue) {
      return;
    }
    setInputValueState(newInputValue);
    if (onInputChange) {
      onInputChange(event, newInputValue, 'reset');
    }
  }, [getOptionLabel, inputValue, multiple, onInputChange, setInputValueState, clearOnBlur, value]);
  const [open, setOpenState] = useControlled({
    controlled: openProp,
    default: false,
    name: componentName,
    state: 'open'
  });
  const [inputPristine, setInputPristine] = reactExports$1.useState(true);
  const inputValueIsSelectedValue = !multiple && value != null && inputValue === getOptionLabel(value);
  const popupOpen = open && !readOnly;
  const filteredOptions = popupOpen ? filterOptions(options.filter(option => {
    if (filterSelectedOptions && (multiple ? value : [value]).some(value2 => value2 !== null && isOptionEqualToValue(option, value2))) {
      return false;
    }
    return true;
  }),
  // we use the empty string to manipulate `filterOptions` to not filter any options
  // i.e. the filter predicate always returns true
  {
    inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
    getOptionLabel
  }) : [];
  const previousProps = usePreviousProps$1({
    filteredOptions,
    value
  });
  reactExports$1.useEffect(() => {
    const valueChange = value !== previousProps.value;
    if (focused && !valueChange) {
      return;
    }

    // Only reset the input's value when freeSolo if the component's value changes.
    if (freeSolo && !valueChange) {
      return;
    }
    resetInputValue(null, value);
  }, [value, resetInputValue, focused, previousProps.value, freeSolo]);
  const listboxAvailable = open && filteredOptions.length > 0 && !readOnly;
  {
    if (value !== null && !freeSolo && options.length > 0) {
      const missingValue = (multiple ? value : [value]).filter(value2 => !options.some(option => isOptionEqualToValue(option, value2)));
      if (missingValue.length > 0) {
        console.warn([`MUI: The value provided to ${componentName} is invalid.`, `None of the options match with \`${missingValue.length > 1 ? JSON.stringify(missingValue) : JSON.stringify(missingValue[0])}\`.`, 'You can use the `isOptionEqualToValue` prop to customize the equality test.'].join('\n'));
      }
    }
  }
  const focusTag = useEventCallback(tagToFocus => {
    if (tagToFocus === -1) {
      inputRef.current.focus();
    } else {
      anchorEl.querySelector(`[data-tag-index="${tagToFocus}"]`).focus();
    }
  });

  // Ensure the focusedTag is never inconsistent
  reactExports$1.useEffect(() => {
    if (multiple && focusedTag > value.length - 1) {
      setFocusedTag(-1);
      focusTag(-1);
    }
  }, [value, multiple, focusedTag, focusTag]);
  function validOptionIndex(index, direction) {
    if (!listboxRef.current || index === -1) {
      return -1;
    }
    let nextFocus = index;
    while (true) {
      // Out of range
      if (direction === 'next' && nextFocus === filteredOptions.length || direction === 'previous' && nextFocus === -1) {
        return -1;
      }
      const option = listboxRef.current.querySelector(`[data-option-index="${nextFocus}"]`);

      // Same logic as MenuList.js
      const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
      if (option && !option.hasAttribute('tabindex') || nextFocusDisabled) {
        // Move to the next element.
        nextFocus += direction === 'next' ? 1 : -1;
      } else {
        return nextFocus;
      }
    }
  }
  const setHighlightedIndex = useEventCallback(({
    event,
    index,
    reason = 'auto'
  }) => {
    highlightedIndexRef.current = index;

    // does the index exist?
    if (index === -1) {
      inputRef.current.removeAttribute('aria-activedescendant');
    } else {
      inputRef.current.setAttribute('aria-activedescendant', `${id}-option-${index}`);
    }
    if (onHighlightChange) {
      onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);
    }
    if (!listboxRef.current) {
      return;
    }
    const prev = listboxRef.current.querySelector(`[role="option"].${unstable_classNamePrefix}-focused`);
    if (prev) {
      prev.classList.remove(`${unstable_classNamePrefix}-focused`);
      prev.classList.remove(`${unstable_classNamePrefix}-focusVisible`);
    }
    let listboxNode = listboxRef.current;
    if (listboxRef.current.getAttribute('role') !== 'listbox') {
      listboxNode = listboxRef.current.parentElement.querySelector('[role="listbox"]');
    }

    // "No results"
    if (!listboxNode) {
      return;
    }
    if (index === -1) {
      listboxNode.scrollTop = 0;
      return;
    }
    const option = listboxRef.current.querySelector(`[data-option-index="${index}"]`);
    if (!option) {
      return;
    }
    option.classList.add(`${unstable_classNamePrefix}-focused`);
    if (reason === 'keyboard') {
      option.classList.add(`${unstable_classNamePrefix}-focusVisible`);
    }

    // Scroll active descendant into view.
    // Logic copied from https://www.w3.org/WAI/content-assets/wai-aria-practices/patterns/combobox/examples/js/select-only.js
    //
    // Consider this API instead once it has a better browser support:
    // .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });
    if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse') {
      const element = option;
      const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
      const elementBottom = element.offsetTop + element.offsetHeight;
      if (elementBottom > scrollBottom) {
        listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;
      } else if (element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) < listboxNode.scrollTop) {
        listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);
      }
    }
  });
  const changeHighlightedIndex = useEventCallback(({
    event,
    diff,
    direction = 'next',
    reason = 'auto'
  }) => {
    if (!popupOpen) {
      return;
    }
    const getNextIndex = () => {
      const maxIndex = filteredOptions.length - 1;
      if (diff === 'reset') {
        return defaultHighlighted;
      }
      if (diff === 'start') {
        return 0;
      }
      if (diff === 'end') {
        return maxIndex;
      }
      const newIndex = highlightedIndexRef.current + diff;
      if (newIndex < 0) {
        if (newIndex === -1 && includeInputInList) {
          return -1;
        }
        if (disableListWrap && highlightedIndexRef.current !== -1 || Math.abs(diff) > 1) {
          return 0;
        }
        return maxIndex;
      }
      if (newIndex > maxIndex) {
        if (newIndex === maxIndex + 1 && includeInputInList) {
          return -1;
        }
        if (disableListWrap || Math.abs(diff) > 1) {
          return maxIndex;
        }
        return 0;
      }
      return newIndex;
    };
    const nextIndex = validOptionIndex(getNextIndex(), direction);
    setHighlightedIndex({
      index: nextIndex,
      reason,
      event
    });

    // Sync the content of the input with the highlighted option.
    if (autoComplete && diff !== 'reset') {
      if (nextIndex === -1) {
        inputRef.current.value = inputValue;
      } else {
        const option = getOptionLabel(filteredOptions[nextIndex]);
        inputRef.current.value = option;

        // The portion of the selected suggestion that has not been typed by the user,
        // a completion string, appears inline after the input cursor in the textbox.
        const index = option.toLowerCase().indexOf(inputValue.toLowerCase());
        if (index === 0 && inputValue.length > 0) {
          inputRef.current.setSelectionRange(inputValue.length, option.length);
        }
      }
    }
  });
  const checkHighlightedOptionExists = () => {
    const isSameValue = (value1, value2) => {
      const label1 = value1 ? getOptionLabel(value1) : '';
      const label2 = value2 ? getOptionLabel(value2) : '';
      return label1 === label2;
    };
    if (highlightedIndexRef.current !== -1 && previousProps.filteredOptions && previousProps.filteredOptions.length !== filteredOptions.length && (multiple ? value.length === previousProps.value.length && previousProps.value.every((val, i) => getOptionLabel(value[i]) === getOptionLabel(val)) : isSameValue(previousProps.value, value))) {
      const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current];
      if (previousHighlightedOption) {
        const previousHighlightedOptionExists = filteredOptions.some(option => {
          return getOptionLabel(option) === getOptionLabel(previousHighlightedOption);
        });
        if (previousHighlightedOptionExists) {
          return true;
        }
      }
    }
    return false;
  };
  const syncHighlightedIndex = reactExports$1.useCallback(() => {
    if (!popupOpen) {
      return;
    }

    // Check if the previously highlighted option still exists in the updated filtered options list and if the value hasn't changed
    // If it exists and the value hasn't changed, return, otherwise continue execution
    if (checkHighlightedOptionExists()) {
      return;
    }
    const valueItem = multiple ? value[0] : value;

    // The popup is empty, reset
    if (filteredOptions.length === 0 || valueItem == null) {
      changeHighlightedIndex({
        diff: 'reset'
      });
      return;
    }
    if (!listboxRef.current) {
      return;
    }

    // Synchronize the value with the highlighted index
    if (valueItem != null) {
      const currentOption = filteredOptions[highlightedIndexRef.current];

      // Keep the current highlighted index if possible
      if (multiple && currentOption && findIndex(value, val => isOptionEqualToValue(currentOption, val)) !== -1) {
        return;
      }
      const itemIndex = findIndex(filteredOptions, optionItem => isOptionEqualToValue(optionItem, valueItem));
      if (itemIndex === -1) {
        changeHighlightedIndex({
          diff: 'reset'
        });
      } else {
        setHighlightedIndex({
          index: itemIndex
        });
      }
      return;
    }

    // Prevent the highlighted index to leak outside the boundaries.
    if (highlightedIndexRef.current >= filteredOptions.length - 1) {
      setHighlightedIndex({
        index: filteredOptions.length - 1
      });
      return;
    }

    // Restore the focus to the previous index.
    setHighlightedIndex({
      index: highlightedIndexRef.current
    });
    // Ignore filteredOptions (and options, isOptionEqualToValue, getOptionLabel) not to break the scroll position
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
  // Only sync the highlighted index when the option switch between empty and not
  filteredOptions.length,
  // Don't sync the highlighted index with the value when multiple
  // eslint-disable-next-line react-hooks/exhaustive-deps
  multiple ? false : value, filterSelectedOptions, changeHighlightedIndex, setHighlightedIndex, popupOpen, inputValue, multiple]);
  const handleListboxRef = useEventCallback(node => {
    setRef(listboxRef, node);
    if (!node) {
      return;
    }
    syncHighlightedIndex();
  });
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(() => {
      if (!inputRef.current || inputRef.current.nodeName !== 'INPUT') {
        if (inputRef.current && inputRef.current.nodeName === 'TEXTAREA') {
          console.warn([`A textarea element was provided to ${componentName} where input was expected.`, `This is not a supported scenario but it may work under certain conditions.`, `A textarea keyboard navigation may conflict with Autocomplete controls (e.g. enter and arrow keys).`, `Make sure to test keyboard navigation and add custom event handlers if necessary.`].join('\n'));
        } else {
          console.error([`MUI: Unable to find the input element. It was resolved to ${inputRef.current} while an HTMLInputElement was expected.`, `Instead, ${componentName} expects an input element.`, '', componentName === 'useAutocomplete' ? 'Make sure you have bound getInputProps correctly and that the normal ref/effect resolutions order is guaranteed.' : 'Make sure you have customized the input component correctly.'].join('\n'));
        }
      }
    }, [componentName]);
  }
  reactExports$1.useEffect(() => {
    syncHighlightedIndex();
  }, [syncHighlightedIndex]);
  const handleOpen = event => {
    if (open) {
      return;
    }
    setOpenState(true);
    setInputPristine(true);
    if (onOpen) {
      onOpen(event);
    }
  };
  const handleClose = (event, reason) => {
    if (!open) {
      return;
    }
    setOpenState(false);
    if (onClose) {
      onClose(event, reason);
    }
  };
  const handleValue = (event, newValue, reason, details) => {
    if (multiple) {
      if (value.length === newValue.length && value.every((val, i) => val === newValue[i])) {
        return;
      }
    } else if (value === newValue) {
      return;
    }
    if (onChange) {
      onChange(event, newValue, reason, details);
    }
    setValueState(newValue);
  };
  const isTouch = reactExports$1.useRef(false);
  const selectNewValue = (event, option, reasonProp = 'selectOption', origin = 'options') => {
    let reason = reasonProp;
    let newValue = option;
    if (multiple) {
      newValue = Array.isArray(value) ? value.slice() : [];
      {
        const matches = newValue.filter(val => isOptionEqualToValue(option, val));
        if (matches.length > 1) {
          console.error([`MUI: The \`isOptionEqualToValue\` method of ${componentName} does not handle the arguments correctly.`, `The component expects a single value to match a given option but found ${matches.length} matches.`].join('\n'));
        }
      }
      const itemIndex = findIndex(newValue, valueItem => isOptionEqualToValue(option, valueItem));
      if (itemIndex === -1) {
        newValue.push(option);
      } else if (origin !== 'freeSolo') {
        newValue.splice(itemIndex, 1);
        reason = 'removeOption';
      }
    }
    resetInputValue(event, newValue);
    handleValue(event, newValue, reason, {
      option
    });
    if (!disableCloseOnSelect && (!event || !event.ctrlKey && !event.metaKey)) {
      handleClose(event, reason);
    }
    if (blurOnSelect === true || blurOnSelect === 'touch' && isTouch.current || blurOnSelect === 'mouse' && !isTouch.current) {
      inputRef.current.blur();
    }
  };
  function validTagIndex(index, direction) {
    if (index === -1) {
      return -1;
    }
    let nextFocus = index;
    while (true) {
      // Out of range
      if (direction === 'next' && nextFocus === value.length || direction === 'previous' && nextFocus === -1) {
        return -1;
      }
      const option = anchorEl.querySelector(`[data-tag-index="${nextFocus}"]`);

      // Same logic as MenuList.js
      if (!option || !option.hasAttribute('tabindex') || option.disabled || option.getAttribute('aria-disabled') === 'true') {
        nextFocus += direction === 'next' ? 1 : -1;
      } else {
        return nextFocus;
      }
    }
  }
  const handleFocusTag = (event, direction) => {
    if (!multiple) {
      return;
    }
    if (inputValue === '') {
      handleClose(event, 'toggleInput');
    }
    let nextTag = focusedTag;
    if (focusedTag === -1) {
      if (inputValue === '' && direction === 'previous') {
        nextTag = value.length - 1;
      }
    } else {
      nextTag += direction === 'next' ? 1 : -1;
      if (nextTag < 0) {
        nextTag = 0;
      }
      if (nextTag === value.length) {
        nextTag = -1;
      }
    }
    nextTag = validTagIndex(nextTag, direction);
    setFocusedTag(nextTag);
    focusTag(nextTag);
  };
  const handleClear = event => {
    ignoreFocus.current = true;
    setInputValueState('');
    if (onInputChange) {
      onInputChange(event, '', 'clear');
    }
    handleValue(event, multiple ? [] : null, 'clear');
  };
  const handleKeyDown = other => event => {
    if (other.onKeyDown) {
      other.onKeyDown(event);
    }
    if (event.defaultMuiPrevented) {
      return;
    }
    if (focusedTag !== -1 && ['ArrowLeft', 'ArrowRight'].indexOf(event.key) === -1) {
      setFocusedTag(-1);
      focusTag(-1);
    }

    // Wait until IME is settled.
    if (event.which !== 229) {
      switch (event.key) {
        case 'Home':
          if (popupOpen && handleHomeEndKeys) {
            // Prevent scroll of the page
            event.preventDefault();
            changeHighlightedIndex({
              diff: 'start',
              direction: 'next',
              reason: 'keyboard',
              event
            });
          }
          break;
        case 'End':
          if (popupOpen && handleHomeEndKeys) {
            // Prevent scroll of the page
            event.preventDefault();
            changeHighlightedIndex({
              diff: 'end',
              direction: 'previous',
              reason: 'keyboard',
              event
            });
          }
          break;
        case 'PageUp':
          // Prevent scroll of the page
          event.preventDefault();
          changeHighlightedIndex({
            diff: -pageSize,
            direction: 'previous',
            reason: 'keyboard',
            event
          });
          handleOpen(event);
          break;
        case 'PageDown':
          // Prevent scroll of the page
          event.preventDefault();
          changeHighlightedIndex({
            diff: pageSize,
            direction: 'next',
            reason: 'keyboard',
            event
          });
          handleOpen(event);
          break;
        case 'ArrowDown':
          // Prevent cursor move
          event.preventDefault();
          changeHighlightedIndex({
            diff: 1,
            direction: 'next',
            reason: 'keyboard',
            event
          });
          handleOpen(event);
          break;
        case 'ArrowUp':
          // Prevent cursor move
          event.preventDefault();
          changeHighlightedIndex({
            diff: -1,
            direction: 'previous',
            reason: 'keyboard',
            event
          });
          handleOpen(event);
          break;
        case 'ArrowLeft':
          handleFocusTag(event, 'previous');
          break;
        case 'ArrowRight':
          handleFocusTag(event, 'next');
          break;
        case 'Enter':
          if (highlightedIndexRef.current !== -1 && popupOpen) {
            const option = filteredOptions[highlightedIndexRef.current];
            const disabled = getOptionDisabled ? getOptionDisabled(option) : false;

            // Avoid early form validation, let the end-users continue filling the form.
            event.preventDefault();
            if (disabled) {
              return;
            }
            selectNewValue(event, option, 'selectOption');

            // Move the selection to the end.
            if (autoComplete) {
              inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);
            }
          } else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
            if (multiple) {
              // Allow people to add new values before they submit the form.
              event.preventDefault();
            }
            selectNewValue(event, inputValue, 'createOption', 'freeSolo');
          }
          break;
        case 'Escape':
          if (popupOpen) {
            // Avoid Opera to exit fullscreen mode.
            event.preventDefault();
            // Avoid the Modal to handle the event.
            event.stopPropagation();
            handleClose(event, 'escape');
          } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
            // Avoid Opera to exit fullscreen mode.
            event.preventDefault();
            // Avoid the Modal to handle the event.
            event.stopPropagation();
            handleClear(event);
          }
          break;
        case 'Backspace':
          if (multiple && !readOnly && inputValue === '' && value.length > 0) {
            const index = focusedTag === -1 ? value.length - 1 : focusedTag;
            const newValue = value.slice();
            newValue.splice(index, 1);
            handleValue(event, newValue, 'removeOption', {
              option: value[index]
            });
          }
          break;
        case 'Delete':
          if (multiple && !readOnly && inputValue === '' && value.length > 0 && focusedTag !== -1) {
            const index = focusedTag;
            const newValue = value.slice();
            newValue.splice(index, 1);
            handleValue(event, newValue, 'removeOption', {
              option: value[index]
            });
          }
          break;
      }
    }
  };
  const handleFocus = event => {
    setFocused(true);
    if (openOnFocus && !ignoreFocus.current) {
      handleOpen(event);
    }
  };
  const handleBlur = event => {
    // Ignore the event when using the scrollbar with IE11
    if (unstable_isActiveElementInListbox(listboxRef)) {
      inputRef.current.focus();
      return;
    }
    setFocused(false);
    firstFocus.current = true;
    ignoreFocus.current = false;
    if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
      selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');
    } else if (autoSelect && freeSolo && inputValue !== '') {
      selectNewValue(event, inputValue, 'blur', 'freeSolo');
    } else if (clearOnBlur) {
      resetInputValue(event, value);
    }
    handleClose(event, 'blur');
  };
  const handleInputChange = event => {
    const newValue = event.target.value;
    if (inputValue !== newValue) {
      setInputValueState(newValue);
      setInputPristine(false);
      if (onInputChange) {
        onInputChange(event, newValue, 'input');
      }
    }
    if (newValue === '') {
      if (!disableClearable && !multiple) {
        handleValue(event, null, 'clear');
      }
    } else {
      handleOpen(event);
    }
  };
  const handleOptionMouseMove = event => {
    const index = Number(event.currentTarget.getAttribute('data-option-index'));
    if (highlightedIndexRef.current !== index) {
      setHighlightedIndex({
        event,
        index,
        reason: 'mouse'
      });
    }
  };
  const handleOptionTouchStart = event => {
    setHighlightedIndex({
      event,
      index: Number(event.currentTarget.getAttribute('data-option-index')),
      reason: 'touch'
    });
    isTouch.current = true;
  };
  const handleOptionClick = event => {
    const index = Number(event.currentTarget.getAttribute('data-option-index'));
    selectNewValue(event, filteredOptions[index], 'selectOption');
    isTouch.current = false;
  };
  const handleTagDelete = index => event => {
    const newValue = value.slice();
    newValue.splice(index, 1);
    handleValue(event, newValue, 'removeOption', {
      option: value[index]
    });
  };
  const handlePopupIndicator = event => {
    if (open) {
      handleClose(event, 'toggleInput');
    } else {
      handleOpen(event);
    }
  };

  // Prevent input blur when interacting with the combobox
  const handleMouseDown = event => {
    // Prevent focusing the input if click is anywhere outside the Autocomplete
    if (!event.currentTarget.contains(event.target)) {
      return;
    }
    if (event.target.getAttribute('id') !== id) {
      event.preventDefault();
    }
  };

  // Focus the input when interacting with the combobox
  const handleClick = event => {
    // Prevent focusing the input if click is anywhere outside the Autocomplete
    if (!event.currentTarget.contains(event.target)) {
      return;
    }
    inputRef.current.focus();
    if (selectOnFocus && firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {
      inputRef.current.select();
    }
    firstFocus.current = false;
  };
  const handleInputMouseDown = event => {
    if (inputValue === '' || !open) {
      handlePopupIndicator(event);
    }
  };
  let dirty = freeSolo && inputValue.length > 0;
  dirty = dirty || (multiple ? value.length > 0 : value !== null);
  let groupedOptions = filteredOptions;
  if (groupBy) {
    // used to keep track of key and indexes in the result array
    const indexBy = new Map();
    let warn = false;
    groupedOptions = filteredOptions.reduce((acc, option, index) => {
      const group = groupBy(option);
      if (acc.length > 0 && acc[acc.length - 1].group === group) {
        acc[acc.length - 1].options.push(option);
      } else {
        {
          if (indexBy.get(group) && !warn) {
            console.warn(`MUI: The options provided combined with the \`groupBy\` method of ${componentName} returns duplicated headers.`, 'You can solve the issue by sorting the options with the output of `groupBy`.');
            warn = true;
          }
          indexBy.set(group, true);
        }
        acc.push({
          key: index,
          index,
          group,
          options: [option]
        });
      }
      return acc;
    }, []);
  }
  if (disabledProp && focused) {
    handleBlur();
  }
  return {
    getRootProps: (other = {}) => _extends({
      'aria-owns': listboxAvailable ? `${id}-listbox` : null
    }, other, {
      onKeyDown: handleKeyDown(other),
      onMouseDown: handleMouseDown,
      onClick: handleClick
    }),
    getInputLabelProps: () => ({
      id: `${id}-label`,
      htmlFor: id
    }),
    getInputProps: () => ({
      id,
      value: inputValue,
      onBlur: handleBlur,
      onFocus: handleFocus,
      onChange: handleInputChange,
      onMouseDown: handleInputMouseDown,
      // if open then this is handled imperatively so don't let react override
      // only have an opinion about this when closed
      'aria-activedescendant': popupOpen ? '' : null,
      'aria-autocomplete': autoComplete ? 'both' : 'list',
      'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,
      'aria-expanded': listboxAvailable,
      // Disable browser's suggestion that might overlap with the popup.
      // Handle autocomplete but not autofill.
      autoComplete: 'off',
      ref: inputRef,
      autoCapitalize: 'none',
      spellCheck: 'false',
      role: 'combobox',
      disabled: disabledProp
    }),
    getClearProps: () => ({
      tabIndex: -1,
      onClick: handleClear
    }),
    getPopupIndicatorProps: () => ({
      tabIndex: -1,
      onClick: handlePopupIndicator
    }),
    getTagProps: ({
      index
    }) => _extends({
      key: index,
      'data-tag-index': index,
      tabIndex: -1
    }, !readOnly && {
      onDelete: handleTagDelete(index)
    }),
    getListboxProps: () => ({
      role: 'listbox',
      id: `${id}-listbox`,
      'aria-labelledby': `${id}-label`,
      ref: handleListboxRef,
      onMouseDown: event => {
        // Prevent blur
        event.preventDefault();
      }
    }),
    getOptionProps: ({
      index,
      option
    }) => {
      const selected = (multiple ? value : [value]).some(value2 => value2 != null && isOptionEqualToValue(option, value2));
      const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
      return {
        key: getOptionLabel(option),
        tabIndex: -1,
        role: 'option',
        id: `${id}-option-${index}`,
        onMouseMove: handleOptionMouseMove,
        onClick: handleOptionClick,
        onTouchStart: handleOptionTouchStart,
        'data-option-index': index,
        'aria-disabled': disabled,
        'aria-selected': selected
      };
    },
    id,
    inputValue,
    value,
    dirty,
    expanded: popupOpen && anchorEl,
    popupOpen,
    focused: focused || focusedTag !== -1,
    anchorEl,
    setAnchorEl,
    focusedTag,
    groupedOptions
  };
}

function getPaperUtilityClass(slot) {
  return generateUtilityClass('MuiPaper', slot);
}
generateUtilityClasses('MuiPaper', ['root', 'rounded', 'outlined', 'elevation', 'elevation0', 'elevation1', 'elevation2', 'elevation3', 'elevation4', 'elevation5', 'elevation6', 'elevation7', 'elevation8', 'elevation9', 'elevation10', 'elevation11', 'elevation12', 'elevation13', 'elevation14', 'elevation15', 'elevation16', 'elevation17', 'elevation18', 'elevation19', 'elevation20', 'elevation21', 'elevation22', 'elevation23', 'elevation24']);

const _excluded$1t = ["className", "component", "elevation", "square", "variant"];
const useUtilityClasses$1f = ownerState => {
  const {
    square,
    elevation,
    variant,
    classes
  } = ownerState;
  const slots = {
    root: ['root', variant, !square && 'rounded', variant === 'elevation' && `elevation${elevation}`]
  };
  return composeClasses(slots, getPaperUtilityClass, classes);
};
const PaperRoot = styled$1('div', {
  name: 'MuiPaper',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant], !ownerState.square && styles.rounded, ownerState.variant === 'elevation' && styles[`elevation${ownerState.elevation}`]];
  }
})(({
  theme,
  ownerState
}) => {
  var _theme$vars$overlays;
  return _extends({
    backgroundColor: (theme.vars || theme).palette.background.paper,
    color: (theme.vars || theme).palette.text.primary,
    transition: theme.transitions.create('box-shadow')
  }, !ownerState.square && {
    borderRadius: theme.shape.borderRadius
  }, ownerState.variant === 'outlined' && {
    border: `1px solid ${(theme.vars || theme).palette.divider}`
  }, ownerState.variant === 'elevation' && _extends({
    boxShadow: (theme.vars || theme).shadows[ownerState.elevation]
  }, !theme.vars && theme.palette.mode === 'dark' && {
    backgroundImage: `linear-gradient(${alpha('#fff', getOverlayAlpha$1(ownerState.elevation))}, ${alpha('#fff', getOverlayAlpha$1(ownerState.elevation))})`
  }, theme.vars && {
    backgroundImage: (_theme$vars$overlays = theme.vars.overlays) == null ? void 0 : _theme$vars$overlays[ownerState.elevation]
  }));
});
const Paper = /*#__PURE__*/reactExports$1.forwardRef(function Paper(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiPaper'
  });
  const {
      className,
      component = 'div',
      elevation = 1,
      square = false,
      variant = 'elevation'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1t);
  const ownerState = _extends({}, props, {
    component,
    elevation,
    square,
    variant
  });
  const classes = useUtilityClasses$1f(ownerState);
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const theme = useTheme();
    if (theme.shadows[elevation] === undefined) {
      console.error([`MUI: The elevation provided <Paper elevation={${elevation}}> is not available in the theme.`, `Please make sure that \`theme.shadows[${elevation}]\` is defined.`].join('\n'));
    }
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(PaperRoot, _extends({
    as: component,
    ownerState: ownerState,
    className: clsx(classes.root, className),
    ref: ref
  }, other));
});
Paper.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Shadow depth, corresponds to `dp` in the spec.
   * It accepts values between 0 and 24 inclusive.
   * @default 1
   */
  elevation: chainPropTypes(integerPropType, props => {
    const {
      elevation,
      variant
    } = props;
    if (elevation > 0 && variant === 'outlined') {
      return new Error(`MUI: Combining \`elevation={${elevation}}\` with \`variant="${variant}"\` has no effect. Either use \`elevation={0}\` or use a different \`variant\`.`);
    }
    return null;
  }),
  /**
   * If `true`, rounded corners are disabled.
   * @default false
   */
  square: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'elevation'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['elevation', 'outlined']), PropTypes.string])
} ;
var Paper$1 = Paper;

function getAppBarUtilityClass(slot) {
  return generateUtilityClass('MuiAppBar', slot);
}
generateUtilityClasses('MuiAppBar', ['root', 'positionFixed', 'positionAbsolute', 'positionSticky', 'positionStatic', 'positionRelative', 'colorDefault', 'colorPrimary', 'colorSecondary', 'colorInherit', 'colorTransparent']);

const _excluded$1s = ["className", "color", "enableColorOnDark", "position"];
const useUtilityClasses$1e = ownerState => {
  const {
    color,
    position,
    classes
  } = ownerState;
  const slots = {
    root: ['root', `color${capitalize(color)}`, `position${capitalize(position)}`]
  };
  return composeClasses(slots, getAppBarUtilityClass, classes);
};

// var2 is the fallback.
// Ex. var1: 'var(--a)', var2: 'var(--b)'; return: 'var(--a, var(--b))'
const joinVars = (var1, var2) => var1 ? `${var1 == null ? void 0 : var1.replace(')', '')}, ${var2})` : var2;
const AppBarRoot = styled$1(Paper$1, {
  name: 'MuiAppBar',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`position${capitalize(ownerState.position)}`], styles[`color${capitalize(ownerState.color)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  const backgroundColorDefault = theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[900];
  return _extends({
    display: 'flex',
    flexDirection: 'column',
    width: '100%',
    boxSizing: 'border-box',
    // Prevent padding issue with the Modal and fixed positioned AppBar.
    flexShrink: 0
  }, ownerState.position === 'fixed' && {
    position: 'fixed',
    zIndex: (theme.vars || theme).zIndex.appBar,
    top: 0,
    left: 'auto',
    right: 0,
    '@media print': {
      // Prevent the app bar to be visible on each printed page.
      position: 'absolute'
    }
  }, ownerState.position === 'absolute' && {
    position: 'absolute',
    zIndex: (theme.vars || theme).zIndex.appBar,
    top: 0,
    left: 'auto',
    right: 0
  }, ownerState.position === 'sticky' && {
    // ⚠️ sticky is not supported by IE11.
    position: 'sticky',
    zIndex: (theme.vars || theme).zIndex.appBar,
    top: 0,
    left: 'auto',
    right: 0
  }, ownerState.position === 'static' && {
    position: 'static'
  }, ownerState.position === 'relative' && {
    position: 'relative'
  }, !theme.vars && _extends({}, ownerState.color === 'default' && {
    backgroundColor: backgroundColorDefault,
    color: theme.palette.getContrastText(backgroundColorDefault)
  }, ownerState.color && ownerState.color !== 'default' && ownerState.color !== 'inherit' && ownerState.color !== 'transparent' && {
    backgroundColor: theme.palette[ownerState.color].main,
    color: theme.palette[ownerState.color].contrastText
  }, ownerState.color === 'inherit' && {
    color: 'inherit'
  }, theme.palette.mode === 'dark' && !ownerState.enableColorOnDark && {
    backgroundColor: null,
    color: null
  }, ownerState.color === 'transparent' && _extends({
    backgroundColor: 'transparent',
    color: 'inherit'
  }, theme.palette.mode === 'dark' && {
    backgroundImage: 'none'
  })), theme.vars && _extends({}, ownerState.color === 'default' && {
    '--AppBar-background': ownerState.enableColorOnDark ? theme.vars.palette.AppBar.defaultBg : joinVars(theme.vars.palette.AppBar.darkBg, theme.vars.palette.AppBar.defaultBg),
    '--AppBar-color': ownerState.enableColorOnDark ? theme.vars.palette.text.primary : joinVars(theme.vars.palette.AppBar.darkColor, theme.vars.palette.text.primary)
  }, ownerState.color && !ownerState.color.match(/^(default|inherit|transparent)$/) && {
    '--AppBar-background': ownerState.enableColorOnDark ? theme.vars.palette[ownerState.color].main : joinVars(theme.vars.palette.AppBar.darkBg, theme.vars.palette[ownerState.color].main),
    '--AppBar-color': ownerState.enableColorOnDark ? theme.vars.palette[ownerState.color].contrastText : joinVars(theme.vars.palette.AppBar.darkColor, theme.vars.palette[ownerState.color].contrastText)
  }, {
    backgroundColor: 'var(--AppBar-background)',
    color: ownerState.color === 'inherit' ? 'inherit' : 'var(--AppBar-color)'
  }, ownerState.color === 'transparent' && {
    backgroundImage: 'none',
    backgroundColor: 'transparent',
    color: 'inherit'
  }));
});
const AppBar = /*#__PURE__*/reactExports$1.forwardRef(function AppBar(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAppBar'
  });
  const {
      className,
      color = 'primary',
      enableColorOnDark = false,
      position = 'fixed'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1s);
  const ownerState = _extends({}, props, {
    color,
    position,
    enableColorOnDark
  });
  const classes = useUtilityClasses$1e(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(AppBarRoot, _extends({
    square: true,
    component: "header",
    ownerState: ownerState,
    elevation: 4,
    className: clsx(classes.root, className, position === 'fixed' && 'mui-fixed'),
    ref: ref
  }, other));
});
AppBar.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary', 'transparent']), PropTypes.string]),
  /**
   * If true, the `color` prop is applied in dark mode.
   * @default false
   */
  enableColorOnDark: PropTypes.bool,
  /**
   * The positioning type. The behavior of the different options is described
   * [in the MDN web docs](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning).
   * Note: `sticky` is not universally supported and will fall back to `static` when unavailable.
   * @default 'fixed'
   */
  position: PropTypes.oneOf(['absolute', 'fixed', 'relative', 'static', 'sticky']),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var AppBar$1 = AppBar;

function getToolbarUtilityClass(slot) {
  return generateUtilityClass('MuiToolbar', slot);
}
generateUtilityClasses('MuiToolbar', ['root', 'gutters', 'regular', 'dense']);

const _excluded$1r = ["className", "component", "disableGutters", "variant"];
const useUtilityClasses$1d = ownerState => {
  const {
    classes,
    disableGutters,
    variant
  } = ownerState;
  const slots = {
    root: ['root', !disableGutters && 'gutters', variant]
  };
  return composeClasses(slots, getToolbarUtilityClass, classes);
};
const ToolbarRoot = styled$1('div', {
  name: 'MuiToolbar',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, !ownerState.disableGutters && styles.gutters, styles[ownerState.variant]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  position: 'relative',
  display: 'flex',
  alignItems: 'center'
}, !ownerState.disableGutters && {
  paddingLeft: theme.spacing(2),
  paddingRight: theme.spacing(2),
  [theme.breakpoints.up('sm')]: {
    paddingLeft: theme.spacing(3),
    paddingRight: theme.spacing(3)
  }
}, ownerState.variant === 'dense' && {
  minHeight: 48
}), ({
  theme,
  ownerState
}) => ownerState.variant === 'regular' && theme.mixins.toolbar);
const Toolbar = /*#__PURE__*/reactExports$1.forwardRef(function Toolbar(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiToolbar'
  });
  const {
      className,
      component = 'div',
      disableGutters = false,
      variant = 'regular'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1r);
  const ownerState = _extends({}, props, {
    component,
    disableGutters,
    variant
  });
  const classes = useUtilityClasses$1d(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ToolbarRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    ref: ref,
    ownerState: ownerState
  }, other));
});
Toolbar.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The Toolbar children, usually a mixture of `IconButton`, `Button` and `Typography`.
   * The Toolbar is a flex container, allowing flex item properties to be used to lay out the children.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, disables gutter padding.
   * @default false
   */
  disableGutters: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'regular'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['dense', 'regular']), PropTypes.string])
} ;
var Toolbar$1 = Toolbar;

function getTypographyUtilityClass(slot) {
  return generateUtilityClass('MuiTypography', slot);
}
generateUtilityClasses('MuiTypography', ['root', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'inherit', 'button', 'caption', 'overline', 'alignLeft', 'alignRight', 'alignCenter', 'alignJustify', 'noWrap', 'gutterBottom', 'paragraph']);

const _excluded$1q = ["align", "className", "component", "gutterBottom", "noWrap", "paragraph", "variant", "variantMapping"];
const useUtilityClasses$1c = ownerState => {
  const {
    align,
    gutterBottom,
    noWrap,
    paragraph,
    variant,
    classes
  } = ownerState;
  const slots = {
    root: ['root', variant, ownerState.align !== 'inherit' && `align${capitalize(align)}`, gutterBottom && 'gutterBottom', noWrap && 'noWrap', paragraph && 'paragraph']
  };
  return composeClasses(slots, getTypographyUtilityClass, classes);
};
const TypographyRoot = styled$1('span', {
  name: 'MuiTypography',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.variant && styles[ownerState.variant], ownerState.align !== 'inherit' && styles[`align${capitalize(ownerState.align)}`], ownerState.noWrap && styles.noWrap, ownerState.gutterBottom && styles.gutterBottom, ownerState.paragraph && styles.paragraph];
  }
})(({
  theme,
  ownerState
}) => _extends({
  margin: 0
}, ownerState.variant && theme.typography[ownerState.variant], ownerState.align !== 'inherit' && {
  textAlign: ownerState.align
}, ownerState.noWrap && {
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap'
}, ownerState.gutterBottom && {
  marginBottom: '0.35em'
}, ownerState.paragraph && {
  marginBottom: 16
}));
const defaultVariantMapping = {
  h1: 'h1',
  h2: 'h2',
  h3: 'h3',
  h4: 'h4',
  h5: 'h5',
  h6: 'h6',
  subtitle1: 'h6',
  subtitle2: 'h6',
  body1: 'p',
  body2: 'p',
  inherit: 'p'
};

// TODO v6: deprecate these color values in v5.x and remove the transformation in v6
const colorTransformations$1 = {
  primary: 'primary.main',
  textPrimary: 'text.primary',
  secondary: 'secondary.main',
  textSecondary: 'text.secondary',
  error: 'error.main'
};
const transformDeprecatedColors$1 = color => {
  return colorTransformations$1[color] || color;
};
const Typography = /*#__PURE__*/reactExports$1.forwardRef(function Typography(inProps, ref) {
  const themeProps = useThemeProps({
    props: inProps,
    name: 'MuiTypography'
  });
  const color = transformDeprecatedColors$1(themeProps.color);
  const props = extendSxProp(_extends({}, themeProps, {
    color
  }));
  const {
      align = 'inherit',
      className,
      component,
      gutterBottom = false,
      noWrap = false,
      paragraph = false,
      variant = 'body1',
      variantMapping = defaultVariantMapping
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1q);
  const ownerState = _extends({}, props, {
    align,
    color,
    className,
    component,
    gutterBottom,
    noWrap,
    paragraph,
    variant,
    variantMapping
  });
  const Component = component || (paragraph ? 'p' : variantMapping[variant] || defaultVariantMapping[variant]) || 'span';
  const classes = useUtilityClasses$1c(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TypographyRoot, _extends({
    as: Component,
    ref: ref,
    ownerState: ownerState,
    className: clsx(classes.root, className)
  }, other));
});
Typography.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Set the text-align on the component.
   * @default 'inherit'
   */
  align: PropTypes.oneOf(['center', 'inherit', 'justify', 'left', 'right']),
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the text will have a bottom margin.
   * @default false
   */
  gutterBottom: PropTypes.bool,
  /**
   * If `true`, the text will not wrap, but instead will truncate with a text overflow ellipsis.
   *
   * Note that text overflow can only happen with block or inline-block level elements
   * (the element needs to have a width in order to overflow).
   * @default false
   */
  noWrap: PropTypes.bool,
  /**
   * If `true`, the element will be a paragraph element.
   * @default false
   */
  paragraph: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Applies the theme typography styles.
   * @default 'body1'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['body1', 'body2', 'button', 'caption', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'inherit', 'overline', 'subtitle1', 'subtitle2']), PropTypes.string]),
  /**
   * The component maps the variant prop to a range of different HTML element types.
   * For instance, subtitle1 to `<h6>`.
   * If you wish to change that mapping, you can provide your own.
   * Alternatively, you can use the `component` prop.
   * @default {
   *   h1: 'h1',
   *   h2: 'h2',
   *   h3: 'h3',
   *   h4: 'h4',
   *   h5: 'h5',
   *   h6: 'h6',
   *   subtitle1: 'h6',
   *   subtitle2: 'h6',
   *   body1: 'p',
   *   body2: 'p',
   *   inherit: 'p',
   * }
   */
  variantMapping: PropTypes /* @typescript-to-proptypes-ignore */.object
} ;
var Typography$1 = Typography;

/**
 * @deprecated Not used internally. Use `MediaQueryListEvent` from lib.dom.d.ts instead.
 */

/**
 * @deprecated Not used internally. Use `MediaQueryList` from lib.dom.d.ts instead.
 */

/**
 * @deprecated Not used internally. Use `(event: MediaQueryListEvent) => void` instead.
 */

function useMediaQueryOld(query, defaultMatches, matchMedia, ssrMatchMedia, noSsr) {
  const [match, setMatch] = reactExports$1.useState(() => {
    if (noSsr && matchMedia) {
      return matchMedia(query).matches;
    }
    if (ssrMatchMedia) {
      return ssrMatchMedia(query).matches;
    }

    // Once the component is mounted, we rely on the
    // event listeners to return the correct matches value.
    return defaultMatches;
  });
  useEnhancedEffect$1(() => {
    let active = true;
    if (!matchMedia) {
      return undefined;
    }
    const queryList = matchMedia(query);
    const updateMatch = () => {
      // Workaround Safari wrong implementation of matchMedia
      // TODO can we remove it?
      // https://github.com/mui/material-ui/pull/17315#issuecomment-528286677
      if (active) {
        setMatch(queryList.matches);
      }
    };
    updateMatch();
    // TODO: Use `addEventListener` once support for Safari < 14 is dropped
    queryList.addListener(updateMatch);
    return () => {
      active = false;
      queryList.removeListener(updateMatch);
    };
  }, [query, matchMedia]);
  return match;
}

// eslint-disable-next-line no-useless-concat -- Workaround for https://github.com/webpack/webpack/issues/14814
const maybeReactUseSyncExternalStore = React$1['useSyncExternalStore' + ''];
function useMediaQueryNew(query, defaultMatches, matchMedia, ssrMatchMedia, noSsr) {
  const getDefaultSnapshot = reactExports$1.useCallback(() => defaultMatches, [defaultMatches]);
  const getServerSnapshot = reactExports$1.useMemo(() => {
    if (noSsr && matchMedia) {
      return () => matchMedia(query).matches;
    }
    if (ssrMatchMedia !== null) {
      const {
        matches
      } = ssrMatchMedia(query);
      return () => matches;
    }
    return getDefaultSnapshot;
  }, [getDefaultSnapshot, query, ssrMatchMedia, noSsr, matchMedia]);
  const [getSnapshot, subscribe] = reactExports$1.useMemo(() => {
    if (matchMedia === null) {
      return [getDefaultSnapshot, () => () => {}];
    }
    const mediaQueryList = matchMedia(query);
    return [() => mediaQueryList.matches, notify => {
      // TODO: Use `addEventListener` once support for Safari < 14 is dropped
      mediaQueryList.addListener(notify);
      return () => {
        mediaQueryList.removeListener(notify);
      };
    }];
  }, [getDefaultSnapshot, matchMedia, query]);
  const match = maybeReactUseSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
  return match;
}
function useMediaQuery(queryInput, options = {}) {
  const theme = useTheme$2();
  // Wait for jsdom to support the match media feature.
  // All the browsers MUI support have this built-in.
  // This defensive check is here for simplicity.
  // Most of the time, the match media logic isn't central to people tests.
  const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined';
  const {
    defaultMatches = false,
    matchMedia = supportMatchMedia ? window.matchMedia : null,
    ssrMatchMedia = null,
    noSsr = false
  } = getThemeProps({
    name: 'MuiUseMediaQuery',
    props: options,
    theme
  });
  {
    if (typeof queryInput === 'function' && theme === null) {
      console.error(['MUI: The `query` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.'].join('\n'));
    }
  }
  let query = typeof queryInput === 'function' ? queryInput(theme) : queryInput;
  query = query.replace(/^@media( ?)/m, '');

  // TODO: Drop `useMediaQueryOld` and use  `use-sync-external-store` shim in `useMediaQueryNew` once the package is stable
  const useMediaQueryImplementation = maybeReactUseSyncExternalStore !== undefined ? useMediaQueryNew : useMediaQueryOld;
  const match = useMediaQueryImplementation(query, defaultMatches, matchMedia, ssrMatchMedia, noSsr);
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useDebugValue({
      query,
      match
    });
  }
  return match;
}

function useMinWidth(minWidth) {
  return useMediaQuery(`(min-width:${minWidth}px)`);
}

function Header() {
  const title = useSiteTitle(),
    links = useBreadcrumbs(),
    {
      Logo,
      Breadcrumbs,
      IconButton,
      NavMenuPopup
    } = useComponents(),
    fixedMenu = useMinWidth(600),
    [open, setOpen] = reactExports$1.useState(false);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(AppBar$1, {
    position: "static",
    sx: {
      zIndex: 500
    }
  }, /*#__PURE__*/React.createElement(Toolbar$1, null, fixedMenu ? /*#__PURE__*/React.createElement(Logo, {
    edge: "start"
  }) : /*#__PURE__*/React.createElement(IconButton, {
    icon: "menu",
    sx: {
      mr: 2
    },
    onClick: () => setOpen(true),
    color: "inherit",
    edge: "start"
  }), /*#__PURE__*/React.createElement(Typography$1, {
    variant: "h6"
  }, title))), /*#__PURE__*/React.createElement(Breadcrumbs, {
    links: links
  }), !fixedMenu && /*#__PURE__*/React.createElement(NavMenuPopup, {
    open: open,
    onClose: () => setOpen(false)
  }));
}

var config = {
  disabled: false
};

var timeoutsShape = PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
  enter: PropTypes.number,
  exit: PropTypes.number,
  appear: PropTypes.number
}).isRequired]) ;
PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
  enter: PropTypes.string,
  exit: PropTypes.string,
  active: PropTypes.string
}), PropTypes.shape({
  enter: PropTypes.string,
  enterDone: PropTypes.string,
  enterActive: PropTypes.string,
  exit: PropTypes.string,
  exitDone: PropTypes.string,
  exitActive: PropTypes.string
})]) ;

var TransitionGroupContext = React.createContext(null);

var forceReflow = function forceReflow(node) {
  return node.scrollTop;
};

var UNMOUNTED = 'unmounted';
var EXITED = 'exited';
var ENTERING = 'entering';
var ENTERED = 'entered';
var EXITING = 'exiting';
/**
 * The Transition component lets you describe a transition from one component
 * state to another _over time_ with a simple declarative API. Most commonly
 * it's used to animate the mounting and unmounting of a component, but can also
 * be used to describe in-place transition states as well.
 *
 * ---
 *
 * **Note**: `Transition` is a platform-agnostic base component. If you're using
 * transitions in CSS, you'll probably want to use
 * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)
 * instead. It inherits all the features of `Transition`, but contains
 * additional features necessary to play nice with CSS transitions (hence the
 * name of the component).
 *
 * ---
 *
 * By default the `Transition` component does not alter the behavior of the
 * component it renders, it only tracks "enter" and "exit" states for the
 * components. It's up to you to give meaning and effect to those states. For
 * example we can add styles to a component when it enters or exits:
 *
 * ```jsx
 * import { Transition } from 'react-transition-group';
 *
 * const duration = 300;
 *
 * const defaultStyle = {
 *   transition: `opacity ${duration}ms ease-in-out`,
 *   opacity: 0,
 * }
 *
 * const transitionStyles = {
 *   entering: { opacity: 1 },
 *   entered:  { opacity: 1 },
 *   exiting:  { opacity: 0 },
 *   exited:  { opacity: 0 },
 * };
 *
 * const Fade = ({ in: inProp }) => (
 *   <Transition in={inProp} timeout={duration}>
 *     {state => (
 *       <div style={{
 *         ...defaultStyle,
 *         ...transitionStyles[state]
 *       }}>
 *         I'm a fade Transition!
 *       </div>
 *     )}
 *   </Transition>
 * );
 * ```
 *
 * There are 4 main states a Transition can be in:
 *  - `'entering'`
 *  - `'entered'`
 *  - `'exiting'`
 *  - `'exited'`
 *
 * Transition state is toggled via the `in` prop. When `true` the component
 * begins the "Enter" stage. During this stage, the component will shift from
 * its current transition state, to `'entering'` for the duration of the
 * transition and then to the `'entered'` stage once it's complete. Let's take
 * the following example (we'll use the
 * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):
 *
 * ```jsx
 * function App() {
 *   const [inProp, setInProp] = useState(false);
 *   return (
 *     <div>
 *       <Transition in={inProp} timeout={500}>
 *         {state => (
 *           // ...
 *         )}
 *       </Transition>
 *       <button onClick={() => setInProp(true)}>
 *         Click to Enter
 *       </button>
 *     </div>
 *   );
 * }
 * ```
 *
 * When the button is clicked the component will shift to the `'entering'` state
 * and stay there for 500ms (the value of `timeout`) before it finally switches
 * to `'entered'`.
 *
 * When `in` is `false` the same thing happens except the state moves from
 * `'exiting'` to `'exited'`.
 */

var Transition = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose$1(Transition, _React$Component);
  function Transition(props, context) {
    var _this;
    _this = _React$Component.call(this, props, context) || this;
    var parentGroup = context; // In the context of a TransitionGroup all enters are really appears

    var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
    var initialStatus;
    _this.appearStatus = null;
    if (props.in) {
      if (appear) {
        initialStatus = EXITED;
        _this.appearStatus = ENTERING;
      } else {
        initialStatus = ENTERED;
      }
    } else {
      if (props.unmountOnExit || props.mountOnEnter) {
        initialStatus = UNMOUNTED;
      } else {
        initialStatus = EXITED;
      }
    }
    _this.state = {
      status: initialStatus
    };
    _this.nextCallback = null;
    return _this;
  }
  Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
    var nextIn = _ref.in;
    if (nextIn && prevState.status === UNMOUNTED) {
      return {
        status: EXITED
      };
    }
    return null;
  } // getSnapshotBeforeUpdate(prevProps) {
  //   let nextStatus = null
  //   if (prevProps !== this.props) {
  //     const { status } = this.state
  //     if (this.props.in) {
  //       if (status !== ENTERING && status !== ENTERED) {
  //         nextStatus = ENTERING
  //       }
  //     } else {
  //       if (status === ENTERING || status === ENTERED) {
  //         nextStatus = EXITING
  //       }
  //     }
  //   }
  //   return { nextStatus }
  // }
  ;

  var _proto = Transition.prototype;
  _proto.componentDidMount = function componentDidMount() {
    this.updateStatus(true, this.appearStatus);
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    var nextStatus = null;
    if (prevProps !== this.props) {
      var status = this.state.status;
      if (this.props.in) {
        if (status !== ENTERING && status !== ENTERED) {
          nextStatus = ENTERING;
        }
      } else {
        if (status === ENTERING || status === ENTERED) {
          nextStatus = EXITING;
        }
      }
    }
    this.updateStatus(false, nextStatus);
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    this.cancelNextCallback();
  };
  _proto.getTimeouts = function getTimeouts() {
    var timeout = this.props.timeout;
    var exit, enter, appear;
    exit = enter = appear = timeout;
    if (timeout != null && typeof timeout !== 'number') {
      exit = timeout.exit;
      enter = timeout.enter; // TODO: remove fallback for next major

      appear = timeout.appear !== undefined ? timeout.appear : enter;
    }
    return {
      exit: exit,
      enter: enter,
      appear: appear
    };
  };
  _proto.updateStatus = function updateStatus(mounting, nextStatus) {
    if (mounting === void 0) {
      mounting = false;
    }
    if (nextStatus !== null) {
      // nextStatus will always be ENTERING or EXITING.
      this.cancelNextCallback();
      if (nextStatus === ENTERING) {
        if (this.props.unmountOnExit || this.props.mountOnEnter) {
          var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this); // https://github.com/reactjs/react-transition-group/pull/749
          // With unmountOnExit or mountOnEnter, the enter animation should happen at the transition between `exited` and `entering`.
          // To make the animation happen,  we have to separate each rendering and avoid being processed as batched.

          if (node) forceReflow(node);
        }
        this.performEnter(mounting);
      } else {
        this.performExit();
      }
    } else if (this.props.unmountOnExit && this.state.status === EXITED) {
      this.setState({
        status: UNMOUNTED
      });
    }
  };
  _proto.performEnter = function performEnter(mounting) {
    var _this2 = this;
    var enter = this.props.enter;
    var appearing = this.context ? this.context.isMounting : mounting;
    var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],
      maybeNode = _ref2[0],
      maybeAppearing = _ref2[1];
    var timeouts = this.getTimeouts();
    var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
    // if we are mounting and running this it means appear _must_ be set

    if (!mounting && !enter || config.disabled) {
      this.safeSetState({
        status: ENTERED
      }, function () {
        _this2.props.onEntered(maybeNode);
      });
      return;
    }
    this.props.onEnter(maybeNode, maybeAppearing);
    this.safeSetState({
      status: ENTERING
    }, function () {
      _this2.props.onEntering(maybeNode, maybeAppearing);
      _this2.onTransitionEnd(enterTimeout, function () {
        _this2.safeSetState({
          status: ENTERED
        }, function () {
          _this2.props.onEntered(maybeNode, maybeAppearing);
        });
      });
    });
  };
  _proto.performExit = function performExit() {
    var _this3 = this;
    var exit = this.props.exit;
    var timeouts = this.getTimeouts();
    var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED

    if (!exit || config.disabled) {
      this.safeSetState({
        status: EXITED
      }, function () {
        _this3.props.onExited(maybeNode);
      });
      return;
    }
    this.props.onExit(maybeNode);
    this.safeSetState({
      status: EXITING
    }, function () {
      _this3.props.onExiting(maybeNode);
      _this3.onTransitionEnd(timeouts.exit, function () {
        _this3.safeSetState({
          status: EXITED
        }, function () {
          _this3.props.onExited(maybeNode);
        });
      });
    });
  };
  _proto.cancelNextCallback = function cancelNextCallback() {
    if (this.nextCallback !== null) {
      this.nextCallback.cancel();
      this.nextCallback = null;
    }
  };
  _proto.safeSetState = function safeSetState(nextState, callback) {
    // This shouldn't be necessary, but there are weird race conditions with
    // setState callbacks and unmounting in testing, so always make sure that
    // we can cancel any pending setState callbacks after we unmount.
    callback = this.setNextCallback(callback);
    this.setState(nextState, callback);
  };
  _proto.setNextCallback = function setNextCallback(callback) {
    var _this4 = this;
    var active = true;
    this.nextCallback = function (event) {
      if (active) {
        active = false;
        _this4.nextCallback = null;
        callback(event);
      }
    };
    this.nextCallback.cancel = function () {
      active = false;
    };
    return this.nextCallback;
  };
  _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {
    this.setNextCallback(handler);
    var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);
    var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;
    if (!node || doesNotHaveTimeoutOrListener) {
      setTimeout(this.nextCallback, 0);
      return;
    }
    if (this.props.addEndListener) {
      var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],
        maybeNode = _ref3[0],
        maybeNextCallback = _ref3[1];
      this.props.addEndListener(maybeNode, maybeNextCallback);
    }
    if (timeout != null) {
      setTimeout(this.nextCallback, timeout);
    }
  };
  _proto.render = function render() {
    var status = this.state.status;
    if (status === UNMOUNTED) {
      return null;
    }
    var _this$props = this.props,
      children = _this$props.children;
      _this$props.in;
      _this$props.mountOnEnter;
      _this$props.unmountOnExit;
      _this$props.appear;
      _this$props.enter;
      _this$props.exit;
      _this$props.timeout;
      _this$props.addEndListener;
      _this$props.onEnter;
      _this$props.onEntering;
      _this$props.onEntered;
      _this$props.onExit;
      _this$props.onExiting;
      _this$props.onExited;
      _this$props.nodeRef;
      var childProps = _objectWithoutPropertiesLoose$2(_this$props, ["children", "in", "mountOnEnter", "unmountOnExit", "appear", "enter", "exit", "timeout", "addEndListener", "onEnter", "onEntering", "onEntered", "onExit", "onExiting", "onExited", "nodeRef"]);
    return /*#__PURE__*/(
      // allows for nested Transitions
      React.createElement(TransitionGroupContext.Provider, {
        value: null
      }, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))
    );
  };
  return Transition;
}(React.Component);
Transition.contextType = TransitionGroupContext;
Transition.propTypes = {
  /**
   * A React reference to DOM element that need to transition:
   * https://stackoverflow.com/a/51127130/4671932
   *
   *   - When `nodeRef` prop is used, `node` is not passed to callback functions
   *      (e.g. `onEnter`) because user already has direct access to the node.
   *   - When changing `key` prop of `Transition` in a `TransitionGroup` a new
   *     `nodeRef` need to be provided to `Transition` with changed `key` prop
   *     (see
   *     [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).
   */
  nodeRef: PropTypes.shape({
    current: typeof Element === 'undefined' ? PropTypes.any : function (propValue, key, componentName, location, propFullName, secret) {
      var value = propValue[key];
      return PropTypes.instanceOf(value && 'ownerDocument' in value ? value.ownerDocument.defaultView.Element : Element)(propValue, key, componentName, location, propFullName, secret);
    }
  }),
  /**
   * A `function` child can be used instead of a React element. This function is
   * called with the current transition status (`'entering'`, `'entered'`,
   * `'exiting'`, `'exited'`), which can be used to apply context
   * specific props to a component.
   *
   * ```jsx
   * <Transition in={this.state.in} timeout={150}>
   *   {state => (
   *     <MyComponent className={`fade fade-${state}`} />
   *   )}
   * </Transition>
   * ```
   */
  children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,
  /**
   * Show the component; triggers the enter or exit states
   */
  in: PropTypes.bool,
  /**
   * By default the child component is mounted immediately along with
   * the parent `Transition` component. If you want to "lazy mount" the component on the
   * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay
   * mounted, even on "exited", unless you also specify `unmountOnExit`.
   */
  mountOnEnter: PropTypes.bool,
  /**
   * By default the child component stays mounted after it reaches the `'exited'` state.
   * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.
   */
  unmountOnExit: PropTypes.bool,
  /**
   * By default the child component does not perform the enter transition when
   * it first mounts, regardless of the value of `in`. If you want this
   * behavior, set both `appear` and `in` to `true`.
   *
   * > **Note**: there are no special appear states like `appearing`/`appeared`, this prop
   * > only adds an additional enter transition. However, in the
   * > `<CSSTransition>` component that first enter transition does result in
   * > additional `.appear-*` classes, that way you can choose to style it
   * > differently.
   */
  appear: PropTypes.bool,
  /**
   * Enable or disable enter transitions.
   */
  enter: PropTypes.bool,
  /**
   * Enable or disable exit transitions.
   */
  exit: PropTypes.bool,
  /**
   * The duration of the transition, in milliseconds.
   * Required unless `addEndListener` is provided.
   *
   * You may specify a single timeout for all transitions:
   *
   * ```jsx
   * timeout={500}
   * ```
   *
   * or individually:
   *
   * ```jsx
   * timeout={{
   *  appear: 500,
   *  enter: 300,
   *  exit: 500,
   * }}
   * ```
   *
   * - `appear` defaults to the value of `enter`
   * - `enter` defaults to `0`
   * - `exit` defaults to `0`
   *
   * @type {number | { enter?: number, exit?: number, appear?: number }}
   */
  timeout: function timeout(props) {
    var pt = timeoutsShape;
    if (!props.addEndListener) pt = pt.isRequired;
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return pt.apply(void 0, [props].concat(args));
  },
  /**
   * Add a custom transition end trigger. Called with the transitioning
   * DOM node and a `done` callback. Allows for more fine grained transition end
   * logic. Timeouts are still used as a fallback if provided.
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed.
   *
   * ```jsx
   * addEndListener={(node, done) => {
   *   // use the css transitionend event to mark the finish of a transition
   *   node.addEventListener('transitionend', done, false);
   * }}
   * ```
   */
  addEndListener: PropTypes.func,
  /**
   * Callback fired before the "entering" status is applied. An extra parameter
   * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed.
   *
   * @type Function(node: HtmlElement, isAppearing: bool) -> void
   */
  onEnter: PropTypes.func,
  /**
   * Callback fired after the "entering" status is applied. An extra parameter
   * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed.
   *
   * @type Function(node: HtmlElement, isAppearing: bool)
   */
  onEntering: PropTypes.func,
  /**
   * Callback fired after the "entered" status is applied. An extra parameter
   * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed.
   *
   * @type Function(node: HtmlElement, isAppearing: bool) -> void
   */
  onEntered: PropTypes.func,
  /**
   * Callback fired before the "exiting" status is applied.
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed.
   *
   * @type Function(node: HtmlElement) -> void
   */
  onExit: PropTypes.func,
  /**
   * Callback fired after the "exiting" status is applied.
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed.
   *
   * @type Function(node: HtmlElement) -> void
   */
  onExiting: PropTypes.func,
  /**
   * Callback fired after the "exited" status is applied.
   *
   * **Note**: when `nodeRef` prop is passed, `node` is not passed
   *
   * @type Function(node: HtmlElement) -> void
   */
  onExited: PropTypes.func
} ; // Name the function so it is clearer in the documentation

function noop() {}
Transition.defaultProps = {
  in: false,
  mountOnEnter: false,
  unmountOnExit: false,
  appear: false,
  enter: true,
  exit: true,
  onEnter: noop,
  onEntering: noop,
  onEntered: noop,
  onExit: noop,
  onExiting: noop,
  onExited: noop
};
Transition.UNMOUNTED = UNMOUNTED;
Transition.EXITED = EXITED;
Transition.ENTERING = ENTERING;
Transition.ENTERED = ENTERED;
Transition.EXITING = EXITING;
var Transition$1 = Transition;

function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}

/**
 * Given `this.props.children`, return an object mapping key to child.
 *
 * @param {*} children `this.props.children`
 * @return {object} Mapping of key to child
 */

function getChildMapping(children, mapFn) {
  var mapper = function mapper(child) {
    return mapFn && reactExports$1.isValidElement(child) ? mapFn(child) : child;
  };
  var result = Object.create(null);
  if (children) reactExports$1.Children.map(children, function (c) {
    return c;
  }).forEach(function (child) {
    // run the map function here instead so that the key is the computed one
    result[child.key] = mapper(child);
  });
  return result;
}
/**
 * When you're adding or removing children some may be added or removed in the
 * same render pass. We want to show *both* since we want to simultaneously
 * animate elements in and out. This function takes a previous set of keys
 * and a new set of keys and merges them with its best guess of the correct
 * ordering. In the future we may expose some of the utilities in
 * ReactMultiChild to make this easy, but for now React itself does not
 * directly have this concept of the union of prevChildren and nextChildren
 * so we implement it here.
 *
 * @param {object} prev prev children as returned from
 * `ReactTransitionChildMapping.getChildMapping()`.
 * @param {object} next next children as returned from
 * `ReactTransitionChildMapping.getChildMapping()`.
 * @return {object} a key set that contains all keys in `prev` and all keys
 * in `next` in a reasonable order.
 */

function mergeChildMappings(prev, next) {
  prev = prev || {};
  next = next || {};
  function getValueForKey(key) {
    return key in next ? next[key] : prev[key];
  } // For each key of `next`, the list of keys to insert before that key in
  // the combined list

  var nextKeysPending = Object.create(null);
  var pendingKeys = [];
  for (var prevKey in prev) {
    if (prevKey in next) {
      if (pendingKeys.length) {
        nextKeysPending[prevKey] = pendingKeys;
        pendingKeys = [];
      }
    } else {
      pendingKeys.push(prevKey);
    }
  }
  var i;
  var childMapping = {};
  for (var nextKey in next) {
    if (nextKeysPending[nextKey]) {
      for (i = 0; i < nextKeysPending[nextKey].length; i++) {
        var pendingNextKey = nextKeysPending[nextKey][i];
        childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
      }
    }
    childMapping[nextKey] = getValueForKey(nextKey);
  } // Finally, add the keys which didn't appear before any key in `next`

  for (i = 0; i < pendingKeys.length; i++) {
    childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
  }
  return childMapping;
}
function getProp(child, prop, props) {
  return props[prop] != null ? props[prop] : child.props[prop];
}
function getInitialChildMapping(props, onExited) {
  return getChildMapping(props.children, function (child) {
    return reactExports$1.cloneElement(child, {
      onExited: onExited.bind(null, child),
      in: true,
      appear: getProp(child, 'appear', props),
      enter: getProp(child, 'enter', props),
      exit: getProp(child, 'exit', props)
    });
  });
}
function getNextChildMapping(nextProps, prevChildMapping, onExited) {
  var nextChildMapping = getChildMapping(nextProps.children);
  var children = mergeChildMappings(prevChildMapping, nextChildMapping);
  Object.keys(children).forEach(function (key) {
    var child = children[key];
    if (!reactExports$1.isValidElement(child)) return;
    var hasPrev = (key in prevChildMapping);
    var hasNext = (key in nextChildMapping);
    var prevChild = prevChildMapping[key];
    var isLeaving = reactExports$1.isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)

    if (hasNext && (!hasPrev || isLeaving)) {
      // console.log('entering', key)
      children[key] = reactExports$1.cloneElement(child, {
        onExited: onExited.bind(null, child),
        in: true,
        exit: getProp(child, 'exit', nextProps),
        enter: getProp(child, 'enter', nextProps)
      });
    } else if (!hasNext && hasPrev && !isLeaving) {
      // item is old (exiting)
      // console.log('leaving', key)
      children[key] = reactExports$1.cloneElement(child, {
        in: false
      });
    } else if (hasNext && hasPrev && reactExports$1.isValidElement(prevChild)) {
      // item hasn't changed transition states
      // copy over the last transition props;
      // console.log('unchanged', key)
      children[key] = reactExports$1.cloneElement(child, {
        onExited: onExited.bind(null, child),
        in: prevChild.props.in,
        exit: getProp(child, 'exit', nextProps),
        enter: getProp(child, 'enter', nextProps)
      });
    }
  });
  return children;
}

var values = Object.values || function (obj) {
  return Object.keys(obj).map(function (k) {
    return obj[k];
  });
};
var defaultProps$3 = {
  component: 'div',
  childFactory: function childFactory(child) {
    return child;
  }
};
/**
 * The `<TransitionGroup>` component manages a set of transition components
 * (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition
 * components, `<TransitionGroup>` is a state machine for managing the mounting
 * and unmounting of components over time.
 *
 * Consider the example below. As items are removed or added to the TodoList the
 * `in` prop is toggled automatically by the `<TransitionGroup>`.
 *
 * Note that `<TransitionGroup>`  does not define any animation behavior!
 * Exactly _how_ a list item animates is up to the individual transition
 * component. This means you can mix and match animations across different list
 * items.
 */

var TransitionGroup = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose$1(TransitionGroup, _React$Component);
  function TransitionGroup(props, context) {
    var _this;
    _this = _React$Component.call(this, props, context) || this;
    var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear

    _this.state = {
      contextValue: {
        isMounting: true
      },
      handleExited: handleExited,
      firstRender: true
    };
    return _this;
  }
  var _proto = TransitionGroup.prototype;
  _proto.componentDidMount = function componentDidMount() {
    this.mounted = true;
    this.setState({
      contextValue: {
        isMounting: false
      }
    });
  };
  _proto.componentWillUnmount = function componentWillUnmount() {
    this.mounted = false;
  };
  TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {
    var prevChildMapping = _ref.children,
      handleExited = _ref.handleExited,
      firstRender = _ref.firstRender;
    return {
      children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),
      firstRender: false
    };
  } // node is `undefined` when user provided `nodeRef` prop
  ;

  _proto.handleExited = function handleExited(child, node) {
    var currentChildMapping = getChildMapping(this.props.children);
    if (child.key in currentChildMapping) return;
    if (child.props.onExited) {
      child.props.onExited(node);
    }
    if (this.mounted) {
      this.setState(function (state) {
        var children = _extends({}, state.children);
        delete children[child.key];
        return {
          children: children
        };
      });
    }
  };
  _proto.render = function render() {
    var _this$props = this.props,
      Component = _this$props.component,
      childFactory = _this$props.childFactory,
      props = _objectWithoutPropertiesLoose$2(_this$props, ["component", "childFactory"]);
    var contextValue = this.state.contextValue;
    var children = values(this.state.children).map(childFactory);
    delete props.appear;
    delete props.enter;
    delete props.exit;
    if (Component === null) {
      return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {
        value: contextValue
      }, children);
    }
    return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {
      value: contextValue
    }, /*#__PURE__*/React.createElement(Component, props, children));
  };
  return TransitionGroup;
}(React.Component);
TransitionGroup.propTypes = {
  /**
   * `<TransitionGroup>` renders a `<div>` by default. You can change this
   * behavior by providing a `component` prop.
   * If you use React v16+ and would like to avoid a wrapping `<div>` element
   * you can pass in `component={null}`. This is useful if the wrapping div
   * borks your css styles.
   */
  component: PropTypes.any,
  /**
   * A set of `<Transition>` components, that are toggled `in` and out as they
   * leave. the `<TransitionGroup>` will inject specific transition props, so
   * remember to spread them through if you are wrapping the `<Transition>` as
   * with our `<Fade>` example.
   *
   * While this component is meant for multiple `Transition` or `CSSTransition`
   * children, sometimes you may want to have a single transition child with
   * content that you want to be transitioned out and in when you change it
   * (e.g. routes, images etc.) In that case you can change the `key` prop of
   * the transition child as you change its content, this will cause
   * `TransitionGroup` to transition the child out and back in.
   */
  children: PropTypes.node,
  /**
   * A convenience prop that enables or disables appear animations
   * for all children. Note that specifying this will override any defaults set
   * on individual children Transitions.
   */
  appear: PropTypes.bool,
  /**
   * A convenience prop that enables or disables enter animations
   * for all children. Note that specifying this will override any defaults set
   * on individual children Transitions.
   */
  enter: PropTypes.bool,
  /**
   * A convenience prop that enables or disables exit animations
   * for all children. Note that specifying this will override any defaults set
   * on individual children Transitions.
   */
  exit: PropTypes.bool,
  /**
   * You may need to apply reactive updates to a child as it is exiting.
   * This is generally done by using `cloneElement` however in the case of an exiting
   * child the element has already been removed and not accessible to the consumer.
   *
   * If you do need to update a child as it leaves you can provide a `childFactory`
   * to wrap every child, even the ones that are leaving.
   *
   * @type Function(child: ReactElement) -> ReactElement
   */
  childFactory: PropTypes.func
} ;
TransitionGroup.defaultProps = defaultProps$3;
var TransitionGroup$1 = TransitionGroup;

const reflow = node => node.scrollTop;
function getTransitionProps(props, options) {
  var _style$transitionDura, _style$transitionTimi;
  const {
    timeout,
    easing,
    style = {}
  } = props;
  return {
    duration: (_style$transitionDura = style.transitionDuration) != null ? _style$transitionDura : typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,
    easing: (_style$transitionTimi = style.transitionTimingFunction) != null ? _style$transitionTimi : typeof easing === 'object' ? easing[options.mode] : easing,
    delay: style.transitionDelay
  };
}

const _excluded$1p = ["addEndListener", "appear", "children", "easing", "in", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "style", "timeout", "TransitionComponent"];
const styles$3 = {
  entering: {
    opacity: 1
  },
  entered: {
    opacity: 1
  }
};

/**
 * The Fade transition is used by the [Modal](/material-ui/react-modal/) component.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */
const Fade = /*#__PURE__*/reactExports$1.forwardRef(function Fade(props, ref) {
  const theme = useTheme();
  const defaultTimeout = {
    enter: theme.transitions.duration.enteringScreen,
    exit: theme.transitions.duration.leavingScreen
  };
  const {
      addEndListener,
      appear = true,
      children,
      easing,
      in: inProp,
      onEnter,
      onEntered,
      onEntering,
      onExit,
      onExited,
      onExiting,
      style,
      timeout = defaultTimeout,
      // eslint-disable-next-line react/prop-types
      TransitionComponent = Transition$1
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1p);
  const nodeRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(nodeRef, children.ref, ref);
  const normalizedTransitionCallback = callback => maybeIsAppearing => {
    if (callback) {
      const node = nodeRef.current;

      // onEnterXxx and onExitXxx callbacks have a different arguments.length value.
      if (maybeIsAppearing === undefined) {
        callback(node);
      } else {
        callback(node, maybeIsAppearing);
      }
    }
  };
  const handleEntering = normalizedTransitionCallback(onEntering);
  const handleEnter = normalizedTransitionCallback((node, isAppearing) => {
    reflow(node); // So the animation always start from the start.

    const transitionProps = getTransitionProps({
      style,
      timeout,
      easing
    }, {
      mode: 'enter'
    });
    node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
    node.style.transition = theme.transitions.create('opacity', transitionProps);
    if (onEnter) {
      onEnter(node, isAppearing);
    }
  });
  const handleEntered = normalizedTransitionCallback(onEntered);
  const handleExiting = normalizedTransitionCallback(onExiting);
  const handleExit = normalizedTransitionCallback(node => {
    const transitionProps = getTransitionProps({
      style,
      timeout,
      easing
    }, {
      mode: 'exit'
    });
    node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
    node.style.transition = theme.transitions.create('opacity', transitionProps);
    if (onExit) {
      onExit(node);
    }
  });
  const handleExited = normalizedTransitionCallback(onExited);
  const handleAddEndListener = next => {
    if (addEndListener) {
      // Old call signature before `react-transition-group` implemented `nodeRef`
      addEndListener(nodeRef.current, next);
    }
  };
  return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
    appear: appear,
    in: inProp,
    nodeRef: nodeRef ,
    onEnter: handleEnter,
    onEntered: handleEntered,
    onEntering: handleEntering,
    onExit: handleExit,
    onExited: handleExited,
    onExiting: handleExiting,
    addEndListener: handleAddEndListener,
    timeout: timeout
  }, other, {
    children: (state, childProps) => {
      return /*#__PURE__*/reactExports$1.cloneElement(children, _extends({
        style: _extends({
          opacity: 0,
          visibility: state === 'exited' && !inProp ? 'hidden' : undefined
        }, styles$3[state], style, children.props.style),
        ref: handleRef
      }, childProps));
    }
  }));
});
Fade.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Add a custom transition end trigger. Called with the transitioning DOM
   * node and a done callback. Allows for more fine grained transition end
   * logic. Note: Timeouts are still used as a fallback if provided.
   */
  addEndListener: PropTypes.func,
  /**
   * Perform the enter transition when it first mounts if `in` is also `true`.
   * Set this to `false` to disable this behavior.
   * @default true
   */
  appear: PropTypes.bool,
  /**
   * A single child content element.
   */
  children: elementAcceptingRef$1.isRequired,
  /**
   * The transition timing function.
   * You may specify a single easing or a object containing enter and exit values.
   */
  easing: PropTypes.oneOfType([PropTypes.shape({
    enter: PropTypes.string,
    exit: PropTypes.string
  }), PropTypes.string]),
  /**
   * If `true`, the component will transition in.
   */
  in: PropTypes.bool,
  /**
   * @ignore
   */
  onEnter: PropTypes.func,
  /**
   * @ignore
   */
  onEntered: PropTypes.func,
  /**
   * @ignore
   */
  onEntering: PropTypes.func,
  /**
   * @ignore
   */
  onExit: PropTypes.func,
  /**
   * @ignore
   */
  onExited: PropTypes.func,
  /**
   * @ignore
   */
  onExiting: PropTypes.func,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default {
   *   enter: theme.transitions.duration.enteringScreen,
   *   exit: theme.transitions.duration.leavingScreen,
   * }
   */
  timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })])
} ;
var Fade$1 = Fade;

function getBackdropUtilityClass(slot) {
  return generateUtilityClass('MuiBackdrop', slot);
}
generateUtilityClasses('MuiBackdrop', ['root', 'invisible']);

const _excluded$1o = ["children", "className", "component", "components", "componentsProps", "invisible", "open", "slotProps", "slots", "TransitionComponent", "transitionDuration"];
const useUtilityClasses$1b = ownerState => {
  const {
    classes,
    invisible
  } = ownerState;
  const slots = {
    root: ['root', invisible && 'invisible']
  };
  return composeClasses(slots, getBackdropUtilityClass, classes);
};
const BackdropRoot = styled$1('div', {
  name: 'MuiBackdrop',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.invisible && styles.invisible];
  }
})(({
  ownerState
}) => _extends({
  position: 'fixed',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  right: 0,
  bottom: 0,
  top: 0,
  left: 0,
  backgroundColor: 'rgba(0, 0, 0, 0.5)',
  WebkitTapHighlightColor: 'transparent'
}, ownerState.invisible && {
  backgroundColor: 'transparent'
}));
const Backdrop = /*#__PURE__*/reactExports$1.forwardRef(function Backdrop(inProps, ref) {
  var _slotProps$root, _ref, _slots$root;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiBackdrop'
  });
  const {
      children,
      className,
      component = 'div',
      components = {},
      componentsProps = {},
      invisible = false,
      open,
      slotProps = {},
      slots = {},
      TransitionComponent = Fade$1,
      transitionDuration
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1o);
  const ownerState = _extends({}, props, {
    component,
    invisible
  });
  const classes = useUtilityClasses$1b(ownerState);
  const rootSlotProps = (_slotProps$root = slotProps.root) != null ? _slotProps$root : componentsProps.root;
  return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
    in: open,
    timeout: transitionDuration
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(BackdropRoot, _extends({
      "aria-hidden": true
    }, rootSlotProps, {
      as: (_ref = (_slots$root = slots.root) != null ? _slots$root : components.Root) != null ? _ref : component,
      className: clsx(classes.root, className, rootSlotProps == null ? void 0 : rootSlotProps.className),
      ownerState: _extends({}, ownerState, rootSlotProps == null ? void 0 : rootSlotProps.ownerState),
      classes: classes,
      ref: ref,
      children: children
    }))
  }));
});
Backdrop.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    root: PropTypes.object
  }),
  /**
   * If `true`, the backdrop is invisible.
   * It can be used when rendering a popover or a custom select component.
   * @default false
   */
  invisible: PropTypes.bool,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    root: PropTypes.object
  }),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    root: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The component used for the transition.
   * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   * @default Fade
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })])
} ;
var Backdrop$1 = Backdrop;

const _excluded$1n = ["BackdropComponent", "BackdropProps", "classes", "className", "closeAfterTransition", "children", "container", "component", "components", "componentsProps", "disableAutoFocus", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "onBackdropClick", "onClose", "open", "slotProps", "slots", "theme"];
const ModalRoot = styled$1('div', {
  name: 'MuiModal',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, !ownerState.open && ownerState.exited && styles.hidden];
  }
})(({
  theme,
  ownerState
}) => _extends({
  position: 'fixed',
  zIndex: (theme.vars || theme).zIndex.modal,
  right: 0,
  bottom: 0,
  top: 0,
  left: 0
}, !ownerState.open && ownerState.exited && {
  visibility: 'hidden'
}));
const ModalBackdrop = styled$1(Backdrop$1, {
  name: 'MuiModal',
  slot: 'Backdrop',
  overridesResolver: (props, styles) => {
    return styles.backdrop;
  }
})({
  zIndex: -1
});

/**
 * Modal is a lower-level construct that is leveraged by the following components:
 *
 * - [Dialog](/material-ui/api/dialog/)
 * - [Drawer](/material-ui/api/drawer/)
 * - [Menu](/material-ui/api/menu/)
 * - [Popover](/material-ui/api/popover/)
 *
 * If you are creating a modal dialog, you probably want to use the [Dialog](/material-ui/api/dialog/) component
 * rather than directly using Modal.
 *
 * This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
 */
const Modal = /*#__PURE__*/reactExports$1.forwardRef(function Modal(inProps, ref) {
  var _ref, _slots$root, _ref2, _slots$backdrop, _slotProps$root, _slotProps$backdrop;
  const props = useThemeProps({
    name: 'MuiModal',
    props: inProps
  });
  const {
      BackdropComponent = ModalBackdrop,
      BackdropProps,
      classes,
      className,
      closeAfterTransition = false,
      children,
      container,
      component,
      components = {},
      componentsProps = {},
      disableAutoFocus = false,
      disableEnforceFocus = false,
      disableEscapeKeyDown = false,
      disablePortal = false,
      disableRestoreFocus = false,
      disableScrollLock = false,
      hideBackdrop = false,
      keepMounted = false,
      onBackdropClick,
      onClose,
      open,
      slotProps,
      slots,
      // eslint-disable-next-line react/prop-types
      theme
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1n);
  const [exited, setExited] = reactExports$1.useState(true);
  const commonProps = {
    container,
    closeAfterTransition,
    disableAutoFocus,
    disableEnforceFocus,
    disableEscapeKeyDown,
    disablePortal,
    disableRestoreFocus,
    disableScrollLock,
    hideBackdrop,
    keepMounted,
    onBackdropClick,
    onClose,
    open
  };
  const ownerState = _extends({}, props, commonProps, {
    exited
  });
  const RootSlot = (_ref = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : components.Root) != null ? _ref : ModalRoot;
  const BackdropSlot = (_ref2 = (_slots$backdrop = slots == null ? void 0 : slots.backdrop) != null ? _slots$backdrop : components.Backdrop) != null ? _ref2 : BackdropComponent;
  const rootSlotProps = (_slotProps$root = slotProps == null ? void 0 : slotProps.root) != null ? _slotProps$root : componentsProps.root;
  const backdropSlotProps = (_slotProps$backdrop = slotProps == null ? void 0 : slotProps.backdrop) != null ? _slotProps$backdrop : componentsProps.backdrop;
  return /*#__PURE__*/jsxRuntimeExports.jsx(ModalUnstyled, _extends({
    slots: {
      root: RootSlot,
      backdrop: BackdropSlot
    },
    slotProps: {
      root: () => _extends({}, resolveComponentProps(rootSlotProps, ownerState), !isHostComponent(RootSlot) && {
        as: component,
        theme
      }, {
        className: clsx(className, rootSlotProps == null ? void 0 : rootSlotProps.className, classes == null ? void 0 : classes.root, !ownerState.open && ownerState.exited && (classes == null ? void 0 : classes.hidden))
      }),
      backdrop: () => _extends({}, BackdropProps, resolveComponentProps(backdropSlotProps, ownerState), {
        className: clsx(backdropSlotProps == null ? void 0 : backdropSlotProps.className, BackdropProps == null ? void 0 : BackdropProps.className, classes == null ? void 0 : classes.backdrop)
      })
    },
    onTransitionEnter: () => setExited(false),
    onTransitionExited: () => setExited(true),
    ref: ref
  }, other, commonProps, {
    children: children
  }));
});
Modal.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * A backdrop component. This prop enables custom backdrop rendering.
   * @deprecated Use `slots.backdrop` instead. While this prop currently works, it will be removed in the next major version.
   * Use the `slots.backdrop` prop to make your application ready for the next version of Material UI.
   * @default styled(Backdrop, {
   *   name: 'MuiModal',
   *   slot: 'Backdrop',
   *   overridesResolver: (props, styles) => {
   *     return styles.backdrop;
   *   },
   * })({
   *   zIndex: -1,
   * })
   */
  BackdropComponent: PropTypes.elementType,
  /**
   * Props applied to the [`Backdrop`](/material-ui/api/backdrop/) element.
   * @deprecated Use `slotProps.backdrop` instead.
   */
  BackdropProps: PropTypes.object,
  /**
   * A single child content element.
   */
  children: elementAcceptingRef$1.isRequired,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * When set to true the Modal waits until a nested Transition is completed before closing.
   * @default false
   */
  closeAfterTransition: PropTypes.bool,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Backdrop: PropTypes.elementType,
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    backdrop: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * If `true`, the modal will not automatically shift focus to itself when it opens, and
   * replace it to the last focused element when it closes.
   * This also works correctly with any modal children that have the `disableAutoFocus` prop.
   *
   * Generally this should never be set to `true` as it makes the modal less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableAutoFocus: PropTypes.bool,
  /**
   * If `true`, the modal will not prevent focus from leaving the modal while open.
   *
   * Generally this should never be set to `true` as it makes the modal less
   * accessible to assistive technologies, like screen readers.
   * @default false
   */
  disableEnforceFocus: PropTypes.bool,
  /**
   * If `true`, hitting escape will not fire the `onClose` callback.
   * @default false
   */
  disableEscapeKeyDown: PropTypes.bool,
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: PropTypes.bool,
  /**
   * If `true`, the modal will not restore focus to previously focused element once
   * modal is hidden or unmounted.
   * @default false
   */
  disableRestoreFocus: PropTypes.bool,
  /**
   * Disable the scroll lock behavior.
   * @default false
   */
  disableScrollLock: PropTypes.bool,
  /**
   * If `true`, the backdrop is not rendered.
   * @default false
   */
  hideBackdrop: PropTypes.bool,
  /**
   * Always keep the children in the DOM.
   * This prop can be useful in SEO situation or
   * when you want to maximize the responsiveness of the Modal.
   * @default false
   */
  keepMounted: PropTypes.bool,
  /**
   * Callback fired when the backdrop is clicked.
   * @deprecated Use the `onClose` prop with the `reason` argument to handle the `backdropClick` events.
   */
  onBackdropClick: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   * The `reason` parameter can optionally be used to control the response to `onClose`.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
   */
  onClose: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * The props used for each slot inside the Modal.
   * @default {}
   */
  slotProps: PropTypes.shape({
    backdrop: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the Modal.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    backdrop: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var Modal$1 = Modal;

function getSvgIconUtilityClass(slot) {
  return generateUtilityClass('MuiSvgIcon', slot);
}
generateUtilityClasses('MuiSvgIcon', ['root', 'colorPrimary', 'colorSecondary', 'colorAction', 'colorError', 'colorDisabled', 'fontSizeInherit', 'fontSizeSmall', 'fontSizeMedium', 'fontSizeLarge']);

const _excluded$1m = ["children", "className", "color", "component", "fontSize", "htmlColor", "inheritViewBox", "titleAccess", "viewBox"];
const useUtilityClasses$1a = ownerState => {
  const {
    color,
    fontSize,
    classes
  } = ownerState;
  const slots = {
    root: ['root', color !== 'inherit' && `color${capitalize(color)}`, `fontSize${capitalize(fontSize)}`]
  };
  return composeClasses(slots, getSvgIconUtilityClass, classes);
};
const SvgIconRoot = styled$1('svg', {
  name: 'MuiSvgIcon',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize(ownerState.color)}`], styles[`fontSize${capitalize(ownerState.fontSize)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  var _theme$transitions, _theme$transitions$cr, _theme$transitions2, _theme$transitions2$d, _theme$typography, _theme$typography$pxT, _theme$typography2, _theme$typography2$px, _theme$typography3, _theme$typography3$px, _palette$ownerState$c, _palette, _palette$ownerState$c2, _palette2, _palette2$action, _palette3, _palette3$action;
  return {
    userSelect: 'none',
    width: '1em',
    height: '1em',
    display: 'inline-block',
    fill: 'currentColor',
    flexShrink: 0,
    transition: (_theme$transitions = theme.transitions) == null ? void 0 : (_theme$transitions$cr = _theme$transitions.create) == null ? void 0 : _theme$transitions$cr.call(_theme$transitions, 'fill', {
      duration: (_theme$transitions2 = theme.transitions) == null ? void 0 : (_theme$transitions2$d = _theme$transitions2.duration) == null ? void 0 : _theme$transitions2$d.shorter
    }),
    fontSize: {
      inherit: 'inherit',
      small: ((_theme$typography = theme.typography) == null ? void 0 : (_theme$typography$pxT = _theme$typography.pxToRem) == null ? void 0 : _theme$typography$pxT.call(_theme$typography, 20)) || '1.25rem',
      medium: ((_theme$typography2 = theme.typography) == null ? void 0 : (_theme$typography2$px = _theme$typography2.pxToRem) == null ? void 0 : _theme$typography2$px.call(_theme$typography2, 24)) || '1.5rem',
      large: ((_theme$typography3 = theme.typography) == null ? void 0 : (_theme$typography3$px = _theme$typography3.pxToRem) == null ? void 0 : _theme$typography3$px.call(_theme$typography3, 35)) || '2.1875rem'
    }[ownerState.fontSize],
    // TODO v5 deprecate, v6 remove for sx
    color: (_palette$ownerState$c = (_palette = (theme.vars || theme).palette) == null ? void 0 : (_palette$ownerState$c2 = _palette[ownerState.color]) == null ? void 0 : _palette$ownerState$c2.main) != null ? _palette$ownerState$c : {
      action: (_palette2 = (theme.vars || theme).palette) == null ? void 0 : (_palette2$action = _palette2.action) == null ? void 0 : _palette2$action.active,
      disabled: (_palette3 = (theme.vars || theme).palette) == null ? void 0 : (_palette3$action = _palette3.action) == null ? void 0 : _palette3$action.disabled,
      inherit: undefined
    }[ownerState.color]
  };
});
const SvgIcon = /*#__PURE__*/reactExports$1.forwardRef(function SvgIcon(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiSvgIcon'
  });
  const {
      children,
      className,
      color = 'inherit',
      component = 'svg',
      fontSize = 'medium',
      htmlColor,
      inheritViewBox = false,
      titleAccess,
      viewBox = '0 0 24 24'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1m);
  const ownerState = _extends({}, props, {
    color,
    component,
    fontSize,
    instanceFontSize: inProps.fontSize,
    inheritViewBox,
    viewBox
  });
  const more = {};
  if (!inheritViewBox) {
    more.viewBox = viewBox;
  }
  const classes = useUtilityClasses$1a(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(SvgIconRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    focusable: "false",
    color: htmlColor,
    "aria-hidden": titleAccess ? undefined : true,
    role: titleAccess ? 'img' : undefined,
    ref: ref
  }, more, other, {
    ownerState: ownerState,
    children: [children, titleAccess ? /*#__PURE__*/jsxRuntimeExports.jsx("title", {
      children: titleAccess
    }) : null]
  }));
});
SvgIcon.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Node passed into the SVG element.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * You can use the `htmlColor` prop to apply a color attribute to the SVG element.
   * @default 'inherit'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'action', 'disabled', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size.
   * @default 'medium'
   */
  fontSize: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'large', 'medium', 'small']), PropTypes.string]),
  /**
   * Applies a color attribute to the SVG element.
   */
  htmlColor: PropTypes.string,
  /**
   * If `true`, the root node will inherit the custom `component`'s viewBox and the `viewBox`
   * prop will be ignored.
   * Useful when you want to reference a custom `component` and have `SvgIcon` pass that
   * `component`'s viewBox to the root node.
   * @default false
   */
  inheritViewBox: PropTypes.bool,
  /**
   * The shape-rendering attribute. The behavior of the different options is described on the
   * [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering).
   * If you are having issues with blurry icons you should investigate this prop.
   */
  shapeRendering: PropTypes.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Provides a human-readable title for the element that contains it.
   * https://www.w3.org/TR/SVG-access/#Equivalent
   */
  titleAccess: PropTypes.string,
  /**
   * Allows you to redefine what the coordinates without units mean inside an SVG element.
   * For example, if the SVG element is 500 (width) by 200 (height),
   * and you pass viewBox="0 0 50 20",
   * this means that the coordinates inside the SVG will go from the top left corner (0,0)
   * to bottom right (50,20) and each unit will be worth 10px.
   * @default '0 0 24 24'
   */
  viewBox: PropTypes.string
} ;
SvgIcon.muiName = 'SvgIcon';
var SvgIcon$1 = SvgIcon;

function createSvgIcon$1(path, displayName) {
  function Component(props, ref) {
    return /*#__PURE__*/jsxRuntimeExports.jsx(SvgIcon$1, _extends({
      "data-testid": `${displayName}Icon`,
      ref: ref
    }, props, {
      children: path
    }));
  }
  {
    // Need to set `displayName` on the inner component for React.memo.
    // React prior to 16.14 ignores `displayName` on the wrapper.
    Component.displayName = `${displayName}Icon`;
  }
  Component.muiName = SvgIcon$1.muiName;
  return /*#__PURE__*/reactExports$1.memo( /*#__PURE__*/reactExports$1.forwardRef(Component));
}

// TODO: remove this export once ClassNameGenerator is stable
// eslint-disable-next-line @typescript-eslint/naming-convention
const unstable_ClassNameGenerator = {
  configure: generator => {
    {
      console.warn(['MUI: `ClassNameGenerator` import from `@mui/material/utils` is outdated and might cause unexpected issues.', '', "You should use `import { unstable_ClassNameGenerator } from '@mui/material/className'` instead", '', 'The detail of the issue: https://github.com/mui/material-ui/issues/30011#issuecomment-1024993401', '', 'The updated documentation: https://mui.com/guides/classname-generator/'].join('\n'));
    }
    ClassNameGenerator$1.configure(generator);
  }
};

var muiMaterialUtils = /*#__PURE__*/Object.freeze({
  __proto__: null,
  capitalize: capitalize,
  createChainedFunction: createChainedFunction,
  createSvgIcon: createSvgIcon$1,
  debounce: debounce$1,
  deprecatedPropType: deprecatedPropType,
  isMuiElement: isMuiElement,
  ownerDocument: ownerDocument,
  ownerWindow: ownerWindow,
  requirePropFactory: requirePropFactory,
  setRef: setRef,
  unstable_ClassNameGenerator: unstable_ClassNameGenerator,
  unstable_useEnhancedEffect: useEnhancedEffect$1,
  unstable_useId: useId,
  unsupportedProp: unsupportedProp,
  useControlled: useControlled,
  useEventCallback: useEventCallback,
  useForkRef: useForkRef,
  useIsFocusVisible: useIsFocusVisible
});

const _excluded$1l = ["addEndListener", "appear", "children", "container", "direction", "easing", "in", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "style", "timeout", "TransitionComponent"];
function getTranslateValue(direction, node, resolvedContainer) {
  const rect = node.getBoundingClientRect();
  const containerRect = resolvedContainer && resolvedContainer.getBoundingClientRect();
  const containerWindow = ownerWindow(node);
  let transform;
  if (node.fakeTransform) {
    transform = node.fakeTransform;
  } else {
    const computedStyle = containerWindow.getComputedStyle(node);
    transform = computedStyle.getPropertyValue('-webkit-transform') || computedStyle.getPropertyValue('transform');
  }
  let offsetX = 0;
  let offsetY = 0;
  if (transform && transform !== 'none' && typeof transform === 'string') {
    const transformValues = transform.split('(')[1].split(')')[0].split(',');
    offsetX = parseInt(transformValues[4], 10);
    offsetY = parseInt(transformValues[5], 10);
  }
  if (direction === 'left') {
    if (containerRect) {
      return `translateX(${containerRect.right + offsetX - rect.left}px)`;
    }
    return `translateX(${containerWindow.innerWidth + offsetX - rect.left}px)`;
  }
  if (direction === 'right') {
    if (containerRect) {
      return `translateX(-${rect.right - containerRect.left - offsetX}px)`;
    }
    return `translateX(-${rect.left + rect.width - offsetX}px)`;
  }
  if (direction === 'up') {
    if (containerRect) {
      return `translateY(${containerRect.bottom + offsetY - rect.top}px)`;
    }
    return `translateY(${containerWindow.innerHeight + offsetY - rect.top}px)`;
  }

  // direction === 'down'
  if (containerRect) {
    return `translateY(-${rect.top - containerRect.top + rect.height - offsetY}px)`;
  }
  return `translateY(-${rect.top + rect.height - offsetY}px)`;
}
function resolveContainer(containerPropProp) {
  return typeof containerPropProp === 'function' ? containerPropProp() : containerPropProp;
}
function setTranslateValue(direction, node, containerProp) {
  const resolvedContainer = resolveContainer(containerProp);
  const transform = getTranslateValue(direction, node, resolvedContainer);
  if (transform) {
    node.style.webkitTransform = transform;
    node.style.transform = transform;
  }
}

/**
 * The Slide transition is used by the [Drawer](/material-ui/react-drawer/) component.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */
const Slide = /*#__PURE__*/reactExports$1.forwardRef(function Slide(props, ref) {
  const theme = useTheme();
  const defaultEasing = {
    enter: theme.transitions.easing.easeOut,
    exit: theme.transitions.easing.sharp
  };
  const defaultTimeout = {
    enter: theme.transitions.duration.enteringScreen,
    exit: theme.transitions.duration.leavingScreen
  };
  const {
      addEndListener,
      appear = true,
      children,
      container: containerProp,
      direction = 'down',
      easing: easingProp = defaultEasing,
      in: inProp,
      onEnter,
      onEntered,
      onEntering,
      onExit,
      onExited,
      onExiting,
      style,
      timeout = defaultTimeout,
      // eslint-disable-next-line react/prop-types
      TransitionComponent = Transition$1
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1l);
  const childrenRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(children.ref, childrenRef, ref);
  const normalizedTransitionCallback = callback => isAppearing => {
    if (callback) {
      // onEnterXxx and onExitXxx callbacks have a different arguments.length value.
      if (isAppearing === undefined) {
        callback(childrenRef.current);
      } else {
        callback(childrenRef.current, isAppearing);
      }
    }
  };
  const handleEnter = normalizedTransitionCallback((node, isAppearing) => {
    setTranslateValue(direction, node, containerProp);
    reflow(node);
    if (onEnter) {
      onEnter(node, isAppearing);
    }
  });
  const handleEntering = normalizedTransitionCallback((node, isAppearing) => {
    const transitionProps = getTransitionProps({
      timeout,
      style,
      easing: easingProp
    }, {
      mode: 'enter'
    });
    node.style.webkitTransition = theme.transitions.create('-webkit-transform', _extends({}, transitionProps));
    node.style.transition = theme.transitions.create('transform', _extends({}, transitionProps));
    node.style.webkitTransform = 'none';
    node.style.transform = 'none';
    if (onEntering) {
      onEntering(node, isAppearing);
    }
  });
  const handleEntered = normalizedTransitionCallback(onEntered);
  const handleExiting = normalizedTransitionCallback(onExiting);
  const handleExit = normalizedTransitionCallback(node => {
    const transitionProps = getTransitionProps({
      timeout,
      style,
      easing: easingProp
    }, {
      mode: 'exit'
    });
    node.style.webkitTransition = theme.transitions.create('-webkit-transform', transitionProps);
    node.style.transition = theme.transitions.create('transform', transitionProps);
    setTranslateValue(direction, node, containerProp);
    if (onExit) {
      onExit(node);
    }
  });
  const handleExited = normalizedTransitionCallback(node => {
    // No need for transitions when the component is hidden
    node.style.webkitTransition = '';
    node.style.transition = '';
    if (onExited) {
      onExited(node);
    }
  });
  const handleAddEndListener = next => {
    if (addEndListener) {
      // Old call signature before `react-transition-group` implemented `nodeRef`
      addEndListener(childrenRef.current, next);
    }
  };
  const updatePosition = reactExports$1.useCallback(() => {
    if (childrenRef.current) {
      setTranslateValue(direction, childrenRef.current, containerProp);
    }
  }, [direction, containerProp]);
  reactExports$1.useEffect(() => {
    // Skip configuration where the position is screen size invariant.
    if (inProp || direction === 'down' || direction === 'right') {
      return undefined;
    }
    const handleResize = debounce$1(() => {
      if (childrenRef.current) {
        setTranslateValue(direction, childrenRef.current, containerProp);
      }
    });
    const containerWindow = ownerWindow(childrenRef.current);
    containerWindow.addEventListener('resize', handleResize);
    return () => {
      handleResize.clear();
      containerWindow.removeEventListener('resize', handleResize);
    };
  }, [direction, inProp, containerProp]);
  reactExports$1.useEffect(() => {
    if (!inProp) {
      // We need to update the position of the drawer when the direction change and
      // when it's hidden.
      updatePosition();
    }
  }, [inProp, updatePosition]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
    nodeRef: childrenRef,
    onEnter: handleEnter,
    onEntered: handleEntered,
    onEntering: handleEntering,
    onExit: handleExit,
    onExited: handleExited,
    onExiting: handleExiting,
    addEndListener: handleAddEndListener,
    appear: appear,
    in: inProp,
    timeout: timeout
  }, other, {
    children: (state, childProps) => {
      return /*#__PURE__*/reactExports$1.cloneElement(children, _extends({
        ref: handleRef,
        style: _extends({
          visibility: state === 'exited' && !inProp ? 'hidden' : undefined
        }, style, children.props.style)
      }, childProps));
    }
  }));
});
Slide.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Add a custom transition end trigger. Called with the transitioning DOM
   * node and a done callback. Allows for more fine grained transition end
   * logic. Note: Timeouts are still used as a fallback if provided.
   */
  addEndListener: PropTypes.func,
  /**
   * Perform the enter transition when it first mounts if `in` is also `true`.
   * Set this to `false` to disable this behavior.
   * @default true
   */
  appear: PropTypes.bool,
  /**
   * A single child content element.
   */
  children: elementAcceptingRef$1.isRequired,
  /**
   * An HTML element, or a function that returns one.
   * It's used to set the container the Slide is transitioning from.
   */
  container: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.func]), props => {
    if (props.open) {
      const resolvedContainer = resolveContainer(props.container);
      if (resolvedContainer && resolvedContainer.nodeType === 1) {
        const box = resolvedContainer.getBoundingClientRect();
        if (box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
          return new Error(['MUI: The `container` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
        }
      } else if (!resolvedContainer || typeof resolvedContainer.getBoundingClientRect !== 'function' || resolvedContainer.contextElement != null && resolvedContainer.contextElement.nodeType !== 1) {
        return new Error(['MUI: The `container` prop provided to the component is invalid.', 'It should be an HTML element instance.'].join('\n'));
      }
    }
    return null;
  }),
  /**
   * Direction the child node will enter from.
   * @default 'down'
   */
  direction: PropTypes.oneOf(['down', 'left', 'right', 'up']),
  /**
   * The transition timing function.
   * You may specify a single easing or a object containing enter and exit values.
   * @default {
   *   enter: theme.transitions.easing.easeOut,
   *   exit: theme.transitions.easing.sharp,
   * }
   */
  easing: PropTypes.oneOfType([PropTypes.shape({
    enter: PropTypes.string,
    exit: PropTypes.string
  }), PropTypes.string]),
  /**
   * If `true`, the component will transition in.
   */
  in: PropTypes.bool,
  /**
   * @ignore
   */
  onEnter: PropTypes.func,
  /**
   * @ignore
   */
  onEntered: PropTypes.func,
  /**
   * @ignore
   */
  onEntering: PropTypes.func,
  /**
   * @ignore
   */
  onExit: PropTypes.func,
  /**
   * @ignore
   */
  onExited: PropTypes.func,
  /**
   * @ignore
   */
  onExiting: PropTypes.func,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default {
   *   enter: theme.transitions.duration.enteringScreen,
   *   exit: theme.transitions.duration.leavingScreen,
   * }
   */
  timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })])
} ;
var Slide$1 = Slide;

function getDrawerUtilityClass(slot) {
  return generateUtilityClass('MuiDrawer', slot);
}
generateUtilityClasses('MuiDrawer', ['root', 'docked', 'paper', 'paperAnchorLeft', 'paperAnchorRight', 'paperAnchorTop', 'paperAnchorBottom', 'paperAnchorDockedLeft', 'paperAnchorDockedRight', 'paperAnchorDockedTop', 'paperAnchorDockedBottom', 'modal']);

const _excluded$1k = ["BackdropProps"],
  _excluded2$5 = ["anchor", "BackdropProps", "children", "className", "elevation", "hideBackdrop", "ModalProps", "onClose", "open", "PaperProps", "SlideProps", "TransitionComponent", "transitionDuration", "variant"];
const overridesResolver$2 = (props, styles) => {
  const {
    ownerState
  } = props;
  return [styles.root, (ownerState.variant === 'permanent' || ownerState.variant === 'persistent') && styles.docked, styles.modal];
};
const useUtilityClasses$19 = ownerState => {
  const {
    classes,
    anchor,
    variant
  } = ownerState;
  const slots = {
    root: ['root'],
    docked: [(variant === 'permanent' || variant === 'persistent') && 'docked'],
    modal: ['modal'],
    paper: ['paper', `paperAnchor${capitalize(anchor)}`, variant !== 'temporary' && `paperAnchorDocked${capitalize(anchor)}`]
  };
  return composeClasses(slots, getDrawerUtilityClass, classes);
};
const DrawerRoot = styled$1(Modal$1, {
  name: 'MuiDrawer',
  slot: 'Root',
  overridesResolver: overridesResolver$2
})(({
  theme
}) => ({
  zIndex: (theme.vars || theme).zIndex.drawer
}));
const DrawerDockedRoot = styled$1('div', {
  shouldForwardProp: rootShouldForwardProp,
  name: 'MuiDrawer',
  slot: 'Docked',
  skipVariantsResolver: false,
  overridesResolver: overridesResolver$2
})({
  flex: '0 0 auto'
});
const DrawerPaper = styled$1(Paper$1, {
  name: 'MuiDrawer',
  slot: 'Paper',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.paper, styles[`paperAnchor${capitalize(ownerState.anchor)}`], ownerState.variant !== 'temporary' && styles[`paperAnchorDocked${capitalize(ownerState.anchor)}`]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  overflowY: 'auto',
  display: 'flex',
  flexDirection: 'column',
  height: '100%',
  flex: '1 0 auto',
  zIndex: (theme.vars || theme).zIndex.drawer,
  // Add iOS momentum scrolling for iOS < 13.0
  WebkitOverflowScrolling: 'touch',
  // temporary style
  position: 'fixed',
  top: 0,
  // We disable the focus ring for mouse, touch and keyboard users.
  // At some point, it would be better to keep it for keyboard users.
  // :focus-ring CSS pseudo-class will help.
  outline: 0
}, ownerState.anchor === 'left' && {
  left: 0
}, ownerState.anchor === 'top' && {
  top: 0,
  left: 0,
  right: 0,
  height: 'auto',
  maxHeight: '100%'
}, ownerState.anchor === 'right' && {
  right: 0
}, ownerState.anchor === 'bottom' && {
  top: 'auto',
  left: 0,
  bottom: 0,
  right: 0,
  height: 'auto',
  maxHeight: '100%'
}, ownerState.anchor === 'left' && ownerState.variant !== 'temporary' && {
  borderRight: `1px solid ${(theme.vars || theme).palette.divider}`
}, ownerState.anchor === 'top' && ownerState.variant !== 'temporary' && {
  borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`
}, ownerState.anchor === 'right' && ownerState.variant !== 'temporary' && {
  borderLeft: `1px solid ${(theme.vars || theme).palette.divider}`
}, ownerState.anchor === 'bottom' && ownerState.variant !== 'temporary' && {
  borderTop: `1px solid ${(theme.vars || theme).palette.divider}`
}));
const oppositeDirection = {
  left: 'right',
  right: 'left',
  top: 'down',
  bottom: 'up'
};
function isHorizontal(anchor) {
  return ['left', 'right'].indexOf(anchor) !== -1;
}
function getAnchor(theme, anchor) {
  return theme.direction === 'rtl' && isHorizontal(anchor) ? oppositeDirection[anchor] : anchor;
}

/**
 * The props of the [Modal](/material-ui/api/modal/) component are available
 * when `variant="temporary"` is set.
 */
const Drawer = /*#__PURE__*/reactExports$1.forwardRef(function Drawer(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiDrawer'
  });
  const theme = useTheme();
  const defaultTransitionDuration = {
    enter: theme.transitions.duration.enteringScreen,
    exit: theme.transitions.duration.leavingScreen
  };
  const {
      anchor: anchorProp = 'left',
      BackdropProps,
      children,
      className,
      elevation = 16,
      hideBackdrop = false,
      ModalProps: {
        BackdropProps: BackdropPropsProp
      } = {},
      onClose,
      open = false,
      PaperProps = {},
      SlideProps,
      // eslint-disable-next-line react/prop-types
      TransitionComponent = Slide$1,
      transitionDuration = defaultTransitionDuration,
      variant = 'temporary'
    } = props,
    ModalProps = _objectWithoutPropertiesLoose$2(props.ModalProps, _excluded$1k),
    other = _objectWithoutPropertiesLoose$2(props, _excluded2$5);

  // Let's assume that the Drawer will always be rendered on user space.
  // We use this state is order to skip the appear transition during the
  // initial mount of the component.
  const mounted = reactExports$1.useRef(false);
  reactExports$1.useEffect(() => {
    mounted.current = true;
  }, []);
  const anchorInvariant = getAnchor(theme, anchorProp);
  const anchor = anchorProp;
  const ownerState = _extends({}, props, {
    anchor,
    elevation,
    open,
    variant
  }, other);
  const classes = useUtilityClasses$19(ownerState);
  const drawer = /*#__PURE__*/jsxRuntimeExports.jsx(DrawerPaper, _extends({
    elevation: variant === 'temporary' ? elevation : 0,
    square: true
  }, PaperProps, {
    className: clsx(classes.paper, PaperProps.className),
    ownerState: ownerState,
    children: children
  }));
  if (variant === 'permanent') {
    return /*#__PURE__*/jsxRuntimeExports.jsx(DrawerDockedRoot, _extends({
      className: clsx(classes.root, classes.docked, className),
      ownerState: ownerState,
      ref: ref
    }, other, {
      children: drawer
    }));
  }
  const slidingDrawer = /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
    in: open,
    direction: oppositeDirection[anchorInvariant],
    timeout: transitionDuration,
    appear: mounted.current
  }, SlideProps, {
    children: drawer
  }));
  if (variant === 'persistent') {
    return /*#__PURE__*/jsxRuntimeExports.jsx(DrawerDockedRoot, _extends({
      className: clsx(classes.root, classes.docked, className),
      ownerState: ownerState,
      ref: ref
    }, other, {
      children: slidingDrawer
    }));
  }

  // variant === temporary
  return /*#__PURE__*/jsxRuntimeExports.jsx(DrawerRoot, _extends({
    BackdropProps: _extends({}, BackdropProps, BackdropPropsProp, {
      transitionDuration
    }),
    className: clsx(classes.root, classes.modal, className),
    open: open,
    ownerState: ownerState,
    onClose: onClose,
    hideBackdrop: hideBackdrop,
    ref: ref
  }, other, ModalProps, {
    children: slidingDrawer
  }));
});
Drawer.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Side from which the drawer will appear.
   * @default 'left'
   */
  anchor: PropTypes.oneOf(['bottom', 'left', 'right', 'top']),
  /**
   * @ignore
   */
  BackdropProps: PropTypes.object,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The elevation of the drawer.
   * @default 16
   */
  elevation: integerPropType,
  /**
   * If `true`, the backdrop is not rendered.
   * @default false
   */
  hideBackdrop: PropTypes.bool,
  /**
   * Props applied to the [`Modal`](/material-ui/api/modal/) element.
   * @default {}
   */
  ModalProps: PropTypes.object,
  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   */
  onClose: PropTypes.func,
  /**
   * If `true`, the component is shown.
   * @default false
   */
  open: PropTypes.bool,
  /**
   * Props applied to the [`Paper`](/material-ui/api/paper/) element.
   * @default {}
   */
  PaperProps: PropTypes.object,
  /**
   * Props applied to the [`Slide`](/material-ui/api/slide/) element.
   */
  SlideProps: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default {
   *   enter: theme.transitions.duration.enteringScreen,
   *   exit: theme.transitions.duration.leavingScreen,
   * }
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })]),
  /**
   * The variant to use.
   * @default 'temporary'
   */
  variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary'])
} ;
var Drawer$1 = Drawer;

function NavMenuPopup({
  open,
  onClose
}) {
  const title = useSiteTitle(),
    {
      NavMenu
    } = useViewComponents(),
    {
      Logo
    } = useComponents();
  return /*#__PURE__*/React.createElement(Drawer$1, {
    open: open,
    onClose: onClose,
    anchor: "left",
    keepMounted: true,
    PaperProps: {
      style: {
        maxWidth: "80%",
        width: 500
      }
    }
  }, /*#__PURE__*/React.createElement(AppBar$1, {
    position: "static",
    color: "default",
    style: {
      borderBottom: "1px solid #999"
    }
  }, /*#__PURE__*/React.createElement(Toolbar$1, {
    variant: "regular"
  }, /*#__PURE__*/React.createElement(Logo, {
    edge: "start"
  }), /*#__PURE__*/React.createElement(Typography$1, {
    variant: "h6"
  }, title))), /*#__PURE__*/React.createElement(NavMenu, {
    onNavigate: onClose
  }));
}

function NavMenuFixed() {
  const {
      NavMenu,
      Index
    } = useViewComponents(),
    {
      name
    } = useRouteInfo(),
    fixedMenu = useMinWidth(600);
  if (!fixedMenu) {
    return null;
  }
  if (name === "index" && NavMenu === Index) {
    return null;
  }
  return /*#__PURE__*/React.createElement(Paper$1, {
    elevation: 2,
    square: true,
    sx: {
      minWidth: 180,
      width: "25%",
      maxWidth: 360,
      display: "flex",
      flexDirection: "column",
      zIndex: 600
    }
  }, /*#__PURE__*/React.createElement(NavMenu, null));
}

function Main({
  children
}) {
  return /*#__PURE__*/React.createElement(Box$1, {
    component: "main",
    sx: {
      flex: "1",
      display: "flex",
      overflowY: "hidden"
    }
  }, children);
}
Main.propTypes = {
  children: PropTypes.node
};

function Footer() {
  const {
    Typography,
    FooterContent
  } = useComponents();
  return /*#__PURE__*/React.createElement("div", {
    style: {
      height: "3em",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      backgroundColor: "white",
      borderTop: "1px solid rgba(0, 0, 0, 0.12)"
    }
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "caption",
    color: "textSecondary"
  }, /*#__PURE__*/React.createElement(FooterContent, null)));
}

function FooterContent() {
  const {
    Link
  } = useComponents();
  return /*#__PURE__*/React.createElement(React.Fragment, null, "Powered by", " ", /*#__PURE__*/React.createElement(Link, {
    component: "a",
    href: "https://wq.io/",
    target: "_blank"
  }, "wq"));
}

function View(props) {
  return /*#__PURE__*/React.createElement(Box$1, {
    ...props,
    sx: {
      position: "relative",
      ...props.sx
    }
  });
}

function ScrollView({
  children,
  style
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      overflowX: "hidden",
      overflowY: "auto",
      flex: 1,
      ...style
    }
  }, children);
}
ScrollView.propTypes = {
  children: PropTypes.node,
  style: PropTypes.object
};

function HorizontalView({
  children,
  ...rest
}) {
  return /*#__PURE__*/React.createElement(Box$1, {
    ...rest,
    sx: {
      display: "flex",
      justifyContent: "space-between",
      alignItems: "center",
      p: 1,
      ...rest.sx
    }
  }, children);
}
HorizontalView.propTypes = {
  children: PropTypes.node
};

var Fragment = reactExports$1.Fragment;

function FormatJson({
  json
}) {
  return /*#__PURE__*/React.createElement("pre", null, /*#__PURE__*/React.createElement("code", null, JSON.stringify(json, null, 4)));
}
FormatJson.propTypes = {
  json: PropTypes.object
};

function getLinkUtilityClass(slot) {
  return generateUtilityClass('MuiLink', slot);
}
const linkClasses = generateUtilityClasses('MuiLink', ['root', 'underlineNone', 'underlineHover', 'underlineAlways', 'button', 'focusVisible']);
var linkClasses$1 = linkClasses;

const colorTransformations = {
  primary: 'primary.main',
  textPrimary: 'text.primary',
  secondary: 'secondary.main',
  textSecondary: 'text.secondary',
  error: 'error.main'
};
const transformDeprecatedColors = color => {
  return colorTransformations[color] || color;
};
const getTextDecoration = ({
  theme,
  ownerState
}) => {
  const transformedColor = transformDeprecatedColors(ownerState.color);
  const color = getPath(theme, `palette.${transformedColor}`, false) || ownerState.color;
  const channelColor = getPath(theme, `palette.${transformedColor}Channel`);
  if ('vars' in theme && channelColor) {
    return `rgba(${channelColor} / 0.4)`;
  }
  return alpha(color, 0.4);
};
var getTextDecoration$1 = getTextDecoration;

const _excluded$1j = ["className", "color", "component", "onBlur", "onFocus", "TypographyClasses", "underline", "variant", "sx"];
const useUtilityClasses$18 = ownerState => {
  const {
    classes,
    component,
    focusVisible,
    underline
  } = ownerState;
  const slots = {
    root: ['root', `underline${capitalize(underline)}`, component === 'button' && 'button', focusVisible && 'focusVisible']
  };
  return composeClasses(slots, getLinkUtilityClass, classes);
};
const LinkRoot = styled$1(Typography$1, {
  name: 'MuiLink',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`underline${capitalize(ownerState.underline)}`], ownerState.component === 'button' && styles.button];
  }
})(({
  theme,
  ownerState
}) => {
  return _extends({}, ownerState.underline === 'none' && {
    textDecoration: 'none'
  }, ownerState.underline === 'hover' && {
    textDecoration: 'none',
    '&:hover': {
      textDecoration: 'underline'
    }
  }, ownerState.underline === 'always' && _extends({
    textDecoration: 'underline'
  }, ownerState.color !== 'inherit' && {
    textDecorationColor: getTextDecoration$1({
      theme,
      ownerState
    })
  }, {
    '&:hover': {
      textDecorationColor: 'inherit'
    }
  }), ownerState.component === 'button' && {
    position: 'relative',
    WebkitTapHighlightColor: 'transparent',
    backgroundColor: 'transparent',
    // Reset default value
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,
    border: 0,
    margin: 0,
    // Remove the margin in Safari
    borderRadius: 0,
    padding: 0,
    // Remove the padding in Firefox
    cursor: 'pointer',
    userSelect: 'none',
    verticalAlign: 'middle',
    MozAppearance: 'none',
    // Reset
    WebkitAppearance: 'none',
    // Reset
    '&::-moz-focus-inner': {
      borderStyle: 'none' // Remove Firefox dotted outline.
    },

    [`&.${linkClasses$1.focusVisible}`]: {
      outline: 'auto'
    }
  });
});
const Link$1 = /*#__PURE__*/reactExports$1.forwardRef(function Link(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiLink'
  });
  const {
      className,
      color = 'primary',
      component = 'a',
      onBlur,
      onFocus,
      TypographyClasses,
      underline = 'always',
      variant = 'inherit',
      sx
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1j);
  const {
    isFocusVisibleRef,
    onBlur: handleBlurVisible,
    onFocus: handleFocusVisible,
    ref: focusVisibleRef
  } = useIsFocusVisible();
  const [focusVisible, setFocusVisible] = reactExports$1.useState(false);
  const handlerRef = useForkRef(ref, focusVisibleRef);
  const handleBlur = event => {
    handleBlurVisible(event);
    if (isFocusVisibleRef.current === false) {
      setFocusVisible(false);
    }
    if (onBlur) {
      onBlur(event);
    }
  };
  const handleFocus = event => {
    handleFocusVisible(event);
    if (isFocusVisibleRef.current === true) {
      setFocusVisible(true);
    }
    if (onFocus) {
      onFocus(event);
    }
  };
  const ownerState = _extends({}, props, {
    color,
    component,
    focusVisible,
    underline,
    variant
  });
  const classes = useUtilityClasses$18(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(LinkRoot, _extends({
    color: color,
    className: clsx(classes.root, className),
    classes: TypographyClasses,
    component: component,
    onBlur: handleBlur,
    onFocus: handleFocus,
    ref: handlerRef,
    ownerState: ownerState,
    variant: variant,
    sx: [...(!Object.keys(colorTransformations).includes(color) ? [{
      color
    }] : []), ...(Array.isArray(sx) ? sx : [sx])]
  }, other));
});
Link$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the link.
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.any,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: elementTypeAcceptingRef$1,
  /**
   * @ignore
   */
  onBlur: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * `classes` prop applied to the [`Typography`](/material-ui/api/typography/) element.
   */
  TypographyClasses: PropTypes.object,
  /**
   * Controls when the link should have an underline.
   * @default 'always'
   */
  underline: PropTypes.oneOf(['always', 'hover', 'none']),
  /**
   * Applies the theme typography styles.
   * @default 'inherit'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['body1', 'body2', 'button', 'caption', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'inherit', 'overline', 'subtitle1', 'subtitle2']), PropTypes.string])
} ;
var Link$2 = Link$1;

function Link(props) {
  return /*#__PURE__*/React.createElement(Link$2, {
    component: Link$3,
    ...props
  });
}

function Ripple(props) {
  const {
    className,
    classes,
    pulsate = false,
    rippleX,
    rippleY,
    rippleSize,
    in: inProp,
    onExited,
    timeout
  } = props;
  const [leaving, setLeaving] = reactExports$1.useState(false);
  const rippleClassName = clsx(className, classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);
  const rippleStyles = {
    width: rippleSize,
    height: rippleSize,
    top: -(rippleSize / 2) + rippleY,
    left: -(rippleSize / 2) + rippleX
  };
  const childClassName = clsx(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);
  if (!inProp && !leaving) {
    setLeaving(true);
  }
  reactExports$1.useEffect(() => {
    if (!inProp && onExited != null) {
      // react-transition-group#onExited
      const timeoutId = setTimeout(onExited, timeout);
      return () => {
        clearTimeout(timeoutId);
      };
    }
    return undefined;
  }, [onExited, inProp, timeout]);
  return /*#__PURE__*/jsxRuntimeExports.jsx("span", {
    className: rippleClassName,
    style: rippleStyles,
    children: /*#__PURE__*/jsxRuntimeExports.jsx("span", {
      className: childClassName
    })
  });
}
Ripple.propTypes = {
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object.isRequired,
  className: PropTypes.string,
  /**
   * @ignore - injected from TransitionGroup
   */
  in: PropTypes.bool,
  /**
   * @ignore - injected from TransitionGroup
   */
  onExited: PropTypes.func,
  /**
   * If `true`, the ripple pulsates, typically indicating the keyboard focus state of an element.
   */
  pulsate: PropTypes.bool,
  /**
   * Diameter of the ripple.
   */
  rippleSize: PropTypes.number,
  /**
   * Horizontal position of the ripple center.
   */
  rippleX: PropTypes.number,
  /**
   * Vertical position of the ripple center.
   */
  rippleY: PropTypes.number,
  /**
   * exit delay
   */
  timeout: PropTypes.number.isRequired
} ;

const touchRippleClasses = generateUtilityClasses('MuiTouchRipple', ['root', 'ripple', 'rippleVisible', 'ripplePulsate', 'child', 'childLeaving', 'childPulsate']);
var touchRippleClasses$1 = touchRippleClasses;

const _excluded$1i = ["center", "classes", "className"];
let _$2 = t => t,
  _t$2,
  _t2$2,
  _t3$2,
  _t4$2;
const DURATION = 550;
const DELAY_RIPPLE = 80;
const enterKeyframe = keyframes(_t$2 || (_t$2 = _$2`
  0% {
    transform: scale(0);
    opacity: 0.1;
  }

  100% {
    transform: scale(1);
    opacity: 0.3;
  }
`));
const exitKeyframe = keyframes(_t2$2 || (_t2$2 = _$2`
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
`));
const pulsateKeyframe = keyframes(_t3$2 || (_t3$2 = _$2`
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(0.92);
  }

  100% {
    transform: scale(1);
  }
`));
const TouchRippleRoot = styled$1('span', {
  name: 'MuiTouchRipple',
  slot: 'Root'
})({
  overflow: 'hidden',
  pointerEvents: 'none',
  position: 'absolute',
  zIndex: 0,
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
  borderRadius: 'inherit'
});

// This `styled()` function invokes keyframes. `styled-components` only supports keyframes
// in string templates. Do not convert these styles in JS object as it will break.
const TouchRippleRipple = styled$1(Ripple, {
  name: 'MuiTouchRipple',
  slot: 'Ripple'
})(_t4$2 || (_t4$2 = _$2`
  opacity: 0;
  position: absolute;

  &.${0} {
    opacity: 0.3;
    transform: scale(1);
    animation-name: ${0};
    animation-duration: ${0}ms;
    animation-timing-function: ${0};
  }

  &.${0} {
    animation-duration: ${0}ms;
  }

  & .${0} {
    opacity: 1;
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: currentColor;
  }

  & .${0} {
    opacity: 0;
    animation-name: ${0};
    animation-duration: ${0}ms;
    animation-timing-function: ${0};
  }

  & .${0} {
    position: absolute;
    /* @noflip */
    left: 0px;
    top: 0;
    animation-name: ${0};
    animation-duration: 2500ms;
    animation-timing-function: ${0};
    animation-iteration-count: infinite;
    animation-delay: 200ms;
  }
`), touchRippleClasses$1.rippleVisible, enterKeyframe, DURATION, ({
  theme
}) => theme.transitions.easing.easeInOut, touchRippleClasses$1.ripplePulsate, ({
  theme
}) => theme.transitions.duration.shorter, touchRippleClasses$1.child, touchRippleClasses$1.childLeaving, exitKeyframe, DURATION, ({
  theme
}) => theme.transitions.easing.easeInOut, touchRippleClasses$1.childPulsate, pulsateKeyframe, ({
  theme
}) => theme.transitions.easing.easeInOut);

/**
 * @ignore - internal component.
 *
 * TODO v5: Make private
 */
const TouchRipple = /*#__PURE__*/reactExports$1.forwardRef(function TouchRipple(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTouchRipple'
  });
  const {
      center: centerProp = false,
      classes = {},
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1i);
  const [ripples, setRipples] = reactExports$1.useState([]);
  const nextKey = reactExports$1.useRef(0);
  const rippleCallback = reactExports$1.useRef(null);
  reactExports$1.useEffect(() => {
    if (rippleCallback.current) {
      rippleCallback.current();
      rippleCallback.current = null;
    }
  }, [ripples]);

  // Used to filter out mouse emulated events on mobile.
  const ignoringMouseDown = reactExports$1.useRef(false);
  // We use a timer in order to only show the ripples for touch "click" like events.
  // We don't want to display the ripple for touch scroll events.
  const startTimer = reactExports$1.useRef(null);

  // This is the hook called once the previous timeout is ready.
  const startTimerCommit = reactExports$1.useRef(null);
  const container = reactExports$1.useRef(null);
  reactExports$1.useEffect(() => {
    return () => {
      clearTimeout(startTimer.current);
    };
  }, []);
  const startCommit = reactExports$1.useCallback(params => {
    const {
      pulsate,
      rippleX,
      rippleY,
      rippleSize,
      cb
    } = params;
    setRipples(oldRipples => [...oldRipples, /*#__PURE__*/jsxRuntimeExports.jsx(TouchRippleRipple, {
      classes: {
        ripple: clsx(classes.ripple, touchRippleClasses$1.ripple),
        rippleVisible: clsx(classes.rippleVisible, touchRippleClasses$1.rippleVisible),
        ripplePulsate: clsx(classes.ripplePulsate, touchRippleClasses$1.ripplePulsate),
        child: clsx(classes.child, touchRippleClasses$1.child),
        childLeaving: clsx(classes.childLeaving, touchRippleClasses$1.childLeaving),
        childPulsate: clsx(classes.childPulsate, touchRippleClasses$1.childPulsate)
      },
      timeout: DURATION,
      pulsate: pulsate,
      rippleX: rippleX,
      rippleY: rippleY,
      rippleSize: rippleSize
    }, nextKey.current)]);
    nextKey.current += 1;
    rippleCallback.current = cb;
  }, [classes]);
  const start = reactExports$1.useCallback((event = {}, options = {}, cb = () => {}) => {
    const {
      pulsate = false,
      center = centerProp || options.pulsate,
      fakeElement = false // For test purposes
    } = options;
    if ((event == null ? void 0 : event.type) === 'mousedown' && ignoringMouseDown.current) {
      ignoringMouseDown.current = false;
      return;
    }
    if ((event == null ? void 0 : event.type) === 'touchstart') {
      ignoringMouseDown.current = true;
    }
    const element = fakeElement ? null : container.current;
    const rect = element ? element.getBoundingClientRect() : {
      width: 0,
      height: 0,
      left: 0,
      top: 0
    };

    // Get the size of the ripple
    let rippleX;
    let rippleY;
    let rippleSize;
    if (center || event === undefined || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {
      rippleX = Math.round(rect.width / 2);
      rippleY = Math.round(rect.height / 2);
    } else {
      const {
        clientX,
        clientY
      } = event.touches && event.touches.length > 0 ? event.touches[0] : event;
      rippleX = Math.round(clientX - rect.left);
      rippleY = Math.round(clientY - rect.top);
    }
    if (center) {
      rippleSize = Math.sqrt((2 * rect.width ** 2 + rect.height ** 2) / 3);

      // For some reason the animation is broken on Mobile Chrome if the size is even.
      if (rippleSize % 2 === 0) {
        rippleSize += 1;
      }
    } else {
      const sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;
      const sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;
      rippleSize = Math.sqrt(sizeX ** 2 + sizeY ** 2);
    }

    // Touche devices
    if (event != null && event.touches) {
      // check that this isn't another touchstart due to multitouch
      // otherwise we will only clear a single timer when unmounting while two
      // are running
      if (startTimerCommit.current === null) {
        // Prepare the ripple effect.
        startTimerCommit.current = () => {
          startCommit({
            pulsate,
            rippleX,
            rippleY,
            rippleSize,
            cb
          });
        };
        // Delay the execution of the ripple effect.
        startTimer.current = setTimeout(() => {
          if (startTimerCommit.current) {
            startTimerCommit.current();
            startTimerCommit.current = null;
          }
        }, DELAY_RIPPLE); // We have to make a tradeoff with this value.
      }
    } else {
      startCommit({
        pulsate,
        rippleX,
        rippleY,
        rippleSize,
        cb
      });
    }
  }, [centerProp, startCommit]);
  const pulsate = reactExports$1.useCallback(() => {
    start({}, {
      pulsate: true
    });
  }, [start]);
  const stop = reactExports$1.useCallback((event, cb) => {
    clearTimeout(startTimer.current);

    // The touch interaction occurs too quickly.
    // We still want to show ripple effect.
    if ((event == null ? void 0 : event.type) === 'touchend' && startTimerCommit.current) {
      startTimerCommit.current();
      startTimerCommit.current = null;
      startTimer.current = setTimeout(() => {
        stop(event, cb);
      });
      return;
    }
    startTimerCommit.current = null;
    setRipples(oldRipples => {
      if (oldRipples.length > 0) {
        return oldRipples.slice(1);
      }
      return oldRipples;
    });
    rippleCallback.current = cb;
  }, []);
  reactExports$1.useImperativeHandle(ref, () => ({
    pulsate,
    start,
    stop
  }), [pulsate, start, stop]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TouchRippleRoot, _extends({
    className: clsx(touchRippleClasses$1.root, classes.root, className),
    ref: container
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(TransitionGroup$1, {
      component: null,
      exit: true,
      children: ripples
    })
  }));
});
TouchRipple.propTypes = {
  /**
   * If `true`, the ripple starts at the center of the component
   * rather than at the point of interaction.
   */
  center: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string
} ;
var TouchRipple$1 = TouchRipple;

function getButtonBaseUtilityClass(slot) {
  return generateUtilityClass('MuiButtonBase', slot);
}
const buttonBaseClasses = generateUtilityClasses('MuiButtonBase', ['root', 'disabled', 'focusVisible']);
var buttonBaseClasses$1 = buttonBaseClasses;

const _excluded$1h = ["action", "centerRipple", "children", "className", "component", "disabled", "disableRipple", "disableTouchRipple", "focusRipple", "focusVisibleClassName", "LinkComponent", "onBlur", "onClick", "onContextMenu", "onDragLeave", "onFocus", "onFocusVisible", "onKeyDown", "onKeyUp", "onMouseDown", "onMouseLeave", "onMouseUp", "onTouchEnd", "onTouchMove", "onTouchStart", "tabIndex", "TouchRippleProps", "touchRippleRef", "type"];
const useUtilityClasses$17 = ownerState => {
  const {
    disabled,
    focusVisible,
    focusVisibleClassName,
    classes
  } = ownerState;
  const slots = {
    root: ['root', disabled && 'disabled', focusVisible && 'focusVisible']
  };
  const composedClasses = composeClasses(slots, getButtonBaseUtilityClass, classes);
  if (focusVisible && focusVisibleClassName) {
    composedClasses.root += ` ${focusVisibleClassName}`;
  }
  return composedClasses;
};
const ButtonBaseRoot = styled$1('button', {
  name: 'MuiButtonBase',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  position: 'relative',
  boxSizing: 'border-box',
  WebkitTapHighlightColor: 'transparent',
  backgroundColor: 'transparent',
  // Reset default value
  // We disable the focus ring for mouse, touch and keyboard users.
  outline: 0,
  border: 0,
  margin: 0,
  // Remove the margin in Safari
  borderRadius: 0,
  padding: 0,
  // Remove the padding in Firefox
  cursor: 'pointer',
  userSelect: 'none',
  verticalAlign: 'middle',
  MozAppearance: 'none',
  // Reset
  WebkitAppearance: 'none',
  // Reset
  textDecoration: 'none',
  // So we take precedent over the style of a native <a /> element.
  color: 'inherit',
  '&::-moz-focus-inner': {
    borderStyle: 'none' // Remove Firefox dotted outline.
  },

  [`&.${buttonBaseClasses$1.disabled}`]: {
    pointerEvents: 'none',
    // Disable link interactions
    cursor: 'default'
  },
  '@media print': {
    colorAdjust: 'exact'
  }
});

/**
 * `ButtonBase` contains as few styles as possible.
 * It aims to be a simple building block for creating a button.
 * It contains a load of style reset and some focus/ripple logic.
 */
const ButtonBase = /*#__PURE__*/reactExports$1.forwardRef(function ButtonBase(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiButtonBase'
  });
  const {
      action,
      centerRipple = false,
      children,
      className,
      component = 'button',
      disabled = false,
      disableRipple = false,
      disableTouchRipple = false,
      focusRipple = false,
      LinkComponent = 'a',
      onBlur,
      onClick,
      onContextMenu,
      onDragLeave,
      onFocus,
      onFocusVisible,
      onKeyDown,
      onKeyUp,
      onMouseDown,
      onMouseLeave,
      onMouseUp,
      onTouchEnd,
      onTouchMove,
      onTouchStart,
      tabIndex = 0,
      TouchRippleProps,
      touchRippleRef,
      type
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1h);
  const buttonRef = reactExports$1.useRef(null);
  const rippleRef = reactExports$1.useRef(null);
  const handleRippleRef = useForkRef(rippleRef, touchRippleRef);
  const {
    isFocusVisibleRef,
    onFocus: handleFocusVisible,
    onBlur: handleBlurVisible,
    ref: focusVisibleRef
  } = useIsFocusVisible();
  const [focusVisible, setFocusVisible] = reactExports$1.useState(false);
  if (disabled && focusVisible) {
    setFocusVisible(false);
  }
  reactExports$1.useImperativeHandle(action, () => ({
    focusVisible: () => {
      setFocusVisible(true);
      buttonRef.current.focus();
    }
  }), []);
  const [mountedState, setMountedState] = reactExports$1.useState(false);
  reactExports$1.useEffect(() => {
    setMountedState(true);
  }, []);
  const enableTouchRipple = mountedState && !disableRipple && !disabled;
  reactExports$1.useEffect(() => {
    if (focusVisible && focusRipple && !disableRipple && mountedState) {
      rippleRef.current.pulsate();
    }
  }, [disableRipple, focusRipple, focusVisible, mountedState]);
  function useRippleHandler(rippleAction, eventCallback, skipRippleAction = disableTouchRipple) {
    return useEventCallback(event => {
      if (eventCallback) {
        eventCallback(event);
      }
      const ignore = skipRippleAction;
      if (!ignore && rippleRef.current) {
        rippleRef.current[rippleAction](event);
      }
      return true;
    });
  }
  const handleMouseDown = useRippleHandler('start', onMouseDown);
  const handleContextMenu = useRippleHandler('stop', onContextMenu);
  const handleDragLeave = useRippleHandler('stop', onDragLeave);
  const handleMouseUp = useRippleHandler('stop', onMouseUp);
  const handleMouseLeave = useRippleHandler('stop', event => {
    if (focusVisible) {
      event.preventDefault();
    }
    if (onMouseLeave) {
      onMouseLeave(event);
    }
  });
  const handleTouchStart = useRippleHandler('start', onTouchStart);
  const handleTouchEnd = useRippleHandler('stop', onTouchEnd);
  const handleTouchMove = useRippleHandler('stop', onTouchMove);
  const handleBlur = useRippleHandler('stop', event => {
    handleBlurVisible(event);
    if (isFocusVisibleRef.current === false) {
      setFocusVisible(false);
    }
    if (onBlur) {
      onBlur(event);
    }
  }, false);
  const handleFocus = useEventCallback(event => {
    // Fix for https://github.com/facebook/react/issues/7769
    if (!buttonRef.current) {
      buttonRef.current = event.currentTarget;
    }
    handleFocusVisible(event);
    if (isFocusVisibleRef.current === true) {
      setFocusVisible(true);
      if (onFocusVisible) {
        onFocusVisible(event);
      }
    }
    if (onFocus) {
      onFocus(event);
    }
  });
  const isNonNativeButton = () => {
    const button = buttonRef.current;
    return component && component !== 'button' && !(button.tagName === 'A' && button.href);
  };

  /**
   * IE11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat
   */
  const keydownRef = reactExports$1.useRef(false);
  const handleKeyDown = useEventCallback(event => {
    // Check if key is already down to avoid repeats being counted as multiple activations
    if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') {
      keydownRef.current = true;
      rippleRef.current.stop(event, () => {
        rippleRef.current.start(event);
      });
    }
    if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {
      event.preventDefault();
    }
    if (onKeyDown) {
      onKeyDown(event);
    }

    // Keyboard accessibility for non interactive elements
    if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) {
      event.preventDefault();
      if (onClick) {
        onClick(event);
      }
    }
  });
  const handleKeyUp = useEventCallback(event => {
    // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
    // https://codesandbox.io/s/button-keyup-preventdefault-dn7f0
    if (focusRipple && event.key === ' ' && rippleRef.current && focusVisible && !event.defaultPrevented) {
      keydownRef.current = false;
      rippleRef.current.stop(event, () => {
        rippleRef.current.pulsate(event);
      });
    }
    if (onKeyUp) {
      onKeyUp(event);
    }

    // Keyboard accessibility for non interactive elements
    if (onClick && event.target === event.currentTarget && isNonNativeButton() && event.key === ' ' && !event.defaultPrevented) {
      onClick(event);
    }
  });
  let ComponentProp = component;
  if (ComponentProp === 'button' && (other.href || other.to)) {
    ComponentProp = LinkComponent;
  }
  const buttonProps = {};
  if (ComponentProp === 'button') {
    buttonProps.type = type === undefined ? 'button' : type;
    buttonProps.disabled = disabled;
  } else {
    if (!other.href && !other.to) {
      buttonProps.role = 'button';
    }
    if (disabled) {
      buttonProps['aria-disabled'] = disabled;
    }
  }
  const handleRef = useForkRef(ref, focusVisibleRef, buttonRef);
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(() => {
      if (enableTouchRipple && !rippleRef.current) {
        console.error(['MUI: The `component` prop provided to ButtonBase is invalid.', 'Please make sure the children prop is rendered in this custom component.'].join('\n'));
      }
    }, [enableTouchRipple]);
  }
  const ownerState = _extends({}, props, {
    centerRipple,
    component,
    disabled,
    disableRipple,
    disableTouchRipple,
    focusRipple,
    tabIndex,
    focusVisible
  });
  const classes = useUtilityClasses$17(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(ButtonBaseRoot, _extends({
    as: ComponentProp,
    className: clsx(classes.root, className),
    ownerState: ownerState,
    onBlur: handleBlur,
    onClick: onClick,
    onContextMenu: handleContextMenu,
    onFocus: handleFocus,
    onKeyDown: handleKeyDown,
    onKeyUp: handleKeyUp,
    onMouseDown: handleMouseDown,
    onMouseLeave: handleMouseLeave,
    onMouseUp: handleMouseUp,
    onDragLeave: handleDragLeave,
    onTouchEnd: handleTouchEnd,
    onTouchMove: handleTouchMove,
    onTouchStart: handleTouchStart,
    ref: handleRef,
    tabIndex: disabled ? -1 : tabIndex,
    type: type
  }, buttonProps, other, {
    children: [children, enableTouchRipple ? /*#__PURE__*/
    /* TouchRipple is only needed client-side, x2 boost on the server. */
    jsxRuntimeExports.jsx(TouchRipple$1, _extends({
      ref: handleRippleRef,
      center: centerRipple
    }, TouchRippleProps)) : null]
  }));
});
ButtonBase.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * A ref for imperative actions.
   * It currently only supports `focusVisible()` action.
   */
  action: refType$1,
  /**
   * If `true`, the ripples are centered.
   * They won't start at the cursor interaction position.
   * @default false
   */
  centerRipple: PropTypes.bool,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: elementTypeAcceptingRef$1,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   *
   * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
   * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * If `true`, the touch ripple effect is disabled.
   * @default false
   */
  disableTouchRipple: PropTypes.bool,
  /**
   * If `true`, the base button will have a keyboard focus ripple.
   * @default false
   */
  focusRipple: PropTypes.bool,
  /**
   * This prop can help identify which element has keyboard focus.
   * The class name will be applied when the element gains the focus through keyboard interaction.
   * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).
   * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/HEAD/explainer.md).
   * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components
   * if needed.
   */
  focusVisibleClassName: PropTypes.string,
  /**
   * @ignore
   */
  href: PropTypes /* @typescript-to-proptypes-ignore */.any,
  /**
   * The component used to render a link when the `href` prop is provided.
   * @default 'a'
   */
  LinkComponent: PropTypes.elementType,
  /**
   * @ignore
   */
  onBlur: PropTypes.func,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * @ignore
   */
  onContextMenu: PropTypes.func,
  /**
   * @ignore
   */
  onDragLeave: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * Callback fired when the component is focused with a keyboard.
   * We trigger a `onFocus` callback too.
   */
  onFocusVisible: PropTypes.func,
  /**
   * @ignore
   */
  onKeyDown: PropTypes.func,
  /**
   * @ignore
   */
  onKeyUp: PropTypes.func,
  /**
   * @ignore
   */
  onMouseDown: PropTypes.func,
  /**
   * @ignore
   */
  onMouseLeave: PropTypes.func,
  /**
   * @ignore
   */
  onMouseUp: PropTypes.func,
  /**
   * @ignore
   */
  onTouchEnd: PropTypes.func,
  /**
   * @ignore
   */
  onTouchMove: PropTypes.func,
  /**
   * @ignore
   */
  onTouchStart: PropTypes.func,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * @default 0
   */
  tabIndex: PropTypes.number,
  /**
   * Props applied to the `TouchRipple` element.
   */
  TouchRippleProps: PropTypes.object,
  /**
   * A ref that points to the `TouchRipple` element.
   */
  touchRippleRef: PropTypes.oneOfType([PropTypes.func, PropTypes.shape({
    current: PropTypes.shape({
      pulsate: PropTypes.func.isRequired,
      start: PropTypes.func.isRequired,
      stop: PropTypes.func.isRequired
    })
  })]),
  /**
   * @ignore
   */
  type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string])
} ;
var ButtonBase$1 = ButtonBase;

function getButtonUtilityClass(slot) {
  return generateUtilityClass('MuiButton', slot);
}
const buttonClasses = generateUtilityClasses('MuiButton', ['root', 'text', 'textInherit', 'textPrimary', 'textSecondary', 'textSuccess', 'textError', 'textInfo', 'textWarning', 'outlined', 'outlinedInherit', 'outlinedPrimary', 'outlinedSecondary', 'outlinedSuccess', 'outlinedError', 'outlinedInfo', 'outlinedWarning', 'contained', 'containedInherit', 'containedPrimary', 'containedSecondary', 'containedSuccess', 'containedError', 'containedInfo', 'containedWarning', 'disableElevation', 'focusVisible', 'disabled', 'colorInherit', 'textSizeSmall', 'textSizeMedium', 'textSizeLarge', 'outlinedSizeSmall', 'outlinedSizeMedium', 'outlinedSizeLarge', 'containedSizeSmall', 'containedSizeMedium', 'containedSizeLarge', 'sizeMedium', 'sizeSmall', 'sizeLarge', 'fullWidth', 'startIcon', 'endIcon', 'iconSizeSmall', 'iconSizeMedium', 'iconSizeLarge']);
var buttonClasses$1 = buttonClasses;

/**
 * @ignore - internal component.
 */
const ButtonGroupContext = /*#__PURE__*/reactExports$1.createContext({});
{
  ButtonGroupContext.displayName = 'ButtonGroupContext';
}
var ButtonGroupContext$1 = ButtonGroupContext;

const _excluded$1g = ["children", "color", "component", "className", "disabled", "disableElevation", "disableFocusRipple", "endIcon", "focusVisibleClassName", "fullWidth", "size", "startIcon", "type", "variant"];
const useUtilityClasses$16 = ownerState => {
  const {
    color,
    disableElevation,
    fullWidth,
    size,
    variant,
    classes
  } = ownerState;
  const slots = {
    root: ['root', variant, `${variant}${capitalize(color)}`, `size${capitalize(size)}`, `${variant}Size${capitalize(size)}`, color === 'inherit' && 'colorInherit', disableElevation && 'disableElevation', fullWidth && 'fullWidth'],
    label: ['label'],
    startIcon: ['startIcon', `iconSize${capitalize(size)}`],
    endIcon: ['endIcon', `iconSize${capitalize(size)}`]
  };
  const composedClasses = composeClasses(slots, getButtonUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const commonIconStyles = ownerState => _extends({}, ownerState.size === 'small' && {
  '& > *:nth-of-type(1)': {
    fontSize: 18
  }
}, ownerState.size === 'medium' && {
  '& > *:nth-of-type(1)': {
    fontSize: 20
  }
}, ownerState.size === 'large' && {
  '& > *:nth-of-type(1)': {
    fontSize: 22
  }
});
const ButtonRoot = styled$1(ButtonBase$1, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiButton',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant], styles[`${ownerState.variant}${capitalize(ownerState.color)}`], styles[`size${capitalize(ownerState.size)}`], styles[`${ownerState.variant}Size${capitalize(ownerState.size)}`], ownerState.color === 'inherit' && styles.colorInherit, ownerState.disableElevation && styles.disableElevation, ownerState.fullWidth && styles.fullWidth];
  }
})(({
  theme,
  ownerState
}) => {
  var _theme$palette$getCon, _theme$palette;
  const inheritContainedBackgroundColor = theme.palette.mode === 'light' ? theme.palette.grey[300] : theme.palette.grey[800];
  const inheritContainedHoverBackgroundColor = theme.palette.mode === 'light' ? theme.palette.grey.A100 : theme.palette.grey[700];
  return _extends({}, theme.typography.button, {
    minWidth: 64,
    padding: '6px 16px',
    borderRadius: (theme.vars || theme).shape.borderRadius,
    transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color', 'color'], {
      duration: theme.transitions.duration.short
    }),
    '&:hover': _extends({
      textDecoration: 'none',
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity),
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    }, ownerState.variant === 'text' && ownerState.color !== 'inherit' && {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[ownerState.color].main, theme.palette.action.hoverOpacity),
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    }, ownerState.variant === 'outlined' && ownerState.color !== 'inherit' && {
      border: `1px solid ${(theme.vars || theme).palette[ownerState.color].main}`,
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[ownerState.color].main, theme.palette.action.hoverOpacity),
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    }, ownerState.variant === 'contained' && {
      backgroundColor: theme.vars ? theme.vars.palette.Button.inheritContainedHoverBg : inheritContainedHoverBackgroundColor,
      boxShadow: (theme.vars || theme).shadows[4],
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        boxShadow: (theme.vars || theme).shadows[2],
        backgroundColor: (theme.vars || theme).palette.grey[300]
      }
    }, ownerState.variant === 'contained' && ownerState.color !== 'inherit' && {
      backgroundColor: (theme.vars || theme).palette[ownerState.color].dark,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: (theme.vars || theme).palette[ownerState.color].main
      }
    }),
    '&:active': _extends({}, ownerState.variant === 'contained' && {
      boxShadow: (theme.vars || theme).shadows[8]
    }),
    [`&.${buttonClasses$1.focusVisible}`]: _extends({}, ownerState.variant === 'contained' && {
      boxShadow: (theme.vars || theme).shadows[6]
    }),
    [`&.${buttonClasses$1.disabled}`]: _extends({
      color: (theme.vars || theme).palette.action.disabled
    }, ownerState.variant === 'outlined' && {
      border: `1px solid ${(theme.vars || theme).palette.action.disabledBackground}`
    }, ownerState.variant === 'contained' && {
      color: (theme.vars || theme).palette.action.disabled,
      boxShadow: (theme.vars || theme).shadows[0],
      backgroundColor: (theme.vars || theme).palette.action.disabledBackground
    })
  }, ownerState.variant === 'text' && {
    padding: '6px 8px'
  }, ownerState.variant === 'text' && ownerState.color !== 'inherit' && {
    color: (theme.vars || theme).palette[ownerState.color].main
  }, ownerState.variant === 'outlined' && {
    padding: '5px 15px',
    border: '1px solid currentColor'
  }, ownerState.variant === 'outlined' && ownerState.color !== 'inherit' && {
    color: (theme.vars || theme).palette[ownerState.color].main,
    border: theme.vars ? `1px solid rgba(${theme.vars.palette[ownerState.color].mainChannel} / 0.5)` : `1px solid ${alpha(theme.palette[ownerState.color].main, 0.5)}`
  }, ownerState.variant === 'contained' && {
    color: theme.vars ?
    // this is safe because grey does not change between default light/dark mode
    theme.vars.palette.text.primary : (_theme$palette$getCon = (_theme$palette = theme.palette).getContrastText) == null ? void 0 : _theme$palette$getCon.call(_theme$palette, theme.palette.grey[300]),
    backgroundColor: theme.vars ? theme.vars.palette.Button.inheritContainedBg : inheritContainedBackgroundColor,
    boxShadow: (theme.vars || theme).shadows[2]
  }, ownerState.variant === 'contained' && ownerState.color !== 'inherit' && {
    color: (theme.vars || theme).palette[ownerState.color].contrastText,
    backgroundColor: (theme.vars || theme).palette[ownerState.color].main
  }, ownerState.color === 'inherit' && {
    color: 'inherit',
    borderColor: 'currentColor'
  }, ownerState.size === 'small' && ownerState.variant === 'text' && {
    padding: '4px 5px',
    fontSize: theme.typography.pxToRem(13)
  }, ownerState.size === 'large' && ownerState.variant === 'text' && {
    padding: '8px 11px',
    fontSize: theme.typography.pxToRem(15)
  }, ownerState.size === 'small' && ownerState.variant === 'outlined' && {
    padding: '3px 9px',
    fontSize: theme.typography.pxToRem(13)
  }, ownerState.size === 'large' && ownerState.variant === 'outlined' && {
    padding: '7px 21px',
    fontSize: theme.typography.pxToRem(15)
  }, ownerState.size === 'small' && ownerState.variant === 'contained' && {
    padding: '4px 10px',
    fontSize: theme.typography.pxToRem(13)
  }, ownerState.size === 'large' && ownerState.variant === 'contained' && {
    padding: '8px 22px',
    fontSize: theme.typography.pxToRem(15)
  }, ownerState.fullWidth && {
    width: '100%'
  });
}, ({
  ownerState
}) => ownerState.disableElevation && {
  boxShadow: 'none',
  '&:hover': {
    boxShadow: 'none'
  },
  [`&.${buttonClasses$1.focusVisible}`]: {
    boxShadow: 'none'
  },
  '&:active': {
    boxShadow: 'none'
  },
  [`&.${buttonClasses$1.disabled}`]: {
    boxShadow: 'none'
  }
});
const ButtonStartIcon = styled$1('span', {
  name: 'MuiButton',
  slot: 'StartIcon',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.startIcon, styles[`iconSize${capitalize(ownerState.size)}`]];
  }
})(({
  ownerState
}) => _extends({
  display: 'inherit',
  marginRight: 8,
  marginLeft: -4
}, ownerState.size === 'small' && {
  marginLeft: -2
}, commonIconStyles(ownerState)));
const ButtonEndIcon = styled$1('span', {
  name: 'MuiButton',
  slot: 'EndIcon',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.endIcon, styles[`iconSize${capitalize(ownerState.size)}`]];
  }
})(({
  ownerState
}) => _extends({
  display: 'inherit',
  marginRight: -4,
  marginLeft: 8
}, ownerState.size === 'small' && {
  marginRight: -2
}, commonIconStyles(ownerState)));
const Button$1 = /*#__PURE__*/reactExports$1.forwardRef(function Button(inProps, ref) {
  // props priority: `inProps` > `contextProps` > `themeDefaultProps`
  const contextProps = reactExports$1.useContext(ButtonGroupContext$1);
  const resolvedProps = resolveProps(contextProps, inProps);
  const props = useThemeProps({
    props: resolvedProps,
    name: 'MuiButton'
  });
  const {
      children,
      color = 'primary',
      component = 'button',
      className,
      disabled = false,
      disableElevation = false,
      disableFocusRipple = false,
      endIcon: endIconProp,
      focusVisibleClassName,
      fullWidth = false,
      size = 'medium',
      startIcon: startIconProp,
      type,
      variant = 'text'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1g);
  const ownerState = _extends({}, props, {
    color,
    component,
    disabled,
    disableElevation,
    disableFocusRipple,
    fullWidth,
    size,
    type,
    variant
  });
  const classes = useUtilityClasses$16(ownerState);
  const startIcon = startIconProp && /*#__PURE__*/jsxRuntimeExports.jsx(ButtonStartIcon, {
    className: classes.startIcon,
    ownerState: ownerState,
    children: startIconProp
  });
  const endIcon = endIconProp && /*#__PURE__*/jsxRuntimeExports.jsx(ButtonEndIcon, {
    className: classes.endIcon,
    ownerState: ownerState,
    children: endIconProp
  });
  return /*#__PURE__*/jsxRuntimeExports.jsxs(ButtonRoot, _extends({
    ownerState: ownerState,
    className: clsx(contextProps.className, classes.root, className),
    component: component,
    disabled: disabled,
    focusRipple: !disableFocusRipple,
    focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
    ref: ref,
    type: type
  }, other, {
    classes: classes,
    children: [startIcon, children, endIcon]
  }));
});
Button$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'primary', 'secondary', 'success', 'error', 'info', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, no elevation is used.
   * @default false
   */
  disableElevation: PropTypes.bool,
  /**
   * If `true`, the  keyboard focus ripple is disabled.
   * @default false
   */
  disableFocusRipple: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   *
   * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
   * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * Element placed after the children.
   */
  endIcon: PropTypes.node,
  /**
   * @ignore
   */
  focusVisibleClassName: PropTypes.string,
  /**
   * If `true`, the button will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * The URL to link to when the button is clicked.
   * If defined, an `a` element will be used as the root node.
   */
  href: PropTypes.string,
  /**
   * The size of the component.
   * `small` is equivalent to the dense button styling.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string]),
  /**
   * Element placed before the children.
   */
  startIcon: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * @ignore
   */
  type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string]),
  /**
   * The variant to use.
   * @default 'text'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['contained', 'outlined', 'text']), PropTypes.string])
} ;
var Button$2 = Button$1;

function Button({
  icon,
  ...rest
}) {
  const Icon = useIcon(icon),
    startIcon = Icon ? /*#__PURE__*/React.createElement(Icon, null) : null;
  return /*#__PURE__*/React.createElement(Button$2, {
    startIcon: startIcon,
    ...rest
  });
}
Button.propTypes = {
  icon: PropTypes.string
};

function ButtonLink(props) {
  const {
    Button
  } = useComponents();
  return /*#__PURE__*/React.createElement(Button, {
    component: Link$3,
    ...props
  });
}

function HomeLink({
  to,
  label,
  active,
  ...rest
}) {
  const HomeIcon = useIcon("home") || (() => "Home");
  return /*#__PURE__*/React.createElement(Button$2, {
    component: Link$3,
    to: to,
    color: active ? "inherit" : "primary",
    "aria-label": label,
    ...rest
  }, /*#__PURE__*/React.createElement(HomeIcon, {
    sx: {
      verticalAlign: "middle"
    }
  }));
}
HomeLink.propTypes = {
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  label: PropTypes.string,
  active: PropTypes.bool
};

function getIconButtonUtilityClass(slot) {
  return generateUtilityClass('MuiIconButton', slot);
}
const iconButtonClasses = generateUtilityClasses('MuiIconButton', ['root', 'disabled', 'colorInherit', 'colorPrimary', 'colorSecondary', 'colorError', 'colorInfo', 'colorSuccess', 'colorWarning', 'edgeStart', 'edgeEnd', 'sizeSmall', 'sizeMedium', 'sizeLarge']);
var iconButtonClasses$1 = iconButtonClasses;

const _excluded$1f = ["edge", "children", "className", "color", "disabled", "disableFocusRipple", "size"];
const useUtilityClasses$15 = ownerState => {
  const {
    classes,
    disabled,
    color,
    edge,
    size
  } = ownerState;
  const slots = {
    root: ['root', disabled && 'disabled', color !== 'default' && `color${capitalize(color)}`, edge && `edge${capitalize(edge)}`, `size${capitalize(size)}`]
  };
  return composeClasses(slots, getIconButtonUtilityClass, classes);
};
const IconButtonRoot = styled$1(ButtonBase$1, {
  name: 'MuiIconButton',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`], ownerState.edge && styles[`edge${capitalize(ownerState.edge)}`], styles[`size${capitalize(ownerState.size)}`]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  textAlign: 'center',
  flex: '0 0 auto',
  fontSize: theme.typography.pxToRem(24),
  padding: 8,
  borderRadius: '50%',
  overflow: 'visible',
  // Explicitly set the default value to solve a bug on IE11.
  color: (theme.vars || theme).palette.action.active,
  transition: theme.transitions.create('background-color', {
    duration: theme.transitions.duration.shortest
  })
}, !ownerState.disableRipple && {
  '&:hover': {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.activeChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.action.active, theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  }
}, ownerState.edge === 'start' && {
  marginLeft: ownerState.size === 'small' ? -3 : -12
}, ownerState.edge === 'end' && {
  marginRight: ownerState.size === 'small' ? -3 : -12
}), ({
  theme,
  ownerState
}) => {
  var _palette;
  const palette = (_palette = (theme.vars || theme).palette) == null ? void 0 : _palette[ownerState.color];
  return _extends({}, ownerState.color === 'inherit' && {
    color: 'inherit'
  }, ownerState.color !== 'inherit' && ownerState.color !== 'default' && _extends({
    color: palette == null ? void 0 : palette.main
  }, !ownerState.disableRipple && {
    '&:hover': _extends({}, palette && {
      backgroundColor: theme.vars ? `rgba(${palette.mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(palette.main, theme.palette.action.hoverOpacity)
    }, {
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    })
  }), ownerState.size === 'small' && {
    padding: 5,
    fontSize: theme.typography.pxToRem(18)
  }, ownerState.size === 'large' && {
    padding: 12,
    fontSize: theme.typography.pxToRem(28)
  }, {
    [`&.${iconButtonClasses$1.disabled}`]: {
      backgroundColor: 'transparent',
      color: (theme.vars || theme).palette.action.disabled
    }
  });
});

/**
 * Refer to the [Icons](/material-ui/icons/) section of the documentation
 * regarding the available icon options.
 */
const IconButton$1 = /*#__PURE__*/reactExports$1.forwardRef(function IconButton(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiIconButton'
  });
  const {
      edge = false,
      children,
      className,
      color = 'default',
      disabled = false,
      disableFocusRipple = false,
      size = 'medium'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1f);
  const ownerState = _extends({}, props, {
    edge,
    color,
    disabled,
    disableFocusRipple,
    size
  });
  const classes = useUtilityClasses$15(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(IconButtonRoot, _extends({
    className: clsx(classes.root, className),
    centerRipple: true,
    focusRipple: !disableFocusRipple,
    disabled: disabled,
    ref: ref,
    ownerState: ownerState
  }, other, {
    children: children
  }));
});
IconButton$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The icon to display.
   */
  children: chainPropTypes(PropTypes.node, props => {
    const found = reactExports$1.Children.toArray(props.children).some(child => /*#__PURE__*/reactExports$1.isValidElement(child) && child.props.onClick);
    if (found) {
      return new Error(['MUI: You are providing an onClick event listener to a child of a button element.', 'Prefer applying it to the IconButton directly.', 'This guarantees that the whole <button> will be responsive to click events.'].join('\n'));
    }
    return null;
  }),
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'default'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the  keyboard focus ripple is disabled.
   * @default false
   */
  disableFocusRipple: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   *
   * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
   * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * If given, uses a negative margin to counteract the padding on one
   * side (this is often helpful for aligning the left or right
   * side of the icon with content above or below, without ruining the border
   * size and shape).
   * @default false
   */
  edge: PropTypes.oneOf(['end', 'start', false]),
  /**
   * The size of the component.
   * `small` is equivalent to the dense button styling.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var IconButton$2 = IconButton$1;

function IconButton({
  icon,
  size = "large",
  ...rest
}) {
  const Icon = useIcon(icon);
  if (!Icon) {
    throw new Error(`"${icon}" is not a registered icon!`);
  }
  return /*#__PURE__*/React.createElement(IconButton$2, {
    size: size,
    ...rest
  }, /*#__PURE__*/React.createElement(Icon, null));
}
IconButton.propTypes = {
  icon: PropTypes.string,
  size: PropTypes.string
};

function getFabUtilityClass(slot) {
  return generateUtilityClass('MuiFab', slot);
}
const fabClasses = generateUtilityClasses('MuiFab', ['root', 'primary', 'secondary', 'extended', 'circular', 'focusVisible', 'disabled', 'colorInherit', 'sizeSmall', 'sizeMedium', 'sizeLarge', 'info', 'error', 'warning', 'success']);
var fabClasses$1 = fabClasses;

const _excluded$1e = ["children", "className", "color", "component", "disabled", "disableFocusRipple", "focusVisibleClassName", "size", "variant"];
const useUtilityClasses$14 = ownerState => {
  const {
    color,
    variant,
    classes,
    size
  } = ownerState;
  const slots = {
    root: ['root', variant, `size${capitalize(size)}`, color === 'inherit' ? 'colorInherit' : color]
  };
  const composedClasses = composeClasses(slots, getFabUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const FabRoot = styled$1(ButtonBase$1, {
  name: 'MuiFab',
  slot: 'Root',
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant], styles[`size${capitalize(ownerState.size)}`], ownerState.color === 'inherit' && styles.colorInherit, styles[capitalize(ownerState.size)], styles[ownerState.color]];
  }
})(({
  theme,
  ownerState
}) => {
  var _theme$palette$getCon, _theme$palette;
  return _extends({}, theme.typography.button, {
    minHeight: 36,
    transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color'], {
      duration: theme.transitions.duration.short
    }),
    borderRadius: '50%',
    padding: 0,
    minWidth: 0,
    width: 56,
    height: 56,
    zIndex: (theme.vars || theme).zIndex.fab,
    boxShadow: (theme.vars || theme).shadows[6],
    '&:active': {
      boxShadow: (theme.vars || theme).shadows[12]
    },
    color: theme.vars ? theme.vars.palette.text.primary : (_theme$palette$getCon = (_theme$palette = theme.palette).getContrastText) == null ? void 0 : _theme$palette$getCon.call(_theme$palette, theme.palette.grey[300]),
    backgroundColor: (theme.vars || theme).palette.grey[300],
    '&:hover': {
      backgroundColor: (theme.vars || theme).palette.grey.A100,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: (theme.vars || theme).palette.grey[300]
      },
      textDecoration: 'none'
    },
    [`&.${fabClasses$1.focusVisible}`]: {
      boxShadow: (theme.vars || theme).shadows[6]
    }
  }, ownerState.size === 'small' && {
    width: 40,
    height: 40
  }, ownerState.size === 'medium' && {
    width: 48,
    height: 48
  }, ownerState.variant === 'extended' && {
    borderRadius: 48 / 2,
    padding: '0 16px',
    width: 'auto',
    minHeight: 'auto',
    minWidth: 48,
    height: 48
  }, ownerState.variant === 'extended' && ownerState.size === 'small' && {
    width: 'auto',
    padding: '0 8px',
    borderRadius: 34 / 2,
    minWidth: 34,
    height: 34
  }, ownerState.variant === 'extended' && ownerState.size === 'medium' && {
    width: 'auto',
    padding: '0 16px',
    borderRadius: 40 / 2,
    minWidth: 40,
    height: 40
  }, ownerState.color === 'inherit' && {
    color: 'inherit'
  });
}, ({
  theme,
  ownerState
}) => _extends({}, ownerState.color !== 'inherit' && ownerState.color !== 'default' && (theme.vars || theme).palette[ownerState.color] != null && {
  color: (theme.vars || theme).palette[ownerState.color].contrastText,
  backgroundColor: (theme.vars || theme).palette[ownerState.color].main,
  '&:hover': {
    backgroundColor: (theme.vars || theme).palette[ownerState.color].dark,
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: (theme.vars || theme).palette[ownerState.color].main
    }
  }
}), ({
  theme
}) => ({
  [`&.${fabClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.action.disabled,
    boxShadow: (theme.vars || theme).shadows[0],
    backgroundColor: (theme.vars || theme).palette.action.disabledBackground
  }
}));
const Fab$1 = /*#__PURE__*/reactExports$1.forwardRef(function Fab(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFab'
  });
  const {
      children,
      className,
      color = 'default',
      component = 'button',
      disabled = false,
      disableFocusRipple = false,
      focusVisibleClassName,
      size = 'large',
      variant = 'circular'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1e);
  const ownerState = _extends({}, props, {
    color,
    component,
    disabled,
    disableFocusRipple,
    size,
    variant
  });
  const classes = useUtilityClasses$14(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(FabRoot, _extends({
    className: clsx(classes.root, className),
    component: component,
    disabled: disabled,
    focusRipple: !disableFocusRipple,
    focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
    ownerState: ownerState,
    ref: ref
  }, other, {
    classes: classes,
    children: children
  }));
});
Fab$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'default'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'error', 'info', 'inherit', 'primary', 'secondary', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the  keyboard focus ripple is disabled.
   * @default false
   */
  disableFocusRipple: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   */
  disableRipple: PropTypes.bool,
  /**
   * @ignore
   */
  focusVisibleClassName: PropTypes.string,
  /**
   * The URL to link to when the button is clicked.
   * If defined, an `a` element will be used as the root node.
   */
  href: PropTypes.string,
  /**
   * The size of the component.
   * `small` is equivalent to the dense button styling.
   * @default 'large'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'circular'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['circular', 'extended']), PropTypes.string])
} ;
var Fab$2 = Fab$1;

function Fab({
  icon,
  to,
  ...rest
}) {
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement(Fab$2, {
    component: Link$3,
    to: to,
    color: "primary",
    style: {
      position: "absolute",
      right: 16,
      bottom: 16,
      zIndex: 5000
    },
    ...rest
  }, /*#__PURE__*/React.createElement(Icon, null));
}
Fab.propTypes = {
  icon: PropTypes.string,
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
};

function easeInOutSin(time) {
  return (1 + Math.sin(Math.PI * time - Math.PI / 2)) / 2;
}
function animate(property, element, to, options = {}, cb = () => {}) {
  const {
    ease = easeInOutSin,
    duration = 300 // standard
  } = options;
  let start = null;
  const from = element[property];
  let cancelled = false;
  const cancel = () => {
    cancelled = true;
  };
  const step = timestamp => {
    if (cancelled) {
      cb(new Error('Animation cancelled'));
      return;
    }
    if (start === null) {
      start = timestamp;
    }
    const time = Math.min(1, (timestamp - start) / duration);
    element[property] = ease(time) * (to - from) + from;
    if (time >= 1) {
      requestAnimationFrame(() => {
        cb(null);
      });
      return;
    }
    requestAnimationFrame(step);
  };
  if (from === to) {
    cb(new Error('Element already at target position'));
    return cancel;
  }
  requestAnimationFrame(step);
  return cancel;
}

const _excluded$1d = ["onChange"];
const styles$2 = {
  width: 99,
  height: 99,
  position: 'absolute',
  top: -9999,
  overflow: 'scroll'
};

/**
 * @ignore - internal component.
 * The component originates from https://github.com/STORIS/react-scrollbar-size.
 * It has been moved into the core in order to minimize the bundle size.
 */
function ScrollbarSize(props) {
  const {
      onChange
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1d);
  const scrollbarHeight = reactExports$1.useRef();
  const nodeRef = reactExports$1.useRef(null);
  const setMeasurements = () => {
    scrollbarHeight.current = nodeRef.current.offsetHeight - nodeRef.current.clientHeight;
  };
  useEnhancedEffect$1(() => {
    const handleResize = debounce$1(() => {
      const prevHeight = scrollbarHeight.current;
      setMeasurements();
      if (prevHeight !== scrollbarHeight.current) {
        onChange(scrollbarHeight.current);
      }
    });
    const containerWindow = ownerWindow(nodeRef.current);
    containerWindow.addEventListener('resize', handleResize);
    return () => {
      handleResize.clear();
      containerWindow.removeEventListener('resize', handleResize);
    };
  }, [onChange]);
  reactExports$1.useEffect(() => {
    setMeasurements();
    onChange(scrollbarHeight.current);
  }, [onChange]);
  return /*#__PURE__*/jsxRuntimeExports.jsx("div", _extends({
    style: styles$2,
    ref: nodeRef
  }, other));
}
ScrollbarSize.propTypes = {
  onChange: PropTypes.func.isRequired
} ;

var KeyboardArrowLeft = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"
}), 'KeyboardArrowLeft');

var KeyboardArrowRight = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"
}), 'KeyboardArrowRight');

function getTabScrollButtonUtilityClass(slot) {
  return generateUtilityClass('MuiTabScrollButton', slot);
}
const tabScrollButtonClasses = generateUtilityClasses('MuiTabScrollButton', ['root', 'vertical', 'horizontal', 'disabled']);
var tabScrollButtonClasses$1 = tabScrollButtonClasses;

const _excluded$1c = ["className", "slots", "slotProps", "direction", "orientation", "disabled"];
const useUtilityClasses$13 = ownerState => {
  const {
    classes,
    orientation,
    disabled
  } = ownerState;
  const slots = {
    root: ['root', orientation, disabled && 'disabled']
  };
  return composeClasses(slots, getTabScrollButtonUtilityClass, classes);
};
const TabScrollButtonRoot = styled$1(ButtonBase$1, {
  name: 'MuiTabScrollButton',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.orientation && styles[ownerState.orientation]];
  }
})(({
  ownerState
}) => _extends({
  width: 40,
  flexShrink: 0,
  opacity: 0.8,
  [`&.${tabScrollButtonClasses$1.disabled}`]: {
    opacity: 0
  }
}, ownerState.orientation === 'vertical' && {
  width: '100%',
  height: 40,
  '& svg': {
    transform: `rotate(${ownerState.isRtl ? -90 : 90}deg)`
  }
}));
const TabScrollButton = /*#__PURE__*/reactExports$1.forwardRef(function TabScrollButton(inProps, ref) {
  var _slots$StartScrollBut, _slots$EndScrollButto;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTabScrollButton'
  });
  const {
      className,
      slots = {},
      slotProps = {},
      direction
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1c);
  const theme = useTheme();
  const isRtl = theme.direction === 'rtl';
  const ownerState = _extends({
    isRtl
  }, props);
  const classes = useUtilityClasses$13(ownerState);
  const StartButtonIcon = (_slots$StartScrollBut = slots.StartScrollButtonIcon) != null ? _slots$StartScrollBut : KeyboardArrowLeft;
  const EndButtonIcon = (_slots$EndScrollButto = slots.EndScrollButtonIcon) != null ? _slots$EndScrollButto : KeyboardArrowRight;
  const startButtonIconProps = useSlotProps({
    elementType: StartButtonIcon,
    externalSlotProps: slotProps.startScrollButtonIcon,
    additionalProps: {
      fontSize: 'small'
    },
    ownerState
  });
  const endButtonIconProps = useSlotProps({
    elementType: EndButtonIcon,
    externalSlotProps: slotProps.endScrollButtonIcon,
    additionalProps: {
      fontSize: 'small'
    },
    ownerState
  });
  return /*#__PURE__*/jsxRuntimeExports.jsx(TabScrollButtonRoot, _extends({
    component: "div",
    className: clsx(classes.root, className),
    ref: ref,
    role: null,
    ownerState: ownerState,
    tabIndex: null
  }, other, {
    children: direction === 'left' ? /*#__PURE__*/jsxRuntimeExports.jsx(StartButtonIcon, _extends({}, startButtonIconProps)) : /*#__PURE__*/jsxRuntimeExports.jsx(EndButtonIcon, _extends({}, endButtonIconProps))
  }));
});
TabScrollButton.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The direction the button should indicate.
   */
  direction: PropTypes.oneOf(['left', 'right']).isRequired,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * The component orientation (layout flow direction).
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired,
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   * @default {}
   */
  slotProps: PropTypes.shape({
    endScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    startScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside.
   * @default {}
   */
  slots: PropTypes.shape({
    EndScrollButtonIcon: PropTypes.elementType,
    StartScrollButtonIcon: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var TabScrollButton$1 = TabScrollButton;

function getTabsUtilityClass(slot) {
  return generateUtilityClass('MuiTabs', slot);
}
const tabsClasses = generateUtilityClasses('MuiTabs', ['root', 'vertical', 'flexContainer', 'flexContainerVertical', 'centered', 'scroller', 'fixed', 'scrollableX', 'scrollableY', 'hideScrollbar', 'scrollButtons', 'scrollButtonsHideMobile', 'indicator']);
var tabsClasses$1 = tabsClasses;

const _excluded$1b = ["aria-label", "aria-labelledby", "action", "centered", "children", "className", "component", "allowScrollButtonsMobile", "indicatorColor", "onChange", "orientation", "ScrollButtonComponent", "scrollButtons", "selectionFollowsFocus", "slots", "slotProps", "TabIndicatorProps", "TabScrollButtonProps", "textColor", "value", "variant", "visibleScrollbar"];
const nextItem$1 = (list, item) => {
  if (list === item) {
    return list.firstChild;
  }
  if (item && item.nextElementSibling) {
    return item.nextElementSibling;
  }
  return list.firstChild;
};
const previousItem$1 = (list, item) => {
  if (list === item) {
    return list.lastChild;
  }
  if (item && item.previousElementSibling) {
    return item.previousElementSibling;
  }
  return list.lastChild;
};
const moveFocus$1 = (list, currentFocus, traversalFunction) => {
  let wrappedOnce = false;
  let nextFocus = traversalFunction(list, currentFocus);
  while (nextFocus) {
    // Prevent infinite loop.
    if (nextFocus === list.firstChild) {
      if (wrappedOnce) {
        return;
      }
      wrappedOnce = true;
    }

    // Same logic as useAutocomplete.js
    const nextFocusDisabled = nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
    if (!nextFocus.hasAttribute('tabindex') || nextFocusDisabled) {
      // Move to the next element.
      nextFocus = traversalFunction(list, nextFocus);
    } else {
      nextFocus.focus();
      return;
    }
  }
};
const useUtilityClasses$12 = ownerState => {
  const {
    vertical,
    fixed,
    hideScrollbar,
    scrollableX,
    scrollableY,
    centered,
    scrollButtonsHideMobile,
    classes
  } = ownerState;
  const slots = {
    root: ['root', vertical && 'vertical'],
    scroller: ['scroller', fixed && 'fixed', hideScrollbar && 'hideScrollbar', scrollableX && 'scrollableX', scrollableY && 'scrollableY'],
    flexContainer: ['flexContainer', vertical && 'flexContainerVertical', centered && 'centered'],
    indicator: ['indicator'],
    scrollButtons: ['scrollButtons', scrollButtonsHideMobile && 'scrollButtonsHideMobile'],
    scrollableX: [scrollableX && 'scrollableX'],
    hideScrollbar: [hideScrollbar && 'hideScrollbar']
  };
  return composeClasses(slots, getTabsUtilityClass, classes);
};
const TabsRoot = styled$1('div', {
  name: 'MuiTabs',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${tabsClasses$1.scrollButtons}`]: styles.scrollButtons
    }, {
      [`& .${tabsClasses$1.scrollButtons}`]: ownerState.scrollButtonsHideMobile && styles.scrollButtonsHideMobile
    }, styles.root, ownerState.vertical && styles.vertical];
  }
})(({
  ownerState,
  theme
}) => _extends({
  overflow: 'hidden',
  minHeight: 48,
  // Add iOS momentum scrolling for iOS < 13.0
  WebkitOverflowScrolling: 'touch',
  display: 'flex'
}, ownerState.vertical && {
  flexDirection: 'column'
}, ownerState.scrollButtonsHideMobile && {
  [`& .${tabsClasses$1.scrollButtons}`]: {
    [theme.breakpoints.down('sm')]: {
      display: 'none'
    }
  }
}));
const TabsScroller = styled$1('div', {
  name: 'MuiTabs',
  slot: 'Scroller',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.scroller, ownerState.fixed && styles.fixed, ownerState.hideScrollbar && styles.hideScrollbar, ownerState.scrollableX && styles.scrollableX, ownerState.scrollableY && styles.scrollableY];
  }
})(({
  ownerState
}) => _extends({
  position: 'relative',
  display: 'inline-block',
  flex: '1 1 auto',
  whiteSpace: 'nowrap'
}, ownerState.fixed && {
  overflowX: 'hidden',
  width: '100%'
}, ownerState.hideScrollbar && {
  // Hide dimensionless scrollbar on macOS
  scrollbarWidth: 'none',
  // Firefox
  '&::-webkit-scrollbar': {
    display: 'none' // Safari + Chrome
  }
}, ownerState.scrollableX && {
  overflowX: 'auto',
  overflowY: 'hidden'
}, ownerState.scrollableY && {
  overflowY: 'auto',
  overflowX: 'hidden'
}));
const FlexContainer = styled$1('div', {
  name: 'MuiTabs',
  slot: 'FlexContainer',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.flexContainer, ownerState.vertical && styles.flexContainerVertical, ownerState.centered && styles.centered];
  }
})(({
  ownerState
}) => _extends({
  display: 'flex'
}, ownerState.vertical && {
  flexDirection: 'column'
}, ownerState.centered && {
  justifyContent: 'center'
}));
const TabsIndicator = styled$1('span', {
  name: 'MuiTabs',
  slot: 'Indicator',
  overridesResolver: (props, styles) => styles.indicator
})(({
  ownerState,
  theme
}) => _extends({
  position: 'absolute',
  height: 2,
  bottom: 0,
  width: '100%',
  transition: theme.transitions.create()
}, ownerState.indicatorColor === 'primary' && {
  backgroundColor: (theme.vars || theme).palette.primary.main
}, ownerState.indicatorColor === 'secondary' && {
  backgroundColor: (theme.vars || theme).palette.secondary.main
}, ownerState.vertical && {
  height: '100%',
  width: 2,
  right: 0
}));
const TabsScrollbarSize = styled$1(ScrollbarSize, {
  name: 'MuiTabs',
  slot: 'ScrollbarSize'
})({
  overflowX: 'auto',
  overflowY: 'hidden',
  // Hide dimensionless scrollbar on macOS
  scrollbarWidth: 'none',
  // Firefox
  '&::-webkit-scrollbar': {
    display: 'none' // Safari + Chrome
  }
});

const defaultIndicatorStyle = {};
let warnedOnceTabPresent = false;
const Tabs = /*#__PURE__*/reactExports$1.forwardRef(function Tabs(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTabs'
  });
  const theme = useTheme();
  const isRtl = theme.direction === 'rtl';
  const {
      'aria-label': ariaLabel,
      'aria-labelledby': ariaLabelledBy,
      action,
      centered = false,
      children: childrenProp,
      className,
      component = 'div',
      allowScrollButtonsMobile = false,
      indicatorColor = 'primary',
      onChange,
      orientation = 'horizontal',
      ScrollButtonComponent = TabScrollButton$1,
      scrollButtons = 'auto',
      selectionFollowsFocus,
      slots = {},
      slotProps = {},
      TabIndicatorProps = {},
      TabScrollButtonProps = {},
      textColor = 'primary',
      value,
      variant = 'standard',
      visibleScrollbar = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1b);
  const scrollable = variant === 'scrollable';
  const vertical = orientation === 'vertical';
  const scrollStart = vertical ? 'scrollTop' : 'scrollLeft';
  const start = vertical ? 'top' : 'left';
  const end = vertical ? 'bottom' : 'right';
  const clientSize = vertical ? 'clientHeight' : 'clientWidth';
  const size = vertical ? 'height' : 'width';
  const ownerState = _extends({}, props, {
    component,
    allowScrollButtonsMobile,
    indicatorColor,
    orientation,
    vertical,
    scrollButtons,
    textColor,
    variant,
    visibleScrollbar,
    fixed: !scrollable,
    hideScrollbar: scrollable && !visibleScrollbar,
    scrollableX: scrollable && !vertical,
    scrollableY: scrollable && vertical,
    centered: centered && !scrollable,
    scrollButtonsHideMobile: !allowScrollButtonsMobile
  });
  const classes = useUtilityClasses$12(ownerState);
  const startScrollButtonIconProps = useSlotProps({
    elementType: slots.StartScrollButtonIcon,
    externalSlotProps: slotProps.startScrollButtonIcon,
    ownerState
  });
  const endScrollButtonIconProps = useSlotProps({
    elementType: slots.EndScrollButtonIcon,
    externalSlotProps: slotProps.endScrollButtonIcon,
    ownerState
  });
  {
    if (centered && scrollable) {
      console.error('MUI: You can not use the `centered={true}` and `variant="scrollable"` properties ' + 'at the same time on a `Tabs` component.');
    }
  }
  const [mounted, setMounted] = reactExports$1.useState(false);
  const [indicatorStyle, setIndicatorStyle] = reactExports$1.useState(defaultIndicatorStyle);
  const [displayScroll, setDisplayScroll] = reactExports$1.useState({
    start: false,
    end: false
  });
  const [scrollerStyle, setScrollerStyle] = reactExports$1.useState({
    overflow: 'hidden',
    scrollbarWidth: 0
  });
  const valueToIndex = new Map();
  const tabsRef = reactExports$1.useRef(null);
  const tabListRef = reactExports$1.useRef(null);
  const getTabsMeta = () => {
    const tabsNode = tabsRef.current;
    let tabsMeta;
    if (tabsNode) {
      const rect = tabsNode.getBoundingClientRect();
      // create a new object with ClientRect class props + scrollLeft
      tabsMeta = {
        clientWidth: tabsNode.clientWidth,
        scrollLeft: tabsNode.scrollLeft,
        scrollTop: tabsNode.scrollTop,
        scrollLeftNormalized: getNormalizedScrollLeft(tabsNode, theme.direction),
        scrollWidth: tabsNode.scrollWidth,
        top: rect.top,
        bottom: rect.bottom,
        left: rect.left,
        right: rect.right
      };
    }
    let tabMeta;
    if (tabsNode && value !== false) {
      const children = tabListRef.current.children;
      if (children.length > 0) {
        const tab = children[valueToIndex.get(value)];
        {
          if (!tab) {
            console.error([`MUI: The \`value\` provided to the Tabs component is invalid.`, `None of the Tabs' children match with "${value}".`, valueToIndex.keys ? `You can provide one of the following values: ${Array.from(valueToIndex.keys()).join(', ')}.` : null].join('\n'));
          }
        }
        tabMeta = tab ? tab.getBoundingClientRect() : null;
        {
          if (!warnedOnceTabPresent && tabMeta && tabMeta.width === 0 && tabMeta.height === 0 &&
          // if the whole Tabs component is hidden, don't warn
          tabsMeta.clientWidth !== 0) {
            tabsMeta = null;
            console.error(['MUI: The `value` provided to the Tabs component is invalid.', `The Tab with this \`value\` ("${value}") is not part of the document layout.`, "Make sure the tab item is present in the document or that it's not `display: none`."].join('\n'));
            warnedOnceTabPresent = true;
          }
        }
      }
    }
    return {
      tabsMeta,
      tabMeta
    };
  };
  const updateIndicatorState = useEventCallback(() => {
    const {
      tabsMeta,
      tabMeta
    } = getTabsMeta();
    let startValue = 0;
    let startIndicator;
    if (vertical) {
      startIndicator = 'top';
      if (tabMeta && tabsMeta) {
        startValue = tabMeta.top - tabsMeta.top + tabsMeta.scrollTop;
      }
    } else {
      startIndicator = isRtl ? 'right' : 'left';
      if (tabMeta && tabsMeta) {
        const correction = isRtl ? tabsMeta.scrollLeftNormalized + tabsMeta.clientWidth - tabsMeta.scrollWidth : tabsMeta.scrollLeft;
        startValue = (isRtl ? -1 : 1) * (tabMeta[startIndicator] - tabsMeta[startIndicator] + correction);
      }
    }
    const newIndicatorStyle = {
      [startIndicator]: startValue,
      // May be wrong until the font is loaded.
      [size]: tabMeta ? tabMeta[size] : 0
    };

    // IE11 support, replace with Number.isNaN
    // eslint-disable-next-line no-restricted-globals
    if (isNaN(indicatorStyle[startIndicator]) || isNaN(indicatorStyle[size])) {
      setIndicatorStyle(newIndicatorStyle);
    } else {
      const dStart = Math.abs(indicatorStyle[startIndicator] - newIndicatorStyle[startIndicator]);
      const dSize = Math.abs(indicatorStyle[size] - newIndicatorStyle[size]);
      if (dStart >= 1 || dSize >= 1) {
        setIndicatorStyle(newIndicatorStyle);
      }
    }
  });
  const scroll = (scrollValue, {
    animation = true
  } = {}) => {
    if (animation) {
      animate(scrollStart, tabsRef.current, scrollValue, {
        duration: theme.transitions.duration.standard
      });
    } else {
      tabsRef.current[scrollStart] = scrollValue;
    }
  };
  const moveTabsScroll = delta => {
    let scrollValue = tabsRef.current[scrollStart];
    if (vertical) {
      scrollValue += delta;
    } else {
      scrollValue += delta * (isRtl ? -1 : 1);
      // Fix for Edge
      scrollValue *= isRtl && detectScrollType() === 'reverse' ? -1 : 1;
    }
    scroll(scrollValue);
  };
  const getScrollSize = () => {
    const containerSize = tabsRef.current[clientSize];
    let totalSize = 0;
    const children = Array.from(tabListRef.current.children);
    for (let i = 0; i < children.length; i += 1) {
      const tab = children[i];
      if (totalSize + tab[clientSize] > containerSize) {
        // If the first item is longer than the container size, then only scroll
        // by the container size.
        if (i === 0) {
          totalSize = containerSize;
        }
        break;
      }
      totalSize += tab[clientSize];
    }
    return totalSize;
  };
  const handleStartScrollClick = () => {
    moveTabsScroll(-1 * getScrollSize());
  };
  const handleEndScrollClick = () => {
    moveTabsScroll(getScrollSize());
  };

  // TODO Remove <ScrollbarSize /> as browser support for hiding the scrollbar
  // with CSS improves.
  const handleScrollbarSizeChange = reactExports$1.useCallback(scrollbarWidth => {
    setScrollerStyle({
      overflow: null,
      scrollbarWidth
    });
  }, []);
  const getConditionalElements = () => {
    const conditionalElements = {};
    conditionalElements.scrollbarSizeListener = scrollable ? /*#__PURE__*/jsxRuntimeExports.jsx(TabsScrollbarSize, {
      onChange: handleScrollbarSizeChange,
      className: clsx(classes.scrollableX, classes.hideScrollbar)
    }) : null;
    const scrollButtonsActive = displayScroll.start || displayScroll.end;
    const showScrollButtons = scrollable && (scrollButtons === 'auto' && scrollButtonsActive || scrollButtons === true);
    conditionalElements.scrollButtonStart = showScrollButtons ? /*#__PURE__*/jsxRuntimeExports.jsx(ScrollButtonComponent, _extends({
      slots: {
        StartScrollButtonIcon: slots.StartScrollButtonIcon
      },
      slotProps: {
        startScrollButtonIcon: startScrollButtonIconProps
      },
      orientation: orientation,
      direction: isRtl ? 'right' : 'left',
      onClick: handleStartScrollClick,
      disabled: !displayScroll.start
    }, TabScrollButtonProps, {
      className: clsx(classes.scrollButtons, TabScrollButtonProps.className)
    })) : null;
    conditionalElements.scrollButtonEnd = showScrollButtons ? /*#__PURE__*/jsxRuntimeExports.jsx(ScrollButtonComponent, _extends({
      slots: {
        EndScrollButtonIcon: slots.EndScrollButtonIcon
      },
      slotProps: {
        endScrollButtonIcon: endScrollButtonIconProps
      },
      orientation: orientation,
      direction: isRtl ? 'left' : 'right',
      onClick: handleEndScrollClick,
      disabled: !displayScroll.end
    }, TabScrollButtonProps, {
      className: clsx(classes.scrollButtons, TabScrollButtonProps.className)
    })) : null;
    return conditionalElements;
  };
  const scrollSelectedIntoView = useEventCallback(animation => {
    const {
      tabsMeta,
      tabMeta
    } = getTabsMeta();
    if (!tabMeta || !tabsMeta) {
      return;
    }
    if (tabMeta[start] < tabsMeta[start]) {
      // left side of button is out of view
      const nextScrollStart = tabsMeta[scrollStart] + (tabMeta[start] - tabsMeta[start]);
      scroll(nextScrollStart, {
        animation
      });
    } else if (tabMeta[end] > tabsMeta[end]) {
      // right side of button is out of view
      const nextScrollStart = tabsMeta[scrollStart] + (tabMeta[end] - tabsMeta[end]);
      scroll(nextScrollStart, {
        animation
      });
    }
  });
  const updateScrollButtonState = useEventCallback(() => {
    if (scrollable && scrollButtons !== false) {
      const {
        scrollTop,
        scrollHeight,
        clientHeight,
        scrollWidth,
        clientWidth
      } = tabsRef.current;
      let showStartScroll;
      let showEndScroll;
      if (vertical) {
        showStartScroll = scrollTop > 1;
        showEndScroll = scrollTop < scrollHeight - clientHeight - 1;
      } else {
        const scrollLeft = getNormalizedScrollLeft(tabsRef.current, theme.direction);
        // use 1 for the potential rounding error with browser zooms.
        showStartScroll = isRtl ? scrollLeft < scrollWidth - clientWidth - 1 : scrollLeft > 1;
        showEndScroll = !isRtl ? scrollLeft < scrollWidth - clientWidth - 1 : scrollLeft > 1;
      }
      if (showStartScroll !== displayScroll.start || showEndScroll !== displayScroll.end) {
        setDisplayScroll({
          start: showStartScroll,
          end: showEndScroll
        });
      }
    }
  });
  reactExports$1.useEffect(() => {
    const handleResize = debounce$1(() => {
      // If the Tabs component is replaced by Suspense with a fallback, the last
      // ResizeObserver's handler that runs because of the change in the layout is trying to
      // access a dom node that is no longer there (as the fallback component is being shown instead).
      // See https://github.com/mui/material-ui/issues/33276
      // TODO: Add tests that will ensure the component is not failing when
      // replaced by Suspense with a fallback, once React is updated to version 18
      if (tabsRef.current) {
        updateIndicatorState();
        updateScrollButtonState();
      }
    });
    const win = ownerWindow(tabsRef.current);
    win.addEventListener('resize', handleResize);
    let resizeObserver;
    if (typeof ResizeObserver !== 'undefined') {
      resizeObserver = new ResizeObserver(handleResize);
      Array.from(tabListRef.current.children).forEach(child => {
        resizeObserver.observe(child);
      });
    }
    return () => {
      handleResize.clear();
      win.removeEventListener('resize', handleResize);
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  }, [updateIndicatorState, updateScrollButtonState]);
  const handleTabsScroll = reactExports$1.useMemo(() => debounce$1(() => {
    updateScrollButtonState();
  }), [updateScrollButtonState]);
  reactExports$1.useEffect(() => {
    return () => {
      handleTabsScroll.clear();
    };
  }, [handleTabsScroll]);
  reactExports$1.useEffect(() => {
    setMounted(true);
  }, []);
  reactExports$1.useEffect(() => {
    updateIndicatorState();
    updateScrollButtonState();
  });
  reactExports$1.useEffect(() => {
    // Don't animate on the first render.
    scrollSelectedIntoView(defaultIndicatorStyle !== indicatorStyle);
  }, [scrollSelectedIntoView, indicatorStyle]);
  reactExports$1.useImperativeHandle(action, () => ({
    updateIndicator: updateIndicatorState,
    updateScrollButtons: updateScrollButtonState
  }), [updateIndicatorState, updateScrollButtonState]);
  const indicator = /*#__PURE__*/jsxRuntimeExports.jsx(TabsIndicator, _extends({}, TabIndicatorProps, {
    className: clsx(classes.indicator, TabIndicatorProps.className),
    ownerState: ownerState,
    style: _extends({}, indicatorStyle, TabIndicatorProps.style)
  }));
  let childIndex = 0;
  const children = reactExports$1.Children.map(childrenProp, child => {
    if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
      return null;
    }
    {
      if (reactIsExports$1.isFragment(child)) {
        console.error(["MUI: The Tabs component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
      }
    }
    const childValue = child.props.value === undefined ? childIndex : child.props.value;
    valueToIndex.set(childValue, childIndex);
    const selected = childValue === value;
    childIndex += 1;
    return /*#__PURE__*/reactExports$1.cloneElement(child, _extends({
      fullWidth: variant === 'fullWidth',
      indicator: selected && !mounted && indicator,
      selected,
      selectionFollowsFocus,
      onChange,
      textColor,
      value: childValue
    }, childIndex === 1 && value === false && !child.props.tabIndex ? {
      tabIndex: 0
    } : {}));
  });
  const handleKeyDown = event => {
    const list = tabListRef.current;
    const currentFocus = ownerDocument(list).activeElement;
    // Keyboard navigation assumes that [role="tab"] are siblings
    // though we might warn in the future about nested, interactive elements
    // as a a11y violation
    const role = currentFocus.getAttribute('role');
    if (role !== 'tab') {
      return;
    }
    let previousItemKey = orientation === 'horizontal' ? 'ArrowLeft' : 'ArrowUp';
    let nextItemKey = orientation === 'horizontal' ? 'ArrowRight' : 'ArrowDown';
    if (orientation === 'horizontal' && isRtl) {
      // swap previousItemKey with nextItemKey
      previousItemKey = 'ArrowRight';
      nextItemKey = 'ArrowLeft';
    }
    switch (event.key) {
      case previousItemKey:
        event.preventDefault();
        moveFocus$1(list, currentFocus, previousItem$1);
        break;
      case nextItemKey:
        event.preventDefault();
        moveFocus$1(list, currentFocus, nextItem$1);
        break;
      case 'Home':
        event.preventDefault();
        moveFocus$1(list, null, nextItem$1);
        break;
      case 'End':
        event.preventDefault();
        moveFocus$1(list, null, previousItem$1);
        break;
    }
  };
  const conditionalElements = getConditionalElements();
  return /*#__PURE__*/jsxRuntimeExports.jsxs(TabsRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref,
    as: component
  }, other, {
    children: [conditionalElements.scrollButtonStart, conditionalElements.scrollbarSizeListener, /*#__PURE__*/jsxRuntimeExports.jsxs(TabsScroller, {
      className: classes.scroller,
      ownerState: ownerState,
      style: {
        overflow: scrollerStyle.overflow,
        [vertical ? `margin${isRtl ? 'Left' : 'Right'}` : 'marginBottom']: visibleScrollbar ? undefined : -scrollerStyle.scrollbarWidth
      },
      ref: tabsRef,
      onScroll: handleTabsScroll,
      children: [/*#__PURE__*/jsxRuntimeExports.jsx(FlexContainer, {
        "aria-label": ariaLabel,
        "aria-labelledby": ariaLabelledBy,
        "aria-orientation": orientation === 'vertical' ? 'vertical' : null,
        className: classes.flexContainer,
        ownerState: ownerState,
        onKeyDown: handleKeyDown,
        ref: tabListRef,
        role: "tablist",
        children: children
      }), mounted && indicator]
    }), conditionalElements.scrollButtonEnd]
  }));
});
Tabs.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Callback fired when the component mounts.
   * This is useful when you want to trigger an action programmatically.
   * It supports two actions: `updateIndicator()` and `updateScrollButtons()`
   *
   * @param {object} actions This object contains all possible actions
   * that can be triggered programmatically.
   */
  action: refType$1,
  /**
   * If `true`, the scroll buttons aren't forced hidden on mobile.
   * By default the scroll buttons are hidden on mobile and takes precedence over `scrollButtons`.
   * @default false
   */
  allowScrollButtonsMobile: PropTypes.bool,
  /**
   * The label for the Tabs as a string.
   */
  'aria-label': PropTypes.string,
  /**
   * An id or list of ids separated by a space that label the Tabs.
   */
  'aria-labelledby': PropTypes.string,
  /**
   * If `true`, the tabs are centered.
   * This prop is intended for large views.
   * @default false
   */
  centered: PropTypes.bool,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Determines the color of the indicator.
   * @default 'primary'
   */
  indicatorColor: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]),
  /**
   * Callback fired when the value changes.
   *
   * @param {React.SyntheticEvent} event The event source of the callback. **Warning**: This is a generic event not a change event.
   * @param {any} value We default to the index of the child (number)
   */
  onChange: PropTypes.func,
  /**
   * The component orientation (layout flow direction).
   * @default 'horizontal'
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']),
  /**
   * The component used to render the scroll buttons.
   * @default TabScrollButton
   */
  ScrollButtonComponent: PropTypes.elementType,
  /**
   * Determine behavior of scroll buttons when tabs are set to scroll:
   *
   * - `auto` will only present them when not all the items are visible.
   * - `true` will always present them.
   * - `false` will never present them.
   *
   * By default the scroll buttons are hidden on mobile.
   * This behavior can be disabled with `allowScrollButtonsMobile`.
   * @default 'auto'
   */
  scrollButtons: PropTypes /* @typescript-to-proptypes-ignore */.oneOf(['auto', false, true]),
  /**
   * If `true` the selected tab changes on focus. Otherwise it only
   * changes on activation.
   */
  selectionFollowsFocus: PropTypes.bool,
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   * @default {}
   */
  slotProps: PropTypes.shape({
    endScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    startScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside.
   * @default {}
   */
  slots: PropTypes.shape({
    EndScrollButtonIcon: PropTypes.elementType,
    StartScrollButtonIcon: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Props applied to the tab indicator element.
   * @default  {}
   */
  TabIndicatorProps: PropTypes.object,
  /**
   * Props applied to the [`TabScrollButton`](/material-ui/api/tab-scroll-button/) element.
   * @default {}
   */
  TabScrollButtonProps: PropTypes.object,
  /**
   * Determines the color of the `Tab`.
   * @default 'primary'
   */
  textColor: PropTypes.oneOf(['inherit', 'primary', 'secondary']),
  /**
   * The value of the currently selected `Tab`.
   * If you don't want any selected `Tab`, you can set this prop to `false`.
   */
  value: PropTypes.any,
  /**
   * Determines additional display behavior of the tabs:
   *
   *  - `scrollable` will invoke scrolling properties and allow for horizontally
   *  scrolling (or swiping) of the tab bar.
   *  -`fullWidth` will make the tabs grow to use all the available space,
   *  which should be used for small views, like on mobile.
   *  - `standard` will render the default state.
   * @default 'standard'
   */
  variant: PropTypes.oneOf(['fullWidth', 'scrollable', 'standard']),
  /**
   * If `true`, the scrollbar is visible. It can be useful when displaying
   * a long vertical list of tabs.
   * @default false
   */
  visibleScrollbar: PropTypes.bool
} ;
var Tabs$1 = Tabs;

function TabGroup(props) {
  if (props.value || props.setValue) {
    return /*#__PURE__*/React.createElement(ControlledTabGroup, {
      ...props
    });
  } else {
    return /*#__PURE__*/React.createElement(UncontrolledTabGroup, {
      ...props
    });
  }
}
function UncontrolledTabGroup({
  children,
  ...rest
}) {
  const tabs = React.Children.toArray(children),
    [value, setValue] = reactExports$1.useState(tabs[0].props.value);
  return /*#__PURE__*/React.createElement(ControlledTabGroup, {
    value: value,
    setValue: setValue,
    ...rest
  }, children);
}
function ControlledTabGroup({
  children,
  value,
  setValue,
  ...rest
}) {
  const tabs = React.Children.toArray(children),
    activeTab = tabs.find(tab => tab.props.value === value),
    handleChange = (evt, tab) => setValue(tab);
  return /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1,
      display: "flex",
      flexDirection: "column",
      overflow: "hidden"
    }
  }, /*#__PURE__*/React.createElement(Tabs$1, {
    value: value,
    onChange: handleChange,
    variant: "fullWidth",
    ...rest
  }, tabs), /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1,
      display: "flex",
      flexDirection: "column",
      overflow: "hidden"
    }
  }, activeTab && activeTab.props.children));
}

function getTabUtilityClass(slot) {
  return generateUtilityClass('MuiTab', slot);
}
const tabClasses = generateUtilityClasses('MuiTab', ['root', 'labelIcon', 'textColorInherit', 'textColorPrimary', 'textColorSecondary', 'selected', 'disabled', 'fullWidth', 'wrapped', 'iconWrapper']);
var tabClasses$1 = tabClasses;

const _excluded$1a = ["className", "disabled", "disableFocusRipple", "fullWidth", "icon", "iconPosition", "indicator", "label", "onChange", "onClick", "onFocus", "selected", "selectionFollowsFocus", "textColor", "value", "wrapped"];
const useUtilityClasses$11 = ownerState => {
  const {
    classes,
    textColor,
    fullWidth,
    wrapped,
    icon,
    label,
    selected,
    disabled
  } = ownerState;
  const slots = {
    root: ['root', icon && label && 'labelIcon', `textColor${capitalize(textColor)}`, fullWidth && 'fullWidth', wrapped && 'wrapped', selected && 'selected', disabled && 'disabled'],
    iconWrapper: ['iconWrapper']
  };
  return composeClasses(slots, getTabUtilityClass, classes);
};
const TabRoot = styled$1(ButtonBase$1, {
  name: 'MuiTab',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.label && ownerState.icon && styles.labelIcon, styles[`textColor${capitalize(ownerState.textColor)}`], ownerState.fullWidth && styles.fullWidth, ownerState.wrapped && styles.wrapped];
  }
})(({
  theme,
  ownerState
}) => _extends({}, theme.typography.button, {
  maxWidth: 360,
  minWidth: 90,
  position: 'relative',
  minHeight: 48,
  flexShrink: 0,
  padding: '12px 16px',
  overflow: 'hidden',
  whiteSpace: 'normal',
  textAlign: 'center'
}, ownerState.label && {
  flexDirection: ownerState.iconPosition === 'top' || ownerState.iconPosition === 'bottom' ? 'column' : 'row'
}, {
  lineHeight: 1.25
}, ownerState.icon && ownerState.label && {
  minHeight: 72,
  paddingTop: 9,
  paddingBottom: 9,
  [`& > .${tabClasses$1.iconWrapper}`]: _extends({}, ownerState.iconPosition === 'top' && {
    marginBottom: 6
  }, ownerState.iconPosition === 'bottom' && {
    marginTop: 6
  }, ownerState.iconPosition === 'start' && {
    marginRight: theme.spacing(1)
  }, ownerState.iconPosition === 'end' && {
    marginLeft: theme.spacing(1)
  })
}, ownerState.textColor === 'inherit' && {
  color: 'inherit',
  opacity: 0.6,
  // same opacity as theme.palette.text.secondary
  [`&.${tabClasses$1.selected}`]: {
    opacity: 1
  },
  [`&.${tabClasses$1.disabled}`]: {
    opacity: (theme.vars || theme).palette.action.disabledOpacity
  }
}, ownerState.textColor === 'primary' && {
  color: (theme.vars || theme).palette.text.secondary,
  [`&.${tabClasses$1.selected}`]: {
    color: (theme.vars || theme).palette.primary.main
  },
  [`&.${tabClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.text.disabled
  }
}, ownerState.textColor === 'secondary' && {
  color: (theme.vars || theme).palette.text.secondary,
  [`&.${tabClasses$1.selected}`]: {
    color: (theme.vars || theme).palette.secondary.main
  },
  [`&.${tabClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.text.disabled
  }
}, ownerState.fullWidth && {
  flexShrink: 1,
  flexGrow: 1,
  flexBasis: 0,
  maxWidth: 'none'
}, ownerState.wrapped && {
  fontSize: theme.typography.pxToRem(12)
}));
const Tab = /*#__PURE__*/reactExports$1.forwardRef(function Tab(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTab'
  });
  const {
      className,
      disabled = false,
      disableFocusRipple = false,
      // eslint-disable-next-line react/prop-types
      fullWidth,
      icon: iconProp,
      iconPosition = 'top',
      // eslint-disable-next-line react/prop-types
      indicator,
      label,
      onChange,
      onClick,
      onFocus,
      // eslint-disable-next-line react/prop-types
      selected,
      // eslint-disable-next-line react/prop-types
      selectionFollowsFocus,
      // eslint-disable-next-line react/prop-types
      textColor = 'inherit',
      value,
      wrapped = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1a);
  const ownerState = _extends({}, props, {
    disabled,
    disableFocusRipple,
    selected,
    icon: !!iconProp,
    iconPosition,
    label: !!label,
    fullWidth,
    textColor,
    wrapped
  });
  const classes = useUtilityClasses$11(ownerState);
  const icon = iconProp && label && /*#__PURE__*/reactExports$1.isValidElement(iconProp) ? /*#__PURE__*/reactExports$1.cloneElement(iconProp, {
    className: clsx(classes.iconWrapper, iconProp.props.className)
  }) : iconProp;
  const handleClick = event => {
    if (!selected && onChange) {
      onChange(event, value);
    }
    if (onClick) {
      onClick(event);
    }
  };
  const handleFocus = event => {
    if (selectionFollowsFocus && !selected && onChange) {
      onChange(event, value);
    }
    if (onFocus) {
      onFocus(event);
    }
  };
  return /*#__PURE__*/jsxRuntimeExports.jsxs(TabRoot, _extends({
    focusRipple: !disableFocusRipple,
    className: clsx(classes.root, className),
    ref: ref,
    role: "tab",
    "aria-selected": selected,
    disabled: disabled,
    onClick: handleClick,
    onFocus: handleFocus,
    ownerState: ownerState,
    tabIndex: selected ? 0 : -1
  }, other, {
    children: [iconPosition === 'top' || iconPosition === 'start' ? /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
      children: [icon, label]
    }) : /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
      children: [label, icon]
    }), indicator]
  }));
});
Tab.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * This prop isn't supported.
   * Use the `component` prop if you need to change the children structure.
   */
  children: unsupportedProp,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the  keyboard focus ripple is disabled.
   * @default false
   */
  disableFocusRipple: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   *
   * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
   * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * The icon to display.
   */
  icon: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
  /**
   * The position of the icon relative to the label.
   * @default 'top'
   */
  iconPosition: PropTypes.oneOf(['bottom', 'end', 'start', 'top']),
  /**
   * The label element.
   */
  label: PropTypes.node,
  /**
   * @ignore
   */
  onChange: PropTypes.func,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * You can provide your own value. Otherwise, we fallback to the child position index.
   */
  value: PropTypes.any,
  /**
   * Tab labels appear in a single row.
   * They can use a second line if needed.
   * @default false
   */
  wrapped: PropTypes.bool
} ;
var Tab$1 = Tab;

function TabItem({
  icon,
  to,
  children,
  ...rest
}) {
  /* eslint no-unused-vars: off */
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement(Tab$1, {
    component: to && Link$3,
    icon: Icon && /*#__PURE__*/React.createElement(Icon, null),
    to: to,
    ...rest
  });
  // children rendered by TabGroup
}

TabItem.propTypes = {
  icon: PropTypes.string,
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  children: PropTypes.node
};

function getBottomNavigationUtilityClass(slot) {
  return generateUtilityClass('MuiBottomNavigation', slot);
}
generateUtilityClasses('MuiBottomNavigation', ['root']);

const _excluded$19 = ["children", "className", "component", "onChange", "showLabels", "value"];
const useUtilityClasses$10 = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getBottomNavigationUtilityClass, classes);
};
const BottomNavigationRoot = styled$1('div', {
  name: 'MuiBottomNavigation',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  display: 'flex',
  justifyContent: 'center',
  height: 56,
  backgroundColor: (theme.vars || theme).palette.background.paper
}));
const BottomNavigation = /*#__PURE__*/reactExports$1.forwardRef(function BottomNavigation(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiBottomNavigation'
  });
  const {
      children,
      className,
      component = 'div',
      onChange,
      showLabels = false,
      value
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$19);
  const ownerState = _extends({}, props, {
    component,
    showLabels
  });
  const classes = useUtilityClasses$10(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(BottomNavigationRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    ref: ref,
    ownerState: ownerState
  }, other, {
    children: reactExports$1.Children.map(children, (child, childIndex) => {
      if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
        return null;
      }
      {
        if (reactIsExports$1.isFragment(child)) {
          console.error(["MUI: The BottomNavigation component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
        }
      }
      const childValue = child.props.value === undefined ? childIndex : child.props.value;
      return /*#__PURE__*/reactExports$1.cloneElement(child, {
        selected: childValue === value,
        showLabel: child.props.showLabel !== undefined ? child.props.showLabel : showLabels,
        value: childValue,
        onChange
      });
    })
  }));
});
BottomNavigation.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Callback fired when the value changes.
   *
   * @param {React.SyntheticEvent} event The event source of the callback. **Warning**: This is a generic event not a change event.
   * @param {any} value We default to the index of the child.
   */
  onChange: PropTypes.func,
  /**
   * If `true`, all `BottomNavigationAction`s will show their labels.
   * By default, only the selected `BottomNavigationAction` will show its label.
   * @default false
   */
  showLabels: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the currently selected `BottomNavigationAction`.
   */
  value: PropTypes.any
} ;
var BottomNavigation$1 = BottomNavigation;

function getBottomNavigationActionUtilityClass(slot) {
  return generateUtilityClass('MuiBottomNavigationAction', slot);
}
const bottomNavigationActionClasses = generateUtilityClasses('MuiBottomNavigationAction', ['root', 'iconOnly', 'selected', 'label']);
var bottomNavigationActionClasses$1 = bottomNavigationActionClasses;

const _excluded$18 = ["className", "icon", "label", "onChange", "onClick", "selected", "showLabel", "value"];
const useUtilityClasses$$ = ownerState => {
  const {
    classes,
    showLabel,
    selected
  } = ownerState;
  const slots = {
    root: ['root', !showLabel && !selected && 'iconOnly', selected && 'selected'],
    label: ['label', !showLabel && !selected && 'iconOnly', selected && 'selected']
  };
  return composeClasses(slots, getBottomNavigationActionUtilityClass, classes);
};
const BottomNavigationActionRoot = styled$1(ButtonBase$1, {
  name: 'MuiBottomNavigationAction',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, !ownerState.showLabel && !ownerState.selected && styles.iconOnly];
  }
})(({
  theme,
  ownerState
}) => _extends({
  transition: theme.transitions.create(['color', 'padding-top'], {
    duration: theme.transitions.duration.short
  }),
  padding: '0px 12px',
  minWidth: 80,
  maxWidth: 168,
  color: (theme.vars || theme).palette.text.secondary,
  flexDirection: 'column',
  flex: '1'
}, !ownerState.showLabel && !ownerState.selected && {
  paddingTop: 14
}, !ownerState.showLabel && !ownerState.selected && !ownerState.label && {
  paddingTop: 0
}, {
  [`&.${bottomNavigationActionClasses$1.selected}`]: {
    color: (theme.vars || theme).palette.primary.main
  }
}));
const BottomNavigationActionLabel = styled$1('span', {
  name: 'MuiBottomNavigationAction',
  slot: 'Label',
  overridesResolver: (props, styles) => styles.label
})(({
  theme,
  ownerState
}) => _extends({
  fontFamily: theme.typography.fontFamily,
  fontSize: theme.typography.pxToRem(12),
  opacity: 1,
  transition: 'font-size 0.2s, opacity 0.2s',
  transitionDelay: '0.1s'
}, !ownerState.showLabel && !ownerState.selected && {
  opacity: 0,
  transitionDelay: '0s'
}, {
  [`&.${bottomNavigationActionClasses$1.selected}`]: {
    fontSize: theme.typography.pxToRem(14)
  }
}));
const BottomNavigationAction$1 = /*#__PURE__*/reactExports$1.forwardRef(function BottomNavigationAction(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiBottomNavigationAction'
  });
  const {
      className,
      icon,
      label,
      onChange,
      onClick
      // eslint-disable-next-line react/prop-types -- private, always overridden by BottomNavigation
      ,

      value
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$18);
  const ownerState = props;
  const classes = useUtilityClasses$$(ownerState);
  const handleChange = event => {
    if (onChange) {
      onChange(event, value);
    }
    if (onClick) {
      onClick(event);
    }
  };
  return /*#__PURE__*/jsxRuntimeExports.jsxs(BottomNavigationActionRoot, _extends({
    ref: ref,
    className: clsx(classes.root, className),
    focusRipple: true,
    onClick: handleChange,
    ownerState: ownerState
  }, other, {
    children: [icon, /*#__PURE__*/jsxRuntimeExports.jsx(BottomNavigationActionLabel, {
      className: classes.label,
      ownerState: ownerState,
      children: label
    })]
  }));
});
BottomNavigationAction$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * This prop isn't supported.
   * Use the `component` prop if you need to change the children structure.
   */
  children: unsupportedProp,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The icon to display.
   */
  icon: PropTypes.node,
  /**
   * The label element.
   */
  label: PropTypes.node,
  /**
   * @ignore
   */
  onChange: PropTypes.func,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * If `true`, the `BottomNavigationAction` will show its label.
   * By default, only the selected `BottomNavigationAction`
   * inside `BottomNavigation` will show its label.
   *
   * The prop defaults to the value (`false`) inherited from the parent BottomNavigation component.
   */
  showLabel: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * You can provide your own value. Otherwise, we fallback to the child position index.
   */
  value: PropTypes.any
} ;
var BottomNavigationAction$2 = BottomNavigationAction$1;

function BottomNavigationAction({
  icon,
  to,
  ...rest
}) {
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement(BottomNavigationAction$2, {
    component: to && Link$3,
    icon: Icon && /*#__PURE__*/React.createElement(Icon, null),
    to: to,
    ...rest
  });
}
BottomNavigationAction.propTypes = {
  icon: PropTypes.string,
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
};

var CancelIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"
}), 'Cancel');

function getChipUtilityClass(slot) {
  return generateUtilityClass('MuiChip', slot);
}
const chipClasses = generateUtilityClasses('MuiChip', ['root', 'sizeSmall', 'sizeMedium', 'colorError', 'colorInfo', 'colorPrimary', 'colorSecondary', 'colorSuccess', 'colorWarning', 'disabled', 'clickable', 'clickableColorPrimary', 'clickableColorSecondary', 'deletable', 'deletableColorPrimary', 'deletableColorSecondary', 'outlined', 'filled', 'outlinedPrimary', 'outlinedSecondary', 'filledPrimary', 'filledSecondary', 'avatar', 'avatarSmall', 'avatarMedium', 'avatarColorPrimary', 'avatarColorSecondary', 'icon', 'iconSmall', 'iconMedium', 'iconColorPrimary', 'iconColorSecondary', 'label', 'labelSmall', 'labelMedium', 'deleteIcon', 'deleteIconSmall', 'deleteIconMedium', 'deleteIconColorPrimary', 'deleteIconColorSecondary', 'deleteIconOutlinedColorPrimary', 'deleteIconOutlinedColorSecondary', 'deleteIconFilledColorPrimary', 'deleteIconFilledColorSecondary', 'focusVisible']);
var chipClasses$1 = chipClasses;

const _excluded$17 = ["avatar", "className", "clickable", "color", "component", "deleteIcon", "disabled", "icon", "label", "onClick", "onDelete", "onKeyDown", "onKeyUp", "size", "variant", "tabIndex", "skipFocusWhenDisabled"];
const useUtilityClasses$_ = ownerState => {
  const {
    classes,
    disabled,
    size,
    color,
    iconColor,
    onDelete,
    clickable,
    variant
  } = ownerState;
  const slots = {
    root: ['root', variant, disabled && 'disabled', `size${capitalize(size)}`, `color${capitalize(color)}`, clickable && 'clickable', clickable && `clickableColor${capitalize(color)}`, onDelete && 'deletable', onDelete && `deletableColor${capitalize(color)}`, `${variant}${capitalize(color)}`],
    label: ['label', `label${capitalize(size)}`],
    avatar: ['avatar', `avatar${capitalize(size)}`, `avatarColor${capitalize(color)}`],
    icon: ['icon', `icon${capitalize(size)}`, `iconColor${capitalize(iconColor)}`],
    deleteIcon: ['deleteIcon', `deleteIcon${capitalize(size)}`, `deleteIconColor${capitalize(color)}`, `deleteIcon${capitalize(variant)}Color${capitalize(color)}`]
  };
  return composeClasses(slots, getChipUtilityClass, classes);
};
const ChipRoot = styled$1('div', {
  name: 'MuiChip',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    const {
      color,
      iconColor,
      clickable,
      onDelete,
      size,
      variant
    } = ownerState;
    return [{
      [`& .${chipClasses$1.avatar}`]: styles.avatar
    }, {
      [`& .${chipClasses$1.avatar}`]: styles[`avatar${capitalize(size)}`]
    }, {
      [`& .${chipClasses$1.avatar}`]: styles[`avatarColor${capitalize(color)}`]
    }, {
      [`& .${chipClasses$1.icon}`]: styles.icon
    }, {
      [`& .${chipClasses$1.icon}`]: styles[`icon${capitalize(size)}`]
    }, {
      [`& .${chipClasses$1.icon}`]: styles[`iconColor${capitalize(iconColor)}`]
    }, {
      [`& .${chipClasses$1.deleteIcon}`]: styles.deleteIcon
    }, {
      [`& .${chipClasses$1.deleteIcon}`]: styles[`deleteIcon${capitalize(size)}`]
    }, {
      [`& .${chipClasses$1.deleteIcon}`]: styles[`deleteIconColor${capitalize(color)}`]
    }, {
      [`& .${chipClasses$1.deleteIcon}`]: styles[`deleteIcon${capitalize(variant)}Color${capitalize(color)}`]
    }, styles.root, styles[`size${capitalize(size)}`], styles[`color${capitalize(color)}`], clickable && styles.clickable, clickable && color !== 'default' && styles[`clickableColor${capitalize(color)})`], onDelete && styles.deletable, onDelete && color !== 'default' && styles[`deletableColor${capitalize(color)}`], styles[variant], styles[`${variant}${capitalize(color)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  const textColor = theme.palette.mode === 'light' ? theme.palette.grey[700] : theme.palette.grey[300];
  return _extends({
    maxWidth: '100%',
    fontFamily: theme.typography.fontFamily,
    fontSize: theme.typography.pxToRem(13),
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    height: 32,
    color: (theme.vars || theme).palette.text.primary,
    backgroundColor: (theme.vars || theme).palette.action.selected,
    borderRadius: 32 / 2,
    whiteSpace: 'nowrap',
    transition: theme.transitions.create(['background-color', 'box-shadow']),
    // label will inherit this from root, then `clickable` class overrides this for both
    cursor: 'default',
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,
    textDecoration: 'none',
    border: 0,
    // Remove `button` border
    padding: 0,
    // Remove `button` padding
    verticalAlign: 'middle',
    boxSizing: 'border-box',
    [`&.${chipClasses$1.disabled}`]: {
      opacity: (theme.vars || theme).palette.action.disabledOpacity,
      pointerEvents: 'none'
    },
    [`& .${chipClasses$1.avatar}`]: {
      marginLeft: 5,
      marginRight: -6,
      width: 24,
      height: 24,
      color: theme.vars ? theme.vars.palette.Chip.defaultAvatarColor : textColor,
      fontSize: theme.typography.pxToRem(12)
    },
    [`& .${chipClasses$1.avatarColorPrimary}`]: {
      color: (theme.vars || theme).palette.primary.contrastText,
      backgroundColor: (theme.vars || theme).palette.primary.dark
    },
    [`& .${chipClasses$1.avatarColorSecondary}`]: {
      color: (theme.vars || theme).palette.secondary.contrastText,
      backgroundColor: (theme.vars || theme).palette.secondary.dark
    },
    [`& .${chipClasses$1.avatarSmall}`]: {
      marginLeft: 4,
      marginRight: -4,
      width: 18,
      height: 18,
      fontSize: theme.typography.pxToRem(10)
    },
    [`& .${chipClasses$1.icon}`]: _extends({
      marginLeft: 5,
      marginRight: -6
    }, ownerState.size === 'small' && {
      fontSize: 18,
      marginLeft: 4,
      marginRight: -4
    }, ownerState.iconColor === ownerState.color && _extends({
      color: theme.vars ? theme.vars.palette.Chip.defaultIconColor : textColor
    }, ownerState.color !== 'default' && {
      color: 'inherit'
    })),
    [`& .${chipClasses$1.deleteIcon}`]: _extends({
      WebkitTapHighlightColor: 'transparent',
      color: theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / 0.26)` : alpha(theme.palette.text.primary, 0.26),
      fontSize: 22,
      cursor: 'pointer',
      margin: '0 5px 0 -6px',
      '&:hover': {
        color: theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / 0.4)` : alpha(theme.palette.text.primary, 0.4)
      }
    }, ownerState.size === 'small' && {
      fontSize: 16,
      marginRight: 4,
      marginLeft: -4
    }, ownerState.color !== 'default' && {
      color: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].contrastTextChannel} / 0.7)` : alpha(theme.palette[ownerState.color].contrastText, 0.7),
      '&:hover, &:active': {
        color: (theme.vars || theme).palette[ownerState.color].contrastText
      }
    })
  }, ownerState.size === 'small' && {
    height: 24
  }, ownerState.color !== 'default' && {
    backgroundColor: (theme.vars || theme).palette[ownerState.color].main,
    color: (theme.vars || theme).palette[ownerState.color].contrastText
  }, ownerState.onDelete && {
    [`&.${chipClasses$1.focusVisible}`]: {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.selectedChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.action.selected, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
    }
  }, ownerState.onDelete && ownerState.color !== 'default' && {
    [`&.${chipClasses$1.focusVisible}`]: {
      backgroundColor: (theme.vars || theme).palette[ownerState.color].dark
    }
  });
}, ({
  theme,
  ownerState
}) => _extends({}, ownerState.clickable && {
  userSelect: 'none',
  WebkitTapHighlightColor: 'transparent',
  cursor: 'pointer',
  '&:hover': {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.selectedChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.action.selected, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity)
  },
  [`&.${chipClasses$1.focusVisible}`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.selectedChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.action.selected, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
  },
  '&:active': {
    boxShadow: (theme.vars || theme).shadows[1]
  }
}, ownerState.clickable && ownerState.color !== 'default' && {
  [`&:hover, &.${chipClasses$1.focusVisible}`]: {
    backgroundColor: (theme.vars || theme).palette[ownerState.color].dark
  }
}), ({
  theme,
  ownerState
}) => _extends({}, ownerState.variant === 'outlined' && {
  backgroundColor: 'transparent',
  border: theme.vars ? `1px solid ${theme.vars.palette.Chip.defaultBorder}` : `1px solid ${theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[700]}`,
  [`&.${chipClasses$1.clickable}:hover`]: {
    backgroundColor: (theme.vars || theme).palette.action.hover
  },
  [`&.${chipClasses$1.focusVisible}`]: {
    backgroundColor: (theme.vars || theme).palette.action.focus
  },
  [`& .${chipClasses$1.avatar}`]: {
    marginLeft: 4
  },
  [`& .${chipClasses$1.avatarSmall}`]: {
    marginLeft: 2
  },
  [`& .${chipClasses$1.icon}`]: {
    marginLeft: 4
  },
  [`& .${chipClasses$1.iconSmall}`]: {
    marginLeft: 2
  },
  [`& .${chipClasses$1.deleteIcon}`]: {
    marginRight: 5
  },
  [`& .${chipClasses$1.deleteIconSmall}`]: {
    marginRight: 3
  }
}, ownerState.variant === 'outlined' && ownerState.color !== 'default' && {
  color: (theme.vars || theme).palette[ownerState.color].main,
  border: `1px solid ${theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / 0.7)` : alpha(theme.palette[ownerState.color].main, 0.7)}`,
  [`&.${chipClasses$1.clickable}:hover`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[ownerState.color].main, theme.palette.action.hoverOpacity)
  },
  [`&.${chipClasses$1.focusVisible}`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / ${theme.vars.palette.action.focusOpacity})` : alpha(theme.palette[ownerState.color].main, theme.palette.action.focusOpacity)
  },
  [`& .${chipClasses$1.deleteIcon}`]: {
    color: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / 0.7)` : alpha(theme.palette[ownerState.color].main, 0.7),
    '&:hover, &:active': {
      color: (theme.vars || theme).palette[ownerState.color].main
    }
  }
}));
const ChipLabel = styled$1('span', {
  name: 'MuiChip',
  slot: 'Label',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    const {
      size
    } = ownerState;
    return [styles.label, styles[`label${capitalize(size)}`]];
  }
})(({
  ownerState
}) => _extends({
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  paddingLeft: 12,
  paddingRight: 12,
  whiteSpace: 'nowrap'
}, ownerState.size === 'small' && {
  paddingLeft: 8,
  paddingRight: 8
}));
function isDeleteKeyboardEvent(keyboardEvent) {
  return keyboardEvent.key === 'Backspace' || keyboardEvent.key === 'Delete';
}

/**
 * Chips represent complex entities in small blocks, such as a contact.
 */
const Chip$1 = /*#__PURE__*/reactExports$1.forwardRef(function Chip(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiChip'
  });
  const {
      avatar: avatarProp,
      className,
      clickable: clickableProp,
      color = 'default',
      component: ComponentProp,
      deleteIcon: deleteIconProp,
      disabled = false,
      icon: iconProp,
      label,
      onClick,
      onDelete,
      onKeyDown,
      onKeyUp,
      size = 'medium',
      variant = 'filled',
      tabIndex,
      skipFocusWhenDisabled = false // TODO v6: Rename to `focusableWhenDisabled`.
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$17);
  const chipRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(chipRef, ref);
  const handleDeleteIconClick = event => {
    // Stop the event from bubbling up to the `Chip`
    event.stopPropagation();
    if (onDelete) {
      onDelete(event);
    }
  };
  const handleKeyDown = event => {
    // Ignore events from children of `Chip`.
    if (event.currentTarget === event.target && isDeleteKeyboardEvent(event)) {
      // Will be handled in keyUp, otherwise some browsers
      // might init navigation
      event.preventDefault();
    }
    if (onKeyDown) {
      onKeyDown(event);
    }
  };
  const handleKeyUp = event => {
    // Ignore events from children of `Chip`.
    if (event.currentTarget === event.target) {
      if (onDelete && isDeleteKeyboardEvent(event)) {
        onDelete(event);
      } else if (event.key === 'Escape' && chipRef.current) {
        chipRef.current.blur();
      }
    }
    if (onKeyUp) {
      onKeyUp(event);
    }
  };
  const clickable = clickableProp !== false && onClick ? true : clickableProp;
  const component = clickable || onDelete ? ButtonBase$1 : ComponentProp || 'div';
  const ownerState = _extends({}, props, {
    component,
    disabled,
    size,
    color,
    iconColor: /*#__PURE__*/reactExports$1.isValidElement(iconProp) ? iconProp.props.color || color : color,
    onDelete: !!onDelete,
    clickable,
    variant
  });
  const classes = useUtilityClasses$_(ownerState);
  const moreProps = component === ButtonBase$1 ? _extends({
    component: ComponentProp || 'div',
    focusVisibleClassName: classes.focusVisible
  }, onDelete && {
    disableRipple: true
  }) : {};
  let deleteIcon = null;
  if (onDelete) {
    deleteIcon = deleteIconProp && /*#__PURE__*/reactExports$1.isValidElement(deleteIconProp) ? /*#__PURE__*/reactExports$1.cloneElement(deleteIconProp, {
      className: clsx(deleteIconProp.props.className, classes.deleteIcon),
      onClick: handleDeleteIconClick
    }) : /*#__PURE__*/jsxRuntimeExports.jsx(CancelIcon, {
      className: clsx(classes.deleteIcon),
      onClick: handleDeleteIconClick
    });
  }
  let avatar = null;
  if (avatarProp && /*#__PURE__*/reactExports$1.isValidElement(avatarProp)) {
    avatar = /*#__PURE__*/reactExports$1.cloneElement(avatarProp, {
      className: clsx(classes.avatar, avatarProp.props.className)
    });
  }
  let icon = null;
  if (iconProp && /*#__PURE__*/reactExports$1.isValidElement(iconProp)) {
    icon = /*#__PURE__*/reactExports$1.cloneElement(iconProp, {
      className: clsx(classes.icon, iconProp.props.className)
    });
  }
  {
    if (avatar && icon) {
      console.error('MUI: The Chip component can not handle the avatar ' + 'and the icon prop at the same time. Pick one.');
    }
  }
  return /*#__PURE__*/jsxRuntimeExports.jsxs(ChipRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    disabled: clickable && disabled ? true : undefined,
    onClick: onClick,
    onKeyDown: handleKeyDown,
    onKeyUp: handleKeyUp,
    ref: handleRef,
    tabIndex: skipFocusWhenDisabled && disabled ? -1 : tabIndex,
    ownerState: ownerState
  }, moreProps, other, {
    children: [avatar || icon, /*#__PURE__*/jsxRuntimeExports.jsx(ChipLabel, {
      className: clsx(classes.label),
      ownerState: ownerState,
      children: label
    }), deleteIcon]
  }));
});
Chip$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The Avatar element to display.
   */
  avatar: PropTypes.element,
  /**
   * This prop isn't supported.
   * Use the `component` prop if you need to change the children structure.
   */
  children: unsupportedProp,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the chip will appear clickable, and will raise when pressed,
   * even if the onClick prop is not defined.
   * If `false`, the chip will not appear clickable, even if onClick prop is defined.
   * This can be used, for example,
   * along with the component prop to indicate an anchor Chip is clickable.
   * Note: this controls the UI and does not affect the onClick event.
   */
  clickable: PropTypes.bool,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'default'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Override the default delete icon element. Shown only if `onDelete` is set.
   */
  deleteIcon: PropTypes.element,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * Icon element.
   */
  icon: PropTypes.element,
  /**
   * The content of the component.
   */
  label: PropTypes.node,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * Callback fired when the delete icon is clicked.
   * If set, the delete icon will be shown.
   */
  onDelete: PropTypes.func,
  /**
   * @ignore
   */
  onKeyDown: PropTypes.func,
  /**
   * @ignore
   */
  onKeyUp: PropTypes.func,
  /**
   * The size of the component.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * If `true`, allows the disabled chip to escape focus.
   * If `false`, allows the disabled chip to receive focus.
   * @default false
   */
  skipFocusWhenDisabled: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * @ignore
   */
  tabIndex: PropTypes.number,
  /**
   * The variant to use.
   * @default 'filled'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['filled', 'outlined']), PropTypes.string])
} ;
var Chip$2 = Chip$1;

function Chip({
  icon,
  ...rest
}) {
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement(Chip$2, {
    icon: Icon ? /*#__PURE__*/React.createElement(Icon, null) : null,
    ...rest
  });
}
Chip.propTypes = {
  icon: PropTypes.string
};

/**
 * @ignore - internal component.
 */
const FormControlContext = /*#__PURE__*/reactExports$1.createContext(undefined);
{
  FormControlContext.displayName = 'FormControlContext';
}
var FormControlContext$1 = FormControlContext;

function useFormControl() {
  return reactExports$1.useContext(FormControlContext$1);
}

function getSwitchBaseUtilityClass(slot) {
  return generateUtilityClass('PrivateSwitchBase', slot);
}
generateUtilityClasses('PrivateSwitchBase', ['root', 'checked', 'disabled', 'input', 'edgeStart', 'edgeEnd']);

const _excluded$16 = ["autoFocus", "checked", "checkedIcon", "className", "defaultChecked", "disabled", "disableFocusRipple", "edge", "icon", "id", "inputProps", "inputRef", "name", "onBlur", "onChange", "onFocus", "readOnly", "required", "tabIndex", "type", "value"];
const useUtilityClasses$Z = ownerState => {
  const {
    classes,
    checked,
    disabled,
    edge
  } = ownerState;
  const slots = {
    root: ['root', checked && 'checked', disabled && 'disabled', edge && `edge${capitalize(edge)}`],
    input: ['input']
  };
  return composeClasses(slots, getSwitchBaseUtilityClass, classes);
};
const SwitchBaseRoot = styled$1(ButtonBase$1)(({
  ownerState
}) => _extends({
  padding: 9,
  borderRadius: '50%'
}, ownerState.edge === 'start' && {
  marginLeft: ownerState.size === 'small' ? -3 : -12
}, ownerState.edge === 'end' && {
  marginRight: ownerState.size === 'small' ? -3 : -12
}));
const SwitchBaseInput = styled$1('input')({
  cursor: 'inherit',
  position: 'absolute',
  opacity: 0,
  width: '100%',
  height: '100%',
  top: 0,
  left: 0,
  margin: 0,
  padding: 0,
  zIndex: 1
});

/**
 * @ignore - internal component.
 */
const SwitchBase = /*#__PURE__*/reactExports$1.forwardRef(function SwitchBase(props, ref) {
  const {
      autoFocus,
      checked: checkedProp,
      checkedIcon,
      className,
      defaultChecked,
      disabled: disabledProp,
      disableFocusRipple = false,
      edge = false,
      icon,
      id,
      inputProps,
      inputRef,
      name,
      onBlur,
      onChange,
      onFocus,
      readOnly,
      required = false,
      tabIndex,
      type,
      value
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$16);
  const [checked, setCheckedState] = useControlled({
    controlled: checkedProp,
    default: Boolean(defaultChecked),
    name: 'SwitchBase',
    state: 'checked'
  });
  const muiFormControl = useFormControl();
  const handleFocus = event => {
    if (onFocus) {
      onFocus(event);
    }
    if (muiFormControl && muiFormControl.onFocus) {
      muiFormControl.onFocus(event);
    }
  };
  const handleBlur = event => {
    if (onBlur) {
      onBlur(event);
    }
    if (muiFormControl && muiFormControl.onBlur) {
      muiFormControl.onBlur(event);
    }
  };
  const handleInputChange = event => {
    // Workaround for https://github.com/facebook/react/issues/9023
    if (event.nativeEvent.defaultPrevented) {
      return;
    }
    const newChecked = event.target.checked;
    setCheckedState(newChecked);
    if (onChange) {
      // TODO v6: remove the second argument.
      onChange(event, newChecked);
    }
  };
  let disabled = disabledProp;
  if (muiFormControl) {
    if (typeof disabled === 'undefined') {
      disabled = muiFormControl.disabled;
    }
  }
  const hasLabelFor = type === 'checkbox' || type === 'radio';
  const ownerState = _extends({}, props, {
    checked,
    disabled,
    disableFocusRipple,
    edge
  });
  const classes = useUtilityClasses$Z(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(SwitchBaseRoot, _extends({
    component: "span",
    className: clsx(classes.root, className),
    centerRipple: true,
    focusRipple: !disableFocusRipple,
    disabled: disabled,
    tabIndex: null,
    role: undefined,
    onFocus: handleFocus,
    onBlur: handleBlur,
    ownerState: ownerState,
    ref: ref
  }, other, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(SwitchBaseInput, _extends({
      autoFocus: autoFocus,
      checked: checkedProp,
      defaultChecked: defaultChecked,
      className: classes.input,
      disabled: disabled,
      id: hasLabelFor ? id : undefined,
      name: name,
      onChange: handleInputChange,
      readOnly: readOnly,
      ref: inputRef,
      required: required,
      ownerState: ownerState,
      tabIndex: tabIndex,
      type: type
    }, type === 'checkbox' && value === undefined ? {} : {
      value
    }, inputProps)), checked ? checkedIcon : icon]
  }));
});

// NB: If changed, please update Checkbox, Switch and Radio
// so that the API documentation is updated.
SwitchBase.propTypes = {
  /**
   * If `true`, the `input` element is focused during the first mount.
   */
  autoFocus: PropTypes.bool,
  /**
   * If `true`, the component is checked.
   */
  checked: PropTypes.bool,
  /**
   * The icon to display when the component is checked.
   */
  checkedIcon: PropTypes.node.isRequired,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * @ignore
   */
  defaultChecked: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the  keyboard focus ripple is disabled.
   * @default false
   */
  disableFocusRipple: PropTypes.bool,
  /**
   * If given, uses a negative margin to counteract the padding on one
   * side (this is often helpful for aligning the left or right
   * side of the icon with content above or below, without ruining the border
   * size and shape).
   * @default false
   */
  edge: PropTypes.oneOf(['end', 'start', false]),
  /**
   * The icon to display when the component is unchecked.
   */
  icon: PropTypes.node.isRequired,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /*
   * @ignore
   */
  name: PropTypes.string,
  /**
   * @ignore
   */
  onBlur: PropTypes.func,
  /**
   * Callback fired when the state is changed.
   *
   * @param {object} event The event source of the callback.
   * You can pull out the new checked state by accessing `event.target.checked` (boolean).
   */
  onChange: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * It prevents the user from changing the value of the field
   * (not from interacting with the field).
   */
  readOnly: PropTypes.bool,
  /**
   * If `true`, the `input` element is required.
   */
  required: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.object,
  /**
   * @ignore
   */
  tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * The input component prop `type`.
   */
  type: PropTypes.string.isRequired,
  /**
   * The value of the component.
   */
  value: PropTypes.any
} ;
var SwitchBase$1 = SwitchBase;

function getSwitchUtilityClass(slot) {
  return generateUtilityClass('MuiSwitch', slot);
}
const switchClasses = generateUtilityClasses('MuiSwitch', ['root', 'edgeStart', 'edgeEnd', 'switchBase', 'colorPrimary', 'colorSecondary', 'sizeSmall', 'sizeMedium', 'checked', 'disabled', 'input', 'thumb', 'track']);
var switchClasses$1 = switchClasses;

const _excluded$15 = ["className", "color", "edge", "size", "sx"];
const useUtilityClasses$Y = ownerState => {
  const {
    classes,
    edge,
    size,
    color,
    checked,
    disabled
  } = ownerState;
  const slots = {
    root: ['root', edge && `edge${capitalize(edge)}`, `size${capitalize(size)}`],
    switchBase: ['switchBase', `color${capitalize(color)}`, checked && 'checked', disabled && 'disabled'],
    thumb: ['thumb'],
    track: ['track'],
    input: ['input']
  };
  const composedClasses = composeClasses(slots, getSwitchUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const SwitchRoot = styled$1('span', {
  name: 'MuiSwitch',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.edge && styles[`edge${capitalize(ownerState.edge)}`], styles[`size${capitalize(ownerState.size)}`]];
  }
})(({
  ownerState
}) => _extends({
  display: 'inline-flex',
  width: 34 + 12 * 2,
  height: 14 + 12 * 2,
  overflow: 'hidden',
  padding: 12,
  boxSizing: 'border-box',
  position: 'relative',
  flexShrink: 0,
  zIndex: 0,
  // Reset the stacking context.
  verticalAlign: 'middle',
  // For correct alignment with the text.
  '@media print': {
    colorAdjust: 'exact'
  }
}, ownerState.edge === 'start' && {
  marginLeft: -8
}, ownerState.edge === 'end' && {
  marginRight: -8
}, ownerState.size === 'small' && {
  width: 40,
  height: 24,
  padding: 7,
  [`& .${switchClasses$1.thumb}`]: {
    width: 16,
    height: 16
  },
  [`& .${switchClasses$1.switchBase}`]: {
    padding: 4,
    [`&.${switchClasses$1.checked}`]: {
      transform: 'translateX(16px)'
    }
  }
}));
const SwitchSwitchBase = styled$1(SwitchBase$1, {
  name: 'MuiSwitch',
  slot: 'SwitchBase',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.switchBase, {
      [`& .${switchClasses$1.input}`]: styles.input
    }, ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`]];
  }
})(({
  theme
}) => ({
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 1,
  // Render above the focus ripple.
  color: theme.vars ? theme.vars.palette.Switch.defaultColor : `${theme.palette.mode === 'light' ? theme.palette.common.white : theme.palette.grey[300]}`,
  transition: theme.transitions.create(['left', 'transform'], {
    duration: theme.transitions.duration.shortest
  }),
  [`&.${switchClasses$1.checked}`]: {
    transform: 'translateX(20px)'
  },
  [`&.${switchClasses$1.disabled}`]: {
    color: theme.vars ? theme.vars.palette.Switch.defaultDisabledColor : `${theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[600]}`
  },
  [`&.${switchClasses$1.checked} + .${switchClasses$1.track}`]: {
    opacity: 0.5
  },
  [`&.${switchClasses$1.disabled} + .${switchClasses$1.track}`]: {
    opacity: theme.vars ? theme.vars.opacity.switchTrackDisabled : `${theme.palette.mode === 'light' ? 0.12 : 0.2}`
  },
  [`& .${switchClasses$1.input}`]: {
    left: '-100%',
    width: '300%'
  }
}), ({
  theme,
  ownerState
}) => _extends({
  '&:hover': {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.activeChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.action.active, theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  }
}, ownerState.color !== 'default' && {
  [`&.${switchClasses$1.checked}`]: {
    color: (theme.vars || theme).palette[ownerState.color].main,
    '&:hover': {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette[ownerState.color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[ownerState.color].main, theme.palette.action.hoverOpacity),
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    },
    [`&.${switchClasses$1.disabled}`]: {
      color: theme.vars ? theme.vars.palette.Switch[`${ownerState.color}DisabledColor`] : `${theme.palette.mode === 'light' ? lighten(theme.palette[ownerState.color].main, 0.62) : darken(theme.palette[ownerState.color].main, 0.55)}`
    }
  },
  [`&.${switchClasses$1.checked} + .${switchClasses$1.track}`]: {
    backgroundColor: (theme.vars || theme).palette[ownerState.color].main
  }
}));
const SwitchTrack = styled$1('span', {
  name: 'MuiSwitch',
  slot: 'Track',
  overridesResolver: (props, styles) => styles.track
})(({
  theme
}) => ({
  height: '100%',
  width: '100%',
  borderRadius: 14 / 2,
  zIndex: -1,
  transition: theme.transitions.create(['opacity', 'background-color'], {
    duration: theme.transitions.duration.shortest
  }),
  backgroundColor: theme.vars ? theme.vars.palette.common.onBackground : `${theme.palette.mode === 'light' ? theme.palette.common.black : theme.palette.common.white}`,
  opacity: theme.vars ? theme.vars.opacity.switchTrack : `${theme.palette.mode === 'light' ? 0.38 : 0.3}`
}));
const SwitchThumb = styled$1('span', {
  name: 'MuiSwitch',
  slot: 'Thumb',
  overridesResolver: (props, styles) => styles.thumb
})(({
  theme
}) => ({
  boxShadow: (theme.vars || theme).shadows[1],
  backgroundColor: 'currentColor',
  width: 20,
  height: 20,
  borderRadius: '50%'
}));
const Switch = /*#__PURE__*/reactExports$1.forwardRef(function Switch(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiSwitch'
  });
  const {
      className,
      color = 'primary',
      edge = false,
      size = 'medium',
      sx
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$15);
  const ownerState = _extends({}, props, {
    color,
    edge,
    size
  });
  const classes = useUtilityClasses$Y(ownerState);
  const icon = /*#__PURE__*/jsxRuntimeExports.jsx(SwitchThumb, {
    className: classes.thumb,
    ownerState: ownerState
  });
  return /*#__PURE__*/jsxRuntimeExports.jsxs(SwitchRoot, {
    className: clsx(classes.root, className),
    sx: sx,
    ownerState: ownerState,
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(SwitchSwitchBase, _extends({
      type: "checkbox",
      icon: icon,
      checkedIcon: icon,
      ref: ref,
      ownerState: ownerState
    }, other, {
      classes: _extends({}, classes, {
        root: classes.switchBase
      })
    })), /*#__PURE__*/jsxRuntimeExports.jsx(SwitchTrack, {
      className: classes.track,
      ownerState: ownerState
    })]
  });
});
Switch.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the component is checked.
   */
  checked: PropTypes.bool,
  /**
   * The icon to display when the component is checked.
   */
  checkedIcon: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The default checked state. Use when the component is not controlled.
   */
  defaultChecked: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * If given, uses a negative margin to counteract the padding on one
   * side (this is often helpful for aligning the left or right
   * side of the icon with content above or below, without ruining the border
   * size and shape).
   * @default false
   */
  edge: PropTypes.oneOf(['end', 'start', false]),
  /**
   * The icon to display when the component is unchecked.
   */
  icon: PropTypes.node,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * Callback fired when the state is changed.
   *
   * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   * You can pull out the new checked state by accessing `event.target.checked` (boolean).
   */
  onChange: PropTypes.func,
  /**
   * If `true`, the `input` element is required.
   * @default false
   */
  required: PropTypes.bool,
  /**
   * The size of the component.
   * `small` is equivalent to the dense switch styling.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the component. The DOM API casts this to a string.
   * The browser uses "on" as the default value.
   */
  value: PropTypes.any
} ;
var Switch$1 = Switch;

var CheckBoxOutlineBlankIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
}), 'CheckBoxOutlineBlank');

var CheckBoxIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
}), 'CheckBox');

var IndeterminateCheckBoxIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z"
}), 'IndeterminateCheckBox');

function getCheckboxUtilityClass(slot) {
  return generateUtilityClass('MuiCheckbox', slot);
}
const checkboxClasses = generateUtilityClasses('MuiCheckbox', ['root', 'checked', 'disabled', 'indeterminate', 'colorPrimary', 'colorSecondary']);
var checkboxClasses$1 = checkboxClasses;

const _excluded$14 = ["checkedIcon", "color", "icon", "indeterminate", "indeterminateIcon", "inputProps", "size", "className"];
const useUtilityClasses$X = ownerState => {
  const {
    classes,
    indeterminate,
    color
  } = ownerState;
  const slots = {
    root: ['root', indeterminate && 'indeterminate', `color${capitalize(color)}`]
  };
  const composedClasses = composeClasses(slots, getCheckboxUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const CheckboxRoot = styled$1(SwitchBase$1, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiCheckbox',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.indeterminate && styles.indeterminate, ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  color: (theme.vars || theme).palette.text.secondary
}, !ownerState.disableRipple && {
  '&:hover': {
    backgroundColor: theme.vars ? `rgba(${ownerState.color === 'default' ? theme.vars.palette.action.activeChannel : theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(ownerState.color === 'default' ? theme.palette.action.active : theme.palette[ownerState.color].main, theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  }
}, ownerState.color !== 'default' && {
  [`&.${checkboxClasses$1.checked}, &.${checkboxClasses$1.indeterminate}`]: {
    color: (theme.vars || theme).palette[ownerState.color].main
  },
  [`&.${checkboxClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.action.disabled
  }
}));
const defaultCheckedIcon$1 = /*#__PURE__*/jsxRuntimeExports.jsx(CheckBoxIcon, {});
const defaultIcon$1 = /*#__PURE__*/jsxRuntimeExports.jsx(CheckBoxOutlineBlankIcon, {});
const defaultIndeterminateIcon = /*#__PURE__*/jsxRuntimeExports.jsx(IndeterminateCheckBoxIcon, {});
const Checkbox = /*#__PURE__*/reactExports$1.forwardRef(function Checkbox(inProps, ref) {
  var _icon$props$fontSize, _indeterminateIcon$pr;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiCheckbox'
  });
  const {
      checkedIcon = defaultCheckedIcon$1,
      color = 'primary',
      icon: iconProp = defaultIcon$1,
      indeterminate = false,
      indeterminateIcon: indeterminateIconProp = defaultIndeterminateIcon,
      inputProps,
      size = 'medium',
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$14);
  const icon = indeterminate ? indeterminateIconProp : iconProp;
  const indeterminateIcon = indeterminate ? indeterminateIconProp : checkedIcon;
  const ownerState = _extends({}, props, {
    color,
    indeterminate,
    size
  });
  const classes = useUtilityClasses$X(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(CheckboxRoot, _extends({
    type: "checkbox",
    inputProps: _extends({
      'data-indeterminate': indeterminate
    }, inputProps),
    icon: /*#__PURE__*/reactExports$1.cloneElement(icon, {
      fontSize: (_icon$props$fontSize = icon.props.fontSize) != null ? _icon$props$fontSize : size
    }),
    checkedIcon: /*#__PURE__*/reactExports$1.cloneElement(indeterminateIcon, {
      fontSize: (_indeterminateIcon$pr = indeterminateIcon.props.fontSize) != null ? _indeterminateIcon$pr : size
    }),
    ownerState: ownerState,
    ref: ref,
    className: clsx(classes.root, className)
  }, other, {
    classes: classes
  }));
});
Checkbox.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the component is checked.
   */
  checked: PropTypes.bool,
  /**
   * The icon to display when the component is checked.
   * @default <CheckBoxIcon />
   */
  checkedIcon: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The default checked state. Use when the component is not controlled.
   */
  defaultChecked: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * The icon to display when the component is unchecked.
   * @default <CheckBoxOutlineBlankIcon />
   */
  icon: PropTypes.node,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * If `true`, the component appears indeterminate.
   * This does not set the native input element to indeterminate due
   * to inconsistent behavior across browsers.
   * However, we set a `data-indeterminate` attribute on the `input`.
   * @default false
   */
  indeterminate: PropTypes.bool,
  /**
   * The icon to display when the component is indeterminate.
   * @default <IndeterminateCheckBoxIcon />
   */
  indeterminateIcon: PropTypes.node,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * Callback fired when the state is changed.
   *
   * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
   * You can pull out the new checked state by accessing `event.target.checked` (boolean).
   */
  onChange: PropTypes.func,
  /**
   * If `true`, the `input` element is required.
   * @default false
   */
  required: PropTypes.bool,
  /**
   * The size of the component.
   * `small` is equivalent to the dense checkbox styling.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the component. The DOM API casts this to a string.
   * The browser uses "on" as the default value.
   */
  value: PropTypes.any
} ;
var Checkbox$1 = Checkbox;

var RadioButtonUncheckedIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
}), 'RadioButtonUnchecked');

var RadioButtonCheckedIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M8.465 8.465C9.37 7.56 10.62 7 12 7C14.76 7 17 9.24 17 12C17 13.38 16.44 14.63 15.535 15.535C14.63 16.44 13.38 17 12 17C9.24 17 7 14.76 7 12C7 10.62 7.56 9.37 8.465 8.465Z"
}), 'RadioButtonChecked');

const RadioButtonIconRoot = styled$1('span')({
  position: 'relative',
  display: 'flex'
});
const RadioButtonIconBackground = styled$1(RadioButtonUncheckedIcon)({
  // Scale applied to prevent dot misalignment in Safari
  transform: 'scale(1)'
});
const RadioButtonIconDot = styled$1(RadioButtonCheckedIcon)(({
  theme,
  ownerState
}) => _extends({
  left: 0,
  position: 'absolute',
  transform: 'scale(0)',
  transition: theme.transitions.create('transform', {
    easing: theme.transitions.easing.easeIn,
    duration: theme.transitions.duration.shortest
  })
}, ownerState.checked && {
  transform: 'scale(1)',
  transition: theme.transitions.create('transform', {
    easing: theme.transitions.easing.easeOut,
    duration: theme.transitions.duration.shortest
  })
}));

/**
 * @ignore - internal component.
 */
function RadioButtonIcon(props) {
  const {
    checked = false,
    classes = {},
    fontSize
  } = props;
  const ownerState = _extends({}, props, {
    checked
  });
  return /*#__PURE__*/jsxRuntimeExports.jsxs(RadioButtonIconRoot, {
    className: classes.root,
    ownerState: ownerState,
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIconBackground, {
      fontSize: fontSize,
      className: classes.background,
      ownerState: ownerState
    }), /*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIconDot, {
      fontSize: fontSize,
      className: classes.dot,
      ownerState: ownerState
    })]
  });
}
RadioButtonIcon.propTypes = {
  /**
   * If `true`, the component is checked.
   */
  checked: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * The size of the component.
   * `small` is equivalent to the dense radio styling.
   */
  fontSize: PropTypes.oneOf(['small', 'medium'])
} ;

/**
 * @ignore - internal component.
 */
const RadioGroupContext = /*#__PURE__*/reactExports$1.createContext(undefined);
{
  RadioGroupContext.displayName = 'RadioGroupContext';
}
var RadioGroupContext$1 = RadioGroupContext;

function useRadioGroup() {
  return reactExports$1.useContext(RadioGroupContext$1);
}

function getRadioUtilityClass(slot) {
  return generateUtilityClass('MuiRadio', slot);
}
const radioClasses = generateUtilityClasses('MuiRadio', ['root', 'checked', 'disabled', 'colorPrimary', 'colorSecondary']);
var radioClasses$1 = radioClasses;

const _excluded$13 = ["checked", "checkedIcon", "color", "icon", "name", "onChange", "size", "className"];
const useUtilityClasses$W = ownerState => {
  const {
    classes,
    color
  } = ownerState;
  const slots = {
    root: ['root', `color${capitalize(color)}`]
  };
  return _extends({}, classes, composeClasses(slots, getRadioUtilityClass, classes));
};
const RadioRoot = styled$1(SwitchBase$1, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiRadio',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`color${capitalize(ownerState.color)}`]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  color: (theme.vars || theme).palette.text.secondary
}, !ownerState.disableRipple && {
  '&:hover': {
    backgroundColor: theme.vars ? `rgba(${ownerState.color === 'default' ? theme.vars.palette.action.activeChannel : theme.vars.palette[ownerState.color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(ownerState.color === 'default' ? theme.palette.action.active : theme.palette[ownerState.color].main, theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  }
}, ownerState.color !== 'default' && {
  [`&.${radioClasses$1.checked}`]: {
    color: (theme.vars || theme).palette[ownerState.color].main
  }
}, {
  [`&.${radioClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.action.disabled
  }
}));
function areEqualValues$1(a, b) {
  if (typeof b === 'object' && b !== null) {
    return a === b;
  }

  // The value could be a number, the DOM will stringify it anyway.
  return String(a) === String(b);
}
const defaultCheckedIcon = /*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIcon, {
  checked: true
});
const defaultIcon = /*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIcon, {});
const Radio$1 = /*#__PURE__*/reactExports$1.forwardRef(function Radio(inProps, ref) {
  var _defaultIcon$props$fo, _defaultCheckedIcon$p;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiRadio'
  });
  const {
      checked: checkedProp,
      checkedIcon = defaultCheckedIcon,
      color = 'primary',
      icon = defaultIcon,
      name: nameProp,
      onChange: onChangeProp,
      size = 'medium',
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$13);
  const ownerState = _extends({}, props, {
    color,
    size
  });
  const classes = useUtilityClasses$W(ownerState);
  const radioGroup = useRadioGroup();
  let checked = checkedProp;
  const onChange = createChainedFunction(onChangeProp, radioGroup && radioGroup.onChange);
  let name = nameProp;
  if (radioGroup) {
    if (typeof checked === 'undefined') {
      checked = areEqualValues$1(radioGroup.value, props.value);
    }
    if (typeof name === 'undefined') {
      name = radioGroup.name;
    }
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(RadioRoot, _extends({
    type: "radio",
    icon: /*#__PURE__*/reactExports$1.cloneElement(icon, {
      fontSize: (_defaultIcon$props$fo = defaultIcon.props.fontSize) != null ? _defaultIcon$props$fo : size
    }),
    checkedIcon: /*#__PURE__*/reactExports$1.cloneElement(checkedIcon, {
      fontSize: (_defaultCheckedIcon$p = defaultCheckedIcon.props.fontSize) != null ? _defaultCheckedIcon$p : size
    }),
    ownerState: ownerState,
    classes: classes,
    name: name,
    checked: checked,
    onChange: onChange,
    ref: ref,
    className: clsx(classes.root, className)
  }, other));
});
Radio$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the component is checked.
   */
  checked: PropTypes.bool,
  /**
   * The icon to display when the component is checked.
   * @default <RadioButtonIcon checked />
   */
  checkedIcon: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * If `true`, the component is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * The icon to display when the component is unchecked.
   * @default <RadioButtonIcon />
   */
  icon: PropTypes.node,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * Name attribute of the `input` element.
   */
  name: PropTypes.string,
  /**
   * Callback fired when the state is changed.
   *
   * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   * You can pull out the new checked state by accessing `event.target.checked` (boolean).
   */
  onChange: PropTypes.func,
  /**
   * If `true`, the `input` element is required.
   * @default false
   */
  required: PropTypes.bool,
  /**
   * The size of the component.
   * `small` is equivalent to the dense radio styling.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the component. The DOM API casts this to a string.
   */
  value: PropTypes.any
} ;
var Radio$2 = Radio$1;

/**
 * @ignore - internal component.
 */
const ListContext = /*#__PURE__*/reactExports$1.createContext({});
{
  ListContext.displayName = 'ListContext';
}
var ListContext$1 = ListContext;

function getListUtilityClass(slot) {
  return generateUtilityClass('MuiList', slot);
}
generateUtilityClasses('MuiList', ['root', 'padding', 'dense', 'subheader']);

const _excluded$12 = ["children", "className", "component", "dense", "disablePadding", "subheader"];
const useUtilityClasses$V = ownerState => {
  const {
    classes,
    disablePadding,
    dense,
    subheader
  } = ownerState;
  const slots = {
    root: ['root', !disablePadding && 'padding', dense && 'dense', subheader && 'subheader']
  };
  return composeClasses(slots, getListUtilityClass, classes);
};
const ListRoot = styled$1('ul', {
  name: 'MuiList',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, !ownerState.disablePadding && styles.padding, ownerState.dense && styles.dense, ownerState.subheader && styles.subheader];
  }
})(({
  ownerState
}) => _extends({
  listStyle: 'none',
  margin: 0,
  padding: 0,
  position: 'relative'
}, !ownerState.disablePadding && {
  paddingTop: 8,
  paddingBottom: 8
}, ownerState.subheader && {
  paddingTop: 0
}));
const List$1 = /*#__PURE__*/reactExports$1.forwardRef(function List(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiList'
  });
  const {
      children,
      className,
      component = 'ul',
      dense = false,
      disablePadding = false,
      subheader
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$12);
  const context = reactExports$1.useMemo(() => ({
    dense
  }), [dense]);
  const ownerState = _extends({}, props, {
    component,
    dense,
    disablePadding
  });
  const classes = useUtilityClasses$V(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext$1.Provider, {
    value: context,
    children: /*#__PURE__*/jsxRuntimeExports.jsxs(ListRoot, _extends({
      as: component,
      className: clsx(classes.root, className),
      ref: ref,
      ownerState: ownerState
    }, other, {
      children: [subheader, children]
    }))
  });
});
List$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used for
   * the list and list items.
   * The prop is available to descendant components as the `dense` context.
   * @default false
   */
  dense: PropTypes.bool,
  /**
   * If `true`, vertical padding is removed from the list.
   * @default false
   */
  disablePadding: PropTypes.bool,
  /**
   * The content of the subheader, normally `ListSubheader`.
   */
  subheader: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var List$2 = List$1;

function List(props) {
  return /*#__PURE__*/React.createElement(List$2, {
    sx: {
      bgcolor: "background.paper"
    },
    ...props
  });
}

function getListItemUtilityClass(slot) {
  return generateUtilityClass('MuiListItem', slot);
}
const listItemClasses = generateUtilityClasses('MuiListItem', ['root', 'container', 'focusVisible', 'dense', 'alignItemsFlexStart', 'disabled', 'divider', 'gutters', 'padding', 'button', 'secondaryAction', 'selected']);
var listItemClasses$1 = listItemClasses;

const listItemButtonClasses = generateUtilityClasses('MuiListItemButton', ['root', 'focusVisible', 'dense', 'alignItemsFlexStart', 'disabled', 'divider', 'gutters', 'selected']);
var listItemButtonClasses$1 = listItemButtonClasses;

function getListItemSecondaryActionClassesUtilityClass(slot) {
  return generateUtilityClass('MuiListItemSecondaryAction', slot);
}
generateUtilityClasses('MuiListItemSecondaryAction', ['root', 'disableGutters']);

const _excluded$11 = ["className"];
const useUtilityClasses$U = ownerState => {
  const {
    disableGutters,
    classes
  } = ownerState;
  const slots = {
    root: ['root', disableGutters && 'disableGutters']
  };
  return composeClasses(slots, getListItemSecondaryActionClassesUtilityClass, classes);
};
const ListItemSecondaryActionRoot = styled$1('div', {
  name: 'MuiListItemSecondaryAction',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.disableGutters && styles.disableGutters];
  }
})(({
  ownerState
}) => _extends({
  position: 'absolute',
  right: 16,
  top: '50%',
  transform: 'translateY(-50%)'
}, ownerState.disableGutters && {
  right: 0
}));

/**
 * Must be used as the last child of ListItem to function properly.
 */
const ListItemSecondaryAction = /*#__PURE__*/reactExports$1.forwardRef(function ListItemSecondaryAction(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiListItemSecondaryAction'
  });
  const {
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$11);
  const context = reactExports$1.useContext(ListContext$1);
  const ownerState = _extends({}, props, {
    disableGutters: context.disableGutters
  });
  const classes = useUtilityClasses$U(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ListItemSecondaryActionRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other));
});
ListItemSecondaryAction.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally an `IconButton` or selection control.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
ListItemSecondaryAction.muiName = 'ListItemSecondaryAction';
var ListItemSecondaryAction$1 = ListItemSecondaryAction;

const _excluded$10 = ["className"],
  _excluded2$4 = ["alignItems", "autoFocus", "button", "children", "className", "component", "components", "componentsProps", "ContainerComponent", "ContainerProps", "dense", "disabled", "disableGutters", "disablePadding", "divider", "focusVisibleClassName", "secondaryAction", "selected", "slotProps", "slots"];
const overridesResolver$1 = (props, styles) => {
  const {
    ownerState
  } = props;
  return [styles.root, ownerState.dense && styles.dense, ownerState.alignItems === 'flex-start' && styles.alignItemsFlexStart, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters, !ownerState.disablePadding && styles.padding, ownerState.button && styles.button, ownerState.hasSecondaryAction && styles.secondaryAction];
};
const useUtilityClasses$T = ownerState => {
  const {
    alignItems,
    button,
    classes,
    dense,
    disabled,
    disableGutters,
    disablePadding,
    divider,
    hasSecondaryAction,
    selected
  } = ownerState;
  const slots = {
    root: ['root', dense && 'dense', !disableGutters && 'gutters', !disablePadding && 'padding', divider && 'divider', disabled && 'disabled', button && 'button', alignItems === 'flex-start' && 'alignItemsFlexStart', hasSecondaryAction && 'secondaryAction', selected && 'selected'],
    container: ['container']
  };
  return composeClasses(slots, getListItemUtilityClass, classes);
};
const ListItemRoot = styled$1('div', {
  name: 'MuiListItem',
  slot: 'Root',
  overridesResolver: overridesResolver$1
})(({
  theme,
  ownerState
}) => _extends({
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'center',
  position: 'relative',
  textDecoration: 'none',
  width: '100%',
  boxSizing: 'border-box',
  textAlign: 'left'
}, !ownerState.disablePadding && _extends({
  paddingTop: 8,
  paddingBottom: 8
}, ownerState.dense && {
  paddingTop: 4,
  paddingBottom: 4
}, !ownerState.disableGutters && {
  paddingLeft: 16,
  paddingRight: 16
}, !!ownerState.secondaryAction && {
  // Add some space to avoid collision as `ListItemSecondaryAction`
  // is absolutely positioned.
  paddingRight: 48
}), !!ownerState.secondaryAction && {
  [`& > .${listItemButtonClasses$1.root}`]: {
    paddingRight: 48
  }
}, {
  [`&.${listItemClasses$1.focusVisible}`]: {
    backgroundColor: (theme.vars || theme).palette.action.focus
  },
  [`&.${listItemClasses$1.selected}`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
    [`&.${listItemClasses$1.focusVisible}`]: {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
    }
  },
  [`&.${listItemClasses$1.disabled}`]: {
    opacity: (theme.vars || theme).palette.action.disabledOpacity
  }
}, ownerState.alignItems === 'flex-start' && {
  alignItems: 'flex-start'
}, ownerState.divider && {
  borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,
  backgroundClip: 'padding-box'
}, ownerState.button && {
  transition: theme.transitions.create('background-color', {
    duration: theme.transitions.duration.shortest
  }),
  '&:hover': {
    textDecoration: 'none',
    backgroundColor: (theme.vars || theme).palette.action.hover,
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  },
  [`&.${listItemClasses$1.selected}:hover`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)
    }
  }
}, ownerState.hasSecondaryAction && {
  // Add some space to avoid collision as `ListItemSecondaryAction`
  // is absolutely positioned.
  paddingRight: 48
}));
const ListItemContainer = styled$1('li', {
  name: 'MuiListItem',
  slot: 'Container',
  overridesResolver: (props, styles) => styles.container
})({
  position: 'relative'
});

/**
 * Uses an additional container component if `ListItemSecondaryAction` is the last child.
 */
const ListItem$1 = /*#__PURE__*/reactExports$1.forwardRef(function ListItem(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiListItem'
  });
  const {
      alignItems = 'center',
      autoFocus = false,
      button = false,
      children: childrenProp,
      className,
      component: componentProp,
      components = {},
      componentsProps = {},
      ContainerComponent = 'li',
      ContainerProps: {
        className: ContainerClassName
      } = {},
      dense = false,
      disabled = false,
      disableGutters = false,
      disablePadding = false,
      divider = false,
      focusVisibleClassName,
      secondaryAction,
      selected = false,
      slotProps = {},
      slots = {}
    } = props,
    ContainerProps = _objectWithoutPropertiesLoose$2(props.ContainerProps, _excluded$10),
    other = _objectWithoutPropertiesLoose$2(props, _excluded2$4);
  const context = reactExports$1.useContext(ListContext$1);
  const childContext = reactExports$1.useMemo(() => ({
    dense: dense || context.dense || false,
    alignItems,
    disableGutters
  }), [alignItems, context.dense, dense, disableGutters]);
  const listItemRef = reactExports$1.useRef(null);
  useEnhancedEffect$1(() => {
    if (autoFocus) {
      if (listItemRef.current) {
        listItemRef.current.focus();
      } else {
        console.error('MUI: Unable to set focus to a ListItem whose component has not been rendered.');
      }
    }
  }, [autoFocus]);
  const children = reactExports$1.Children.toArray(childrenProp);

  // v4 implementation, deprecated in v5, will be removed in v6
  const hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);
  const ownerState = _extends({}, props, {
    alignItems,
    autoFocus,
    button,
    dense: childContext.dense,
    disabled,
    disableGutters,
    disablePadding,
    divider,
    hasSecondaryAction,
    selected
  });
  const classes = useUtilityClasses$T(ownerState);
  const handleRef = useForkRef(listItemRef, ref);
  const Root = slots.root || components.Root || ListItemRoot;
  const rootProps = slotProps.root || componentsProps.root || {};
  const componentProps = _extends({
    className: clsx(classes.root, rootProps.className, className),
    disabled
  }, other);
  let Component = componentProp || 'li';
  if (button) {
    componentProps.component = componentProp || 'div';
    componentProps.focusVisibleClassName = clsx(listItemClasses$1.focusVisible, focusVisibleClassName);
    Component = ButtonBase$1;
  }

  // v4 implementation, deprecated in v5, will be removed in v6
  if (hasSecondaryAction) {
    // Use div by default.
    Component = !componentProps.component && !componentProp ? 'div' : Component;

    // Avoid nesting of li > li.
    if (ContainerComponent === 'li') {
      if (Component === 'li') {
        Component = 'div';
      } else if (componentProps.component === 'li') {
        componentProps.component = 'div';
      }
    }
    return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext$1.Provider, {
      value: childContext,
      children: /*#__PURE__*/jsxRuntimeExports.jsxs(ListItemContainer, _extends({
        as: ContainerComponent,
        className: clsx(classes.container, ContainerClassName),
        ref: handleRef,
        ownerState: ownerState
      }, ContainerProps, {
        children: [/*#__PURE__*/jsxRuntimeExports.jsx(Root, _extends({}, rootProps, !isHostComponent(Root) && {
          as: Component,
          ownerState: _extends({}, ownerState, rootProps.ownerState)
        }, componentProps, {
          children: children
        })), children.pop()]
      }))
    });
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext$1.Provider, {
    value: childContext,
    children: /*#__PURE__*/jsxRuntimeExports.jsxs(Root, _extends({}, rootProps, {
      as: Component,
      ref: handleRef
    }, !isHostComponent(Root) && {
      ownerState: _extends({}, ownerState, rootProps.ownerState)
    }, componentProps, {
      children: [children, secondaryAction && /*#__PURE__*/jsxRuntimeExports.jsx(ListItemSecondaryAction$1, {
        children: secondaryAction
      })]
    }))
  });
});
ListItem$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Defines the `align-items` style property.
   * @default 'center'
   */
  alignItems: PropTypes.oneOf(['center', 'flex-start']),
  /**
   * If `true`, the list item is focused during the first mount.
   * Focus will also be triggered if the value changes from false to true.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  autoFocus: PropTypes.bool,
  /**
   * If `true`, the list item is a button (using `ButtonBase`). Props intended
   * for `ButtonBase` can then be applied to `ListItem`.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  button: PropTypes.bool,
  /**
   * The content of the component if a `ListItemSecondaryAction` is used it must
   * be the last child.
   */
  children: chainPropTypes(PropTypes.node, props => {
    const children = reactExports$1.Children.toArray(props.children);

    // React.Children.toArray(props.children).findLastIndex(isListItemSecondaryAction)
    let secondaryActionIndex = -1;
    for (let i = children.length - 1; i >= 0; i -= 1) {
      const child = children[i];
      if (isMuiElement(child, ['ListItemSecondaryAction'])) {
        secondaryActionIndex = i;
        break;
      }
    }

    //  is ListItemSecondaryAction the last child of ListItem
    if (secondaryActionIndex !== -1 && secondaryActionIndex !== children.length - 1) {
      return new Error('MUI: You used an element after ListItemSecondaryAction. ' + 'For ListItem to detect that it has a secondary action ' + 'you must pass it as the last child to ListItem.');
    }
    return null;
  }),
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    root: PropTypes.object
  }),
  /**
   * The container component used when a `ListItemSecondaryAction` is the last child.
   * @default 'li'
   * @deprecated
   */
  ContainerComponent: elementTypeAcceptingRef$1,
  /**
   * Props applied to the container component if used.
   * @default {}
   * @deprecated
   */
  ContainerProps: PropTypes.object,
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used.
   * The prop defaults to the value inherited from the parent List component.
   * @default false
   */
  dense: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the left and right padding is removed.
   * @default false
   */
  disableGutters: PropTypes.bool,
  /**
   * If `true`, all padding is removed.
   * @default false
   */
  disablePadding: PropTypes.bool,
  /**
   * If `true`, a 1px light border is added to the bottom of the list item.
   * @default false
   */
  divider: PropTypes.bool,
  /**
   * @ignore
   */
  focusVisibleClassName: PropTypes.string,
  /**
   * The element to display at the end of ListItem.
   */
  secondaryAction: PropTypes.node,
  /**
   * Use to apply selected styling.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  selected: PropTypes.bool,
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    root: PropTypes.object
  }),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    root: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var ListItem$2 = ListItem$1;

function getListItemTextUtilityClass(slot) {
  return generateUtilityClass('MuiListItemText', slot);
}
const listItemTextClasses = generateUtilityClasses('MuiListItemText', ['root', 'multiline', 'dense', 'inset', 'primary', 'secondary']);
var listItemTextClasses$1 = listItemTextClasses;

const _excluded$$ = ["children", "className", "disableTypography", "inset", "primary", "primaryTypographyProps", "secondary", "secondaryTypographyProps"];
const useUtilityClasses$S = ownerState => {
  const {
    classes,
    inset,
    primary,
    secondary,
    dense
  } = ownerState;
  const slots = {
    root: ['root', inset && 'inset', dense && 'dense', primary && secondary && 'multiline'],
    primary: ['primary'],
    secondary: ['secondary']
  };
  return composeClasses(slots, getListItemTextUtilityClass, classes);
};
const ListItemTextRoot = styled$1('div', {
  name: 'MuiListItemText',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${listItemTextClasses$1.primary}`]: styles.primary
    }, {
      [`& .${listItemTextClasses$1.secondary}`]: styles.secondary
    }, styles.root, ownerState.inset && styles.inset, ownerState.primary && ownerState.secondary && styles.multiline, ownerState.dense && styles.dense];
  }
})(({
  ownerState
}) => _extends({
  flex: '1 1 auto',
  minWidth: 0,
  marginTop: 4,
  marginBottom: 4
}, ownerState.primary && ownerState.secondary && {
  marginTop: 6,
  marginBottom: 6
}, ownerState.inset && {
  paddingLeft: 56
}));
const ListItemText = /*#__PURE__*/reactExports$1.forwardRef(function ListItemText(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiListItemText'
  });
  const {
      children,
      className,
      disableTypography = false,
      inset = false,
      primary: primaryProp,
      primaryTypographyProps,
      secondary: secondaryProp,
      secondaryTypographyProps
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$$);
  const {
    dense
  } = reactExports$1.useContext(ListContext$1);
  let primary = primaryProp != null ? primaryProp : children;
  let secondary = secondaryProp;
  const ownerState = _extends({}, props, {
    disableTypography,
    inset,
    primary: !!primary,
    secondary: !!secondary,
    dense
  });
  const classes = useUtilityClasses$S(ownerState);
  if (primary != null && primary.type !== Typography$1 && !disableTypography) {
    primary = /*#__PURE__*/jsxRuntimeExports.jsx(Typography$1, _extends({
      variant: dense ? 'body2' : 'body1',
      className: classes.primary,
      component: primaryTypographyProps != null && primaryTypographyProps.variant ? undefined : 'span',
      display: "block"
    }, primaryTypographyProps, {
      children: primary
    }));
  }
  if (secondary != null && secondary.type !== Typography$1 && !disableTypography) {
    secondary = /*#__PURE__*/jsxRuntimeExports.jsx(Typography$1, _extends({
      variant: "body2",
      className: classes.secondary,
      color: "text.secondary",
      display: "block"
    }, secondaryTypographyProps, {
      children: secondary
    }));
  }
  return /*#__PURE__*/jsxRuntimeExports.jsxs(ListItemTextRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other, {
    children: [primary, secondary]
  }));
});
ListItemText.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Alias for the `primary` prop.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the children won't be wrapped by a Typography component.
   * This can be useful to render an alternative Typography variant by wrapping
   * the `children` (or `primary`) text, and optional `secondary` text
   * with the Typography component.
   * @default false
   */
  disableTypography: PropTypes.bool,
  /**
   * If `true`, the children are indented.
   * This should be used if there is no left avatar or left icon.
   * @default false
   */
  inset: PropTypes.bool,
  /**
   * The main content element.
   */
  primary: PropTypes.node,
  /**
   * These props will be forwarded to the primary typography component
   * (as long as disableTypography is not `true`).
   */
  primaryTypographyProps: PropTypes.object,
  /**
   * The secondary content element.
   */
  secondary: PropTypes.node,
  /**
   * These props will be forwarded to the secondary typography component
   * (as long as disableTypography is not `true`).
   */
  secondaryTypographyProps: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var ListItemText$1 = ListItemText;

function getListItemIconUtilityClass(slot) {
  return generateUtilityClass('MuiListItemIcon', slot);
}
const listItemIconClasses = generateUtilityClasses('MuiListItemIcon', ['root', 'alignItemsFlexStart']);
var listItemIconClasses$1 = listItemIconClasses;

const _excluded$_ = ["className"];
const useUtilityClasses$R = ownerState => {
  const {
    alignItems,
    classes
  } = ownerState;
  const slots = {
    root: ['root', alignItems === 'flex-start' && 'alignItemsFlexStart']
  };
  return composeClasses(slots, getListItemIconUtilityClass, classes);
};
const ListItemIconRoot = styled$1('div', {
  name: 'MuiListItemIcon',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.alignItems === 'flex-start' && styles.alignItemsFlexStart];
  }
})(({
  theme,
  ownerState
}) => _extends({
  minWidth: 56,
  color: (theme.vars || theme).palette.action.active,
  flexShrink: 0,
  display: 'inline-flex'
}, ownerState.alignItems === 'flex-start' && {
  marginTop: 8
}));

/**
 * A simple wrapper to apply `List` styles to an `Icon` or `SvgIcon`.
 */
const ListItemIcon = /*#__PURE__*/reactExports$1.forwardRef(function ListItemIcon(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiListItemIcon'
  });
  const {
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$_);
  const context = reactExports$1.useContext(ListContext$1);
  const ownerState = _extends({}, props, {
    alignItems: context.alignItems
  });
  const classes = useUtilityClasses$R(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ListItemIconRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other));
});
ListItemIcon.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally `Icon`, `SvgIcon`,
   * or a `@mui/icons-material` SVG icon element.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var ListItemIcon$1 = ListItemIcon;

function ListItem({
  children,
  description,
  icon,
  secondaryAction,
  ...rest
}) {
  const Icon = useIcon(icon);
  return /*#__PURE__*/React.createElement(ListItem$2, {
    ...rest
  }, Icon && /*#__PURE__*/React.createElement(ListItemIcon$1, null, /*#__PURE__*/React.createElement(Icon, null)), /*#__PURE__*/React.createElement(ListItemText$1, {
    primary: children,
    secondary: description
  }), secondaryAction && /*#__PURE__*/React.createElement(ListItemSecondaryAction$1, null, secondaryAction));
}
ListItem.propTypes = {
  children: PropTypes.node,
  description: PropTypes.node,
  icon: PropTypes.string,
  secondaryAction: PropTypes.node
};

function ListItemLink(props) {
  const {
    ListItem
  } = useComponents();
  return /*#__PURE__*/React.createElement(ListItem, {
    button: true,
    component: Link$3,
    ...props
  });
}

function getListSubheaderUtilityClass(slot) {
  return generateUtilityClass('MuiListSubheader', slot);
}
generateUtilityClasses('MuiListSubheader', ['root', 'colorPrimary', 'colorInherit', 'gutters', 'inset', 'sticky']);

const _excluded$Z = ["className", "color", "component", "disableGutters", "disableSticky", "inset"];
const useUtilityClasses$Q = ownerState => {
  const {
    classes,
    color,
    disableGutters,
    inset,
    disableSticky
  } = ownerState;
  const slots = {
    root: ['root', color !== 'default' && `color${capitalize(color)}`, !disableGutters && 'gutters', inset && 'inset', !disableSticky && 'sticky']
  };
  return composeClasses(slots, getListSubheaderUtilityClass, classes);
};
const ListSubheaderRoot = styled$1('li', {
  name: 'MuiListSubheader',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`], !ownerState.disableGutters && styles.gutters, ownerState.inset && styles.inset, !ownerState.disableSticky && styles.sticky];
  }
})(({
  theme,
  ownerState
}) => _extends({
  boxSizing: 'border-box',
  lineHeight: '48px',
  listStyle: 'none',
  color: (theme.vars || theme).palette.text.secondary,
  fontFamily: theme.typography.fontFamily,
  fontWeight: theme.typography.fontWeightMedium,
  fontSize: theme.typography.pxToRem(14)
}, ownerState.color === 'primary' && {
  color: (theme.vars || theme).palette.primary.main
}, ownerState.color === 'inherit' && {
  color: 'inherit'
}, !ownerState.disableGutters && {
  paddingLeft: 16,
  paddingRight: 16
}, ownerState.inset && {
  paddingLeft: 72
}, !ownerState.disableSticky && {
  position: 'sticky',
  top: 0,
  zIndex: 1,
  backgroundColor: (theme.vars || theme).palette.background.paper
}));
const ListSubheader = /*#__PURE__*/reactExports$1.forwardRef(function ListSubheader(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiListSubheader'
  });
  const {
      className,
      color = 'default',
      component = 'li',
      disableGutters = false,
      disableSticky = false,
      inset = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$Z);
  const ownerState = _extends({}, props, {
    color,
    component,
    disableGutters,
    disableSticky,
    inset
  });
  const classes = useUtilityClasses$Q(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ListSubheaderRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    ref: ref,
    ownerState: ownerState
  }, other));
});
ListSubheader.muiSkipListHighlight = true;
ListSubheader.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component. It supports those theme colors that make sense for this component.
   * @default 'default'
   */
  color: PropTypes.oneOf(['default', 'inherit', 'primary']),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the List Subheader will not have gutters.
   * @default false
   */
  disableGutters: PropTypes.bool,
  /**
   * If `true`, the List Subheader will not stick to the top during scroll.
   * @default false
   */
  disableSticky: PropTypes.bool,
  /**
   * If `true`, the List Subheader is indented.
   * @default false
   */
  inset: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var ListSubheader$1 = ListSubheader;

function getCollapseUtilityClass(slot) {
  return generateUtilityClass('MuiCollapse', slot);
}
generateUtilityClasses('MuiCollapse', ['root', 'horizontal', 'vertical', 'entered', 'hidden', 'wrapper', 'wrapperInner']);

const _excluded$Y = ["addEndListener", "children", "className", "collapsedSize", "component", "easing", "in", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "orientation", "style", "timeout", "TransitionComponent"];
const useUtilityClasses$P = ownerState => {
  const {
    orientation,
    classes
  } = ownerState;
  const slots = {
    root: ['root', `${orientation}`],
    entered: ['entered'],
    hidden: ['hidden'],
    wrapper: ['wrapper', `${orientation}`],
    wrapperInner: ['wrapperInner', `${orientation}`]
  };
  return composeClasses(slots, getCollapseUtilityClass, classes);
};
const CollapseRoot = styled$1('div', {
  name: 'MuiCollapse',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.orientation], ownerState.state === 'entered' && styles.entered, ownerState.state === 'exited' && !ownerState.in && ownerState.collapsedSize === '0px' && styles.hidden];
  }
})(({
  theme,
  ownerState
}) => _extends({
  height: 0,
  overflow: 'hidden',
  transition: theme.transitions.create('height')
}, ownerState.orientation === 'horizontal' && {
  height: 'auto',
  width: 0,
  transition: theme.transitions.create('width')
}, ownerState.state === 'entered' && _extends({
  height: 'auto',
  overflow: 'visible'
}, ownerState.orientation === 'horizontal' && {
  width: 'auto'
}), ownerState.state === 'exited' && !ownerState.in && ownerState.collapsedSize === '0px' && {
  visibility: 'hidden'
}));
const CollapseWrapper = styled$1('div', {
  name: 'MuiCollapse',
  slot: 'Wrapper',
  overridesResolver: (props, styles) => styles.wrapper
})(({
  ownerState
}) => _extends({
  // Hack to get children with a negative margin to not falsify the height computation.
  display: 'flex',
  width: '100%'
}, ownerState.orientation === 'horizontal' && {
  width: 'auto',
  height: '100%'
}));
const CollapseWrapperInner = styled$1('div', {
  name: 'MuiCollapse',
  slot: 'WrapperInner',
  overridesResolver: (props, styles) => styles.wrapperInner
})(({
  ownerState
}) => _extends({
  width: '100%'
}, ownerState.orientation === 'horizontal' && {
  width: 'auto',
  height: '100%'
}));

/**
 * The Collapse transition is used by the
 * [Vertical Stepper](/material-ui/react-stepper/#vertical-stepper) StepContent component.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */
const Collapse = /*#__PURE__*/reactExports$1.forwardRef(function Collapse(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiCollapse'
  });
  const {
      addEndListener,
      children,
      className,
      collapsedSize: collapsedSizeProp = '0px',
      component,
      easing,
      in: inProp,
      onEnter,
      onEntered,
      onEntering,
      onExit,
      onExited,
      onExiting,
      orientation = 'vertical',
      style,
      timeout = duration.standard,
      // eslint-disable-next-line react/prop-types
      TransitionComponent = Transition$1
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$Y);
  const ownerState = _extends({}, props, {
    orientation,
    collapsedSize: collapsedSizeProp
  });
  const classes = useUtilityClasses$P(ownerState);
  const theme = useTheme();
  const timer = reactExports$1.useRef();
  const wrapperRef = reactExports$1.useRef(null);
  const autoTransitionDuration = reactExports$1.useRef();
  const collapsedSize = typeof collapsedSizeProp === 'number' ? `${collapsedSizeProp}px` : collapsedSizeProp;
  const isHorizontal = orientation === 'horizontal';
  const size = isHorizontal ? 'width' : 'height';
  reactExports$1.useEffect(() => {
    return () => {
      clearTimeout(timer.current);
    };
  }, []);
  const nodeRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(ref, nodeRef);
  const normalizedTransitionCallback = callback => maybeIsAppearing => {
    if (callback) {
      const node = nodeRef.current;

      // onEnterXxx and onExitXxx callbacks have a different arguments.length value.
      if (maybeIsAppearing === undefined) {
        callback(node);
      } else {
        callback(node, maybeIsAppearing);
      }
    }
  };
  const getWrapperSize = () => wrapperRef.current ? wrapperRef.current[isHorizontal ? 'clientWidth' : 'clientHeight'] : 0;
  const handleEnter = normalizedTransitionCallback((node, isAppearing) => {
    if (wrapperRef.current && isHorizontal) {
      // Set absolute position to get the size of collapsed content
      wrapperRef.current.style.position = 'absolute';
    }
    node.style[size] = collapsedSize;
    if (onEnter) {
      onEnter(node, isAppearing);
    }
  });
  const handleEntering = normalizedTransitionCallback((node, isAppearing) => {
    const wrapperSize = getWrapperSize();
    if (wrapperRef.current && isHorizontal) {
      // After the size is read reset the position back to default
      wrapperRef.current.style.position = '';
    }
    const {
      duration: transitionDuration,
      easing: transitionTimingFunction
    } = getTransitionProps({
      style,
      timeout,
      easing
    }, {
      mode: 'enter'
    });
    if (timeout === 'auto') {
      const duration2 = theme.transitions.getAutoHeightDuration(wrapperSize);
      node.style.transitionDuration = `${duration2}ms`;
      autoTransitionDuration.current = duration2;
    } else {
      node.style.transitionDuration = typeof transitionDuration === 'string' ? transitionDuration : `${transitionDuration}ms`;
    }
    node.style[size] = `${wrapperSize}px`;
    node.style.transitionTimingFunction = transitionTimingFunction;
    if (onEntering) {
      onEntering(node, isAppearing);
    }
  });
  const handleEntered = normalizedTransitionCallback((node, isAppearing) => {
    node.style[size] = 'auto';
    if (onEntered) {
      onEntered(node, isAppearing);
    }
  });
  const handleExit = normalizedTransitionCallback(node => {
    node.style[size] = `${getWrapperSize()}px`;
    if (onExit) {
      onExit(node);
    }
  });
  const handleExited = normalizedTransitionCallback(onExited);
  const handleExiting = normalizedTransitionCallback(node => {
    const wrapperSize = getWrapperSize();
    const {
      duration: transitionDuration,
      easing: transitionTimingFunction
    } = getTransitionProps({
      style,
      timeout,
      easing
    }, {
      mode: 'exit'
    });
    if (timeout === 'auto') {
      // TODO: rename getAutoHeightDuration to something more generic (width support)
      // Actually it just calculates animation duration based on size
      const duration2 = theme.transitions.getAutoHeightDuration(wrapperSize);
      node.style.transitionDuration = `${duration2}ms`;
      autoTransitionDuration.current = duration2;
    } else {
      node.style.transitionDuration = typeof transitionDuration === 'string' ? transitionDuration : `${transitionDuration}ms`;
    }
    node.style[size] = collapsedSize;
    node.style.transitionTimingFunction = transitionTimingFunction;
    if (onExiting) {
      onExiting(node);
    }
  });
  const handleAddEndListener = next => {
    if (timeout === 'auto') {
      timer.current = setTimeout(next, autoTransitionDuration.current || 0);
    }
    if (addEndListener) {
      // Old call signature before `react-transition-group` implemented `nodeRef`
      addEndListener(nodeRef.current, next);
    }
  };
  return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
    in: inProp,
    onEnter: handleEnter,
    onEntered: handleEntered,
    onEntering: handleEntering,
    onExit: handleExit,
    onExited: handleExited,
    onExiting: handleExiting,
    addEndListener: handleAddEndListener,
    nodeRef: nodeRef,
    timeout: timeout === 'auto' ? null : timeout
  }, other, {
    children: (state, childProps) => /*#__PURE__*/jsxRuntimeExports.jsx(CollapseRoot, _extends({
      as: component,
      className: clsx(classes.root, className, {
        'entered': classes.entered,
        'exited': !inProp && collapsedSize === '0px' && classes.hidden
      }[state]),
      style: _extends({
        [isHorizontal ? 'minWidth' : 'minHeight']: collapsedSize
      }, style),
      ownerState: _extends({}, ownerState, {
        state
      }),
      ref: handleRef
    }, childProps, {
      children: /*#__PURE__*/jsxRuntimeExports.jsx(CollapseWrapper, {
        ownerState: _extends({}, ownerState, {
          state
        }),
        className: classes.wrapper,
        ref: wrapperRef,
        children: /*#__PURE__*/jsxRuntimeExports.jsx(CollapseWrapperInner, {
          ownerState: _extends({}, ownerState, {
            state
          }),
          className: classes.wrapperInner,
          children: children
        })
      })
    }))
  }));
});
Collapse.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Add a custom transition end trigger. Called with the transitioning DOM
   * node and a done callback. Allows for more fine grained transition end
   * logic. Note: Timeouts are still used as a fallback if provided.
   */
  addEndListener: PropTypes.func,
  /**
   * The content node to be collapsed.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The width (horizontal) or height (vertical) of the container when collapsed.
   * @default '0px'
   */
  collapsedSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: elementTypeAcceptingRef$1,
  /**
   * The transition timing function.
   * You may specify a single easing or a object containing enter and exit values.
   */
  easing: PropTypes.oneOfType([PropTypes.shape({
    enter: PropTypes.string,
    exit: PropTypes.string
  }), PropTypes.string]),
  /**
   * If `true`, the component will transition in.
   */
  in: PropTypes.bool,
  /**
   * @ignore
   */
  onEnter: PropTypes.func,
  /**
   * @ignore
   */
  onEntered: PropTypes.func,
  /**
   * @ignore
   */
  onEntering: PropTypes.func,
  /**
   * @ignore
   */
  onExit: PropTypes.func,
  /**
   * @ignore
   */
  onExited: PropTypes.func,
  /**
   * @ignore
   */
  onExiting: PropTypes.func,
  /**
   * The transition orientation.
   * @default 'vertical'
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']),
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   *
   * Set to 'auto' to automatically calculate transition time based on height.
   * @default duration.standard
   */
  timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })])
} ;
Collapse.muiSupportAuto = true;
var Collapse$1 = Collapse;

/**
 * @ignore - internal component.
 * @type {React.Context<{} | {expanded: boolean, disabled: boolean, toggle: () => void}>}
 */
const AccordionContext = /*#__PURE__*/reactExports$1.createContext({});
{
  AccordionContext.displayName = 'AccordionContext';
}
var AccordionContext$1 = AccordionContext;

function getAccordionUtilityClass(slot) {
  return generateUtilityClass('MuiAccordion', slot);
}
const accordionClasses = generateUtilityClasses('MuiAccordion', ['root', 'rounded', 'expanded', 'disabled', 'gutters', 'region']);
var accordionClasses$1 = accordionClasses;

const _excluded$X = ["children", "className", "defaultExpanded", "disabled", "disableGutters", "expanded", "onChange", "square", "TransitionComponent", "TransitionProps"];
const useUtilityClasses$O = ownerState => {
  const {
    classes,
    square,
    expanded,
    disabled,
    disableGutters
  } = ownerState;
  const slots = {
    root: ['root', !square && 'rounded', expanded && 'expanded', disabled && 'disabled', !disableGutters && 'gutters'],
    region: ['region']
  };
  return composeClasses(slots, getAccordionUtilityClass, classes);
};
const AccordionRoot = styled$1(Paper$1, {
  name: 'MuiAccordion',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${accordionClasses$1.region}`]: styles.region
    }, styles.root, !ownerState.square && styles.rounded, !ownerState.disableGutters && styles.gutters];
  }
})(({
  theme
}) => {
  const transition = {
    duration: theme.transitions.duration.shortest
  };
  return {
    position: 'relative',
    transition: theme.transitions.create(['margin'], transition),
    overflowAnchor: 'none',
    // Keep the same scrolling position
    '&:before': {
      position: 'absolute',
      left: 0,
      top: -1,
      right: 0,
      height: 1,
      content: '""',
      opacity: 1,
      backgroundColor: (theme.vars || theme).palette.divider,
      transition: theme.transitions.create(['opacity', 'background-color'], transition)
    },
    '&:first-of-type': {
      '&:before': {
        display: 'none'
      }
    },
    [`&.${accordionClasses$1.expanded}`]: {
      '&:before': {
        opacity: 0
      },
      '&:first-of-type': {
        marginTop: 0
      },
      '&:last-of-type': {
        marginBottom: 0
      },
      '& + &': {
        '&:before': {
          display: 'none'
        }
      }
    },
    [`&.${accordionClasses$1.disabled}`]: {
      backgroundColor: (theme.vars || theme).palette.action.disabledBackground
    }
  };
}, ({
  theme,
  ownerState
}) => _extends({}, !ownerState.square && {
  borderRadius: 0,
  '&:first-of-type': {
    borderTopLeftRadius: (theme.vars || theme).shape.borderRadius,
    borderTopRightRadius: (theme.vars || theme).shape.borderRadius
  },
  '&:last-of-type': {
    borderBottomLeftRadius: (theme.vars || theme).shape.borderRadius,
    borderBottomRightRadius: (theme.vars || theme).shape.borderRadius,
    // Fix a rendering issue on Edge
    '@supports (-ms-ime-align: auto)': {
      borderBottomLeftRadius: 0,
      borderBottomRightRadius: 0
    }
  }
}, !ownerState.disableGutters && {
  [`&.${accordionClasses$1.expanded}`]: {
    margin: '16px 0'
  }
}));
const Accordion$1 = /*#__PURE__*/reactExports$1.forwardRef(function Accordion(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAccordion'
  });
  const {
      children: childrenProp,
      className,
      defaultExpanded = false,
      disabled = false,
      disableGutters = false,
      expanded: expandedProp,
      onChange,
      square = false,
      TransitionComponent = Collapse$1,
      TransitionProps
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$X);
  const [expanded, setExpandedState] = useControlled({
    controlled: expandedProp,
    default: defaultExpanded,
    name: 'Accordion',
    state: 'expanded'
  });
  const handleChange = reactExports$1.useCallback(event => {
    setExpandedState(!expanded);
    if (onChange) {
      onChange(event, !expanded);
    }
  }, [expanded, onChange, setExpandedState]);
  const [summary, ...children] = reactExports$1.Children.toArray(childrenProp);
  const contextValue = reactExports$1.useMemo(() => ({
    expanded,
    disabled,
    disableGutters,
    toggle: handleChange
  }), [expanded, disabled, disableGutters, handleChange]);
  const ownerState = _extends({}, props, {
    square,
    disabled,
    disableGutters,
    expanded
  });
  const classes = useUtilityClasses$O(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(AccordionRoot, _extends({
    className: clsx(classes.root, className),
    ref: ref,
    ownerState: ownerState,
    square: square
  }, other, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(AccordionContext$1.Provider, {
      value: contextValue,
      children: summary
    }), /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
      in: expanded,
      timeout: "auto"
    }, TransitionProps, {
      children: /*#__PURE__*/jsxRuntimeExports.jsx("div", {
        "aria-labelledby": summary.props.id,
        id: summary.props['aria-controls'],
        role: "region",
        className: classes.region,
        children: children
      })
    }))]
  }));
});
Accordion$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: chainPropTypes(PropTypes.node.isRequired, props => {
    const summary = reactExports$1.Children.toArray(props.children)[0];
    if (reactIsExports$1.isFragment(summary)) {
      return new Error("MUI: The Accordion doesn't accept a Fragment as a child. " + 'Consider providing an array instead.');
    }
    if (! /*#__PURE__*/reactExports$1.isValidElement(summary)) {
      return new Error('MUI: Expected the first child of Accordion to be a valid element.');
    }
    return null;
  }),
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, expands the accordion by default.
   * @default false
   */
  defaultExpanded: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, it removes the margin between two expanded accordion items and the increase of height.
   * @default false
   */
  disableGutters: PropTypes.bool,
  /**
   * If `true`, expands the accordion, otherwise collapse it.
   * Setting this prop enables control over the accordion.
   */
  expanded: PropTypes.bool,
  /**
   * Callback fired when the expand/collapse state is changed.
   *
   * @param {React.SyntheticEvent} event The event source of the callback. **Warning**: This is a generic event not a change event.
   * @param {boolean} expanded The `expanded` state of the accordion.
   */
  onChange: PropTypes.func,
  /**
   * If `true`, rounded corners are disabled.
   * @default false
   */
  square: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The component used for the transition.
   * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   * @default Collapse
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition/) component.
   */
  TransitionProps: PropTypes.object
} ;
var Accordion$2 = Accordion$1;

function getAccordionSummaryUtilityClass(slot) {
  return generateUtilityClass('MuiAccordionSummary', slot);
}
const accordionSummaryClasses = generateUtilityClasses('MuiAccordionSummary', ['root', 'expanded', 'focusVisible', 'disabled', 'gutters', 'contentGutters', 'content', 'expandIconWrapper']);
var accordionSummaryClasses$1 = accordionSummaryClasses;

const _excluded$W = ["children", "className", "expandIcon", "focusVisibleClassName", "onClick"];
const useUtilityClasses$N = ownerState => {
  const {
    classes,
    expanded,
    disabled,
    disableGutters
  } = ownerState;
  const slots = {
    root: ['root', expanded && 'expanded', disabled && 'disabled', !disableGutters && 'gutters'],
    focusVisible: ['focusVisible'],
    content: ['content', expanded && 'expanded', !disableGutters && 'contentGutters'],
    expandIconWrapper: ['expandIconWrapper', expanded && 'expanded']
  };
  return composeClasses(slots, getAccordionSummaryUtilityClass, classes);
};
const AccordionSummaryRoot = styled$1(ButtonBase$1, {
  name: 'MuiAccordionSummary',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme,
  ownerState
}) => {
  const transition = {
    duration: theme.transitions.duration.shortest
  };
  return _extends({
    display: 'flex',
    minHeight: 48,
    padding: theme.spacing(0, 2),
    transition: theme.transitions.create(['min-height', 'background-color'], transition),
    [`&.${accordionSummaryClasses$1.focusVisible}`]: {
      backgroundColor: (theme.vars || theme).palette.action.focus
    },
    [`&.${accordionSummaryClasses$1.disabled}`]: {
      opacity: (theme.vars || theme).palette.action.disabledOpacity
    },
    [`&:hover:not(.${accordionSummaryClasses$1.disabled})`]: {
      cursor: 'pointer'
    }
  }, !ownerState.disableGutters && {
    [`&.${accordionSummaryClasses$1.expanded}`]: {
      minHeight: 64
    }
  });
});
const AccordionSummaryContent = styled$1('div', {
  name: 'MuiAccordionSummary',
  slot: 'Content',
  overridesResolver: (props, styles) => styles.content
})(({
  theme,
  ownerState
}) => _extends({
  display: 'flex',
  flexGrow: 1,
  margin: '12px 0'
}, !ownerState.disableGutters && {
  transition: theme.transitions.create(['margin'], {
    duration: theme.transitions.duration.shortest
  }),
  [`&.${accordionSummaryClasses$1.expanded}`]: {
    margin: '20px 0'
  }
}));
const AccordionSummaryExpandIconWrapper = styled$1('div', {
  name: 'MuiAccordionSummary',
  slot: 'ExpandIconWrapper',
  overridesResolver: (props, styles) => styles.expandIconWrapper
})(({
  theme
}) => ({
  display: 'flex',
  color: (theme.vars || theme).palette.action.active,
  transform: 'rotate(0deg)',
  transition: theme.transitions.create('transform', {
    duration: theme.transitions.duration.shortest
  }),
  [`&.${accordionSummaryClasses$1.expanded}`]: {
    transform: 'rotate(180deg)'
  }
}));
const AccordionSummary = /*#__PURE__*/reactExports$1.forwardRef(function AccordionSummary(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAccordionSummary'
  });
  const {
      children,
      className,
      expandIcon,
      focusVisibleClassName,
      onClick
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$W);
  const {
    disabled = false,
    disableGutters,
    expanded,
    toggle
  } = reactExports$1.useContext(AccordionContext$1);
  const handleChange = event => {
    if (toggle) {
      toggle(event);
    }
    if (onClick) {
      onClick(event);
    }
  };
  const ownerState = _extends({}, props, {
    expanded,
    disabled,
    disableGutters
  });
  const classes = useUtilityClasses$N(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(AccordionSummaryRoot, _extends({
    focusRipple: false,
    disableRipple: true,
    disabled: disabled,
    component: "div",
    "aria-expanded": expanded,
    className: clsx(classes.root, className),
    focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
    onClick: handleChange,
    ref: ref,
    ownerState: ownerState
  }, other, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(AccordionSummaryContent, {
      className: classes.content,
      ownerState: ownerState,
      children: children
    }), expandIcon && /*#__PURE__*/jsxRuntimeExports.jsx(AccordionSummaryExpandIconWrapper, {
      className: classes.expandIconWrapper,
      ownerState: ownerState,
      children: expandIcon
    })]
  }));
});
AccordionSummary.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The icon to display as the expand indicator.
   */
  expandIcon: PropTypes.node,
  /**
   * This prop can help identify which element has keyboard focus.
   * The class name will be applied when the element gains the focus through keyboard interaction.
   * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).
   * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/HEAD/explainer.md).
   * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components
   * if needed.
   */
  focusVisibleClassName: PropTypes.string,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var AccordionSummary$1 = AccordionSummary;

function getAccordionDetailsUtilityClass(slot) {
  return generateUtilityClass('MuiAccordionDetails', slot);
}
generateUtilityClasses('MuiAccordionDetails', ['root']);

const _excluded$V = ["className"];
const useUtilityClasses$M = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getAccordionDetailsUtilityClass, classes);
};
const AccordionDetailsRoot = styled$1('div', {
  name: 'MuiAccordionDetails',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  padding: theme.spacing(1, 2, 2)
}));
const AccordionDetails = /*#__PURE__*/reactExports$1.forwardRef(function AccordionDetails(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAccordionDetails'
  });
  const {
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$V);
  const ownerState = props;
  const classes = useUtilityClasses$M(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(AccordionDetailsRoot, _extends({
    className: clsx(classes.root, className),
    ref: ref,
    ownerState: ownerState
  }, other));
});
AccordionDetails.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var AccordionDetails$1 = AccordionDetails;

function Accordion({
  summary,
  children,
  open,
  onToggle,
  ...rest
}) {
  const ExpandMoreIcon = useIcon("expand") || (() => "V");
  let handleToggle;
  if (onToggle) {
    handleToggle = (evt, state) => onToggle(state);
  }
  return /*#__PURE__*/React.createElement(Accordion$2, {
    expanded: open,
    onChange: handleToggle,
    ...rest
  }, /*#__PURE__*/React.createElement(AccordionSummary$1, {
    expandIcon: /*#__PURE__*/React.createElement(ExpandMoreIcon, null)
  }, summary), /*#__PURE__*/React.createElement(AccordionDetails$1, null, /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1
    }
  }, children)));
}
Accordion.propTypes = {
  summary: PropTypes.node,
  children: PropTypes.node,
  open: PropTypes.bool,
  onToggle: PropTypes.func
};

function ExpandableListItem({
  children,
  open,
  onToggle,
  ...rest
}) {
  const [summary, ...details] = React.Children.toArray(children),
    [internalOpen, setOpen] = reactExports$1.useState(false),
    {
      ListItem,
      IconButton
    } = useComponents();
  let toggleOpen;
  if (open === false || open || onToggle) {
    toggleOpen = () => onToggle(!open);
  } else {
    open = internalOpen;
    toggleOpen = () => setOpen(!open);
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ListItem, {
    button: true,
    onClick: toggleOpen,
    secondaryAction: /*#__PURE__*/React.createElement(IconButton, {
      icon: open ? "collapse" : "expand",
      onClick: toggleOpen
    }),
    ...rest
  }, summary), /*#__PURE__*/React.createElement(Collapse$1, {
    in: open,
    timeout: "auto"
  }, details));
}
ExpandableListItem.propTypes = {
  children: PropTypes.node,
  open: PropTypes.bool,
  onToggle: PropTypes.func
};

function getDividerUtilityClass(slot) {
  return generateUtilityClass('MuiDivider', slot);
}
const dividerClasses = generateUtilityClasses('MuiDivider', ['root', 'absolute', 'fullWidth', 'inset', 'middle', 'flexItem', 'light', 'vertical', 'withChildren', 'withChildrenVertical', 'textAlignRight', 'textAlignLeft', 'wrapper', 'wrapperVertical']);
var dividerClasses$1 = dividerClasses;

const _excluded$U = ["absolute", "children", "className", "component", "flexItem", "light", "orientation", "role", "textAlign", "variant"];
const useUtilityClasses$L = ownerState => {
  const {
    absolute,
    children,
    classes,
    flexItem,
    light,
    orientation,
    textAlign,
    variant
  } = ownerState;
  const slots = {
    root: ['root', absolute && 'absolute', variant, light && 'light', orientation === 'vertical' && 'vertical', flexItem && 'flexItem', children && 'withChildren', children && orientation === 'vertical' && 'withChildrenVertical', textAlign === 'right' && orientation !== 'vertical' && 'textAlignRight', textAlign === 'left' && orientation !== 'vertical' && 'textAlignLeft'],
    wrapper: ['wrapper', orientation === 'vertical' && 'wrapperVertical']
  };
  return composeClasses(slots, getDividerUtilityClass, classes);
};
const DividerRoot = styled$1('div', {
  name: 'MuiDivider',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.absolute && styles.absolute, styles[ownerState.variant], ownerState.light && styles.light, ownerState.orientation === 'vertical' && styles.vertical, ownerState.flexItem && styles.flexItem, ownerState.children && styles.withChildren, ownerState.children && ownerState.orientation === 'vertical' && styles.withChildrenVertical, ownerState.textAlign === 'right' && ownerState.orientation !== 'vertical' && styles.textAlignRight, ownerState.textAlign === 'left' && ownerState.orientation !== 'vertical' && styles.textAlignLeft];
  }
})(({
  theme,
  ownerState
}) => _extends({
  margin: 0,
  // Reset browser default style.
  flexShrink: 0,
  borderWidth: 0,
  borderStyle: 'solid',
  borderColor: (theme.vars || theme).palette.divider,
  borderBottomWidth: 'thin'
}, ownerState.absolute && {
  position: 'absolute',
  bottom: 0,
  left: 0,
  width: '100%'
}, ownerState.light && {
  borderColor: theme.vars ? `rgba(${theme.vars.palette.dividerChannel} / 0.08)` : alpha(theme.palette.divider, 0.08)
}, ownerState.variant === 'inset' && {
  marginLeft: 72
}, ownerState.variant === 'middle' && ownerState.orientation === 'horizontal' && {
  marginLeft: theme.spacing(2),
  marginRight: theme.spacing(2)
}, ownerState.variant === 'middle' && ownerState.orientation === 'vertical' && {
  marginTop: theme.spacing(1),
  marginBottom: theme.spacing(1)
}, ownerState.orientation === 'vertical' && {
  height: '100%',
  borderBottomWidth: 0,
  borderRightWidth: 'thin'
}, ownerState.flexItem && {
  alignSelf: 'stretch',
  height: 'auto'
}), ({
  ownerState
}) => _extends({}, ownerState.children && {
  display: 'flex',
  whiteSpace: 'nowrap',
  textAlign: 'center',
  border: 0,
  '&::before, &::after': {
    content: '""',
    alignSelf: 'center'
  }
}), ({
  theme,
  ownerState
}) => _extends({}, ownerState.children && ownerState.orientation !== 'vertical' && {
  '&::before, &::after': {
    width: '100%',
    borderTop: `thin solid ${(theme.vars || theme).palette.divider}`
  }
}), ({
  theme,
  ownerState
}) => _extends({}, ownerState.children && ownerState.orientation === 'vertical' && {
  flexDirection: 'column',
  '&::before, &::after': {
    height: '100%',
    borderLeft: `thin solid ${(theme.vars || theme).palette.divider}`
  }
}), ({
  ownerState
}) => _extends({}, ownerState.textAlign === 'right' && ownerState.orientation !== 'vertical' && {
  '&::before': {
    width: '90%'
  },
  '&::after': {
    width: '10%'
  }
}, ownerState.textAlign === 'left' && ownerState.orientation !== 'vertical' && {
  '&::before': {
    width: '10%'
  },
  '&::after': {
    width: '90%'
  }
}));
const DividerWrapper = styled$1('span', {
  name: 'MuiDivider',
  slot: 'Wrapper',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.wrapper, ownerState.orientation === 'vertical' && styles.wrapperVertical];
  }
})(({
  theme,
  ownerState
}) => _extends({
  display: 'inline-block',
  paddingLeft: `calc(${theme.spacing(1)} * 1.2)`,
  paddingRight: `calc(${theme.spacing(1)} * 1.2)`
}, ownerState.orientation === 'vertical' && {
  paddingTop: `calc(${theme.spacing(1)} * 1.2)`,
  paddingBottom: `calc(${theme.spacing(1)} * 1.2)`
}));
const Divider = /*#__PURE__*/reactExports$1.forwardRef(function Divider(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiDivider'
  });
  const {
      absolute = false,
      children,
      className,
      component = children ? 'div' : 'hr',
      flexItem = false,
      light = false,
      orientation = 'horizontal',
      role = component !== 'hr' ? 'separator' : undefined,
      textAlign = 'center',
      variant = 'fullWidth'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$U);
  const ownerState = _extends({}, props, {
    absolute,
    component,
    flexItem,
    light,
    orientation,
    role,
    textAlign,
    variant
  });
  const classes = useUtilityClasses$L(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(DividerRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    role: role,
    ref: ref,
    ownerState: ownerState
  }, other, {
    children: children ? /*#__PURE__*/jsxRuntimeExports.jsx(DividerWrapper, {
      className: classes.wrapper,
      ownerState: ownerState,
      children: children
    }) : null
  }));
});
Divider.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Absolutely position the element.
   * @default false
   */
  absolute: PropTypes.bool,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, a vertical divider will have the correct height when used in flex container.
   * (By default, a vertical divider will have a calculated height of `0px` if it is the child of a flex container.)
   * @default false
   */
  flexItem: PropTypes.bool,
  /**
   * If `true`, the divider will have a lighter color.
   * @default false
   */
  light: PropTypes.bool,
  /**
   * The component orientation.
   * @default 'horizontal'
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']),
  /**
   * @ignore
   */
  role: PropTypes /* @typescript-to-proptypes-ignore */.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The text alignment.
   * @default 'center'
   */
  textAlign: PropTypes.oneOf(['center', 'left', 'right']),
  /**
   * The variant to use.
   * @default 'fullWidth'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['fullWidth', 'inset', 'middle']), PropTypes.string])
} ;
var Divider$1 = Divider;

/**
 * @ignore - internal component.
 */
const TableContext = /*#__PURE__*/reactExports$1.createContext();
{
  TableContext.displayName = 'TableContext';
}
var TableContext$1 = TableContext;

function getTableUtilityClass(slot) {
  return generateUtilityClass('MuiTable', slot);
}
generateUtilityClasses('MuiTable', ['root', 'stickyHeader']);

const _excluded$T = ["className", "component", "padding", "size", "stickyHeader"];
const useUtilityClasses$K = ownerState => {
  const {
    classes,
    stickyHeader
  } = ownerState;
  const slots = {
    root: ['root', stickyHeader && 'stickyHeader']
  };
  return composeClasses(slots, getTableUtilityClass, classes);
};
const TableRoot = styled$1('table', {
  name: 'MuiTable',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.stickyHeader && styles.stickyHeader];
  }
})(({
  theme,
  ownerState
}) => _extends({
  display: 'table',
  width: '100%',
  borderCollapse: 'collapse',
  borderSpacing: 0,
  '& caption': _extends({}, theme.typography.body2, {
    padding: theme.spacing(2),
    color: (theme.vars || theme).palette.text.secondary,
    textAlign: 'left',
    captionSide: 'bottom'
  })
}, ownerState.stickyHeader && {
  borderCollapse: 'separate'
}));
const defaultComponent$3 = 'table';
const Table = /*#__PURE__*/reactExports$1.forwardRef(function Table(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTable'
  });
  const {
      className,
      component = defaultComponent$3,
      padding = 'normal',
      size = 'medium',
      stickyHeader = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$T);
  const ownerState = _extends({}, props, {
    component,
    padding,
    size,
    stickyHeader
  });
  const classes = useUtilityClasses$K(ownerState);
  const table = reactExports$1.useMemo(() => ({
    padding,
    size,
    stickyHeader
  }), [padding, size, stickyHeader]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TableContext$1.Provider, {
    value: table,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(TableRoot, _extends({
      as: component,
      role: component === defaultComponent$3 ? null : 'table',
      ref: ref,
      className: clsx(classes.root, className),
      ownerState: ownerState
    }, other))
  });
});
Table.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the table, normally `TableHead` and `TableBody`.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Allows TableCells to inherit padding of the Table.
   * @default 'normal'
   */
  padding: PropTypes.oneOf(['checkbox', 'none', 'normal']),
  /**
   * Allows TableCells to inherit size of the Table.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * Set the header sticky.
   *
   * ⚠️ It doesn't work with IE11.
   * @default false
   */
  stickyHeader: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var Table$1 = Table;

/**
 * @ignore - internal component.
 */
const Tablelvl2Context = /*#__PURE__*/reactExports$1.createContext();
{
  Tablelvl2Context.displayName = 'Tablelvl2Context';
}
var Tablelvl2Context$1 = Tablelvl2Context;

function getTableHeadUtilityClass(slot) {
  return generateUtilityClass('MuiTableHead', slot);
}
generateUtilityClasses('MuiTableHead', ['root']);

const _excluded$S = ["className", "component"];
const useUtilityClasses$J = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getTableHeadUtilityClass, classes);
};
const TableHeadRoot = styled$1('thead', {
  name: 'MuiTableHead',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  display: 'table-header-group'
});
const tablelvl2$1 = {
  variant: 'head'
};
const defaultComponent$2 = 'thead';
const TableHead = /*#__PURE__*/reactExports$1.forwardRef(function TableHead(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTableHead'
  });
  const {
      className,
      component = defaultComponent$2
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$S);
  const ownerState = _extends({}, props, {
    component
  });
  const classes = useUtilityClasses$J(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(Tablelvl2Context$1.Provider, {
    value: tablelvl2$1,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(TableHeadRoot, _extends({
      as: component,
      className: clsx(classes.root, className),
      ref: ref,
      role: component === defaultComponent$2 ? null : 'rowgroup',
      ownerState: ownerState
    }, other))
  });
});
TableHead.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally `TableRow`.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var TableHead$1 = TableHead;

function getTableBodyUtilityClass(slot) {
  return generateUtilityClass('MuiTableBody', slot);
}
generateUtilityClasses('MuiTableBody', ['root']);

const _excluded$R = ["className", "component"];
const useUtilityClasses$I = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getTableBodyUtilityClass, classes);
};
const TableBodyRoot = styled$1('tbody', {
  name: 'MuiTableBody',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  display: 'table-row-group'
});
const tablelvl2 = {
  variant: 'body'
};
const defaultComponent$1 = 'tbody';
const TableBody = /*#__PURE__*/reactExports$1.forwardRef(function TableBody(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTableBody'
  });
  const {
      className,
      component = defaultComponent$1
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$R);
  const ownerState = _extends({}, props, {
    component
  });
  const classes = useUtilityClasses$I(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(Tablelvl2Context$1.Provider, {
    value: tablelvl2,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(TableBodyRoot, _extends({
      className: clsx(classes.root, className),
      as: component,
      ref: ref,
      role: component === defaultComponent$1 ? null : 'rowgroup',
      ownerState: ownerState
    }, other))
  });
});
TableBody.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally `TableRow`.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var TableBody$1 = TableBody;

function getTableRowUtilityClass(slot) {
  return generateUtilityClass('MuiTableRow', slot);
}
const tableRowClasses = generateUtilityClasses('MuiTableRow', ['root', 'selected', 'hover', 'head', 'footer']);
var tableRowClasses$1 = tableRowClasses;

const _excluded$Q = ["className", "component", "hover", "selected"];
const useUtilityClasses$H = ownerState => {
  const {
    classes,
    selected,
    hover,
    head,
    footer
  } = ownerState;
  const slots = {
    root: ['root', selected && 'selected', hover && 'hover', head && 'head', footer && 'footer']
  };
  return composeClasses(slots, getTableRowUtilityClass, classes);
};
const TableRowRoot = styled$1('tr', {
  name: 'MuiTableRow',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.head && styles.head, ownerState.footer && styles.footer];
  }
})(({
  theme
}) => ({
  color: 'inherit',
  display: 'table-row',
  verticalAlign: 'middle',
  // We disable the focus ring for mouse, touch and keyboard users.
  outline: 0,
  [`&.${tableRowClasses$1.hover}:hover`]: {
    backgroundColor: (theme.vars || theme).palette.action.hover
  },
  [`&.${tableRowClasses$1.selected}`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
    '&:hover': {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity)
    }
  }
}));
const defaultComponent = 'tr';
/**
 * Will automatically set dynamic row height
 * based on the material table element parent (head, body, etc).
 */
const TableRow = /*#__PURE__*/reactExports$1.forwardRef(function TableRow(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTableRow'
  });
  const {
      className,
      component = defaultComponent,
      hover = false,
      selected = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$Q);
  const tablelvl2 = reactExports$1.useContext(Tablelvl2Context$1);
  const ownerState = _extends({}, props, {
    component,
    hover,
    selected,
    head: tablelvl2 && tablelvl2.variant === 'head',
    footer: tablelvl2 && tablelvl2.variant === 'footer'
  });
  const classes = useUtilityClasses$H(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TableRowRoot, _extends({
    as: component,
    ref: ref,
    className: clsx(classes.root, className),
    role: component === defaultComponent ? null : 'row',
    ownerState: ownerState
  }, other));
});
TableRow.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Should be valid <tr> children such as `TableCell`.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the table row will shade on hover.
   * @default false
   */
  hover: PropTypes.bool,
  /**
   * If `true`, the table row will have the selected shading.
   * @default false
   */
  selected: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var TableRow$1 = TableRow;

function getTableCellUtilityClass(slot) {
  return generateUtilityClass('MuiTableCell', slot);
}
const tableCellClasses = generateUtilityClasses('MuiTableCell', ['root', 'head', 'body', 'footer', 'sizeSmall', 'sizeMedium', 'paddingCheckbox', 'paddingNone', 'alignLeft', 'alignCenter', 'alignRight', 'alignJustify', 'stickyHeader']);
var tableCellClasses$1 = tableCellClasses;

const _excluded$P = ["align", "className", "component", "padding", "scope", "size", "sortDirection", "variant"];
const useUtilityClasses$G = ownerState => {
  const {
    classes,
    variant,
    align,
    padding,
    size,
    stickyHeader
  } = ownerState;
  const slots = {
    root: ['root', variant, stickyHeader && 'stickyHeader', align !== 'inherit' && `align${capitalize(align)}`, padding !== 'normal' && `padding${capitalize(padding)}`, `size${capitalize(size)}`]
  };
  return composeClasses(slots, getTableCellUtilityClass, classes);
};
const TableCellRoot = styled$1('td', {
  name: 'MuiTableCell',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant], styles[`size${capitalize(ownerState.size)}`], ownerState.padding !== 'normal' && styles[`padding${capitalize(ownerState.padding)}`], ownerState.align !== 'inherit' && styles[`align${capitalize(ownerState.align)}`], ownerState.stickyHeader && styles.stickyHeader];
  }
})(({
  theme,
  ownerState
}) => _extends({}, theme.typography.body2, {
  display: 'table-cell',
  verticalAlign: 'inherit',
  // Workaround for a rendering bug with spanned columns in Chrome 62.0.
  // Removes the alpha (sets it to 1), and lightens or darkens the theme color.
  borderBottom: theme.vars ? `1px solid ${theme.vars.palette.TableCell.border}` : `1px solid
    ${theme.palette.mode === 'light' ? lighten(alpha(theme.palette.divider, 1), 0.88) : darken(alpha(theme.palette.divider, 1), 0.68)}`,
  textAlign: 'left',
  padding: 16
}, ownerState.variant === 'head' && {
  color: (theme.vars || theme).palette.text.primary,
  lineHeight: theme.typography.pxToRem(24),
  fontWeight: theme.typography.fontWeightMedium
}, ownerState.variant === 'body' && {
  color: (theme.vars || theme).palette.text.primary
}, ownerState.variant === 'footer' && {
  color: (theme.vars || theme).palette.text.secondary,
  lineHeight: theme.typography.pxToRem(21),
  fontSize: theme.typography.pxToRem(12)
}, ownerState.size === 'small' && {
  padding: '6px 16px',
  [`&.${tableCellClasses$1.paddingCheckbox}`]: {
    width: 24,
    // prevent the checkbox column from growing
    padding: '0 12px 0 16px',
    '& > *': {
      padding: 0
    }
  }
}, ownerState.padding === 'checkbox' && {
  width: 48,
  // prevent the checkbox column from growing
  padding: '0 0 0 4px'
}, ownerState.padding === 'none' && {
  padding: 0
}, ownerState.align === 'left' && {
  textAlign: 'left'
}, ownerState.align === 'center' && {
  textAlign: 'center'
}, ownerState.align === 'right' && {
  textAlign: 'right',
  flexDirection: 'row-reverse'
}, ownerState.align === 'justify' && {
  textAlign: 'justify'
}, ownerState.stickyHeader && {
  position: 'sticky',
  top: 0,
  zIndex: 2,
  backgroundColor: (theme.vars || theme).palette.background.default
}));

/**
 * The component renders a `<th>` element when the parent context is a header
 * or otherwise a `<td>` element.
 */
const TableCell = /*#__PURE__*/reactExports$1.forwardRef(function TableCell(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTableCell'
  });
  const {
      align = 'inherit',
      className,
      component: componentProp,
      padding: paddingProp,
      scope: scopeProp,
      size: sizeProp,
      sortDirection,
      variant: variantProp
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$P);
  const table = reactExports$1.useContext(TableContext$1);
  const tablelvl2 = reactExports$1.useContext(Tablelvl2Context$1);
  const isHeadCell = tablelvl2 && tablelvl2.variant === 'head';
  let component;
  if (componentProp) {
    component = componentProp;
  } else {
    component = isHeadCell ? 'th' : 'td';
  }
  let scope = scopeProp;
  // scope is not a valid attribute for <td/> elements.
  // source: https://html.spec.whatwg.org/multipage/tables.html#the-td-element
  if (component === 'td') {
    scope = undefined;
  } else if (!scope && isHeadCell) {
    scope = 'col';
  }
  const variant = variantProp || tablelvl2 && tablelvl2.variant;
  const ownerState = _extends({}, props, {
    align,
    component,
    padding: paddingProp || (table && table.padding ? table.padding : 'normal'),
    size: sizeProp || (table && table.size ? table.size : 'medium'),
    sortDirection,
    stickyHeader: variant === 'head' && table && table.stickyHeader,
    variant
  });
  const classes = useUtilityClasses$G(ownerState);
  let ariaSort = null;
  if (sortDirection) {
    ariaSort = sortDirection === 'asc' ? 'ascending' : 'descending';
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(TableCellRoot, _extends({
    as: component,
    ref: ref,
    className: clsx(classes.root, className),
    "aria-sort": ariaSort,
    scope: scope,
    ownerState: ownerState
  }, other));
});
TableCell.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Set the text-align on the table cell content.
   *
   * Monetary or generally number fields **should be right aligned** as that allows
   * you to add them up quickly in your head without having to worry about decimals.
   * @default 'inherit'
   */
  align: PropTypes.oneOf(['center', 'inherit', 'justify', 'left', 'right']),
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Sets the padding applied to the cell.
   * The prop defaults to the value (`'default'`) inherited from the parent Table component.
   */
  padding: PropTypes.oneOf(['checkbox', 'none', 'normal']),
  /**
   * Set scope attribute.
   */
  scope: PropTypes.string,
  /**
   * Specify the size of the cell.
   * The prop defaults to the value (`'medium'`) inherited from the parent Table component.
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * Set aria-sort direction.
   */
  sortDirection: PropTypes.oneOf(['asc', 'desc', false]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Specify the cell type.
   * The prop defaults to the value inherited from the parent TableHead, TableBody, or TableFooter components.
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['body', 'footer', 'head']), PropTypes.string])
} ;
var TableCell$1 = TableCell;

function getTableContainerUtilityClass(slot) {
  return generateUtilityClass('MuiTableContainer', slot);
}
generateUtilityClasses('MuiTableContainer', ['root']);

const _excluded$O = ["className", "component"];
const useUtilityClasses$F = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getTableContainerUtilityClass, classes);
};
const TableContainerRoot = styled$1('div', {
  name: 'MuiTableContainer',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  width: '100%',
  overflowX: 'auto'
});
const TableContainer = /*#__PURE__*/reactExports$1.forwardRef(function TableContainer(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTableContainer'
  });
  const {
      className,
      component = 'div'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$O);
  const ownerState = _extends({}, props, {
    component
  });
  const classes = useUtilityClasses$F(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TableContainerRoot, _extends({
    ref: ref,
    as: component,
    className: clsx(classes.root, className),
    ownerState: ownerState
  }, other));
});
TableContainer.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally `Table`.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var TableContainer$1 = TableContainer;

function formControlState({
  props,
  states,
  muiFormControl
}) {
  return states.reduce((acc, state) => {
    acc[state] = props[state];
    if (muiFormControl) {
      if (typeof props[state] === 'undefined') {
        acc[state] = muiFormControl[state];
      }
    }
    return acc;
  }, {});
}

// Supports determination of isControlled().
// Controlled input accepts its current value as a prop.
//
// @see https://facebook.github.io/react/docs/forms.html#controlled-components
// @param value
// @returns {boolean} true if string (including '') or number (including zero)
function hasValue(value) {
  return value != null && !(Array.isArray(value) && value.length === 0);
}

// Determine if field is empty or filled.
// Response determines if label is presented above field or as placeholder.
//
// @param obj
// @param SSR
// @returns {boolean} False when not present or empty string.
//                    True when any number or string with length.
function isFilled(obj, SSR = false) {
  return obj && (hasValue(obj.value) && obj.value !== '' || SSR && hasValue(obj.defaultValue) && obj.defaultValue !== '');
}

// Determine if an Input is adorned on start.
// It's corresponding to the left with LTR.
//
// @param obj
// @returns {boolean} False when no adornments.
//                    True when adorned at the start.
function isAdornedStart(obj) {
  return obj.startAdornment;
}

function getInputBaseUtilityClass(slot) {
  return generateUtilityClass('MuiInputBase', slot);
}
const inputBaseClasses = generateUtilityClasses('MuiInputBase', ['root', 'formControl', 'focused', 'disabled', 'adornedStart', 'adornedEnd', 'error', 'sizeSmall', 'multiline', 'colorSecondary', 'fullWidth', 'hiddenLabel', 'readOnly', 'input', 'inputSizeSmall', 'inputMultiline', 'inputTypeSearch', 'inputAdornedStart', 'inputAdornedEnd', 'inputHiddenLabel']);
var inputBaseClasses$1 = inputBaseClasses;

const _excluded$N = ["aria-describedby", "autoComplete", "autoFocus", "className", "color", "components", "componentsProps", "defaultValue", "disabled", "disableInjectingGlobalStyles", "endAdornment", "error", "fullWidth", "id", "inputComponent", "inputProps", "inputRef", "margin", "maxRows", "minRows", "multiline", "name", "onBlur", "onChange", "onClick", "onFocus", "onKeyDown", "onKeyUp", "placeholder", "readOnly", "renderSuffix", "rows", "size", "slotProps", "slots", "startAdornment", "type", "value"];
const rootOverridesResolver = (props, styles) => {
  const {
    ownerState
  } = props;
  return [styles.root, ownerState.formControl && styles.formControl, ownerState.startAdornment && styles.adornedStart, ownerState.endAdornment && styles.adornedEnd, ownerState.error && styles.error, ownerState.size === 'small' && styles.sizeSmall, ownerState.multiline && styles.multiline, ownerState.color && styles[`color${capitalize(ownerState.color)}`], ownerState.fullWidth && styles.fullWidth, ownerState.hiddenLabel && styles.hiddenLabel];
};
const inputOverridesResolver = (props, styles) => {
  const {
    ownerState
  } = props;
  return [styles.input, ownerState.size === 'small' && styles.inputSizeSmall, ownerState.multiline && styles.inputMultiline, ownerState.type === 'search' && styles.inputTypeSearch, ownerState.startAdornment && styles.inputAdornedStart, ownerState.endAdornment && styles.inputAdornedEnd, ownerState.hiddenLabel && styles.inputHiddenLabel];
};
const useUtilityClasses$E = ownerState => {
  const {
    classes,
    color,
    disabled,
    error,
    endAdornment,
    focused,
    formControl,
    fullWidth,
    hiddenLabel,
    multiline,
    readOnly,
    size,
    startAdornment,
    type
  } = ownerState;
  const slots = {
    root: ['root', `color${capitalize(color)}`, disabled && 'disabled', error && 'error', fullWidth && 'fullWidth', focused && 'focused', formControl && 'formControl', size === 'small' && 'sizeSmall', multiline && 'multiline', startAdornment && 'adornedStart', endAdornment && 'adornedEnd', hiddenLabel && 'hiddenLabel', readOnly && 'readOnly'],
    input: ['input', disabled && 'disabled', type === 'search' && 'inputTypeSearch', multiline && 'inputMultiline', size === 'small' && 'inputSizeSmall', hiddenLabel && 'inputHiddenLabel', startAdornment && 'inputAdornedStart', endAdornment && 'inputAdornedEnd', readOnly && 'readOnly']
  };
  return composeClasses(slots, getInputBaseUtilityClass, classes);
};
const InputBaseRoot = styled$1('div', {
  name: 'MuiInputBase',
  slot: 'Root',
  overridesResolver: rootOverridesResolver
})(({
  theme,
  ownerState
}) => _extends({}, theme.typography.body1, {
  color: (theme.vars || theme).palette.text.primary,
  lineHeight: '1.4375em',
  // 23px
  boxSizing: 'border-box',
  // Prevent padding issue with fullWidth.
  position: 'relative',
  cursor: 'text',
  display: 'inline-flex',
  alignItems: 'center',
  [`&.${inputBaseClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.text.disabled,
    cursor: 'default'
  }
}, ownerState.multiline && _extends({
  padding: '4px 0 5px'
}, ownerState.size === 'small' && {
  paddingTop: 1
}), ownerState.fullWidth && {
  width: '100%'
}));
const InputBaseComponent = styled$1('input', {
  name: 'MuiInputBase',
  slot: 'Input',
  overridesResolver: inputOverridesResolver
})(({
  theme,
  ownerState
}) => {
  const light = theme.palette.mode === 'light';
  const placeholder = _extends({
    color: 'currentColor'
  }, theme.vars ? {
    opacity: theme.vars.opacity.inputPlaceholder
  } : {
    opacity: light ? 0.42 : 0.5
  }, {
    transition: theme.transitions.create('opacity', {
      duration: theme.transitions.duration.shorter
    })
  });
  const placeholderHidden = {
    opacity: '0 !important'
  };
  const placeholderVisible = theme.vars ? {
    opacity: theme.vars.opacity.inputPlaceholder
  } : {
    opacity: light ? 0.42 : 0.5
  };
  return _extends({
    font: 'inherit',
    letterSpacing: 'inherit',
    color: 'currentColor',
    padding: '4px 0 5px',
    border: 0,
    boxSizing: 'content-box',
    background: 'none',
    height: '1.4375em',
    // Reset 23pxthe native input line-height
    margin: 0,
    // Reset for Safari
    WebkitTapHighlightColor: 'transparent',
    display: 'block',
    // Make the flex item shrink with Firefox
    minWidth: 0,
    width: '100%',
    // Fix IE11 width issue
    animationName: 'mui-auto-fill-cancel',
    animationDuration: '10ms',
    '&::-webkit-input-placeholder': placeholder,
    '&::-moz-placeholder': placeholder,
    // Firefox 19+
    '&:-ms-input-placeholder': placeholder,
    // IE11
    '&::-ms-input-placeholder': placeholder,
    // Edge
    '&:focus': {
      outline: 0
    },
    // Reset Firefox invalid required input style
    '&:invalid': {
      boxShadow: 'none'
    },
    '&::-webkit-search-decoration': {
      // Remove the padding when type=search.
      WebkitAppearance: 'none'
    },
    // Show and hide the placeholder logic
    [`label[data-shrink=false] + .${inputBaseClasses$1.formControl} &`]: {
      '&::-webkit-input-placeholder': placeholderHidden,
      '&::-moz-placeholder': placeholderHidden,
      // Firefox 19+
      '&:-ms-input-placeholder': placeholderHidden,
      // IE11
      '&::-ms-input-placeholder': placeholderHidden,
      // Edge
      '&:focus::-webkit-input-placeholder': placeholderVisible,
      '&:focus::-moz-placeholder': placeholderVisible,
      // Firefox 19+
      '&:focus:-ms-input-placeholder': placeholderVisible,
      // IE11
      '&:focus::-ms-input-placeholder': placeholderVisible // Edge
    },

    [`&.${inputBaseClasses$1.disabled}`]: {
      opacity: 1,
      // Reset iOS opacity
      WebkitTextFillColor: (theme.vars || theme).palette.text.disabled // Fix opacity Safari bug
    },

    '&:-webkit-autofill': {
      animationDuration: '5000s',
      animationName: 'mui-auto-fill'
    }
  }, ownerState.size === 'small' && {
    paddingTop: 1
  }, ownerState.multiline && {
    height: 'auto',
    resize: 'none',
    padding: 0,
    paddingTop: 0
  }, ownerState.type === 'search' && {
    // Improve type search style.
    MozAppearance: 'textfield'
  });
});
const inputGlobalStyles = /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles, {
  styles: {
    '@keyframes mui-auto-fill': {
      from: {
        display: 'block'
      }
    },
    '@keyframes mui-auto-fill-cancel': {
      from: {
        display: 'block'
      }
    }
  }
});

/**
 * `InputBase` contains as few styles as possible.
 * It aims to be a simple building block for creating an input.
 * It contains a load of style reset and some state logic.
 */
const InputBase = /*#__PURE__*/reactExports$1.forwardRef(function InputBase(inProps, ref) {
  var _slotProps$input;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiInputBase'
  });
  const {
      'aria-describedby': ariaDescribedby,
      autoComplete,
      autoFocus,
      className,
      components = {},
      componentsProps = {},
      defaultValue,
      disabled,
      disableInjectingGlobalStyles,
      endAdornment,
      fullWidth = false,
      id,
      inputComponent = 'input',
      inputProps: inputPropsProp = {},
      inputRef: inputRefProp,
      maxRows,
      minRows,
      multiline = false,
      name,
      onBlur,
      onChange,
      onClick,
      onFocus,
      onKeyDown,
      onKeyUp,
      placeholder,
      readOnly,
      renderSuffix,
      rows,
      slotProps = {},
      slots = {},
      startAdornment,
      type = 'text',
      value: valueProp
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$N);
  const value = inputPropsProp.value != null ? inputPropsProp.value : valueProp;
  const {
    current: isControlled
  } = reactExports$1.useRef(value != null);
  const inputRef = reactExports$1.useRef();
  const handleInputRefWarning = reactExports$1.useCallback(instance => {
    {
      if (instance && instance.nodeName !== 'INPUT' && !instance.focus) {
        console.error(['MUI: You have provided a `inputComponent` to the input component', 'that does not correctly handle the `ref` prop.', 'Make sure the `ref` prop is called with a HTMLInputElement.'].join('\n'));
      }
    }
  }, []);
  const handleInputRef = useForkRef(inputRef, inputRefProp, inputPropsProp.ref, handleInputRefWarning);
  const [focused, setFocused] = reactExports$1.useState(false);
  const muiFormControl = useFormControl();
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(() => {
      if (muiFormControl) {
        return muiFormControl.registerEffect();
      }
      return undefined;
    }, [muiFormControl]);
  }
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['color', 'disabled', 'error', 'hiddenLabel', 'size', 'required', 'filled']
  });
  fcs.focused = muiFormControl ? muiFormControl.focused : focused;

  // The blur won't fire when the disabled state is set on a focused input.
  // We need to book keep the focused state manually.
  reactExports$1.useEffect(() => {
    if (!muiFormControl && disabled && focused) {
      setFocused(false);
      if (onBlur) {
        onBlur();
      }
    }
  }, [muiFormControl, disabled, focused, onBlur]);
  const onFilled = muiFormControl && muiFormControl.onFilled;
  const onEmpty = muiFormControl && muiFormControl.onEmpty;
  const checkDirty = reactExports$1.useCallback(obj => {
    if (isFilled(obj)) {
      if (onFilled) {
        onFilled();
      }
    } else if (onEmpty) {
      onEmpty();
    }
  }, [onFilled, onEmpty]);
  useEnhancedEffect$1(() => {
    if (isControlled) {
      checkDirty({
        value
      });
    }
  }, [value, checkDirty, isControlled]);
  const handleFocus = event => {
    // Fix a bug with IE11 where the focus/blur events are triggered
    // while the component is disabled.
    if (fcs.disabled) {
      event.stopPropagation();
      return;
    }
    if (onFocus) {
      onFocus(event);
    }
    if (inputPropsProp.onFocus) {
      inputPropsProp.onFocus(event);
    }
    if (muiFormControl && muiFormControl.onFocus) {
      muiFormControl.onFocus(event);
    } else {
      setFocused(true);
    }
  };
  const handleBlur = event => {
    if (onBlur) {
      onBlur(event);
    }
    if (inputPropsProp.onBlur) {
      inputPropsProp.onBlur(event);
    }
    if (muiFormControl && muiFormControl.onBlur) {
      muiFormControl.onBlur(event);
    } else {
      setFocused(false);
    }
  };
  const handleChange = (event, ...args) => {
    if (!isControlled) {
      const element = event.target || inputRef.current;
      if (element == null) {
        throw new Error(`MUI: Expected valid input target. Did you use a custom \`inputComponent\` and forget to forward refs? See https://mui.com/r/input-component-ref-interface for more info.` );
      }
      checkDirty({
        value: element.value
      });
    }
    if (inputPropsProp.onChange) {
      inputPropsProp.onChange(event, ...args);
    }

    // Perform in the willUpdate
    if (onChange) {
      onChange(event, ...args);
    }
  };

  // Check the input state on mount, in case it was filled by the user
  // or auto filled by the browser before the hydration (for SSR).
  reactExports$1.useEffect(() => {
    checkDirty(inputRef.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const handleClick = event => {
    if (inputRef.current && event.currentTarget === event.target) {
      inputRef.current.focus();
    }
    if (onClick && !fcs.disabled) {
      onClick(event);
    }
  };
  let InputComponent = inputComponent;
  let inputProps = inputPropsProp;
  if (multiline && InputComponent === 'input') {
    if (rows) {
      {
        if (minRows || maxRows) {
          console.warn('MUI: You can not use the `minRows` or `maxRows` props when the input `rows` prop is set.');
        }
      }
      inputProps = _extends({
        type: undefined,
        minRows: rows,
        maxRows: rows
      }, inputProps);
    } else {
      inputProps = _extends({
        type: undefined,
        maxRows,
        minRows
      }, inputProps);
    }
    InputComponent = TextareaAutosize$1;
  }
  const handleAutoFill = event => {
    // Provide a fake value as Chrome might not let you access it for security reasons.
    checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : {
      value: 'x'
    });
  };
  reactExports$1.useEffect(() => {
    if (muiFormControl) {
      muiFormControl.setAdornedStart(Boolean(startAdornment));
    }
  }, [muiFormControl, startAdornment]);
  const ownerState = _extends({}, props, {
    color: fcs.color || 'primary',
    disabled: fcs.disabled,
    endAdornment,
    error: fcs.error,
    focused: fcs.focused,
    formControl: muiFormControl,
    fullWidth,
    hiddenLabel: fcs.hiddenLabel,
    multiline,
    size: fcs.size,
    startAdornment,
    type
  });
  const classes = useUtilityClasses$E(ownerState);
  const Root = slots.root || components.Root || InputBaseRoot;
  const rootProps = slotProps.root || componentsProps.root || {};
  const Input = slots.input || components.Input || InputBaseComponent;
  inputProps = _extends({}, inputProps, (_slotProps$input = slotProps.input) != null ? _slotProps$input : componentsProps.input);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [!disableInjectingGlobalStyles && inputGlobalStyles, /*#__PURE__*/jsxRuntimeExports.jsxs(Root, _extends({}, rootProps, !isHostComponent(Root) && {
      ownerState: _extends({}, ownerState, rootProps.ownerState)
    }, {
      ref: ref,
      onClick: handleClick
    }, other, {
      className: clsx(classes.root, rootProps.className, className, readOnly && 'MuiInputBase-readOnly'),
      children: [startAdornment, /*#__PURE__*/jsxRuntimeExports.jsx(FormControlContext$1.Provider, {
        value: null,
        children: /*#__PURE__*/jsxRuntimeExports.jsx(Input, _extends({
          ownerState: ownerState,
          "aria-invalid": fcs.error,
          "aria-describedby": ariaDescribedby,
          autoComplete: autoComplete,
          autoFocus: autoFocus,
          defaultValue: defaultValue,
          disabled: fcs.disabled,
          id: id,
          onAnimationStart: handleAutoFill,
          name: name,
          placeholder: placeholder,
          readOnly: readOnly,
          required: fcs.required,
          rows: rows,
          value: value,
          onKeyDown: onKeyDown,
          onKeyUp: onKeyUp,
          type: type
        }, inputProps, !isHostComponent(Input) && {
          as: InputComponent,
          ownerState: _extends({}, ownerState, inputProps.ownerState)
        }, {
          ref: handleInputRef,
          className: clsx(classes.input, inputProps.className, readOnly && 'MuiInputBase-readOnly'),
          onBlur: handleBlur,
          onChange: handleChange,
          onFocus: handleFocus
        }))
      }), endAdornment, renderSuffix ? renderSuffix(_extends({}, fcs, {
        startAdornment
      })) : null]
    }))]
  });
});
InputBase.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * @ignore
   */
  'aria-describedby': PropTypes.string,
  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: PropTypes.string,
  /**
   * If `true`, the `input` element is focused during the first mount.
   */
  autoFocus: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Input: PropTypes.elementType,
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    input: PropTypes.object,
    root: PropTypes.object
  }),
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, the component is disabled.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, GlobalStyles for the auto-fill keyframes will not be injected/removed on mount/unmount. Make sure to inject them at the top of your application.
   * This option is intended to help with boosting the initial rendering performance if you are loading a big amount of Input components at once.
   * @default false
   */
  disableInjectingGlobalStyles: PropTypes.bool,
  /**
   * End `InputAdornment` for this component.
   */
  endAdornment: PropTypes.node,
  /**
   * If `true`, the `input` will indicate an error.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the `input` will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * The component used for the `input` element.
   * Either a string to use a HTML element or a component.
   * @default 'input'
   */
  inputComponent: elementTypeAcceptingRef$1,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   * @default {}
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   * The prop defaults to the value (`'none'`) inherited from the parent FormControl component.
   */
  margin: PropTypes.oneOf(['dense', 'none']),
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Minimum number of rows to display when multiline option is set to true.
   */
  minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * If `true`, a [TextareaAutosize](/material-ui/react-textarea-autosize/) element is rendered.
   * @default false
   */
  multiline: PropTypes.bool,
  /**
   * Name attribute of the `input` element.
   */
  name: PropTypes.string,
  /**
   * Callback fired when the `input` is blurred.
   *
   * Notice that the first argument (event) might be undefined.
   */
  onBlur: PropTypes.func,
  /**
   * Callback fired when the value is changed.
   *
   * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * Callback fired when the `input` doesn't satisfy its constraints.
   */
  onInvalid: PropTypes.func,
  /**
   * @ignore
   */
  onKeyDown: PropTypes.func,
  /**
   * @ignore
   */
  onKeyUp: PropTypes.func,
  /**
   * The short hint displayed in the `input` before the user enters a value.
   */
  placeholder: PropTypes.string,
  /**
   * It prevents the user from changing the value of the field
   * (not from interacting with the field).
   */
  readOnly: PropTypes.bool,
  /**
   * @ignore
   */
  renderSuffix: PropTypes.func,
  /**
   * If `true`, the `input` element is required.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  required: PropTypes.bool,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * The size of the component.
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    input: PropTypes.object,
    root: PropTypes.object
  }),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    input: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * Start `InputAdornment` for this component.
   */
  startAdornment: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   * @default 'text'
   */
  type: PropTypes.string,
  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: PropTypes.any
} ;
var MuiInputBase = InputBase;

function getMenuItemUtilityClass(slot) {
  return generateUtilityClass('MuiMenuItem', slot);
}
const menuItemClasses = generateUtilityClasses('MuiMenuItem', ['root', 'focusVisible', 'dense', 'disabled', 'divider', 'gutters', 'selected']);
var menuItemClasses$1 = menuItemClasses;

const _excluded$M = ["autoFocus", "component", "dense", "divider", "disableGutters", "focusVisibleClassName", "role", "tabIndex", "className"];
const overridesResolver = (props, styles) => {
  const {
    ownerState
  } = props;
  return [styles.root, ownerState.dense && styles.dense, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters];
};
const useUtilityClasses$D = ownerState => {
  const {
    disabled,
    dense,
    divider,
    disableGutters,
    selected,
    classes
  } = ownerState;
  const slots = {
    root: ['root', dense && 'dense', disabled && 'disabled', !disableGutters && 'gutters', divider && 'divider', selected && 'selected']
  };
  const composedClasses = composeClasses(slots, getMenuItemUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const MenuItemRoot = styled$1(ButtonBase$1, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiMenuItem',
  slot: 'Root',
  overridesResolver
})(({
  theme,
  ownerState
}) => _extends({}, theme.typography.body1, {
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'center',
  position: 'relative',
  textDecoration: 'none',
  minHeight: 48,
  paddingTop: 6,
  paddingBottom: 6,
  boxSizing: 'border-box',
  whiteSpace: 'nowrap'
}, !ownerState.disableGutters && {
  paddingLeft: 16,
  paddingRight: 16
}, ownerState.divider && {
  borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,
  backgroundClip: 'padding-box'
}, {
  '&:hover': {
    textDecoration: 'none',
    backgroundColor: (theme.vars || theme).palette.action.hover,
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: 'transparent'
    }
  },
  [`&.${menuItemClasses$1.selected}`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
    [`&.${menuItemClasses$1.focusVisible}`]: {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
    }
  },
  [`&.${menuItemClasses$1.selected}:hover`]: {
    backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)
    }
  },
  [`&.${menuItemClasses$1.focusVisible}`]: {
    backgroundColor: (theme.vars || theme).palette.action.focus
  },
  [`&.${menuItemClasses$1.disabled}`]: {
    opacity: (theme.vars || theme).palette.action.disabledOpacity
  },
  [`& + .${dividerClasses$1.root}`]: {
    marginTop: theme.spacing(1),
    marginBottom: theme.spacing(1)
  },
  [`& + .${dividerClasses$1.inset}`]: {
    marginLeft: 52
  },
  [`& .${listItemTextClasses$1.root}`]: {
    marginTop: 0,
    marginBottom: 0
  },
  [`& .${listItemTextClasses$1.inset}`]: {
    paddingLeft: 36
  },
  [`& .${listItemIconClasses$1.root}`]: {
    minWidth: 36
  }
}, !ownerState.dense && {
  [theme.breakpoints.up('sm')]: {
    minHeight: 'auto'
  }
}, ownerState.dense && _extends({
  minHeight: 32,
  // https://m2.material.io/components/menus#specs > Dense
  paddingTop: 4,
  paddingBottom: 4
}, theme.typography.body2, {
  [`& .${listItemIconClasses$1.root} svg`]: {
    fontSize: '1.25rem'
  }
})));
const MenuItem = /*#__PURE__*/reactExports$1.forwardRef(function MenuItem(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiMenuItem'
  });
  const {
      autoFocus = false,
      component = 'li',
      dense = false,
      divider = false,
      disableGutters = false,
      focusVisibleClassName,
      role = 'menuitem',
      tabIndex: tabIndexProp,
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$M);
  const context = reactExports$1.useContext(ListContext$1);
  const childContext = reactExports$1.useMemo(() => ({
    dense: dense || context.dense || false,
    disableGutters
  }), [context.dense, dense, disableGutters]);
  const menuItemRef = reactExports$1.useRef(null);
  useEnhancedEffect$1(() => {
    if (autoFocus) {
      if (menuItemRef.current) {
        menuItemRef.current.focus();
      } else {
        console.error('MUI: Unable to set focus to a MenuItem whose component has not been rendered.');
      }
    }
  }, [autoFocus]);
  const ownerState = _extends({}, props, {
    dense: childContext.dense,
    divider,
    disableGutters
  });
  const classes = useUtilityClasses$D(props);
  const handleRef = useForkRef(menuItemRef, ref);
  let tabIndex;
  if (!props.disabled) {
    tabIndex = tabIndexProp !== undefined ? tabIndexProp : -1;
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext$1.Provider, {
    value: childContext,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(MenuItemRoot, _extends({
      ref: handleRef,
      role: role,
      tabIndex: tabIndex,
      component: component,
      focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
      className: clsx(classes.root, className)
    }, other, {
      ownerState: ownerState,
      classes: classes
    }))
  });
});
MenuItem.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the list item is focused during the first mount.
   * Focus will also be triggered if the value changes from false to true.
   * @default false
   */
  autoFocus: PropTypes.bool,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used.
   * The prop defaults to the value inherited from the parent Menu component.
   * @default false
   */
  dense: PropTypes.bool,
  /**
   * @ignore
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the left and right padding is removed.
   * @default false
   */
  disableGutters: PropTypes.bool,
  /**
   * If `true`, a 1px light border is added to the bottom of the menu item.
   * @default false
   */
  divider: PropTypes.bool,
  /**
   * This prop can help identify which element has keyboard focus.
   * The class name will be applied when the element gains the focus through keyboard interaction.
   * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).
   * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/HEAD/explainer.md).
   * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components
   * if needed.
   */
  focusVisibleClassName: PropTypes.string,
  /**
   * @ignore
   */
  role: PropTypes /* @typescript-to-proptypes-ignore */.string,
  /**
   * If `true`, the component is selected.
   * @default false
   */
  selected: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * @default 0
   */
  tabIndex: PropTypes.number
} ;
var MenuItem$1 = MenuItem;

const _excluded$L = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function nextItem(list, item, disableListWrap) {
  if (list === item) {
    return list.firstChild;
  }
  if (item && item.nextElementSibling) {
    return item.nextElementSibling;
  }
  return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
  if (list === item) {
    return disableListWrap ? list.firstChild : list.lastChild;
  }
  if (item && item.previousElementSibling) {
    return item.previousElementSibling;
  }
  return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
  if (textCriteria === undefined) {
    return true;
  }
  let text = nextFocus.innerText;
  if (text === undefined) {
    // jsdom doesn't support innerText
    text = nextFocus.textContent;
  }
  text = text.trim().toLowerCase();
  if (text.length === 0) {
    return false;
  }
  if (textCriteria.repeating) {
    return text[0] === textCriteria.keys[0];
  }
  return text.indexOf(textCriteria.keys.join('')) === 0;
}
function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {
  let wrappedOnce = false;
  let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
  while (nextFocus) {
    // Prevent infinite loop.
    if (nextFocus === list.firstChild) {
      if (wrappedOnce) {
        return false;
      }
      wrappedOnce = true;
    }

    // Same logic as useAutocomplete.js
    const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
    if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {
      // Move to the next element.
      nextFocus = traversalFunction(list, nextFocus, disableListWrap);
    } else {
      nextFocus.focus();
      return true;
    }
  }
  return false;
}

/**
 * A permanently displayed menu following https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/.
 * It's exposed to help customization of the [`Menu`](/material-ui/api/menu/) component if you
 * use it separately you need to move focus into the component manually. Once
 * the focus is placed inside the component it is fully keyboard accessible.
 */
const MenuList = /*#__PURE__*/reactExports$1.forwardRef(function MenuList(props, ref) {
  const {
      // private
      // eslint-disable-next-line react/prop-types
      actions,
      autoFocus = false,
      autoFocusItem = false,
      children,
      className,
      disabledItemsFocusable = false,
      disableListWrap = false,
      onKeyDown,
      variant = 'selectedMenu'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$L);
  const listRef = reactExports$1.useRef(null);
  const textCriteriaRef = reactExports$1.useRef({
    keys: [],
    repeating: true,
    previousKeyMatched: true,
    lastTime: null
  });
  useEnhancedEffect$1(() => {
    if (autoFocus) {
      listRef.current.focus();
    }
  }, [autoFocus]);
  reactExports$1.useImperativeHandle(actions, () => ({
    adjustStyleForScrollbar: (containerElement, theme) => {
      // Let's ignore that piece of logic if users are already overriding the width
      // of the menu.
      const noExplicitWidth = !listRef.current.style.width;
      if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
        const scrollbarSize = `${getScrollbarSize(ownerDocument(containerElement))}px`;
        listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
        listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
      }
      return listRef.current;
    }
  }), []);
  const handleKeyDown = event => {
    const list = listRef.current;
    const key = event.key;
    /**
     * @type {Element} - will always be defined since we are in a keydown handler
     * attached to an element. A keydown event is either dispatched to the activeElement
     * or document.body or document.documentElement. Only the first case will
     * trigger this specific handler.
     */
    const currentFocus = ownerDocument(list).activeElement;
    if (key === 'ArrowDown') {
      // Prevent scroll of the page
      event.preventDefault();
      moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
    } else if (key === 'ArrowUp') {
      event.preventDefault();
      moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
    } else if (key === 'Home') {
      event.preventDefault();
      moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
    } else if (key === 'End') {
      event.preventDefault();
      moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
    } else if (key.length === 1) {
      const criteria = textCriteriaRef.current;
      const lowerKey = key.toLowerCase();
      const currTime = performance.now();
      if (criteria.keys.length > 0) {
        // Reset
        if (currTime - criteria.lastTime > 500) {
          criteria.keys = [];
          criteria.repeating = true;
          criteria.previousKeyMatched = true;
        } else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
          criteria.repeating = false;
        }
      }
      criteria.lastTime = currTime;
      criteria.keys.push(lowerKey);
      const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
      if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {
        event.preventDefault();
      } else {
        criteria.previousKeyMatched = false;
      }
    }
    if (onKeyDown) {
      onKeyDown(event);
    }
  };
  const handleRef = useForkRef(listRef, ref);

  /**
   * the index of the item should receive focus
   * in a `variant="selectedMenu"` it's the first `selected` item
   * otherwise it's the very first item.
   */
  let activeItemIndex = -1;
  // since we inject focus related props into children we have to do a lookahead
  // to check if there is a `selected` item. We're looking for the last `selected`
  // item and use the first valid item as a fallback
  reactExports$1.Children.forEach(children, (child, index) => {
    if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
      if (activeItemIndex === index) {
        activeItemIndex += 1;
        if (activeItemIndex >= children.length) {
          // there are no focusable items within the list.
          activeItemIndex = -1;
        }
      }
      return;
    }
    {
      if (reactIsExports$1.isFragment(child)) {
        console.error(["MUI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
      }
    }
    if (!child.props.disabled) {
      if (variant === 'selectedMenu' && child.props.selected) {
        activeItemIndex = index;
      } else if (activeItemIndex === -1) {
        activeItemIndex = index;
      }
    }
    if (activeItemIndex === index && (child.props.disabled || child.props.muiSkipListHighlight || child.type.muiSkipListHighlight)) {
      activeItemIndex += 1;
      if (activeItemIndex >= children.length) {
        // there are no focusable items within the list.
        activeItemIndex = -1;
      }
    }
  });
  const items = reactExports$1.Children.map(children, (child, index) => {
    if (index === activeItemIndex) {
      const newChildProps = {};
      if (autoFocusItem) {
        newChildProps.autoFocus = true;
      }
      if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
        newChildProps.tabIndex = 0;
      }
      return /*#__PURE__*/reactExports$1.cloneElement(child, newChildProps);
    }
    return child;
  });
  return /*#__PURE__*/jsxRuntimeExports.jsx(List$2, _extends({
    role: "menu",
    ref: handleRef,
    className: className,
    onKeyDown: handleKeyDown,
    tabIndex: autoFocus ? 0 : -1
  }, other, {
    children: items
  }));
});
MenuList.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, will focus the `[role="menu"]` container and move into tab order.
   * @default false
   */
  autoFocus: PropTypes.bool,
  /**
   * If `true`, will focus the first menuitem if `variant="menu"` or selected item
   * if `variant="selectedMenu"`.
   * @default false
   */
  autoFocusItem: PropTypes.bool,
  /**
   * MenuList contents, normally `MenuItem`s.
   */
  children: PropTypes.node,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, will allow focus on disabled items.
   * @default false
   */
  disabledItemsFocusable: PropTypes.bool,
  /**
   * If `true`, the menu items will not wrap focus.
   * @default false
   */
  disableListWrap: PropTypes.bool,
  /**
   * @ignore
   */
  onKeyDown: PropTypes.func,
  /**
   * The variant to use. Use `menu` to prevent selected items from impacting the initial focus
   * and the vertical alignment relative to the anchor element.
   * @default 'selectedMenu'
   */
  variant: PropTypes.oneOf(['menu', 'selectedMenu'])
} ;
var MenuList$1 = MenuList;

const _excluded$K = ["addEndListener", "appear", "children", "easing", "in", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "style", "timeout", "TransitionComponent"];
function getScale(value) {
  return `scale(${value}, ${value ** 2})`;
}
const styles$1 = {
  entering: {
    opacity: 1,
    transform: getScale(1)
  },
  entered: {
    opacity: 1,
    transform: 'none'
  }
};

/*
 TODO v6: remove
 Conditionally apply a workaround for the CSS transition bug in Safari 15.4 / WebKit browsers.
 */
const isWebKit154 = typeof navigator !== 'undefined' && /^((?!chrome|android).)*(safari|mobile)/i.test(navigator.userAgent) && /(os |version\/)15(.|_)4/i.test(navigator.userAgent);

/**
 * The Grow transition is used by the [Tooltip](/material-ui/react-tooltip/) and
 * [Popover](/material-ui/react-popover/) components.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */
const Grow = /*#__PURE__*/reactExports$1.forwardRef(function Grow(props, ref) {
  const {
      addEndListener,
      appear = true,
      children,
      easing,
      in: inProp,
      onEnter,
      onEntered,
      onEntering,
      onExit,
      onExited,
      onExiting,
      style,
      timeout = 'auto',
      // eslint-disable-next-line react/prop-types
      TransitionComponent = Transition$1
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$K);
  const timer = reactExports$1.useRef();
  const autoTimeout = reactExports$1.useRef();
  const theme = useTheme();
  const nodeRef = reactExports$1.useRef(null);
  const handleRef = useForkRef(nodeRef, children.ref, ref);
  const normalizedTransitionCallback = callback => maybeIsAppearing => {
    if (callback) {
      const node = nodeRef.current;

      // onEnterXxx and onExitXxx callbacks have a different arguments.length value.
      if (maybeIsAppearing === undefined) {
        callback(node);
      } else {
        callback(node, maybeIsAppearing);
      }
    }
  };
  const handleEntering = normalizedTransitionCallback(onEntering);
  const handleEnter = normalizedTransitionCallback((node, isAppearing) => {
    reflow(node); // So the animation always start from the start.

    const {
      duration: transitionDuration,
      delay,
      easing: transitionTimingFunction
    } = getTransitionProps({
      style,
      timeout,
      easing
    }, {
      mode: 'enter'
    });
    let duration;
    if (timeout === 'auto') {
      duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
      autoTimeout.current = duration;
    } else {
      duration = transitionDuration;
    }
    node.style.transition = [theme.transitions.create('opacity', {
      duration,
      delay
    }), theme.transitions.create('transform', {
      duration: isWebKit154 ? duration : duration * 0.666,
      delay,
      easing: transitionTimingFunction
    })].join(',');
    if (onEnter) {
      onEnter(node, isAppearing);
    }
  });
  const handleEntered = normalizedTransitionCallback(onEntered);
  const handleExiting = normalizedTransitionCallback(onExiting);
  const handleExit = normalizedTransitionCallback(node => {
    const {
      duration: transitionDuration,
      delay,
      easing: transitionTimingFunction
    } = getTransitionProps({
      style,
      timeout,
      easing
    }, {
      mode: 'exit'
    });
    let duration;
    if (timeout === 'auto') {
      duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
      autoTimeout.current = duration;
    } else {
      duration = transitionDuration;
    }
    node.style.transition = [theme.transitions.create('opacity', {
      duration,
      delay
    }), theme.transitions.create('transform', {
      duration: isWebKit154 ? duration : duration * 0.666,
      delay: isWebKit154 ? delay : delay || duration * 0.333,
      easing: transitionTimingFunction
    })].join(',');
    node.style.opacity = 0;
    node.style.transform = getScale(0.75);
    if (onExit) {
      onExit(node);
    }
  });
  const handleExited = normalizedTransitionCallback(onExited);
  const handleAddEndListener = next => {
    if (timeout === 'auto') {
      timer.current = setTimeout(next, autoTimeout.current || 0);
    }
    if (addEndListener) {
      // Old call signature before `react-transition-group` implemented `nodeRef`
      addEndListener(nodeRef.current, next);
    }
  };
  reactExports$1.useEffect(() => {
    return () => {
      clearTimeout(timer.current);
    };
  }, []);
  return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
    appear: appear,
    in: inProp,
    nodeRef: nodeRef,
    onEnter: handleEnter,
    onEntered: handleEntered,
    onEntering: handleEntering,
    onExit: handleExit,
    onExited: handleExited,
    onExiting: handleExiting,
    addEndListener: handleAddEndListener,
    timeout: timeout === 'auto' ? null : timeout
  }, other, {
    children: (state, childProps) => {
      return /*#__PURE__*/reactExports$1.cloneElement(children, _extends({
        style: _extends({
          opacity: 0,
          transform: getScale(0.75),
          visibility: state === 'exited' && !inProp ? 'hidden' : undefined
        }, styles$1[state], style, children.props.style),
        ref: handleRef
      }, childProps));
    }
  }));
});
Grow.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Add a custom transition end trigger. Called with the transitioning DOM
   * node and a done callback. Allows for more fine grained transition end
   * logic. Note: Timeouts are still used as a fallback if provided.
   */
  addEndListener: PropTypes.func,
  /**
   * Perform the enter transition when it first mounts if `in` is also `true`.
   * Set this to `false` to disable this behavior.
   * @default true
   */
  appear: PropTypes.bool,
  /**
   * A single child content element.
   */
  children: elementAcceptingRef$1.isRequired,
  /**
   * The transition timing function.
   * You may specify a single easing or a object containing enter and exit values.
   */
  easing: PropTypes.oneOfType([PropTypes.shape({
    enter: PropTypes.string,
    exit: PropTypes.string
  }), PropTypes.string]),
  /**
   * If `true`, the component will transition in.
   */
  in: PropTypes.bool,
  /**
   * @ignore
   */
  onEnter: PropTypes.func,
  /**
   * @ignore
   */
  onEntered: PropTypes.func,
  /**
   * @ignore
   */
  onEntering: PropTypes.func,
  /**
   * @ignore
   */
  onExit: PropTypes.func,
  /**
   * @ignore
   */
  onExited: PropTypes.func,
  /**
   * @ignore
   */
  onExiting: PropTypes.func,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   *
   * Set to 'auto' to automatically calculate transition time based on height.
   * @default 'auto'
   */
  timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })])
} ;
Grow.muiSupportAuto = true;
var Grow$1 = Grow;

function getPopoverUtilityClass(slot) {
  return generateUtilityClass('MuiPopover', slot);
}
generateUtilityClasses('MuiPopover', ['root', 'paper']);

const _excluded$J = ["onEntering"],
  _excluded2$3 = ["action", "anchorEl", "anchorOrigin", "anchorPosition", "anchorReference", "children", "className", "container", "elevation", "marginThreshold", "open", "PaperProps", "slots", "slotProps", "transformOrigin", "TransitionComponent", "transitionDuration", "TransitionProps"],
  _excluded3 = ["slotProps"];
function getOffsetTop(rect, vertical) {
  let offset = 0;
  if (typeof vertical === 'number') {
    offset = vertical;
  } else if (vertical === 'center') {
    offset = rect.height / 2;
  } else if (vertical === 'bottom') {
    offset = rect.height;
  }
  return offset;
}
function getOffsetLeft(rect, horizontal) {
  let offset = 0;
  if (typeof horizontal === 'number') {
    offset = horizontal;
  } else if (horizontal === 'center') {
    offset = rect.width / 2;
  } else if (horizontal === 'right') {
    offset = rect.width;
  }
  return offset;
}
function getTransformOriginValue(transformOrigin) {
  return [transformOrigin.horizontal, transformOrigin.vertical].map(n => typeof n === 'number' ? `${n}px` : n).join(' ');
}
function resolveAnchorEl(anchorEl) {
  return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
const useUtilityClasses$C = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    paper: ['paper']
  };
  return composeClasses(slots, getPopoverUtilityClass, classes);
};
const PopoverRoot = styled$1(Modal$1, {
  name: 'MuiPopover',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({});
const PopoverPaper = styled$1(Paper$1, {
  name: 'MuiPopover',
  slot: 'Paper',
  overridesResolver: (props, styles) => styles.paper
})({
  position: 'absolute',
  overflowY: 'auto',
  overflowX: 'hidden',
  // So we see the popover when it's empty.
  // It's most likely on issue on userland.
  minWidth: 16,
  minHeight: 16,
  maxWidth: 'calc(100% - 32px)',
  maxHeight: 'calc(100% - 32px)',
  // We disable the focus ring for mouse, touch and keyboard users.
  outline: 0
});
const Popover = /*#__PURE__*/reactExports$1.forwardRef(function Popover(inProps, ref) {
  var _slotProps$paper, _slots$root, _slots$paper;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiPopover'
  });
  const {
      action,
      anchorEl,
      anchorOrigin = {
        vertical: 'top',
        horizontal: 'left'
      },
      anchorPosition,
      anchorReference = 'anchorEl',
      children,
      className,
      container: containerProp,
      elevation = 8,
      marginThreshold = 16,
      open,
      PaperProps: PaperPropsProp = {},
      slots,
      slotProps,
      transformOrigin = {
        vertical: 'top',
        horizontal: 'left'
      },
      TransitionComponent = Grow$1,
      transitionDuration: transitionDurationProp = 'auto',
      TransitionProps: {
        onEntering
      } = {}
    } = props,
    TransitionProps = _objectWithoutPropertiesLoose$2(props.TransitionProps, _excluded$J),
    other = _objectWithoutPropertiesLoose$2(props, _excluded2$3);
  const externalPaperSlotProps = (_slotProps$paper = slotProps == null ? void 0 : slotProps.paper) != null ? _slotProps$paper : PaperPropsProp;
  const paperRef = reactExports$1.useRef();
  const handlePaperRef = useForkRef(paperRef, externalPaperSlotProps.ref);
  const ownerState = _extends({}, props, {
    anchorOrigin,
    anchorReference,
    elevation,
    marginThreshold,
    externalPaperSlotProps,
    transformOrigin,
    TransitionComponent,
    transitionDuration: transitionDurationProp,
    TransitionProps
  });
  const classes = useUtilityClasses$C(ownerState);

  // Returns the top/left offset of the position
  // to attach to on the anchor element (or body if none is provided)
  const getAnchorOffset = reactExports$1.useCallback(() => {
    if (anchorReference === 'anchorPosition') {
      {
        if (!anchorPosition) {
          console.error('MUI: You need to provide a `anchorPosition` prop when using ' + '<Popover anchorReference="anchorPosition" />.');
        }
      }
      return anchorPosition;
    }
    const resolvedAnchorEl = resolveAnchorEl(anchorEl);

    // If an anchor element wasn't provided, just use the parent body element of this Popover
    const anchorElement = resolvedAnchorEl && resolvedAnchorEl.nodeType === 1 ? resolvedAnchorEl : ownerDocument(paperRef.current).body;
    const anchorRect = anchorElement.getBoundingClientRect();
    {
      const box = anchorElement.getBoundingClientRect();
      if (box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
        console.warn(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
      }
    }
    return {
      top: anchorRect.top + getOffsetTop(anchorRect, anchorOrigin.vertical),
      left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal)
    };
  }, [anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference]);

  // Returns the base transform origin using the element
  const getTransformOrigin = reactExports$1.useCallback(elemRect => {
    return {
      vertical: getOffsetTop(elemRect, transformOrigin.vertical),
      horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal)
    };
  }, [transformOrigin.horizontal, transformOrigin.vertical]);
  const getPositioningStyle = reactExports$1.useCallback(element => {
    const elemRect = {
      width: element.offsetWidth,
      height: element.offsetHeight
    };

    // Get the transform origin point on the element itself
    const elemTransformOrigin = getTransformOrigin(elemRect);
    if (anchorReference === 'none') {
      return {
        top: null,
        left: null,
        transformOrigin: getTransformOriginValue(elemTransformOrigin)
      };
    }

    // Get the offset of the anchoring element
    const anchorOffset = getAnchorOffset();

    // Calculate element positioning
    let top = anchorOffset.top - elemTransformOrigin.vertical;
    let left = anchorOffset.left - elemTransformOrigin.horizontal;
    const bottom = top + elemRect.height;
    const right = left + elemRect.width;

    // Use the parent window of the anchorEl if provided
    const containerWindow = ownerWindow(resolveAnchorEl(anchorEl));

    // Window thresholds taking required margin into account
    const heightThreshold = containerWindow.innerHeight - marginThreshold;
    const widthThreshold = containerWindow.innerWidth - marginThreshold;

    // Check if the vertical axis needs shifting
    if (top < marginThreshold) {
      const diff = top - marginThreshold;
      top -= diff;
      elemTransformOrigin.vertical += diff;
    } else if (bottom > heightThreshold) {
      const diff = bottom - heightThreshold;
      top -= diff;
      elemTransformOrigin.vertical += diff;
    }
    {
      if (elemRect.height > heightThreshold && elemRect.height && heightThreshold) {
        console.error(['MUI: The popover component is too tall.', `Some part of it can not be seen on the screen (${elemRect.height - heightThreshold}px).`, 'Please consider adding a `max-height` to improve the user-experience.'].join('\n'));
      }
    }

    // Check if the horizontal axis needs shifting
    if (left < marginThreshold) {
      const diff = left - marginThreshold;
      left -= diff;
      elemTransformOrigin.horizontal += diff;
    } else if (right > widthThreshold) {
      const diff = right - widthThreshold;
      left -= diff;
      elemTransformOrigin.horizontal += diff;
    }
    return {
      top: `${Math.round(top)}px`,
      left: `${Math.round(left)}px`,
      transformOrigin: getTransformOriginValue(elemTransformOrigin)
    };
  }, [anchorEl, anchorReference, getAnchorOffset, getTransformOrigin, marginThreshold]);
  const [isPositioned, setIsPositioned] = reactExports$1.useState(open);
  const setPositioningStyles = reactExports$1.useCallback(() => {
    const element = paperRef.current;
    if (!element) {
      return;
    }
    const positioning = getPositioningStyle(element);
    if (positioning.top !== null) {
      element.style.top = positioning.top;
    }
    if (positioning.left !== null) {
      element.style.left = positioning.left;
    }
    element.style.transformOrigin = positioning.transformOrigin;
    setIsPositioned(true);
  }, [getPositioningStyle]);
  const handleEntering = (element, isAppearing) => {
    if (onEntering) {
      onEntering(element, isAppearing);
    }
    setPositioningStyles();
  };
  const handleExited = () => {
    setIsPositioned(false);
  };
  reactExports$1.useEffect(() => {
    if (open) {
      setPositioningStyles();
    }
  });
  reactExports$1.useImperativeHandle(action, () => open ? {
    updatePosition: () => {
      setPositioningStyles();
    }
  } : null, [open, setPositioningStyles]);
  reactExports$1.useEffect(() => {
    if (!open) {
      return undefined;
    }
    const handleResize = debounce$1(() => {
      setPositioningStyles();
    });
    const containerWindow = ownerWindow(anchorEl);
    containerWindow.addEventListener('resize', handleResize);
    return () => {
      handleResize.clear();
      containerWindow.removeEventListener('resize', handleResize);
    };
  }, [anchorEl, open, setPositioningStyles]);
  let transitionDuration = transitionDurationProp;
  if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {
    transitionDuration = undefined;
  }

  // If the container prop is provided, use that
  // If the anchorEl prop is provided, use its parent body element as the container
  // If neither are provided let the Modal take care of choosing the container
  const container = containerProp || (anchorEl ? ownerDocument(resolveAnchorEl(anchorEl)).body : undefined);
  const RootSlot = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : PopoverRoot;
  const PaperSlot = (_slots$paper = slots == null ? void 0 : slots.paper) != null ? _slots$paper : PopoverPaper;
  const paperProps = useSlotProps({
    elementType: PaperSlot,
    externalSlotProps: _extends({}, externalPaperSlotProps, {
      style: isPositioned ? externalPaperSlotProps.style : _extends({}, externalPaperSlotProps.style, {
        opacity: 0
      })
    }),
    additionalProps: {
      elevation,
      ref: handlePaperRef
    },
    ownerState,
    className: clsx(classes.paper, externalPaperSlotProps == null ? void 0 : externalPaperSlotProps.className)
  });
  const _useSlotProps = useSlotProps({
      elementType: RootSlot,
      externalSlotProps: (slotProps == null ? void 0 : slotProps.root) || {},
      externalForwardedProps: other,
      additionalProps: {
        ref,
        slotProps: {
          backdrop: {
            invisible: true
          }
        },
        container,
        open
      },
      ownerState,
      className: clsx(classes.root, className)
    }),
    {
      slotProps: rootSlotPropsProp
    } = _useSlotProps,
    rootProps = _objectWithoutPropertiesLoose$2(_useSlotProps, _excluded3);
  return /*#__PURE__*/jsxRuntimeExports.jsx(RootSlot, _extends({}, rootProps, !isHostComponent(RootSlot) && {
    slotProps: rootSlotPropsProp
  }, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
      appear: true,
      in: open,
      onEntering: handleEntering,
      onExited: handleExited,
      timeout: transitionDuration
    }, TransitionProps, {
      children: /*#__PURE__*/jsxRuntimeExports.jsx(PaperSlot, _extends({}, paperProps, {
        children: children
      }))
    }))
  }));
});
Popover.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * A ref for imperative actions.
   * It currently only supports updatePosition() action.
   */
  action: refType$1,
  /**
   * An HTML element, [PopoverVirtualElement](/material-ui/react-popover/#virtual-element),
   * or a function that returns either.
   * It's used to set the position of the popover.
   */
  anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.func]), props => {
    if (props.open && (!props.anchorReference || props.anchorReference === 'anchorEl')) {
      const resolvedAnchorEl = resolveAnchorEl(props.anchorEl);
      if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {
        const box = resolvedAnchorEl.getBoundingClientRect();
        if (box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {
          return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', "Make sure the element is present in the document or that it's not display none."].join('\n'));
        }
      } else {
        return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', `It should be an Element or PopoverVirtualElement instance but it's \`${resolvedAnchorEl}\` instead.`].join('\n'));
      }
    }
    return null;
  }),
  /**
   * This is the point on the anchor where the popover's
   * `anchorEl` will attach to. This is not used when the
   * anchorReference is 'anchorPosition'.
   *
   * Options:
   * vertical: [top, center, bottom];
   * horizontal: [left, center, right].
   * @default {
   *   vertical: 'top',
   *   horizontal: 'left',
   * }
   */
  anchorOrigin: PropTypes.shape({
    horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,
    vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired
  }),
  /**
   * This is the position that may be used to set the position of the popover.
   * The coordinates are relative to the application's client area.
   */
  anchorPosition: PropTypes.shape({
    left: PropTypes.number.isRequired,
    top: PropTypes.number.isRequired
  }),
  /**
   * This determines which anchor prop to refer to when setting
   * the position of the popover.
   * @default 'anchorEl'
   */
  anchorReference: PropTypes.oneOf(['anchorEl', 'anchorPosition', 'none']),
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * An HTML element, component instance, or function that returns either.
   * The `container` will passed to the Modal component.
   *
   * By default, it uses the body of the anchorEl's top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * The elevation of the popover.
   * @default 8
   */
  elevation: integerPropType,
  /**
   * Specifies how close to the edge of the window the popover can appear.
   * @default 16
   */
  marginThreshold: PropTypes.number,
  /**
   * Callback fired when the component requests to be closed.
   * The `reason` parameter can optionally be used to control the response to `onClose`.
   */
  onClose: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * Props applied to the [`Paper`](/material-ui/api/paper/) element.
   *
   * This prop is an alias for `slotProps.paper` and will be overriden by it if both are used.
   * @deprecated Use `slotProps.paper` instead.
   *
   * @default {}
   */
  PaperProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({
    component: elementTypeAcceptingRef$1
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    paper: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    paper: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * This is the point on the popover which
   * will attach to the anchor's origin.
   *
   * Options:
   * vertical: [top, center, bottom, x(px)];
   * horizontal: [left, center, right, x(px)].
   * @default {
   *   vertical: 'top',
   *   horizontal: 'left',
   * }
   */
  transformOrigin: PropTypes.shape({
    horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,
    vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired
  }),
  /**
   * The component used for the transition.
   * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   * @default Grow
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * Set to 'auto' to automatically calculate transition time based on height.
   * @default 'auto'
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })]),
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition/) component.
   * @default {}
   */
  TransitionProps: PropTypes.object
} ;
var Popover$1 = Popover;

function getMenuUtilityClass(slot) {
  return generateUtilityClass('MuiMenu', slot);
}
generateUtilityClasses('MuiMenu', ['root', 'paper', 'list']);

const _excluded$I = ["onEntering"],
  _excluded2$2 = ["autoFocus", "children", "disableAutoFocusItem", "MenuListProps", "onClose", "open", "PaperProps", "PopoverClasses", "transitionDuration", "TransitionProps", "variant"];
const RTL_ORIGIN = {
  vertical: 'top',
  horizontal: 'right'
};
const LTR_ORIGIN = {
  vertical: 'top',
  horizontal: 'left'
};
const useUtilityClasses$B = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    paper: ['paper'],
    list: ['list']
  };
  return composeClasses(slots, getMenuUtilityClass, classes);
};
const MenuRoot = styled$1(Popover$1, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiMenu',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({});
const MenuPaper = styled$1(PopoverPaper, {
  name: 'MuiMenu',
  slot: 'Paper',
  overridesResolver: (props, styles) => styles.paper
})({
  // specZ: The maximum height of a simple menu should be one or more rows less than the view
  // height. This ensures a tappable area outside of the simple menu with which to dismiss
  // the menu.
  maxHeight: 'calc(100% - 96px)',
  // Add iOS momentum scrolling for iOS < 13.0
  WebkitOverflowScrolling: 'touch'
});
const MenuMenuList = styled$1(MenuList$1, {
  name: 'MuiMenu',
  slot: 'List',
  overridesResolver: (props, styles) => styles.list
})({
  // We disable the focus ring for mouse, touch and keyboard users.
  outline: 0
});
const Menu$1 = /*#__PURE__*/reactExports$1.forwardRef(function Menu(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiMenu'
  });
  const {
      autoFocus = true,
      children,
      disableAutoFocusItem = false,
      MenuListProps = {},
      onClose,
      open,
      PaperProps = {},
      PopoverClasses,
      transitionDuration = 'auto',
      TransitionProps: {
        onEntering
      } = {},
      variant = 'selectedMenu'
    } = props,
    TransitionProps = _objectWithoutPropertiesLoose$2(props.TransitionProps, _excluded$I),
    other = _objectWithoutPropertiesLoose$2(props, _excluded2$2);
  const theme = useTheme();
  const isRtl = theme.direction === 'rtl';
  const ownerState = _extends({}, props, {
    autoFocus,
    disableAutoFocusItem,
    MenuListProps,
    onEntering,
    PaperProps,
    transitionDuration,
    TransitionProps,
    variant
  });
  const classes = useUtilityClasses$B(ownerState);
  const autoFocusItem = autoFocus && !disableAutoFocusItem && open;
  const menuListActionsRef = reactExports$1.useRef(null);
  const handleEntering = (element, isAppearing) => {
    if (menuListActionsRef.current) {
      menuListActionsRef.current.adjustStyleForScrollbar(element, theme);
    }
    if (onEntering) {
      onEntering(element, isAppearing);
    }
  };
  const handleListKeyDown = event => {
    if (event.key === 'Tab') {
      event.preventDefault();
      if (onClose) {
        onClose(event, 'tabKeyDown');
      }
    }
  };

  /**
   * the index of the item should receive focus
   * in a `variant="selectedMenu"` it's the first `selected` item
   * otherwise it's the very first item.
   */
  let activeItemIndex = -1;
  // since we inject focus related props into children we have to do a lookahead
  // to check if there is a `selected` item. We're looking for the last `selected`
  // item and use the first valid item as a fallback
  reactExports$1.Children.map(children, (child, index) => {
    if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
      return;
    }
    {
      if (reactIsExports$1.isFragment(child)) {
        console.error(["MUI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
      }
    }
    if (!child.props.disabled) {
      if (variant === 'selectedMenu' && child.props.selected) {
        activeItemIndex = index;
      } else if (activeItemIndex === -1) {
        activeItemIndex = index;
      }
    }
  });
  return /*#__PURE__*/jsxRuntimeExports.jsx(MenuRoot, _extends({
    onClose: onClose,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: isRtl ? 'right' : 'left'
    },
    transformOrigin: isRtl ? RTL_ORIGIN : LTR_ORIGIN,
    slots: {
      paper: MenuPaper
    },
    slotProps: {
      paper: _extends({}, PaperProps, {
        classes: _extends({}, PaperProps.classes, {
          root: classes.paper
        })
      })
    },
    className: classes.root,
    open: open,
    ref: ref,
    transitionDuration: transitionDuration,
    TransitionProps: _extends({
      onEntering: handleEntering
    }, TransitionProps),
    ownerState: ownerState
  }, other, {
    classes: PopoverClasses,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(MenuMenuList, _extends({
      onKeyDown: handleListKeyDown,
      actions: menuListActionsRef,
      autoFocus: autoFocus && (activeItemIndex === -1 || disableAutoFocusItem),
      autoFocusItem: autoFocusItem,
      variant: variant
    }, MenuListProps, {
      className: clsx(classes.list, MenuListProps.className),
      children: children
    }))
  }));
});
Menu$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * An HTML element, or a function that returns one.
   * It's used to set the position of the menu.
   */
  anchorEl: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * If `true` (Default) will focus the `[role="menu"]` if no focusable child is found. Disabled
   * children are not focusable. If you set this prop to `false` focus will be placed
   * on the parent modal container. This has severe accessibility implications
   * and should only be considered if you manage focus otherwise.
   * @default true
   */
  autoFocus: PropTypes.bool,
  /**
   * Menu contents, normally `MenuItem`s.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * When opening the menu will not focus the active item but the `[role="menu"]`
   * unless `autoFocus` is also set to `false`. Not using the default means not
   * following WAI-ARIA authoring practices. Please be considerate about possible
   * accessibility implications.
   * @default false
   */
  disableAutoFocusItem: PropTypes.bool,
  /**
   * Props applied to the [`MenuList`](/material-ui/api/menu-list/) element.
   * @default {}
   */
  MenuListProps: PropTypes.object,
  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`, `"tabKeyDown"`.
   */
  onClose: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * @ignore
   */
  PaperProps: PropTypes.object,
  /**
   * `classes` prop applied to the [`Popover`](/material-ui/api/popover/) element.
   */
  PopoverClasses: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The length of the transition in `ms`, or 'auto'
   * @default 'auto'
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })]),
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition/) component.
   * @default {}
   */
  TransitionProps: PropTypes.object,
  /**
   * The variant to use. Use `menu` to prevent selected items from impacting the initial focus.
   * @default 'selectedMenu'
   */
  variant: PropTypes.oneOf(['menu', 'selectedMenu'])
} ;
var Menu$2 = Menu$1;

function getNativeSelectUtilityClasses(slot) {
  return generateUtilityClass('MuiNativeSelect', slot);
}
const nativeSelectClasses = generateUtilityClasses('MuiNativeSelect', ['root', 'select', 'multiple', 'filled', 'outlined', 'standard', 'disabled', 'icon', 'iconOpen', 'iconFilled', 'iconOutlined', 'iconStandard', 'nativeInput', 'error']);
var nativeSelectClasses$1 = nativeSelectClasses;

const _excluded$H = ["className", "disabled", "error", "IconComponent", "inputRef", "variant"];
const useUtilityClasses$A = ownerState => {
  const {
    classes,
    variant,
    disabled,
    multiple,
    open,
    error
  } = ownerState;
  const slots = {
    select: ['select', variant, disabled && 'disabled', multiple && 'multiple', error && 'error'],
    icon: ['icon', `icon${capitalize(variant)}`, open && 'iconOpen', disabled && 'disabled']
  };
  return composeClasses(slots, getNativeSelectUtilityClasses, classes);
};
const nativeSelectSelectStyles = ({
  ownerState,
  theme
}) => _extends({
  MozAppearance: 'none',
  // Reset
  WebkitAppearance: 'none',
  // Reset
  // When interacting quickly, the text can end up selected.
  // Native select can't be selected either.
  userSelect: 'none',
  borderRadius: 0,
  // Reset
  cursor: 'pointer',
  '&:focus': _extends({}, theme.vars ? {
    backgroundColor: `rgba(${theme.vars.palette.common.onBackgroundChannel} / 0.05)`
  } : {
    backgroundColor: theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.05)' : 'rgba(255, 255, 255, 0.05)'
  }, {
    borderRadius: 0 // Reset Chrome style
  }),

  // Remove IE11 arrow
  '&::-ms-expand': {
    display: 'none'
  },
  [`&.${nativeSelectClasses$1.disabled}`]: {
    cursor: 'default'
  },
  '&[multiple]': {
    height: 'auto'
  },
  '&:not([multiple]) option, &:not([multiple]) optgroup': {
    backgroundColor: (theme.vars || theme).palette.background.paper
  },
  // Bump specificity to allow extending custom inputs
  '&&&': {
    paddingRight: 24,
    minWidth: 16 // So it doesn't collapse.
  }
}, ownerState.variant === 'filled' && {
  '&&&': {
    paddingRight: 32
  }
}, ownerState.variant === 'outlined' && {
  borderRadius: (theme.vars || theme).shape.borderRadius,
  '&:focus': {
    borderRadius: (theme.vars || theme).shape.borderRadius // Reset the reset for Chrome style
  },

  '&&&': {
    paddingRight: 32
  }
});
const NativeSelectSelect = styled$1('select', {
  name: 'MuiNativeSelect',
  slot: 'Select',
  shouldForwardProp: rootShouldForwardProp,
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.select, styles[ownerState.variant], ownerState.error && styles.error, {
      [`&.${nativeSelectClasses$1.multiple}`]: styles.multiple
    }];
  }
})(nativeSelectSelectStyles);
const nativeSelectIconStyles = ({
  ownerState,
  theme
}) => _extends({
  // We use a position absolute over a flexbox in order to forward the pointer events
  // to the input and to support wrapping tags..
  position: 'absolute',
  right: 0,
  top: 'calc(50% - .5em)',
  // Center vertically, height is 1em
  pointerEvents: 'none',
  // Don't block pointer events on the select under the icon.
  color: (theme.vars || theme).palette.action.active,
  [`&.${nativeSelectClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.action.disabled
  }
}, ownerState.open && {
  transform: 'rotate(180deg)'
}, ownerState.variant === 'filled' && {
  right: 7
}, ownerState.variant === 'outlined' && {
  right: 7
});
const NativeSelectIcon = styled$1('svg', {
  name: 'MuiNativeSelect',
  slot: 'Icon',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.icon, ownerState.variant && styles[`icon${capitalize(ownerState.variant)}`], ownerState.open && styles.iconOpen];
  }
})(nativeSelectIconStyles);

/**
 * @ignore - internal component.
 */
const NativeSelectInput = /*#__PURE__*/reactExports$1.forwardRef(function NativeSelectInput(props, ref) {
  const {
      className,
      disabled,
      error,
      IconComponent,
      inputRef,
      variant = 'standard'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$H);
  const ownerState = _extends({}, props, {
    disabled,
    variant,
    error
  });
  const classes = useUtilityClasses$A(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(NativeSelectSelect, _extends({
      ownerState: ownerState,
      className: clsx(classes.select, className),
      disabled: disabled,
      ref: inputRef || ref
    }, other)), props.multiple ? null : /*#__PURE__*/jsxRuntimeExports.jsx(NativeSelectIcon, {
      as: IconComponent,
      ownerState: ownerState,
      className: classes.icon
    })]
  });
});
NativeSelectInput.propTypes = {
  /**
   * The option elements to populate the select with.
   * Can be some `<option>` elements.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * The CSS class name of the select element.
   */
  className: PropTypes.string,
  /**
   * If `true`, the select is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the `select input` will indicate an error.
   */
  error: PropTypes.bool,
  /**
   * The icon that displays the arrow.
   */
  IconComponent: PropTypes.elementType.isRequired,
  /**
   * Use that prop to pass a ref to the native select element.
   * @deprecated
   */
  inputRef: refType$1,
  /**
   * @ignore
   */
  multiple: PropTypes.bool,
  /**
   * Name attribute of the `select` or hidden `input` element.
   */
  name: PropTypes.string,
  /**
   * Callback fired when a menu item is selected.
   *
   * @param {object} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * The input value.
   */
  value: PropTypes.any,
  /**
   * The variant to use.
   */
  variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} ;
var NativeSelectInput$1 = NativeSelectInput;

function getSelectUtilityClasses(slot) {
  return generateUtilityClass('MuiSelect', slot);
}
const selectClasses = generateUtilityClasses('MuiSelect', ['select', 'multiple', 'filled', 'outlined', 'standard', 'disabled', 'focused', 'icon', 'iconOpen', 'iconFilled', 'iconOutlined', 'iconStandard', 'nativeInput', 'error']);
var selectClasses$1 = selectClasses;

var _span$2;
const _excluded$G = ["aria-describedby", "aria-label", "autoFocus", "autoWidth", "children", "className", "defaultOpen", "defaultValue", "disabled", "displayEmpty", "error", "IconComponent", "inputRef", "labelId", "MenuProps", "multiple", "name", "onBlur", "onChange", "onClose", "onFocus", "onOpen", "open", "readOnly", "renderValue", "SelectDisplayProps", "tabIndex", "type", "value", "variant"];
const SelectSelect = styled$1('div', {
  name: 'MuiSelect',
  slot: 'Select',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [
    // Win specificity over the input base
    {
      [`&.${selectClasses$1.select}`]: styles.select
    }, {
      [`&.${selectClasses$1.select}`]: styles[ownerState.variant]
    }, {
      [`&.${selectClasses$1.error}`]: styles.error
    }, {
      [`&.${selectClasses$1.multiple}`]: styles.multiple
    }];
  }
})(nativeSelectSelectStyles, {
  // Win specificity over the input base
  [`&.${selectClasses$1.select}`]: {
    height: 'auto',
    // Resets for multiple select with chips
    minHeight: '1.4375em',
    // Required for select\text-field height consistency
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    overflow: 'hidden'
  }
});
const SelectIcon = styled$1('svg', {
  name: 'MuiSelect',
  slot: 'Icon',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.icon, ownerState.variant && styles[`icon${capitalize(ownerState.variant)}`], ownerState.open && styles.iconOpen];
  }
})(nativeSelectIconStyles);
const SelectNativeInput = styled$1('input', {
  shouldForwardProp: prop => slotShouldForwardProp(prop) && prop !== 'classes',
  name: 'MuiSelect',
  slot: 'NativeInput',
  overridesResolver: (props, styles) => styles.nativeInput
})({
  bottom: 0,
  left: 0,
  position: 'absolute',
  opacity: 0,
  pointerEvents: 'none',
  width: '100%',
  boxSizing: 'border-box'
});
function areEqualValues(a, b) {
  if (typeof b === 'object' && b !== null) {
    return a === b;
  }

  // The value could be a number, the DOM will stringify it anyway.
  return String(a) === String(b);
}
function isEmpty(display) {
  return display == null || typeof display === 'string' && !display.trim();
}
const useUtilityClasses$z = ownerState => {
  const {
    classes,
    variant,
    disabled,
    multiple,
    open,
    error
  } = ownerState;
  const slots = {
    select: ['select', variant, disabled && 'disabled', multiple && 'multiple', error && 'error'],
    icon: ['icon', `icon${capitalize(variant)}`, open && 'iconOpen', disabled && 'disabled'],
    nativeInput: ['nativeInput']
  };
  return composeClasses(slots, getSelectUtilityClasses, classes);
};

/**
 * @ignore - internal component.
 */
const SelectInput = /*#__PURE__*/reactExports$1.forwardRef(function SelectInput(props, ref) {
  const {
      'aria-describedby': ariaDescribedby,
      'aria-label': ariaLabel,
      autoFocus,
      autoWidth,
      children,
      className,
      defaultOpen,
      defaultValue,
      disabled,
      displayEmpty,
      error = false,
      IconComponent,
      inputRef: inputRefProp,
      labelId,
      MenuProps = {},
      multiple,
      name,
      onBlur,
      onChange,
      onClose,
      onFocus,
      onOpen,
      open: openProp,
      readOnly,
      renderValue,
      SelectDisplayProps = {},
      tabIndex: tabIndexProp
      // catching `type` from Input which makes no sense for SelectInput
      ,

      value: valueProp,
      variant = 'standard'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$G);
  const [value, setValueState] = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: 'Select'
  });
  const [openState, setOpenState] = useControlled({
    controlled: openProp,
    default: defaultOpen,
    name: 'Select'
  });
  const inputRef = reactExports$1.useRef(null);
  const displayRef = reactExports$1.useRef(null);
  const [displayNode, setDisplayNode] = reactExports$1.useState(null);
  const {
    current: isOpenControlled
  } = reactExports$1.useRef(openProp != null);
  const [menuMinWidthState, setMenuMinWidthState] = reactExports$1.useState();
  const handleRef = useForkRef(ref, inputRefProp);
  const handleDisplayRef = reactExports$1.useCallback(node => {
    displayRef.current = node;
    if (node) {
      setDisplayNode(node);
    }
  }, []);
  const anchorElement = displayNode == null ? void 0 : displayNode.parentNode;
  reactExports$1.useImperativeHandle(handleRef, () => ({
    focus: () => {
      displayRef.current.focus();
    },
    node: inputRef.current,
    value
  }), [value]);

  // Resize menu on `defaultOpen` automatic toggle.
  reactExports$1.useEffect(() => {
    if (defaultOpen && openState && displayNode && !isOpenControlled) {
      setMenuMinWidthState(autoWidth ? null : anchorElement.clientWidth);
      displayRef.current.focus();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [displayNode, autoWidth]);
  // `isOpenControlled` is ignored because the component should never switch between controlled and uncontrolled modes.
  // `defaultOpen` and `openState` are ignored to avoid unnecessary callbacks.
  reactExports$1.useEffect(() => {
    if (autoFocus) {
      displayRef.current.focus();
    }
  }, [autoFocus]);
  reactExports$1.useEffect(() => {
    if (!labelId) {
      return undefined;
    }
    const label = ownerDocument(displayRef.current).getElementById(labelId);
    if (label) {
      const handler = () => {
        if (getSelection().isCollapsed) {
          displayRef.current.focus();
        }
      };
      label.addEventListener('click', handler);
      return () => {
        label.removeEventListener('click', handler);
      };
    }
    return undefined;
  }, [labelId]);
  const update = (open, event) => {
    if (open) {
      if (onOpen) {
        onOpen(event);
      }
    } else if (onClose) {
      onClose(event);
    }
    if (!isOpenControlled) {
      setMenuMinWidthState(autoWidth ? null : anchorElement.clientWidth);
      setOpenState(open);
    }
  };
  const handleMouseDown = event => {
    // Ignore everything but left-click
    if (event.button !== 0) {
      return;
    }
    // Hijack the default focus behavior.
    event.preventDefault();
    displayRef.current.focus();
    update(true, event);
  };
  const handleClose = event => {
    update(false, event);
  };
  const childrenArray = reactExports$1.Children.toArray(children);

  // Support autofill.
  const handleChange = event => {
    const child = childrenArray.find(childItem => childItem.props.value === event.target.value);
    if (child === undefined) {
      return;
    }
    setValueState(child.props.value);
    if (onChange) {
      onChange(event, child);
    }
  };
  const handleItemClick = child => event => {
    let newValue;

    // We use the tabindex attribute to signal the available options.
    if (!event.currentTarget.hasAttribute('tabindex')) {
      return;
    }
    if (multiple) {
      newValue = Array.isArray(value) ? value.slice() : [];
      const itemIndex = value.indexOf(child.props.value);
      if (itemIndex === -1) {
        newValue.push(child.props.value);
      } else {
        newValue.splice(itemIndex, 1);
      }
    } else {
      newValue = child.props.value;
    }
    if (child.props.onClick) {
      child.props.onClick(event);
    }
    if (value !== newValue) {
      setValueState(newValue);
      if (onChange) {
        // Redefine target to allow name and value to be read.
        // This allows seamless integration with the most popular form libraries.
        // https://github.com/mui/material-ui/issues/13485#issuecomment-676048492
        // Clone the event to not override `target` of the original event.
        const nativeEvent = event.nativeEvent || event;
        const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
        Object.defineProperty(clonedEvent, 'target', {
          writable: true,
          value: {
            value: newValue,
            name
          }
        });
        onChange(clonedEvent, child);
      }
    }
    if (!multiple) {
      update(false, event);
    }
  };
  const handleKeyDown = event => {
    if (!readOnly) {
      const validKeys = [' ', 'ArrowUp', 'ArrowDown',
      // The native select doesn't respond to enter on macOS, but it's recommended by
      // https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/
      'Enter'];
      if (validKeys.indexOf(event.key) !== -1) {
        event.preventDefault();
        update(true, event);
      }
    }
  };
  const open = displayNode !== null && openState;
  const handleBlur = event => {
    // if open event.stopImmediatePropagation
    if (!open && onBlur) {
      // Preact support, target is read only property on a native event.
      Object.defineProperty(event, 'target', {
        writable: true,
        value: {
          value,
          name
        }
      });
      onBlur(event);
    }
  };
  delete other['aria-invalid'];
  let display;
  let displaySingle;
  const displayMultiple = [];
  let computeDisplay = false;
  let foundMatch = false;

  // No need to display any value if the field is empty.
  if (isFilled({
    value
  }) || displayEmpty) {
    if (renderValue) {
      display = renderValue(value);
    } else {
      computeDisplay = true;
    }
  }
  const items = childrenArray.map(child => {
    if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
      return null;
    }
    {
      if (reactIsExports$1.isFragment(child)) {
        console.error(["MUI: The Select component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
      }
    }
    let selected;
    if (multiple) {
      if (!Array.isArray(value)) {
        throw new Error(`MUI: The \`value\` prop must be an array when using the \`Select\` component with \`multiple\`.` );
      }
      selected = value.some(v => areEqualValues(v, child.props.value));
      if (selected && computeDisplay) {
        displayMultiple.push(child.props.children);
      }
    } else {
      selected = areEqualValues(value, child.props.value);
      if (selected && computeDisplay) {
        displaySingle = child.props.children;
      }
    }
    if (selected) {
      foundMatch = true;
    }
    return /*#__PURE__*/reactExports$1.cloneElement(child, {
      'aria-selected': selected ? 'true' : 'false',
      onClick: handleItemClick(child),
      onKeyUp: event => {
        if (event.key === ' ') {
          // otherwise our MenuItems dispatches a click event
          // it's not behavior of the native <option> and causes
          // the select to close immediately since we open on space keydown
          event.preventDefault();
        }
        if (child.props.onKeyUp) {
          child.props.onKeyUp(event);
        }
      },
      role: 'option',
      selected,
      value: undefined,
      // The value is most likely not a valid HTML attribute.
      'data-value': child.props.value // Instead, we provide it as a data attribute.
    });
  });

  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    reactExports$1.useEffect(() => {
      if (!foundMatch && !multiple && value !== '') {
        const values = childrenArray.map(child => child.props.value);
        console.warn([`MUI: You have provided an out-of-range value \`${value}\` for the select ${name ? `(name="${name}") ` : ''}component.`, "Consider providing a value that matches one of the available options or ''.", `The available values are ${values.filter(x => x != null).map(x => `\`${x}\``).join(', ') || '""'}.`].join('\n'));
      }
    }, [foundMatch, childrenArray, multiple, name, value]);
  }
  if (computeDisplay) {
    if (multiple) {
      if (displayMultiple.length === 0) {
        display = null;
      } else {
        display = displayMultiple.reduce((output, child, index) => {
          output.push(child);
          if (index < displayMultiple.length - 1) {
            output.push(', ');
          }
          return output;
        }, []);
      }
    } else {
      display = displaySingle;
    }
  }

  // Avoid performing a layout computation in the render method.
  let menuMinWidth = menuMinWidthState;
  if (!autoWidth && isOpenControlled && displayNode) {
    menuMinWidth = anchorElement.clientWidth;
  }
  let tabIndex;
  if (typeof tabIndexProp !== 'undefined') {
    tabIndex = tabIndexProp;
  } else {
    tabIndex = disabled ? null : 0;
  }
  const buttonId = SelectDisplayProps.id || (name ? `mui-component-select-${name}` : undefined);
  const ownerState = _extends({}, props, {
    variant,
    value,
    open,
    error
  });
  const classes = useUtilityClasses$z(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(SelectSelect, _extends({
      ref: handleDisplayRef,
      tabIndex: tabIndex,
      role: "button",
      "aria-disabled": disabled ? 'true' : undefined,
      "aria-expanded": open ? 'true' : 'false',
      "aria-haspopup": "listbox",
      "aria-label": ariaLabel,
      "aria-labelledby": [labelId, buttonId].filter(Boolean).join(' ') || undefined,
      "aria-describedby": ariaDescribedby,
      onKeyDown: handleKeyDown,
      onMouseDown: disabled || readOnly ? null : handleMouseDown,
      onBlur: handleBlur,
      onFocus: onFocus
    }, SelectDisplayProps, {
      ownerState: ownerState,
      className: clsx(SelectDisplayProps.className, classes.select, className)
      // The id is required for proper a11y
      ,

      id: buttonId,
      children: isEmpty(display) ?
      // notranslate needed while Google Translate will not fix zero-width space issue
      _span$2 || (_span$2 = /*#__PURE__*/jsxRuntimeExports.jsx("span", {
        className: "notranslate",
        children: "\u200B"
      })) : display
    })), /*#__PURE__*/jsxRuntimeExports.jsx(SelectNativeInput, _extends({
      "aria-invalid": error,
      value: Array.isArray(value) ? value.join(',') : value,
      name: name,
      ref: inputRef,
      "aria-hidden": true,
      onChange: handleChange,
      tabIndex: -1,
      disabled: disabled,
      className: classes.nativeInput,
      autoFocus: autoFocus,
      ownerState: ownerState
    }, other)), /*#__PURE__*/jsxRuntimeExports.jsx(SelectIcon, {
      as: IconComponent,
      className: classes.icon,
      ownerState: ownerState
    }), /*#__PURE__*/jsxRuntimeExports.jsx(Menu$2, _extends({
      id: `menu-${name || ''}`,
      anchorEl: anchorElement,
      open: open,
      onClose: handleClose,
      anchorOrigin: {
        vertical: 'bottom',
        horizontal: 'center'
      },
      transformOrigin: {
        vertical: 'top',
        horizontal: 'center'
      }
    }, MenuProps, {
      MenuListProps: _extends({
        'aria-labelledby': labelId,
        role: 'listbox',
        disableListWrap: true
      }, MenuProps.MenuListProps),
      PaperProps: _extends({}, MenuProps.PaperProps, {
        style: _extends({
          minWidth: menuMinWidth
        }, MenuProps.PaperProps != null ? MenuProps.PaperProps.style : null)
      }),
      children: items
    }))]
  });
});
SelectInput.propTypes = {
  /**
   * @ignore
   */
  'aria-describedby': PropTypes.string,
  /**
   * @ignore
   */
  'aria-label': PropTypes.string,
  /**
   * @ignore
   */
  autoFocus: PropTypes.bool,
  /**
   * If `true`, the width of the popover will automatically be set according to the items inside the
   * menu, otherwise it will be at least the width of the select input.
   */
  autoWidth: PropTypes.bool,
  /**
   * The option elements to populate the select with.
   * Can be some `<MenuItem>` elements.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * The CSS class name of the select element.
   */
  className: PropTypes.string,
  /**
   * If `true`, the component is toggled on mount. Use when the component open state is not controlled.
   * You can only use it when the `native` prop is `false` (default).
   */
  defaultOpen: PropTypes.bool,
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, the select is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the selected item is displayed even if its value is empty.
   */
  displayEmpty: PropTypes.bool,
  /**
   * If `true`, the `select input` will indicate an error.
   */
  error: PropTypes.bool,
  /**
   * The icon that displays the arrow.
   */
  IconComponent: PropTypes.elementType.isRequired,
  /**
   * Imperative handle implementing `{ value: T, node: HTMLElement, focus(): void }`
   * Equivalent to `ref`
   */
  inputRef: refType$1,
  /**
   * The ID of an element that acts as an additional label. The Select will
   * be labelled by the additional label and the selected value.
   */
  labelId: PropTypes.string,
  /**
   * Props applied to the [`Menu`](/material-ui/api/menu/) element.
   */
  MenuProps: PropTypes.object,
  /**
   * If `true`, `value` must be an array and the menu will support multiple selections.
   */
  multiple: PropTypes.bool,
  /**
   * Name attribute of the `select` or hidden `input` element.
   */
  name: PropTypes.string,
  /**
   * @ignore
   */
  onBlur: PropTypes.func,
  /**
   * Callback fired when a menu item is selected.
   *
   * @param {object} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (any).
   * @param {object} [child] The react element that was selected.
   */
  onChange: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   * Use in controlled mode (see open).
   *
   * @param {object} event The event source of the callback.
   */
  onClose: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * Callback fired when the component requests to be opened.
   * Use in controlled mode (see open).
   *
   * @param {object} event The event source of the callback.
   */
  onOpen: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool,
  /**
   * @ignore
   */
  readOnly: PropTypes.bool,
  /**
   * Render the selected value.
   *
   * @param {any} value The `value` provided to the component.
   * @returns {ReactNode}
   */
  renderValue: PropTypes.func,
  /**
   * Props applied to the clickable div element.
   */
  SelectDisplayProps: PropTypes.object,
  /**
   * @ignore
   */
  tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * @ignore
   */
  type: PropTypes.any,
  /**
   * The input value.
   */
  value: PropTypes.any,
  /**
   * The variant to use.
   */
  variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} ;
var SelectInput$1 = SelectInput;

var ArrowDropDownIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M7 10l5 5 5-5z"
}), 'ArrowDropDown');

function getInputUtilityClass(slot) {
  return generateUtilityClass('MuiInput', slot);
}
const inputClasses = _extends({}, inputBaseClasses$1, generateUtilityClasses('MuiInput', ['root', 'underline', 'input']));
var inputClasses$1 = inputClasses;

const _excluded$F = ["disableUnderline", "components", "componentsProps", "fullWidth", "inputComponent", "multiline", "slotProps", "slots", "type"];
const useUtilityClasses$y = ownerState => {
  const {
    classes,
    disableUnderline
  } = ownerState;
  const slots = {
    root: ['root', !disableUnderline && 'underline'],
    input: ['input']
  };
  const composedClasses = composeClasses(slots, getInputUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const InputRoot = styled$1(InputBaseRoot, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiInput',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [...rootOverridesResolver(props, styles), !ownerState.disableUnderline && styles.underline];
  }
})(({
  theme,
  ownerState
}) => {
  const light = theme.palette.mode === 'light';
  let bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
  if (theme.vars) {
    bottomLineColor = `rgba(${theme.vars.palette.common.onBackgroundChannel} / ${theme.vars.opacity.inputUnderline})`;
  }
  return _extends({
    position: 'relative'
  }, ownerState.formControl && {
    'label + &': {
      marginTop: 16
    }
  }, !ownerState.disableUnderline && {
    '&:after': {
      borderBottom: `2px solid ${(theme.vars || theme).palette[ownerState.color].main}`,
      left: 0,
      bottom: 0,
      // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242
      content: '""',
      position: 'absolute',
      right: 0,
      transform: 'scaleX(0)',
      transition: theme.transitions.create('transform', {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut
      }),
      pointerEvents: 'none' // Transparent to the hover style.
    },

    [`&.${inputClasses$1.focused}:after`]: {
      // translateX(0) is a workaround for Safari transform scale bug
      // See https://github.com/mui/material-ui/issues/31766
      transform: 'scaleX(1) translateX(0)'
    },
    [`&.${inputClasses$1.error}`]: {
      '&:before, &:after': {
        borderBottomColor: (theme.vars || theme).palette.error.main
      }
    },
    '&:before': {
      borderBottom: `1px solid ${bottomLineColor}`,
      left: 0,
      bottom: 0,
      // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242
      content: '"\\00a0"',
      position: 'absolute',
      right: 0,
      transition: theme.transitions.create('border-bottom-color', {
        duration: theme.transitions.duration.shorter
      }),
      pointerEvents: 'none' // Transparent to the hover style.
    },

    [`&:hover:not(.${inputClasses$1.disabled}, .${inputClasses$1.error}):before`]: {
      borderBottom: `2px solid ${(theme.vars || theme).palette.text.primary}`,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        borderBottom: `1px solid ${bottomLineColor}`
      }
    },
    [`&.${inputClasses$1.disabled}:before`]: {
      borderBottomStyle: 'dotted'
    }
  });
});
const InputInput = styled$1(InputBaseComponent, {
  name: 'MuiInput',
  slot: 'Input',
  overridesResolver: inputOverridesResolver
})({});
const Input$2 = /*#__PURE__*/reactExports$1.forwardRef(function Input(inProps, ref) {
  var _ref, _slots$root, _ref2, _slots$input;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiInput'
  });
  const {
      disableUnderline,
      components = {},
      componentsProps: componentsPropsProp,
      fullWidth = false,
      inputComponent = 'input',
      multiline = false,
      slotProps,
      slots = {},
      type = 'text'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$F);
  const classes = useUtilityClasses$y(props);
  const ownerState = {
    disableUnderline
  };
  const inputComponentsProps = {
    root: {
      ownerState
    }
  };
  const componentsProps = (slotProps != null ? slotProps : componentsPropsProp) ? deepmerge(slotProps != null ? slotProps : componentsPropsProp, inputComponentsProps) : inputComponentsProps;
  const RootSlot = (_ref = (_slots$root = slots.root) != null ? _slots$root : components.Root) != null ? _ref : InputRoot;
  const InputSlot = (_ref2 = (_slots$input = slots.input) != null ? _slots$input : components.Input) != null ? _ref2 : InputInput;
  return /*#__PURE__*/jsxRuntimeExports.jsx(MuiInputBase, _extends({
    slots: {
      root: RootSlot,
      input: InputSlot
    },
    slotProps: componentsProps,
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other, {
    classes: classes
  }));
});
Input$2.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: PropTypes.string,
  /**
   * If `true`, the `input` element is focused during the first mount.
   */
  autoFocus: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Input: PropTypes.elementType,
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    input: PropTypes.object,
    root: PropTypes.object
  }),
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, the component is disabled.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the `input` will not have an underline.
   */
  disableUnderline: PropTypes.bool,
  /**
   * End `InputAdornment` for this component.
   */
  endAdornment: PropTypes.node,
  /**
   * If `true`, the `input` will indicate an error.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the `input` will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * The component used for the `input` element.
   * Either a string to use a HTML element or a component.
   * @default 'input'
   */
  inputComponent: PropTypes.elementType,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   * @default {}
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   * The prop defaults to the value (`'none'`) inherited from the parent FormControl component.
   */
  margin: PropTypes.oneOf(['dense', 'none']),
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Minimum number of rows to display when multiline option is set to true.
   */
  minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * If `true`, a [TextareaAutosize](/material-ui/react-textarea-autosize/) element is rendered.
   * @default false
   */
  multiline: PropTypes.bool,
  /**
   * Name attribute of the `input` element.
   */
  name: PropTypes.string,
  /**
   * Callback fired when the value is changed.
   *
   * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * The short hint displayed in the `input` before the user enters a value.
   */
  placeholder: PropTypes.string,
  /**
   * It prevents the user from changing the value of the field
   * (not from interacting with the field).
   */
  readOnly: PropTypes.bool,
  /**
   * If `true`, the `input` element is required.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  required: PropTypes.bool,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    input: PropTypes.object,
    root: PropTypes.object
  }),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    input: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * Start `InputAdornment` for this component.
   */
  startAdornment: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   * @default 'text'
   */
  type: PropTypes.string,
  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: PropTypes.any
} ;
Input$2.muiName = 'Input';
var Input$3 = Input$2;

function getFilledInputUtilityClass(slot) {
  return generateUtilityClass('MuiFilledInput', slot);
}
const filledInputClasses = _extends({}, inputBaseClasses$1, generateUtilityClasses('MuiFilledInput', ['root', 'underline', 'input']));
var filledInputClasses$1 = filledInputClasses;

const _excluded$E = ["disableUnderline", "components", "componentsProps", "fullWidth", "hiddenLabel", "inputComponent", "multiline", "slotProps", "slots", "type"];
const useUtilityClasses$x = ownerState => {
  const {
    classes,
    disableUnderline
  } = ownerState;
  const slots = {
    root: ['root', !disableUnderline && 'underline'],
    input: ['input']
  };
  const composedClasses = composeClasses(slots, getFilledInputUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const FilledInputRoot = styled$1(InputBaseRoot, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiFilledInput',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [...rootOverridesResolver(props, styles), !ownerState.disableUnderline && styles.underline];
  }
})(({
  theme,
  ownerState
}) => {
  var _palette;
  const light = theme.palette.mode === 'light';
  const bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
  const backgroundColor = light ? 'rgba(0, 0, 0, 0.06)' : 'rgba(255, 255, 255, 0.09)';
  const hoverBackground = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.13)';
  const disabledBackground = light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)';
  return _extends({
    position: 'relative',
    backgroundColor: theme.vars ? theme.vars.palette.FilledInput.bg : backgroundColor,
    borderTopLeftRadius: (theme.vars || theme).shape.borderRadius,
    borderTopRightRadius: (theme.vars || theme).shape.borderRadius,
    transition: theme.transitions.create('background-color', {
      duration: theme.transitions.duration.shorter,
      easing: theme.transitions.easing.easeOut
    }),
    '&:hover': {
      backgroundColor: theme.vars ? theme.vars.palette.FilledInput.hoverBg : hoverBackground,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: theme.vars ? theme.vars.palette.FilledInput.bg : backgroundColor
      }
    },
    [`&.${filledInputClasses$1.focused}`]: {
      backgroundColor: theme.vars ? theme.vars.palette.FilledInput.bg : backgroundColor
    },
    [`&.${filledInputClasses$1.disabled}`]: {
      backgroundColor: theme.vars ? theme.vars.palette.FilledInput.disabledBg : disabledBackground
    }
  }, !ownerState.disableUnderline && {
    '&:after': {
      borderBottom: `2px solid ${(_palette = (theme.vars || theme).palette[ownerState.color || 'primary']) == null ? void 0 : _palette.main}`,
      left: 0,
      bottom: 0,
      // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242
      content: '""',
      position: 'absolute',
      right: 0,
      transform: 'scaleX(0)',
      transition: theme.transitions.create('transform', {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut
      }),
      pointerEvents: 'none' // Transparent to the hover style.
    },

    [`&.${filledInputClasses$1.focused}:after`]: {
      // translateX(0) is a workaround for Safari transform scale bug
      // See https://github.com/mui/material-ui/issues/31766
      transform: 'scaleX(1) translateX(0)'
    },
    [`&.${filledInputClasses$1.error}`]: {
      '&:before, &:after': {
        borderBottomColor: (theme.vars || theme).palette.error.main
      }
    },
    '&:before': {
      borderBottom: `1px solid ${theme.vars ? `rgba(${theme.vars.palette.common.onBackgroundChannel} / ${theme.vars.opacity.inputUnderline})` : bottomLineColor}`,
      left: 0,
      bottom: 0,
      // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242
      content: '"\\00a0"',
      position: 'absolute',
      right: 0,
      transition: theme.transitions.create('border-bottom-color', {
        duration: theme.transitions.duration.shorter
      }),
      pointerEvents: 'none' // Transparent to the hover style.
    },

    [`&:hover:not(.${filledInputClasses$1.disabled}, .${filledInputClasses$1.error}):before`]: {
      borderBottom: `1px solid ${(theme.vars || theme).palette.text.primary}`
    },
    [`&.${filledInputClasses$1.disabled}:before`]: {
      borderBottomStyle: 'dotted'
    }
  }, ownerState.startAdornment && {
    paddingLeft: 12
  }, ownerState.endAdornment && {
    paddingRight: 12
  }, ownerState.multiline && _extends({
    padding: '25px 12px 8px'
  }, ownerState.size === 'small' && {
    paddingTop: 21,
    paddingBottom: 4
  }, ownerState.hiddenLabel && {
    paddingTop: 16,
    paddingBottom: 17
  }));
});
const FilledInputInput = styled$1(InputBaseComponent, {
  name: 'MuiFilledInput',
  slot: 'Input',
  overridesResolver: inputOverridesResolver
})(({
  theme,
  ownerState
}) => _extends({
  paddingTop: 25,
  paddingRight: 12,
  paddingBottom: 8,
  paddingLeft: 12
}, !theme.vars && {
  '&:-webkit-autofill': {
    WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset',
    WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff',
    caretColor: theme.palette.mode === 'light' ? null : '#fff',
    borderTopLeftRadius: 'inherit',
    borderTopRightRadius: 'inherit'
  }
}, theme.vars && {
  '&:-webkit-autofill': {
    borderTopLeftRadius: 'inherit',
    borderTopRightRadius: 'inherit'
  },
  [theme.getColorSchemeSelector('dark')]: {
    '&:-webkit-autofill': {
      WebkitBoxShadow: '0 0 0 100px #266798 inset',
      WebkitTextFillColor: '#fff',
      caretColor: '#fff'
    }
  }
}, ownerState.size === 'small' && {
  paddingTop: 21,
  paddingBottom: 4
}, ownerState.hiddenLabel && {
  paddingTop: 16,
  paddingBottom: 17
}, ownerState.multiline && {
  paddingTop: 0,
  paddingBottom: 0,
  paddingLeft: 0,
  paddingRight: 0
}, ownerState.startAdornment && {
  paddingLeft: 0
}, ownerState.endAdornment && {
  paddingRight: 0
}, ownerState.hiddenLabel && ownerState.size === 'small' && {
  paddingTop: 8,
  paddingBottom: 9
}));
const FilledInput = /*#__PURE__*/reactExports$1.forwardRef(function FilledInput(inProps, ref) {
  var _ref, _slots$root, _ref2, _slots$input;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFilledInput'
  });
  const {
      components = {},
      componentsProps: componentsPropsProp,
      fullWidth = false,
      // declare here to prevent spreading to DOM
      inputComponent = 'input',
      multiline = false,
      slotProps,
      slots = {},
      type = 'text'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$E);
  const ownerState = _extends({}, props, {
    fullWidth,
    inputComponent,
    multiline,
    type
  });
  const classes = useUtilityClasses$x(props);
  const filledInputComponentsProps = {
    root: {
      ownerState
    },
    input: {
      ownerState
    }
  };
  const componentsProps = (slotProps != null ? slotProps : componentsPropsProp) ? deepmerge(slotProps != null ? slotProps : componentsPropsProp, filledInputComponentsProps) : filledInputComponentsProps;
  const RootSlot = (_ref = (_slots$root = slots.root) != null ? _slots$root : components.Root) != null ? _ref : FilledInputRoot;
  const InputSlot = (_ref2 = (_slots$input = slots.input) != null ? _slots$input : components.Input) != null ? _ref2 : FilledInputInput;
  return /*#__PURE__*/jsxRuntimeExports.jsx(MuiInputBase, _extends({
    slots: {
      root: RootSlot,
      input: InputSlot
    },
    componentsProps: componentsProps,
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other, {
    classes: classes
  }));
});
FilledInput.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: PropTypes.string,
  /**
   * If `true`, the `input` element is focused during the first mount.
   */
  autoFocus: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Input: PropTypes.elementType,
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    input: PropTypes.object,
    root: PropTypes.object
  }),
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, the component is disabled.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the input will not have an underline.
   */
  disableUnderline: PropTypes.bool,
  /**
   * End `InputAdornment` for this component.
   */
  endAdornment: PropTypes.node,
  /**
   * If `true`, the `input` will indicate an error.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the `input` will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * If `true`, the label is hidden.
   * This is used to increase density for a `FilledInput`.
   * Be sure to add `aria-label` to the `input` element.
   * @default false
   */
  hiddenLabel: PropTypes.bool,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * The component used for the `input` element.
   * Either a string to use a HTML element or a component.
   * @default 'input'
   */
  inputComponent: PropTypes.elementType,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   * @default {}
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   * The prop defaults to the value (`'none'`) inherited from the parent FormControl component.
   */
  margin: PropTypes.oneOf(['dense', 'none']),
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Minimum number of rows to display when multiline option is set to true.
   */
  minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * If `true`, a [TextareaAutosize](/material-ui/react-textarea-autosize/) element is rendered.
   * @default false
   */
  multiline: PropTypes.bool,
  /**
   * Name attribute of the `input` element.
   */
  name: PropTypes.string,
  /**
   * Callback fired when the value is changed.
   *
   * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * The short hint displayed in the `input` before the user enters a value.
   */
  placeholder: PropTypes.string,
  /**
   * It prevents the user from changing the value of the field
   * (not from interacting with the field).
   */
  readOnly: PropTypes.bool,
  /**
   * If `true`, the `input` element is required.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  required: PropTypes.bool,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    input: PropTypes.object,
    root: PropTypes.object
  }),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    input: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * Start `InputAdornment` for this component.
   */
  startAdornment: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   * @default 'text'
   */
  type: PropTypes.string,
  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: PropTypes.any
} ;
FilledInput.muiName = 'Input';
var FilledInput$1 = FilledInput;

var _span$1;
const _excluded$D = ["children", "classes", "className", "label", "notched"];
const NotchedOutlineRoot$1 = styled$1('fieldset')({
  textAlign: 'left',
  position: 'absolute',
  bottom: 0,
  right: 0,
  top: -5,
  left: 0,
  margin: 0,
  padding: '0 8px',
  pointerEvents: 'none',
  borderRadius: 'inherit',
  borderStyle: 'solid',
  borderWidth: 1,
  overflow: 'hidden',
  minWidth: '0%'
});
const NotchedOutlineLegend = styled$1('legend')(({
  ownerState,
  theme
}) => _extends({
  float: 'unset',
  // Fix conflict with bootstrap
  width: 'auto',
  // Fix conflict with bootstrap
  overflow: 'hidden'
}, !ownerState.withLabel && {
  padding: 0,
  lineHeight: '11px',
  // sync with `height` in `legend` styles
  transition: theme.transitions.create('width', {
    duration: 150,
    easing: theme.transitions.easing.easeOut
  })
}, ownerState.withLabel && _extends({
  display: 'block',
  // Fix conflict with normalize.css and sanitize.css
  padding: 0,
  height: 11,
  // sync with `lineHeight` in `legend` styles
  fontSize: '0.75em',
  visibility: 'hidden',
  maxWidth: 0.01,
  transition: theme.transitions.create('max-width', {
    duration: 50,
    easing: theme.transitions.easing.easeOut
  }),
  whiteSpace: 'nowrap',
  '& > span': {
    paddingLeft: 5,
    paddingRight: 5,
    display: 'inline-block',
    opacity: 0,
    visibility: 'visible'
  }
}, ownerState.notched && {
  maxWidth: '100%',
  transition: theme.transitions.create('max-width', {
    duration: 100,
    easing: theme.transitions.easing.easeOut,
    delay: 50
  })
})));

/**
 * @ignore - internal component.
 */
function NotchedOutline(props) {
  const {
      className,
      label,
      notched
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$D);
  const withLabel = label != null && label !== '';
  const ownerState = _extends({}, props, {
    notched,
    withLabel
  });
  return /*#__PURE__*/jsxRuntimeExports.jsx(NotchedOutlineRoot$1, _extends({
    "aria-hidden": true,
    className: className,
    ownerState: ownerState
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(NotchedOutlineLegend, {
      ownerState: ownerState,
      children: withLabel ? /*#__PURE__*/jsxRuntimeExports.jsx("span", {
        children: label
      }) :
      // notranslate needed while Google Translate will not fix zero-width space issue
      _span$1 || (_span$1 = /*#__PURE__*/jsxRuntimeExports.jsx("span", {
        className: "notranslate",
        children: "\u200B"
      }))
    })
  }));
}
NotchedOutline.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The label.
   */
  label: PropTypes.node,
  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: PropTypes.bool.isRequired,
  /**
   * @ignore
   */
  style: PropTypes.object
} ;

function getOutlinedInputUtilityClass(slot) {
  return generateUtilityClass('MuiOutlinedInput', slot);
}
const outlinedInputClasses = _extends({}, inputBaseClasses$1, generateUtilityClasses('MuiOutlinedInput', ['root', 'notchedOutline', 'input']));
var outlinedInputClasses$1 = outlinedInputClasses;

const _excluded$C = ["components", "fullWidth", "inputComponent", "label", "multiline", "notched", "slots", "type"];
const useUtilityClasses$w = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    notchedOutline: ['notchedOutline'],
    input: ['input']
  };
  const composedClasses = composeClasses(slots, getOutlinedInputUtilityClass, classes);
  return _extends({}, classes, composedClasses);
};
const OutlinedInputRoot = styled$1(InputBaseRoot, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiOutlinedInput',
  slot: 'Root',
  overridesResolver: rootOverridesResolver
})(({
  theme,
  ownerState
}) => {
  const borderColor = theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
  return _extends({
    position: 'relative',
    borderRadius: (theme.vars || theme).shape.borderRadius,
    [`&:hover .${outlinedInputClasses$1.notchedOutline}`]: {
      borderColor: (theme.vars || theme).palette.text.primary
    },
    // Reset on touch devices, it doesn't add specificity
    '@media (hover: none)': {
      [`&:hover .${outlinedInputClasses$1.notchedOutline}`]: {
        borderColor: theme.vars ? `rgba(${theme.vars.palette.common.onBackgroundChannel} / 0.23)` : borderColor
      }
    },
    [`&.${outlinedInputClasses$1.focused} .${outlinedInputClasses$1.notchedOutline}`]: {
      borderColor: (theme.vars || theme).palette[ownerState.color].main,
      borderWidth: 2
    },
    [`&.${outlinedInputClasses$1.error} .${outlinedInputClasses$1.notchedOutline}`]: {
      borderColor: (theme.vars || theme).palette.error.main
    },
    [`&.${outlinedInputClasses$1.disabled} .${outlinedInputClasses$1.notchedOutline}`]: {
      borderColor: (theme.vars || theme).palette.action.disabled
    }
  }, ownerState.startAdornment && {
    paddingLeft: 14
  }, ownerState.endAdornment && {
    paddingRight: 14
  }, ownerState.multiline && _extends({
    padding: '16.5px 14px'
  }, ownerState.size === 'small' && {
    padding: '8.5px 14px'
  }));
});
const NotchedOutlineRoot = styled$1(NotchedOutline, {
  name: 'MuiOutlinedInput',
  slot: 'NotchedOutline',
  overridesResolver: (props, styles) => styles.notchedOutline
})(({
  theme
}) => {
  const borderColor = theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
  return {
    borderColor: theme.vars ? `rgba(${theme.vars.palette.common.onBackgroundChannel} / 0.23)` : borderColor
  };
});
const OutlinedInputInput = styled$1(InputBaseComponent, {
  name: 'MuiOutlinedInput',
  slot: 'Input',
  overridesResolver: inputOverridesResolver
})(({
  theme,
  ownerState
}) => _extends({
  padding: '16.5px 14px'
}, !theme.vars && {
  '&:-webkit-autofill': {
    WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset',
    WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff',
    caretColor: theme.palette.mode === 'light' ? null : '#fff',
    borderRadius: 'inherit'
  }
}, theme.vars && {
  '&:-webkit-autofill': {
    borderRadius: 'inherit'
  },
  [theme.getColorSchemeSelector('dark')]: {
    '&:-webkit-autofill': {
      WebkitBoxShadow: '0 0 0 100px #266798 inset',
      WebkitTextFillColor: '#fff',
      caretColor: '#fff'
    }
  }
}, ownerState.size === 'small' && {
  padding: '8.5px 14px'
}, ownerState.multiline && {
  padding: 0
}, ownerState.startAdornment && {
  paddingLeft: 0
}, ownerState.endAdornment && {
  paddingRight: 0
}));
const OutlinedInput = /*#__PURE__*/reactExports$1.forwardRef(function OutlinedInput(inProps, ref) {
  var _ref, _slots$root, _ref2, _slots$input, _React$Fragment;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiOutlinedInput'
  });
  const {
      components = {},
      fullWidth = false,
      inputComponent = 'input',
      label,
      multiline = false,
      notched,
      slots = {},
      type = 'text'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$C);
  const classes = useUtilityClasses$w(props);
  const muiFormControl = useFormControl();
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['required']
  });
  const ownerState = _extends({}, props, {
    color: fcs.color || 'primary',
    disabled: fcs.disabled,
    error: fcs.error,
    focused: fcs.focused,
    formControl: muiFormControl,
    fullWidth,
    hiddenLabel: fcs.hiddenLabel,
    multiline,
    size: fcs.size,
    type
  });
  const RootSlot = (_ref = (_slots$root = slots.root) != null ? _slots$root : components.Root) != null ? _ref : OutlinedInputRoot;
  const InputSlot = (_ref2 = (_slots$input = slots.input) != null ? _slots$input : components.Input) != null ? _ref2 : OutlinedInputInput;
  return /*#__PURE__*/jsxRuntimeExports.jsx(MuiInputBase, _extends({
    slots: {
      root: RootSlot,
      input: InputSlot
    },
    renderSuffix: state => /*#__PURE__*/jsxRuntimeExports.jsx(NotchedOutlineRoot, {
      ownerState: ownerState,
      className: classes.notchedOutline,
      label: label != null && label !== '' && fcs.required ? _React$Fragment || (_React$Fragment = /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
        children: [label, "\u2009", '*']
      })) : label,
      notched: typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused)
    }),
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other, {
    classes: _extends({}, classes, {
      notchedOutline: null
    })
  }));
});
OutlinedInput.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: PropTypes.string,
  /**
   * If `true`, the `input` element is focused during the first mount.
   */
  autoFocus: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Input: PropTypes.elementType,
    Root: PropTypes.elementType
  }),
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, the component is disabled.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  disabled: PropTypes.bool,
  /**
   * End `InputAdornment` for this component.
   */
  endAdornment: PropTypes.node,
  /**
   * If `true`, the `input` will indicate an error.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the `input` will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * The id of the `input` element.
   */
  id: PropTypes.string,
  /**
   * The component used for the `input` element.
   * Either a string to use a HTML element or a component.
   * @default 'input'
   */
  inputComponent: PropTypes.elementType,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   * @default {}
   */
  inputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * The label of the `input`. It is only used for layout. The actual labelling
   * is handled by `InputLabel`.
   */
  label: PropTypes.node,
  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   * The prop defaults to the value (`'none'`) inherited from the parent FormControl component.
   */
  margin: PropTypes.oneOf(['dense', 'none']),
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Minimum number of rows to display when multiline option is set to true.
   */
  minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * If `true`, a [TextareaAutosize](/material-ui/react-textarea-autosize/) element is rendered.
   * @default false
   */
  multiline: PropTypes.bool,
  /**
   * Name attribute of the `input` element.
   */
  name: PropTypes.string,
  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: PropTypes.bool,
  /**
   * Callback fired when the value is changed.
   *
   * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * The short hint displayed in the `input` before the user enters a value.
   */
  placeholder: PropTypes.string,
  /**
   * It prevents the user from changing the value of the field
   * (not from interacting with the field).
   */
  readOnly: PropTypes.bool,
  /**
   * If `true`, the `input` element is required.
   * The prop defaults to the value (`false`) inherited from the parent FormControl component.
   */
  required: PropTypes.bool,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    input: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * Start `InputAdornment` for this component.
   */
  startAdornment: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   * @default 'text'
   */
  type: PropTypes.string,
  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: PropTypes.any
} ;
OutlinedInput.muiName = 'Input';
var OutlinedInput$1 = OutlinedInput;

const _excluded$B = ["autoWidth", "children", "classes", "className", "defaultOpen", "displayEmpty", "IconComponent", "id", "input", "inputProps", "label", "labelId", "MenuProps", "multiple", "native", "onClose", "onOpen", "open", "renderValue", "SelectDisplayProps", "variant"];
const useUtilityClasses$v = ownerState => {
  const {
    classes
  } = ownerState;
  return classes;
};
const styledRootConfig = {
  name: 'MuiSelect',
  overridesResolver: (props, styles) => styles.root,
  shouldForwardProp: prop => rootShouldForwardProp(prop) && prop !== 'variant',
  slot: 'Root'
};
const StyledInput = styled$1(Input$3, styledRootConfig)('');
const StyledOutlinedInput = styled$1(OutlinedInput$1, styledRootConfig)('');
const StyledFilledInput = styled$1(FilledInput$1, styledRootConfig)('');
const Select$2 = /*#__PURE__*/reactExports$1.forwardRef(function Select(inProps, ref) {
  const props = useThemeProps({
    name: 'MuiSelect',
    props: inProps
  });
  const {
      autoWidth = false,
      children,
      classes: classesProp = {},
      className,
      defaultOpen = false,
      displayEmpty = false,
      IconComponent = ArrowDropDownIcon,
      id,
      input,
      inputProps,
      label,
      labelId,
      MenuProps,
      multiple = false,
      native = false,
      onClose,
      onOpen,
      open,
      renderValue,
      SelectDisplayProps,
      variant: variantProp = 'outlined'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$B);
  const inputComponent = native ? NativeSelectInput$1 : SelectInput$1;
  const muiFormControl = useFormControl();
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['variant', 'error']
  });
  const variant = fcs.variant || variantProp;
  const ownerState = _extends({}, props, {
    variant,
    classes: classesProp
  });
  const classes = useUtilityClasses$v(ownerState);
  const InputComponent = input || {
    standard: /*#__PURE__*/jsxRuntimeExports.jsx(StyledInput, {
      ownerState: ownerState
    }),
    outlined: /*#__PURE__*/jsxRuntimeExports.jsx(StyledOutlinedInput, {
      label: label,
      ownerState: ownerState
    }),
    filled: /*#__PURE__*/jsxRuntimeExports.jsx(StyledFilledInput, {
      ownerState: ownerState
    })
  }[variant];
  const inputComponentRef = useForkRef(ref, InputComponent.ref);
  return /*#__PURE__*/jsxRuntimeExports.jsx(reactExports$1.Fragment, {
    children: /*#__PURE__*/reactExports$1.cloneElement(InputComponent, _extends({
      // Most of the logic is implemented in `SelectInput`.
      // The `Select` component is a simple API wrapper to expose something better to play with.
      inputComponent,
      inputProps: _extends({
        children,
        error: fcs.error,
        IconComponent,
        variant,
        type: undefined,
        // We render a select. We can ignore the type provided by the `Input`.
        multiple
      }, native ? {
        id
      } : {
        autoWidth,
        defaultOpen,
        displayEmpty,
        labelId,
        MenuProps,
        onClose,
        onOpen,
        open,
        renderValue,
        SelectDisplayProps: _extends({
          id
        }, SelectDisplayProps)
      }, inputProps, {
        classes: inputProps ? deepmerge(classes, inputProps.classes) : classes
      }, input ? input.props.inputProps : {})
    }, multiple && native && variant === 'outlined' ? {
      notched: true
    } : {}, {
      ref: inputComponentRef,
      className: clsx(InputComponent.props.className, className)
    }, !input && {
      variant
    }, other))
  });
});
Select$2.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the width of the popover will automatically be set according to the items inside the
   * menu, otherwise it will be at least the width of the select input.
   * @default false
   */
  autoWidth: PropTypes.bool,
  /**
   * The option elements to populate the select with.
   * Can be some `MenuItem` when `native` is false and `option` when `native` is true.
   *
   * ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * @default {}
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the component is initially open. Use when the component open state is not controlled (i.e. the `open` prop is not defined).
   * You can only use it when the `native` prop is `false` (default).
   * @default false
   */
  defaultOpen: PropTypes.bool,
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, a value is displayed even if no items are selected.
   *
   * In order to display a meaningful value, a function can be passed to the `renderValue` prop which
   * returns the value to be displayed when no items are selected.
   *
   * ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value.
   * The label should either be hidden or forced to a shrunk state.
   * @default false
   */
  displayEmpty: PropTypes.bool,
  /**
   * The icon that displays the arrow.
   * @default ArrowDropDownIcon
   */
  IconComponent: PropTypes.elementType,
  /**
   * The `id` of the wrapper element or the `select` element when `native`.
   */
  id: PropTypes.string,
  /**
   * An `Input` element; does not have to be a material-ui specific `Input`.
   */
  input: PropTypes.element,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   * When `native` is `true`, the attributes are applied on the `select` element.
   */
  inputProps: PropTypes.object,
  /**
   * See [OutlinedInput#label](/material-ui/api/outlined-input/#props)
   */
  label: PropTypes.node,
  /**
   * The ID of an element that acts as an additional label. The Select will
   * be labelled by the additional label and the selected value.
   */
  labelId: PropTypes.string,
  /**
   * Props applied to the [`Menu`](/material-ui/api/menu/) element.
   */
  MenuProps: PropTypes.object,
  /**
   * If `true`, `value` must be an array and the menu will support multiple selections.
   * @default false
   */
  multiple: PropTypes.bool,
  /**
   * If `true`, the component uses a native `select` element.
   * @default false
   */
  native: PropTypes.bool,
  /**
   * Callback fired when a menu item is selected.
   *
   * @param {SelectChangeEvent<T>} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (any).
   * **Warning**: This is a generic event, not a change event, unless the change event is caused by browser autofill.
   * @param {object} [child] The react element that was selected when `native` is `false` (default).
   */
  onChange: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   * Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select collapses).
   *
   * @param {object} event The event source of the callback.
   */
  onClose: PropTypes.func,
  /**
   * Callback fired when the component requests to be opened.
   * Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select expands).
   *
   * @param {object} event The event source of the callback.
   */
  onOpen: PropTypes.func,
  /**
   * If `true`, the component is shown.
   * You can only use it when the `native` prop is `false` (default).
   */
  open: PropTypes.bool,
  /**
   * Render the selected value.
   * You can only use it when the `native` prop is `false` (default).
   *
   * @param {any} value The `value` provided to the component.
   * @returns {ReactNode}
   */
  renderValue: PropTypes.func,
  /**
   * Props applied to the clickable div element.
   */
  SelectDisplayProps: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The `input` value. Providing an empty string will select no options.
   * Set to an empty string `''` if you don't want any of the available options to be selected.
   *
   * If the value is an object it must have reference equality with the option in order to be selected.
   * If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
   */
  value: PropTypes.oneOfType([PropTypes.oneOf(['']), PropTypes.any]),
  /**
   * The variant to use.
   * @default 'outlined'
   */
  variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} ;
Select$2.muiName = 'Select';
var Select$3 = Select$2;

var LastPageIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z"
}), 'LastPage');

var FirstPageIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z"
}), 'FirstPage');

var _LastPageIcon, _FirstPageIcon, _KeyboardArrowRight, _KeyboardArrowLeft, _KeyboardArrowLeft2, _KeyboardArrowRight2, _FirstPageIcon2, _LastPageIcon2;
const _excluded$A = ["backIconButtonProps", "count", "getItemAriaLabel", "nextIconButtonProps", "onPageChange", "page", "rowsPerPage", "showFirstButton", "showLastButton"];
const TablePaginationActions = /*#__PURE__*/reactExports$1.forwardRef(function TablePaginationActions(props, ref) {
  const {
      backIconButtonProps,
      count,
      getItemAriaLabel,
      nextIconButtonProps,
      onPageChange,
      page,
      rowsPerPage,
      showFirstButton,
      showLastButton
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$A);
  const theme = useTheme();
  const handleFirstPageButtonClick = event => {
    onPageChange(event, 0);
  };
  const handleBackButtonClick = event => {
    onPageChange(event, page - 1);
  };
  const handleNextButtonClick = event => {
    onPageChange(event, page + 1);
  };
  const handleLastPageButtonClick = event => {
    onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
  };
  return /*#__PURE__*/jsxRuntimeExports.jsxs("div", _extends({
    ref: ref
  }, other, {
    children: [showFirstButton && /*#__PURE__*/jsxRuntimeExports.jsx(IconButton$2, {
      onClick: handleFirstPageButtonClick,
      disabled: page === 0,
      "aria-label": getItemAriaLabel('first', page),
      title: getItemAriaLabel('first', page),
      children: theme.direction === 'rtl' ? _LastPageIcon || (_LastPageIcon = /*#__PURE__*/jsxRuntimeExports.jsx(LastPageIcon, {})) : _FirstPageIcon || (_FirstPageIcon = /*#__PURE__*/jsxRuntimeExports.jsx(FirstPageIcon, {}))
    }), /*#__PURE__*/jsxRuntimeExports.jsx(IconButton$2, _extends({
      onClick: handleBackButtonClick,
      disabled: page === 0,
      color: "inherit",
      "aria-label": getItemAriaLabel('previous', page),
      title: getItemAriaLabel('previous', page)
    }, backIconButtonProps, {
      children: theme.direction === 'rtl' ? _KeyboardArrowRight || (_KeyboardArrowRight = /*#__PURE__*/jsxRuntimeExports.jsx(KeyboardArrowRight, {})) : _KeyboardArrowLeft || (_KeyboardArrowLeft = /*#__PURE__*/jsxRuntimeExports.jsx(KeyboardArrowLeft, {}))
    })), /*#__PURE__*/jsxRuntimeExports.jsx(IconButton$2, _extends({
      onClick: handleNextButtonClick,
      disabled: count !== -1 ? page >= Math.ceil(count / rowsPerPage) - 1 : false,
      color: "inherit",
      "aria-label": getItemAriaLabel('next', page),
      title: getItemAriaLabel('next', page)
    }, nextIconButtonProps, {
      children: theme.direction === 'rtl' ? _KeyboardArrowLeft2 || (_KeyboardArrowLeft2 = /*#__PURE__*/jsxRuntimeExports.jsx(KeyboardArrowLeft, {})) : _KeyboardArrowRight2 || (_KeyboardArrowRight2 = /*#__PURE__*/jsxRuntimeExports.jsx(KeyboardArrowRight, {}))
    })), showLastButton && /*#__PURE__*/jsxRuntimeExports.jsx(IconButton$2, {
      onClick: handleLastPageButtonClick,
      disabled: page >= Math.ceil(count / rowsPerPage) - 1,
      "aria-label": getItemAriaLabel('last', page),
      title: getItemAriaLabel('last', page),
      children: theme.direction === 'rtl' ? _FirstPageIcon2 || (_FirstPageIcon2 = /*#__PURE__*/jsxRuntimeExports.jsx(FirstPageIcon, {})) : _LastPageIcon2 || (_LastPageIcon2 = /*#__PURE__*/jsxRuntimeExports.jsx(LastPageIcon, {}))
    })]
  }));
});
TablePaginationActions.propTypes = {
  /**
   * Props applied to the back arrow [`IconButton`](/material-ui/api/icon-button/) element.
   */
  backIconButtonProps: PropTypes.object,
  /**
   * The total number of rows.
   */
  count: PropTypes.number.isRequired,
  /**
   * Accepts a function which returns a string value that provides a user-friendly name for the current page.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   *
   * @param {string} type The link or button type to format ('page' | 'first' | 'last' | 'next' | 'previous'). Defaults to 'page'.
   * @param {number} page The page number to format.
   * @returns {string}
   */
  getItemAriaLabel: PropTypes.func.isRequired,
  /**
   * Props applied to the next arrow [`IconButton`](/material-ui/api/icon-button/) element.
   */
  nextIconButtonProps: PropTypes.object,
  /**
   * Callback fired when the page is changed.
   *
   * @param {object} event The event source of the callback.
   * @param {number} page The page selected.
   */
  onPageChange: PropTypes.func.isRequired,
  /**
   * The zero-based index of the current page.
   */
  page: PropTypes.number.isRequired,
  /**
   * The number of rows per page.
   */
  rowsPerPage: PropTypes.number.isRequired,
  /**
   * If `true`, show the first-page button.
   */
  showFirstButton: PropTypes.bool.isRequired,
  /**
   * If `true`, show the last-page button.
   */
  showLastButton: PropTypes.bool.isRequired
} ;
var TablePaginationActions$1 = TablePaginationActions;

function getTablePaginationUtilityClass(slot) {
  return generateUtilityClass('MuiTablePagination', slot);
}
const tablePaginationClasses = generateUtilityClasses('MuiTablePagination', ['root', 'toolbar', 'spacer', 'selectLabel', 'selectRoot', 'select', 'selectIcon', 'input', 'menuItem', 'displayedRows', 'actions']);
var tablePaginationClasses$1 = tablePaginationClasses;

var _InputBase;
const _excluded$z = ["ActionsComponent", "backIconButtonProps", "className", "colSpan", "component", "count", "getItemAriaLabel", "labelDisplayedRows", "labelRowsPerPage", "nextIconButtonProps", "onPageChange", "onRowsPerPageChange", "page", "rowsPerPage", "rowsPerPageOptions", "SelectProps", "showFirstButton", "showLastButton"];
const TablePaginationRoot = styled$1(TableCell$1, {
  name: 'MuiTablePagination',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  overflow: 'auto',
  color: (theme.vars || theme).palette.text.primary,
  fontSize: theme.typography.pxToRem(14),
  // Increase the specificity to override TableCell.
  '&:last-child': {
    padding: 0
  }
}));
const TablePaginationToolbar = styled$1(Toolbar$1, {
  name: 'MuiTablePagination',
  slot: 'Toolbar',
  overridesResolver: (props, styles) => _extends({
    [`& .${tablePaginationClasses$1.actions}`]: styles.actions
  }, styles.toolbar)
})(({
  theme
}) => ({
  minHeight: 52,
  paddingRight: 2,
  [`${theme.breakpoints.up('xs')} and (orientation: landscape)`]: {
    minHeight: 52
  },
  [theme.breakpoints.up('sm')]: {
    minHeight: 52,
    paddingRight: 2
  },
  [`& .${tablePaginationClasses$1.actions}`]: {
    flexShrink: 0,
    marginLeft: 20
  }
}));
const TablePaginationSpacer = styled$1('div', {
  name: 'MuiTablePagination',
  slot: 'Spacer',
  overridesResolver: (props, styles) => styles.spacer
})({
  flex: '1 1 100%'
});
const TablePaginationSelectLabel = styled$1('p', {
  name: 'MuiTablePagination',
  slot: 'SelectLabel',
  overridesResolver: (props, styles) => styles.selectLabel
})(({
  theme
}) => _extends({}, theme.typography.body2, {
  flexShrink: 0
}));
const TablePaginationSelect = styled$1(Select$3, {
  name: 'MuiTablePagination',
  slot: 'Select',
  overridesResolver: (props, styles) => _extends({
    [`& .${tablePaginationClasses$1.selectIcon}`]: styles.selectIcon,
    [`& .${tablePaginationClasses$1.select}`]: styles.select
  }, styles.input, styles.selectRoot)
})({
  color: 'inherit',
  fontSize: 'inherit',
  flexShrink: 0,
  marginRight: 32,
  marginLeft: 8,
  [`& .${tablePaginationClasses$1.select}`]: {
    paddingLeft: 8,
    paddingRight: 24,
    textAlign: 'right',
    textAlignLast: 'right' // Align <select> on Chrome.
  }
});

const TablePaginationMenuItem = styled$1(MenuItem$1, {
  name: 'MuiTablePagination',
  slot: 'MenuItem',
  overridesResolver: (props, styles) => styles.menuItem
})({});
const TablePaginationDisplayedRows = styled$1('p', {
  name: 'MuiTablePagination',
  slot: 'DisplayedRows',
  overridesResolver: (props, styles) => styles.displayedRows
})(({
  theme
}) => _extends({}, theme.typography.body2, {
  flexShrink: 0
}));
function defaultLabelDisplayedRows({
  from,
  to,
  count
}) {
  return `${from}–${to} of ${count !== -1 ? count : `more than ${to}`}`;
}
function defaultGetAriaLabel(type) {
  return `Go to ${type} page`;
}
const useUtilityClasses$u = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    toolbar: ['toolbar'],
    spacer: ['spacer'],
    selectLabel: ['selectLabel'],
    select: ['select'],
    input: ['input'],
    selectIcon: ['selectIcon'],
    menuItem: ['menuItem'],
    displayedRows: ['displayedRows'],
    actions: ['actions']
  };
  return composeClasses(slots, getTablePaginationUtilityClass, classes);
};

/**
 * A `TableCell` based component for placing inside `TableFooter` for pagination.
 */
const TablePagination = /*#__PURE__*/reactExports$1.forwardRef(function TablePagination(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTablePagination'
  });
  const {
      ActionsComponent = TablePaginationActions$1,
      backIconButtonProps,
      className,
      colSpan: colSpanProp,
      component = TableCell$1,
      count,
      getItemAriaLabel = defaultGetAriaLabel,
      labelDisplayedRows = defaultLabelDisplayedRows,
      labelRowsPerPage = 'Rows per page:',
      nextIconButtonProps,
      onPageChange,
      onRowsPerPageChange,
      page,
      rowsPerPage,
      rowsPerPageOptions = [10, 25, 50, 100],
      SelectProps = {},
      showFirstButton = false,
      showLastButton = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$z);
  const ownerState = props;
  const classes = useUtilityClasses$u(ownerState);
  const MenuItemComponent = SelectProps.native ? 'option' : TablePaginationMenuItem;
  let colSpan;
  if (component === TableCell$1 || component === 'td') {
    colSpan = colSpanProp || 1000; // col-span over everything
  }

  const selectId = useId(SelectProps.id);
  const labelId = useId(SelectProps.labelId);
  const getLabelDisplayedRowsTo = () => {
    if (count === -1) {
      return (page + 1) * rowsPerPage;
    }
    return rowsPerPage === -1 ? count : Math.min(count, (page + 1) * rowsPerPage);
  };
  return /*#__PURE__*/jsxRuntimeExports.jsx(TablePaginationRoot, _extends({
    colSpan: colSpan,
    ref: ref,
    as: component,
    ownerState: ownerState,
    className: clsx(classes.root, className)
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsxs(TablePaginationToolbar, {
      className: classes.toolbar,
      children: [/*#__PURE__*/jsxRuntimeExports.jsx(TablePaginationSpacer, {
        className: classes.spacer
      }), rowsPerPageOptions.length > 1 && /*#__PURE__*/jsxRuntimeExports.jsx(TablePaginationSelectLabel, {
        className: classes.selectLabel,
        id: labelId,
        children: labelRowsPerPage
      }), rowsPerPageOptions.length > 1 && /*#__PURE__*/jsxRuntimeExports.jsx(TablePaginationSelect, _extends({
        variant: "standard"
      }, !SelectProps.variant && {
        input: _InputBase || (_InputBase = /*#__PURE__*/jsxRuntimeExports.jsx(MuiInputBase, {}))
      }, {
        value: rowsPerPage,
        onChange: onRowsPerPageChange,
        id: selectId,
        labelId: labelId
      }, SelectProps, {
        classes: _extends({}, SelectProps.classes, {
          // TODO v5 remove `classes.input`
          root: clsx(classes.input, classes.selectRoot, (SelectProps.classes || {}).root),
          select: clsx(classes.select, (SelectProps.classes || {}).select),
          // TODO v5 remove `selectIcon`
          icon: clsx(classes.selectIcon, (SelectProps.classes || {}).icon)
        }),
        children: rowsPerPageOptions.map(rowsPerPageOption => /*#__PURE__*/reactExports$1.createElement(MenuItemComponent, _extends({}, !isHostComponent(MenuItemComponent) && {
          ownerState
        }, {
          className: classes.menuItem,
          key: rowsPerPageOption.label ? rowsPerPageOption.label : rowsPerPageOption,
          value: rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption
        }), rowsPerPageOption.label ? rowsPerPageOption.label : rowsPerPageOption))
      })), /*#__PURE__*/jsxRuntimeExports.jsx(TablePaginationDisplayedRows, {
        className: classes.displayedRows,
        children: labelDisplayedRows({
          from: count === 0 ? 0 : page * rowsPerPage + 1,
          to: getLabelDisplayedRowsTo(),
          count: count === -1 ? -1 : count,
          page
        })
      }), /*#__PURE__*/jsxRuntimeExports.jsx(ActionsComponent, {
        className: classes.actions,
        backIconButtonProps: backIconButtonProps,
        count: count,
        nextIconButtonProps: nextIconButtonProps,
        onPageChange: onPageChange,
        page: page,
        rowsPerPage: rowsPerPage,
        showFirstButton: showFirstButton,
        showLastButton: showLastButton,
        getItemAriaLabel: getItemAriaLabel
      })]
    })
  }));
});
TablePagination.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The component used for displaying the actions.
   * Either a string to use a HTML element or a component.
   * @default TablePaginationActions
   */
  ActionsComponent: PropTypes.elementType,
  /**
   * Props applied to the back arrow [`IconButton`](/material-ui/api/icon-button/) component.
   */
  backIconButtonProps: PropTypes.object,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * @ignore
   */
  colSpan: PropTypes.number,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The total number of rows.
   *
   * To enable server side pagination for an unknown number of items, provide -1.
   */
  count: integerPropType.isRequired,
  /**
   * Accepts a function which returns a string value that provides a user-friendly name for the current page.
   * This is important for screen reader users.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @param {string} type The link or button type to format ('first' | 'last' | 'next' | 'previous').
   * @returns {string}
   * @default function defaultGetAriaLabel(type) {
   *   return `Go to ${type} page`;
   * }
   */
  getItemAriaLabel: PropTypes.func,
  /**
   * Customize the displayed rows label. Invoked with a `{ from, to, count, page }`
   * object.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default function defaultLabelDisplayedRows({ from, to, count }) {
   *   return `${from}–${to} of ${count !== -1 ? count : `more than ${to}`}`;
   * }
   */
  labelDisplayedRows: PropTypes.func,
  /**
   * Customize the rows per page label.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Rows per page:'
   */
  labelRowsPerPage: PropTypes.node,
  /**
   * Props applied to the next arrow [`IconButton`](/material-ui/api/icon-button/) element.
   */
  nextIconButtonProps: PropTypes.object,
  /**
   * Callback fired when the page is changed.
   *
   * @param {React.MouseEvent<HTMLButtonElement> | null} event The event source of the callback.
   * @param {number} page The page selected.
   */
  onPageChange: PropTypes.func.isRequired,
  /**
   * Callback fired when the number of rows per page is changed.
   *
   * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
   */
  onRowsPerPageChange: PropTypes.func,
  /**
   * The zero-based index of the current page.
   */
  page: chainPropTypes(integerPropType.isRequired, props => {
    const {
      count,
      page,
      rowsPerPage
    } = props;
    if (count === -1) {
      return null;
    }
    const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1);
    if (page < 0 || page > newLastPage) {
      return new Error('MUI: The page prop of a TablePagination is out of range ' + `(0 to ${newLastPage}, but page is ${page}).`);
    }
    return null;
  }),
  /**
   * The number of rows per page.
   *
   * Set -1 to display all the rows.
   */
  rowsPerPage: integerPropType.isRequired,
  /**
   * Customizes the options of the rows per page select field. If less than two options are
   * available, no select field will be displayed.
   * Use -1 for the value with a custom label to show all the rows.
   * @default [10, 25, 50, 100]
   */
  rowsPerPageOptions: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    label: PropTypes.string.isRequired,
    value: PropTypes.number.isRequired
  })]).isRequired),
  /**
   * Props applied to the rows per page [`Select`](/material-ui/api/select/) element.
   * @default {}
   */
  SelectProps: PropTypes.object,
  /**
   * If `true`, show the first-page button.
   * @default false
   */
  showFirstButton: PropTypes.bool,
  /**
   * If `true`, show the last-page button.
   * @default false
   */
  showLastButton: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var TablePagination$1 = TablePagination;

function FormRoot({
  children
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1,
      display: "flex",
      justifyContent: "center"
    }
  }, /*#__PURE__*/React.createElement(Form$2, {
    style: {
      width: "100%",
      maxWidth: "70em",
      padding: "1em",
      boxSizing: "border-box"
    }
  }, children));
}
FormRoot.propTypes = {
  children: PropTypes.node
};

function getFormHelperTextUtilityClasses(slot) {
  return generateUtilityClass('MuiFormHelperText', slot);
}
const formHelperTextClasses = generateUtilityClasses('MuiFormHelperText', ['root', 'error', 'disabled', 'sizeSmall', 'sizeMedium', 'contained', 'focused', 'filled', 'required']);
var formHelperTextClasses$1 = formHelperTextClasses;

var _span;
const _excluded$y = ["children", "className", "component", "disabled", "error", "filled", "focused", "margin", "required", "variant"];
const useUtilityClasses$t = ownerState => {
  const {
    classes,
    contained,
    size,
    disabled,
    error,
    filled,
    focused,
    required
  } = ownerState;
  const slots = {
    root: ['root', disabled && 'disabled', error && 'error', size && `size${capitalize(size)}`, contained && 'contained', focused && 'focused', filled && 'filled', required && 'required']
  };
  return composeClasses(slots, getFormHelperTextUtilityClasses, classes);
};
const FormHelperTextRoot = styled$1('p', {
  name: 'MuiFormHelperText',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.size && styles[`size${capitalize(ownerState.size)}`], ownerState.contained && styles.contained, ownerState.filled && styles.filled];
  }
})(({
  theme,
  ownerState
}) => _extends({
  color: (theme.vars || theme).palette.text.secondary
}, theme.typography.caption, {
  textAlign: 'left',
  marginTop: 3,
  marginRight: 0,
  marginBottom: 0,
  marginLeft: 0,
  [`&.${formHelperTextClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.text.disabled
  },
  [`&.${formHelperTextClasses$1.error}`]: {
    color: (theme.vars || theme).palette.error.main
  }
}, ownerState.size === 'small' && {
  marginTop: 4
}, ownerState.contained && {
  marginLeft: 14,
  marginRight: 14
}));
const FormHelperText = /*#__PURE__*/reactExports$1.forwardRef(function FormHelperText(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFormHelperText'
  });
  const {
      children,
      className,
      component = 'p'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$y);
  const muiFormControl = useFormControl();
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['variant', 'size', 'disabled', 'error', 'filled', 'focused', 'required']
  });
  const ownerState = _extends({}, props, {
    component,
    contained: fcs.variant === 'filled' || fcs.variant === 'outlined',
    variant: fcs.variant,
    size: fcs.size,
    disabled: fcs.disabled,
    error: fcs.error,
    filled: fcs.filled,
    focused: fcs.focused,
    required: fcs.required
  });
  const classes = useUtilityClasses$t(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(FormHelperTextRoot, _extends({
    as: component,
    ownerState: ownerState,
    className: clsx(classes.root, className),
    ref: ref
  }, other, {
    children: children === ' ' ?
    // notranslate needed while Google Translate will not fix zero-width space issue
    _span || (_span = /*#__PURE__*/jsxRuntimeExports.jsx("span", {
      className: "notranslate",
      children: "\u200B"
    })) : children
  }));
});
FormHelperText.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   *
   * If `' '` is provided, the component reserves one line height for displaying a future message.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the helper text should be displayed in a disabled state.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, helper text should be displayed in an error state.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the helper text should use filled classes key.
   */
  filled: PropTypes.bool,
  /**
   * If `true`, the helper text should use focused classes key.
   */
  focused: PropTypes.bool,
  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   */
  margin: PropTypes.oneOf(['dense']),
  /**
   * If `true`, the helper text should use required classes key.
   */
  required: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['filled', 'outlined', 'standard']), PropTypes.string])
} ;
var FormHelperText$1 = FormHelperText;

function FormError(props) {
  const [, {
    error
  }] = useField("__other__");
  if (!error) {
    return null;
  }
  return /*#__PURE__*/React.createElement(FormHelperText$1, {
    error: true,
    ...props
  }, error);
}

function SubmitButton(props) {
  const {
    Button
  } = useComponents();
  return /*#__PURE__*/React.createElement(Button, {
    color: "primary",
    variant: "contained",
    type: "submit",
    ...props
  });
}

function IconSubmitButton(props) {
  const {
    IconButton
  } = useComponents();
  return /*#__PURE__*/React.createElement(IconButton, {
    type: "submit",
    ...props
  });
}

function DeleteForm({
  action
}) {
  const {
      Form,
      SubmitButton,
      View,
      HorizontalView
    } = useComponents(),
    {
      CONFIRM_DELETE
    } = useMessages();
  function confirmSubmit() {
    return window.confirm(CONFIRM_DELETE);
  }
  return /*#__PURE__*/React.createElement(Form, {
    action: action,
    method: "DELETE",
    backgroundSync: false,
    onSubmit: confirmSubmit
  }, /*#__PURE__*/React.createElement(HorizontalView, null, /*#__PURE__*/React.createElement(View, null), /*#__PURE__*/React.createElement(SubmitButton, {
    icon: "delete",
    variant: "text",
    color: "secondary"
  }, "Delete")));
}
DeleteForm.propTypes = {
  action: PropTypes.string
};

function getCircularProgressUtilityClass(slot) {
  return generateUtilityClass('MuiCircularProgress', slot);
}
generateUtilityClasses('MuiCircularProgress', ['root', 'determinate', 'indeterminate', 'colorPrimary', 'colorSecondary', 'svg', 'circle', 'circleDeterminate', 'circleIndeterminate', 'circleDisableShrink']);

const _excluded$x = ["className", "color", "disableShrink", "size", "style", "thickness", "value", "variant"];
let _$1 = t => t,
  _t$1,
  _t2$1,
  _t3$1,
  _t4$1;
const SIZE = 44;
const circularRotateKeyframe = keyframes(_t$1 || (_t$1 = _$1`
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
`));
const circularDashKeyframe = keyframes(_t2$1 || (_t2$1 = _$1`
  0% {
    stroke-dasharray: 1px, 200px;
    stroke-dashoffset: 0;
  }

  50% {
    stroke-dasharray: 100px, 200px;
    stroke-dashoffset: -15px;
  }

  100% {
    stroke-dasharray: 100px, 200px;
    stroke-dashoffset: -125px;
  }
`));
const useUtilityClasses$s = ownerState => {
  const {
    classes,
    variant,
    color,
    disableShrink
  } = ownerState;
  const slots = {
    root: ['root', variant, `color${capitalize(color)}`],
    svg: ['svg'],
    circle: ['circle', `circle${capitalize(variant)}`, disableShrink && 'circleDisableShrink']
  };
  return composeClasses(slots, getCircularProgressUtilityClass, classes);
};
const CircularProgressRoot = styled$1('span', {
  name: 'MuiCircularProgress',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant], styles[`color${capitalize(ownerState.color)}`]];
  }
})(({
  ownerState,
  theme
}) => _extends({
  display: 'inline-block'
}, ownerState.variant === 'determinate' && {
  transition: theme.transitions.create('transform')
}, ownerState.color !== 'inherit' && {
  color: (theme.vars || theme).palette[ownerState.color].main
}), ({
  ownerState
}) => ownerState.variant === 'indeterminate' && css(_t3$1 || (_t3$1 = _$1`
      animation: ${0} 1.4s linear infinite;
    `), circularRotateKeyframe));
const CircularProgressSVG = styled$1('svg', {
  name: 'MuiCircularProgress',
  slot: 'Svg',
  overridesResolver: (props, styles) => styles.svg
})({
  display: 'block' // Keeps the progress centered
});

const CircularProgressCircle = styled$1('circle', {
  name: 'MuiCircularProgress',
  slot: 'Circle',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.circle, styles[`circle${capitalize(ownerState.variant)}`], ownerState.disableShrink && styles.circleDisableShrink];
  }
})(({
  ownerState,
  theme
}) => _extends({
  stroke: 'currentColor'
}, ownerState.variant === 'determinate' && {
  transition: theme.transitions.create('stroke-dashoffset')
}, ownerState.variant === 'indeterminate' && {
  // Some default value that looks fine waiting for the animation to kicks in.
  strokeDasharray: '80px, 200px',
  strokeDashoffset: 0 // Add the unit to fix a Edge 16 and below bug.
}), ({
  ownerState
}) => ownerState.variant === 'indeterminate' && !ownerState.disableShrink && css(_t4$1 || (_t4$1 = _$1`
      animation: ${0} 1.4s ease-in-out infinite;
    `), circularDashKeyframe));

/**
 * ## ARIA
 *
 * If the progress bar is describing the loading progress of a particular region of a page,
 * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`
 * attribute to `true` on that region until it has finished loading.
 */
const CircularProgress = /*#__PURE__*/reactExports$1.forwardRef(function CircularProgress(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiCircularProgress'
  });
  const {
      className,
      color = 'primary',
      disableShrink = false,
      size = 40,
      style,
      thickness = 3.6,
      value = 0,
      variant = 'indeterminate'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$x);
  const ownerState = _extends({}, props, {
    color,
    disableShrink,
    size,
    thickness,
    value,
    variant
  });
  const classes = useUtilityClasses$s(ownerState);
  const circleStyle = {};
  const rootStyle = {};
  const rootProps = {};
  if (variant === 'determinate') {
    const circumference = 2 * Math.PI * ((SIZE - thickness) / 2);
    circleStyle.strokeDasharray = circumference.toFixed(3);
    rootProps['aria-valuenow'] = Math.round(value);
    circleStyle.strokeDashoffset = `${((100 - value) / 100 * circumference).toFixed(3)}px`;
    rootStyle.transform = 'rotate(-90deg)';
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgressRoot, _extends({
    className: clsx(classes.root, className),
    style: _extends({
      width: size,
      height: size
    }, rootStyle, style),
    ownerState: ownerState,
    ref: ref,
    role: "progressbar"
  }, rootProps, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgressSVG, {
      className: classes.svg,
      ownerState: ownerState,
      viewBox: `${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`,
      children: /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgressCircle, {
        className: classes.circle,
        style: circleStyle,
        ownerState: ownerState,
        cx: SIZE,
        cy: SIZE,
        r: (SIZE - thickness) / 2,
        fill: "none",
        strokeWidth: thickness
      })
    })
  }));
});
CircularProgress.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * If `true`, the shrink animation is disabled.
   * This only works if variant is `indeterminate`.
   * @default false
   */
  disableShrink: chainPropTypes(PropTypes.bool, props => {
    if (props.disableShrink && props.variant && props.variant !== 'indeterminate') {
      return new Error('MUI: You have provided the `disableShrink` prop ' + 'with a variant other than `indeterminate`. This will have no effect.');
    }
    return null;
  }),
  /**
   * The size of the component.
   * If using a number, the pixel unit is assumed.
   * If using a string, you need to provide the CSS unit, e.g '3rem'.
   * @default 40
   */
  size: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The thickness of the circle.
   * @default 3.6
   */
  thickness: PropTypes.number,
  /**
   * The value of the progress indicator for the determinate variant.
   * Value between 0 and 100.
   * @default 0
   */
  value: PropTypes.number,
  /**
   * The variant to use.
   * Use indeterminate when there is no progress value.
   * @default 'indeterminate'
   */
  variant: PropTypes.oneOf(['determinate', 'indeterminate'])
} ;
var CircularProgress$1 = CircularProgress;

function Spinner() {
  const {
    active
  } = useSpinner();

  // FIXME: text, type
  return /*#__PURE__*/React.createElement(Modal$1, {
    open: active
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      height: "100vh"
    }
  }, /*#__PURE__*/React.createElement(CircularProgress$1, null)));
}

function Popup$2({
  anchor = "bottom",
  children,
  open,
  onClose,
  ...rest
}) {
  return /*#__PURE__*/React.createElement(Drawer$1, {
    anchor: anchor,
    open: open,
    onClose: onClose,
    ...rest
  }, children);
}
Popup$2.propTypes = {
  anchor: PropTypes.string,
  children: PropTypes.node,
  open: PropTypes.bool,
  onClose: PropTypes.func
};

function SidePanel({
  anchor: anchorSpec = "top-left",
  children,
  compactChildren,
  onChange
}) {
  const mobile = useMediaQuery(theme => theme.breakpoints.down("md")),
    anchor = anchorSpec.endsWith("right") ? "right" : "left",
    vAnchor = anchorSpec.startsWith("bottom") ? "bottom" : "top",
    [open, setOpen] = reactExports$1.useState(!mobile),
    {
      IconButton
    } = useComponents(),
    drawerStyle = {},
    iconStyle = {};
  if (mobile && !open) {
    drawerStyle.position = "absolute";
    if (vAnchor === "bottom") {
      drawerStyle.bottom = 0;
    } else {
      drawerStyle.top = 0;
    }
    if (anchor === "right") {
      drawerStyle.right = 0;
    } else {
      drawerStyle.left = 0;
    }
  }
  if (anchor === "right") {
    iconStyle.transform = "rotate(180deg)";
  }
  reactExports$1.useEffect(() => {
    if (onChange) {
      onChange(open);
    }
  }, [open, onChange]);
  return /*#__PURE__*/React.createElement(Drawer$1, {
    variant: "permanent",
    style: drawerStyle,
    anchor: anchor,
    PaperProps: {
      style: {
        width: open ? 280 : 50,
        borderBottom: mobile && !open && "1px solid rgba(0, 0, 0, 0.12)",
        position: "relative",
        zIndex: 300
      }
    }
  }, open ? /*#__PURE__*/React.createElement("div", {
    style: {
      display: "flex",
      position: "sticky",
      top: 0,
      zIndex: 100
    }
  }, anchor === "left" && /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1
    }
  }), /*#__PURE__*/React.createElement("div", {
    style: {
      backgroundColor: "white"
    }
  }, /*#__PURE__*/React.createElement(IconButton, {
    icon: "panel-close",
    style: iconStyle,
    onClick: () => setOpen(false)
  })), anchor === "right" && /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1
    }
  })) : /*#__PURE__*/React.createElement(IconButton, {
    icon: "panel-open",
    style: iconStyle,
    onClick: () => setOpen(true)
  }), open ? children : compactChildren);
}
SidePanel.propTypes = {
  children: PropTypes.node,
  compactChildren: PropTypes.node,
  onChange: PropTypes.func,
  anchor: PropTypes.string
};

var MoreHorizIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
}), 'MoreHoriz');

const _excluded$w = ["slots", "slotProps"];
const BreadcrumbCollapsedButton = styled$1(ButtonBase$1)(({
  theme
}) => _extends({
  display: 'flex',
  marginLeft: `calc(${theme.spacing(1)} * 0.5)`,
  marginRight: `calc(${theme.spacing(1)} * 0.5)`
}, theme.palette.mode === 'light' ? {
  backgroundColor: theme.palette.grey[100],
  color: theme.palette.grey[700]
} : {
  backgroundColor: theme.palette.grey[700],
  color: theme.palette.grey[100]
}, {
  borderRadius: 2,
  '&:hover, &:focus': _extends({}, theme.palette.mode === 'light' ? {
    backgroundColor: theme.palette.grey[200]
  } : {
    backgroundColor: theme.palette.grey[600]
  }),
  '&:active': _extends({
    boxShadow: theme.shadows[0]
  }, theme.palette.mode === 'light' ? {
    backgroundColor: emphasize(theme.palette.grey[200], 0.12)
  } : {
    backgroundColor: emphasize(theme.palette.grey[600], 0.12)
  })
}));
const BreadcrumbCollapsedIcon = styled$1(MoreHorizIcon)({
  width: 24,
  height: 16
});

/**
 * @ignore - internal component.
 */
function BreadcrumbCollapsed(props) {
  const {
      slots = {},
      slotProps = {}
    } = props,
    otherProps = _objectWithoutPropertiesLoose$2(props, _excluded$w);
  const ownerState = props;
  return /*#__PURE__*/jsxRuntimeExports.jsx("li", {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(BreadcrumbCollapsedButton, _extends({
      focusRipple: true
    }, otherProps, {
      ownerState: ownerState,
      children: /*#__PURE__*/jsxRuntimeExports.jsx(BreadcrumbCollapsedIcon, _extends({
        as: slots.CollapsedIcon,
        ownerState: ownerState
      }, slotProps.collapsedIcon))
    }))
  });
}
BreadcrumbCollapsed.propTypes = {
  /**
   * The props used for the CollapsedIcon slot.
   * @default {}
   */
  slotProps: PropTypes.shape({
    collapsedIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the BreadcumbCollapsed.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    CollapsedIcon: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.object
} ;

function getBreadcrumbsUtilityClass(slot) {
  return generateUtilityClass('MuiBreadcrumbs', slot);
}
const breadcrumbsClasses = generateUtilityClasses('MuiBreadcrumbs', ['root', 'ol', 'li', 'separator']);
var breadcrumbsClasses$1 = breadcrumbsClasses;

const _excluded$v = ["children", "className", "component", "slots", "slotProps", "expandText", "itemsAfterCollapse", "itemsBeforeCollapse", "maxItems", "separator"];
const useUtilityClasses$r = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    li: ['li'],
    ol: ['ol'],
    separator: ['separator']
  };
  return composeClasses(slots, getBreadcrumbsUtilityClass, classes);
};
const BreadcrumbsRoot = styled$1(Typography$1, {
  name: 'MuiBreadcrumbs',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    return [{
      [`& .${breadcrumbsClasses$1.li}`]: styles.li
    }, styles.root];
  }
})({});
const BreadcrumbsOl = styled$1('ol', {
  name: 'MuiBreadcrumbs',
  slot: 'Ol',
  overridesResolver: (props, styles) => styles.ol
})({
  display: 'flex',
  flexWrap: 'wrap',
  alignItems: 'center',
  padding: 0,
  margin: 0,
  listStyle: 'none'
});
const BreadcrumbsSeparator = styled$1('li', {
  name: 'MuiBreadcrumbs',
  slot: 'Separator',
  overridesResolver: (props, styles) => styles.separator
})({
  display: 'flex',
  userSelect: 'none',
  marginLeft: 8,
  marginRight: 8
});
function insertSeparators(items, className, separator, ownerState) {
  return items.reduce((acc, current, index) => {
    if (index < items.length - 1) {
      acc = acc.concat(current, /*#__PURE__*/jsxRuntimeExports.jsx(BreadcrumbsSeparator, {
        "aria-hidden": true,
        className: className,
        ownerState: ownerState,
        children: separator
      }, `separator-${index}`));
    } else {
      acc.push(current);
    }
    return acc;
  }, []);
}
const Breadcrumbs$1 = /*#__PURE__*/reactExports$1.forwardRef(function Breadcrumbs(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiBreadcrumbs'
  });
  const {
      children,
      className,
      component = 'nav',
      slots = {},
      slotProps = {},
      expandText = 'Show path',
      itemsAfterCollapse = 1,
      itemsBeforeCollapse = 1,
      maxItems = 8,
      separator = '/'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$v);
  const [expanded, setExpanded] = reactExports$1.useState(false);
  const ownerState = _extends({}, props, {
    component,
    expanded,
    expandText,
    itemsAfterCollapse,
    itemsBeforeCollapse,
    maxItems,
    separator
  });
  const classes = useUtilityClasses$r(ownerState);
  const collapsedIconSlotProps = useSlotProps({
    elementType: slots.CollapsedIcon,
    externalSlotProps: slotProps.collapsedIcon,
    ownerState
  });
  const listRef = reactExports$1.useRef(null);
  const renderItemsBeforeAndAfter = allItems => {
    const handleClickExpand = () => {
      setExpanded(true);

      // The clicked element received the focus but gets removed from the DOM.
      // Let's keep the focus in the component after expanding.
      // Moving it to the <ol> or <nav> does not cause any announcement in NVDA.
      // By moving it to some link/button at least we have some announcement.
      const focusable = listRef.current.querySelector('a[href],button,[tabindex]');
      if (focusable) {
        focusable.focus();
      }
    };

    // This defends against someone passing weird input, to ensure that if all
    // items would be shown anyway, we just show all items without the EllipsisItem
    if (itemsBeforeCollapse + itemsAfterCollapse >= allItems.length) {
      {
        console.error(['MUI: You have provided an invalid combination of props to the Breadcrumbs.', `itemsAfterCollapse={${itemsAfterCollapse}} + itemsBeforeCollapse={${itemsBeforeCollapse}} >= maxItems={${maxItems}}`].join('\n'));
      }
      return allItems;
    }
    return [...allItems.slice(0, itemsBeforeCollapse), /*#__PURE__*/jsxRuntimeExports.jsx(BreadcrumbCollapsed, {
      "aria-label": expandText,
      slots: {
        CollapsedIcon: slots.CollapsedIcon
      },
      slotProps: {
        collapsedIcon: collapsedIconSlotProps
      },
      onClick: handleClickExpand
    }, "ellipsis"), ...allItems.slice(allItems.length - itemsAfterCollapse, allItems.length)];
  };
  const allItems = reactExports$1.Children.toArray(children).filter(child => {
    {
      if (reactIsExports$1.isFragment(child)) {
        console.error(["MUI: The Breadcrumbs component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
      }
    }
    return /*#__PURE__*/reactExports$1.isValidElement(child);
  }).map((child, index) => /*#__PURE__*/jsxRuntimeExports.jsx("li", {
    className: classes.li,
    children: child
  }, `child-${index}`));
  return /*#__PURE__*/jsxRuntimeExports.jsx(BreadcrumbsRoot, _extends({
    ref: ref,
    component: component,
    color: "text.secondary",
    className: clsx(classes.root, className),
    ownerState: ownerState
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(BreadcrumbsOl, {
      className: classes.ol,
      ref: listRef,
      ownerState: ownerState,
      children: insertSeparators(expanded || maxItems && allItems.length <= maxItems ? allItems : renderItemsBeforeAndAfter(allItems), classes.separator, separator, ownerState)
    })
  }));
});
Breadcrumbs$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Override the default label for the expand button.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Show path'
   */
  expandText: PropTypes.string,
  /**
   * If max items is exceeded, the number of items to show after the ellipsis.
   * @default 1
   */
  itemsAfterCollapse: integerPropType,
  /**
   * If max items is exceeded, the number of items to show before the ellipsis.
   * @default 1
   */
  itemsBeforeCollapse: integerPropType,
  /**
   * Specifies the maximum number of breadcrumbs to display. When there are more
   * than the maximum number, only the first `itemsBeforeCollapse` and last `itemsAfterCollapse`
   * will be shown, with an ellipsis in between.
   * @default 8
   */
  maxItems: integerPropType,
  /**
   * Custom separator node.
   * @default '/'
   */
  separator: PropTypes.node,
  /**
   * The props used for each slot inside the Breadcumb.
   * @default {}
   */
  slotProps: PropTypes.shape({
    collapsedIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the Breadcumb.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    CollapsedIcon: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var Breadcrumbs$2 = Breadcrumbs$1;

function Breadcrumbs({
  links
}) {
  const reverse = useReverse(),
    {
      ButtonLink,
      HomeLink
    } = useComponents(),
    Separator = useIcon("breadcrumb-separator") || (() => ">");
  if (!links) {
    links = [{
      url: reverse("index"),
      label: "Home",
      active: true
    }];
  }

  // FIXME: NavLink should already be able to detect current page
  links[links.length - 1].active = true;
  return /*#__PURE__*/React.createElement(Paper$1, {
    elevation: 2,
    square: true,
    sx: {
      py: 1,
      zIndex: 500,
      borderBottomWidth: 1,
      borderBottomStyle: "solid",
      borderBottomColor: "divider"
    }
  }, /*#__PURE__*/React.createElement(Breadcrumbs$2, {
    separator: /*#__PURE__*/React.createElement(Separator, {
      fontSize: "small"
    })
  }, /*#__PURE__*/React.createElement(HomeLink, {
    to: links[0].url,
    label: links[0].label,
    active: links[0].active
  }), links.slice(1).map(({
    url,
    label,
    active
  }, i) => /*#__PURE__*/React.createElement(ButtonLink, {
    key: i,
    to: url,
    color: active ? "inherit" : "primary"
  }, label))));
}
Breadcrumbs.propTypes = {
  links: PropTypes.arrayOf(PropTypes.object)
};

function Pagination() {
  const reverse = useReverse(),
    nav = useNav(),
    {
      multiple,
      page: pageNum,
      count,
      per_page
    } = useRenderContext(),
    {
      name: routeName,
      params
    } = useRouteInfo();
  if (!(multiple && count && per_page)) {
    return null;
  }
  const updateParams = newParams => {
    nav(reverse(routeName, {}, {
      ...params,
      ...newParams
    }));
  };
  const handleChangePage = (evt, page) => updateParams({
    page: page + 1
  });
  const handleChangeRowsPerPage = evt => updateParams({
    limit: evt.target.value
  });
  return /*#__PURE__*/React.createElement(Paper$1, null, /*#__PURE__*/React.createElement(TablePagination$1, {
    component: "div",
    count: count,
    page: pageNum - 1,
    rowsPerPage: per_page,
    onPageChange: handleChangePage,
    onRowsPerPageChange: handleChangeRowsPerPage
  }));
}

var components = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Accordion: Accordion,
  BottomNavigation: BottomNavigation$1,
  BottomNavigationAction: BottomNavigationAction,
  Breadcrumbs: Breadcrumbs,
  Button: Button,
  ButtonLink: ButtonLink,
  CancelButton: ButtonLink,
  CheckboxButton: Checkbox$1,
  Chip: Chip,
  Container: Container,
  DeleteForm: DeleteForm,
  Divider: Divider$1,
  ExpandableListItem: ExpandableListItem,
  ExpansionPanel: Accordion,
  Fab: Fab,
  Footer: Footer,
  FooterContent: FooterContent,
  FormError: FormError,
  FormRoot: FormRoot,
  FormatJson: FormatJson,
  Header: Header,
  HomeLink: HomeLink,
  HorizontalView: HorizontalView,
  IconButton: IconButton,
  IconSubmitButton: IconSubmitButton,
  Link: Link,
  List: List,
  ListItem: ListItem,
  ListItemLink: ListItemLink,
  ListSubheader: ListSubheader$1,
  Main: Main,
  NavMenuFixed: NavMenuFixed,
  NavMenuPopup: NavMenuPopup,
  Pagination: Pagination,
  Popup: Popup$2,
  RadioButton: Radio$2,
  ScrollView: ScrollView,
  SidePanel: SidePanel,
  Spinner: Spinner,
  SubmitButton: SubmitButton,
  Switch: Switch$1,
  TabGroup: TabGroup,
  TabItem: TabItem,
  Table: Table$1,
  TableBody: TableBody$1,
  TableCell: TableCell$1,
  TableContainer: TableContainer$1,
  TableHead: TableHead$1,
  TablePagination: TablePagination$1,
  TableRow: TableRow$1,
  TableTitle: TableCell$1,
  Text: Fragment,
  Typography: Typography$1,
  View: View
});

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

var __assign = function () {
  __assign = Object.assign || function __assign(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
function __rest(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 __awaiter$1(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator$1(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
    };
  }
}

const _excluded$u = ["anchorEl", "component", "components", "componentsProps", "container", "disablePortal", "keepMounted", "modifiers", "open", "placement", "popperOptions", "popperRef", "transition", "slots", "slotProps"];
const PopperRoot = styled$1(BasePopper, {
  name: 'MuiPopper',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({});

/**
 *
 * Demos:
 *
 * - [Autocomplete](https://mui.com/material-ui/react-autocomplete/)
 * - [Menu](https://mui.com/material-ui/react-menu/)
 * - [Popper](https://mui.com/material-ui/react-popper/)
 *
 * API:
 *
 * - [Popper API](https://mui.com/material-ui/api/popper/)
 */
const Popper = /*#__PURE__*/reactExports$1.forwardRef(function Popper(inProps, ref) {
  var _slots$root;
  const theme = useTheme$2();
  const props = useThemeProps({
    props: inProps,
    name: 'MuiPopper'
  });
  const {
      anchorEl,
      component,
      components,
      componentsProps,
      container,
      disablePortal,
      keepMounted,
      modifiers,
      open,
      placement,
      popperOptions,
      popperRef,
      transition,
      slots,
      slotProps
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$u);
  const RootComponent = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : components == null ? void 0 : components.Root;
  const otherProps = _extends({
    anchorEl,
    container,
    disablePortal,
    keepMounted,
    modifiers,
    open,
    placement,
    popperOptions,
    popperRef,
    transition
  }, other);
  return /*#__PURE__*/jsxRuntimeExports.jsx(PopperRoot, _extends({
    as: component,
    direction: theme == null ? void 0 : theme.direction,
    slots: {
      root: RootComponent
    },
    slotProps: slotProps != null ? slotProps : componentsProps
  }, otherProps, {
    ref: ref
  }));
});
Popper.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),
   * or a function that returns either.
   * It's used to set the position of the popper.
   * The return value will passed as the reference object of the Popper instance.
   */
  anchorEl: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]),
  /**
   * Popper render function or node.
   */
  children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.node, PropTypes.func]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The components used for each slot inside the Popper.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  components: PropTypes.shape({
    Root: PropTypes.elementType
  }),
  /**
   * The props used for each slot inside the Popper.
   * @default {}
   */
  componentsProps: PropTypes.shape({
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: PropTypes.bool,
  /**
   * Always keep the children in the DOM.
   * This prop can be useful in SEO situation or
   * when you want to maximize the responsiveness of the Popper.
   * @default false
   */
  keepMounted: PropTypes.bool,
  /**
   * Popper.js is based on a "plugin-like" architecture,
   * most of its features are fully encapsulated "modifiers".
   *
   * A modifier is a function that is called each time Popper.js needs to
   * compute the position of the popper.
   * For this reason, modifiers should be very performant to avoid bottlenecks.
   * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).
   */
  modifiers: PropTypes.arrayOf(PropTypes.shape({
    data: PropTypes.object,
    effect: PropTypes.func,
    enabled: PropTypes.bool,
    fn: PropTypes.func,
    name: PropTypes.any,
    options: PropTypes.object,
    phase: PropTypes.oneOf(['afterMain', 'afterRead', 'afterWrite', 'beforeMain', 'beforeRead', 'beforeWrite', 'main', 'read', 'write']),
    requires: PropTypes.arrayOf(PropTypes.string),
    requiresIfExists: PropTypes.arrayOf(PropTypes.string)
  })),
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * Popper placement.
   * @default 'bottom'
   */
  placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
  /**
   * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.
   * @default {}
   */
  popperOptions: PropTypes.shape({
    modifiers: PropTypes.array,
    onFirstUpdate: PropTypes.func,
    placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
    strategy: PropTypes.oneOf(['absolute', 'fixed'])
  }),
  /**
   * A ref that points to the used popper instance.
   */
  popperRef: refType$1,
  /**
   * The props used for each slot inside the Popper.
   * @default {}
   */
  slotProps: PropTypes.shape({
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the Popper.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    root: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Help supporting a react-transition-group/Transition component.
   * @default false
   */
  transition: PropTypes.bool
} ;
var Popper$1 = Popper;

var CloseIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), 'Close');

function getAutocompleteUtilityClass(slot) {
  return generateUtilityClass('MuiAutocomplete', slot);
}
const autocompleteClasses = generateUtilityClasses('MuiAutocomplete', ['root', 'expanded', 'fullWidth', 'focused', 'focusVisible', 'tag', 'tagSizeSmall', 'tagSizeMedium', 'hasPopupIcon', 'hasClearIcon', 'inputRoot', 'input', 'inputFocused', 'endAdornment', 'clearIndicator', 'popupIndicator', 'popupIndicatorOpen', 'popper', 'popperDisablePortal', 'paper', 'listbox', 'loading', 'noOptions', 'option', 'groupLabel', 'groupUl']);
var autocompleteClasses$1 = autocompleteClasses;

var _ClearIcon, _ArrowDropDownIcon;
const _excluded$t = ["autoComplete", "autoHighlight", "autoSelect", "blurOnSelect", "ChipProps", "className", "clearIcon", "clearOnBlur", "clearOnEscape", "clearText", "closeText", "componentsProps", "defaultValue", "disableClearable", "disableCloseOnSelect", "disabled", "disabledItemsFocusable", "disableListWrap", "disablePortal", "filterOptions", "filterSelectedOptions", "forcePopupIcon", "freeSolo", "fullWidth", "getLimitTagsText", "getOptionDisabled", "getOptionLabel", "isOptionEqualToValue", "groupBy", "handleHomeEndKeys", "id", "includeInputInList", "inputValue", "limitTags", "ListboxComponent", "ListboxProps", "loading", "loadingText", "multiple", "noOptionsText", "onChange", "onClose", "onHighlightChange", "onInputChange", "onOpen", "open", "openOnFocus", "openText", "options", "PaperComponent", "PopperComponent", "popupIcon", "readOnly", "renderGroup", "renderInput", "renderOption", "renderTags", "selectOnFocus", "size", "slotProps", "value"],
  _excluded2$1 = ["ref"];
const useUtilityClasses$q = ownerState => {
  const {
    classes,
    disablePortal,
    expanded,
    focused,
    fullWidth,
    hasClearIcon,
    hasPopupIcon,
    inputFocused,
    popupOpen,
    size
  } = ownerState;
  const slots = {
    root: ['root', expanded && 'expanded', focused && 'focused', fullWidth && 'fullWidth', hasClearIcon && 'hasClearIcon', hasPopupIcon && 'hasPopupIcon'],
    inputRoot: ['inputRoot'],
    input: ['input', inputFocused && 'inputFocused'],
    tag: ['tag', `tagSize${capitalize(size)}`],
    endAdornment: ['endAdornment'],
    clearIndicator: ['clearIndicator'],
    popupIndicator: ['popupIndicator', popupOpen && 'popupIndicatorOpen'],
    popper: ['popper', disablePortal && 'popperDisablePortal'],
    paper: ['paper'],
    listbox: ['listbox'],
    loading: ['loading'],
    noOptions: ['noOptions'],
    option: ['option'],
    groupLabel: ['groupLabel'],
    groupUl: ['groupUl']
  };
  return composeClasses(slots, getAutocompleteUtilityClass, classes);
};
const AutocompleteRoot = styled$1('div', {
  name: 'MuiAutocomplete',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    const {
      fullWidth,
      hasClearIcon,
      hasPopupIcon,
      inputFocused,
      size
    } = ownerState;
    return [{
      [`& .${autocompleteClasses$1.tag}`]: styles.tag
    }, {
      [`& .${autocompleteClasses$1.tag}`]: styles[`tagSize${capitalize(size)}`]
    }, {
      [`& .${autocompleteClasses$1.inputRoot}`]: styles.inputRoot
    }, {
      [`& .${autocompleteClasses$1.input}`]: styles.input
    }, {
      [`& .${autocompleteClasses$1.input}`]: inputFocused && styles.inputFocused
    }, styles.root, fullWidth && styles.fullWidth, hasPopupIcon && styles.hasPopupIcon, hasClearIcon && styles.hasClearIcon];
  }
})(({
  ownerState
}) => _extends({
  [`&.${autocompleteClasses$1.focused} .${autocompleteClasses$1.clearIndicator}`]: {
    visibility: 'visible'
  },
  /* Avoid double tap issue on iOS */
  '@media (pointer: fine)': {
    [`&:hover .${autocompleteClasses$1.clearIndicator}`]: {
      visibility: 'visible'
    }
  }
}, ownerState.fullWidth && {
  width: '100%'
}, {
  [`& .${autocompleteClasses$1.tag}`]: _extends({
    margin: 3,
    maxWidth: 'calc(100% - 6px)'
  }, ownerState.size === 'small' && {
    margin: 2,
    maxWidth: 'calc(100% - 4px)'
  }),
  [`& .${autocompleteClasses$1.inputRoot}`]: {
    flexWrap: 'wrap',
    [`.${autocompleteClasses$1.hasPopupIcon}&, .${autocompleteClasses$1.hasClearIcon}&`]: {
      paddingRight: 26 + 4
    },
    [`.${autocompleteClasses$1.hasPopupIcon}.${autocompleteClasses$1.hasClearIcon}&`]: {
      paddingRight: 52 + 4
    },
    [`& .${autocompleteClasses$1.input}`]: {
      width: 0,
      minWidth: 30
    }
  },
  [`& .${inputClasses$1.root}`]: {
    paddingBottom: 1,
    '& .MuiInput-input': {
      padding: '4px 4px 4px 0px'
    }
  },
  [`& .${inputClasses$1.root}.${inputBaseClasses$1.sizeSmall}`]: {
    [`& .${inputClasses$1.input}`]: {
      padding: '2px 4px 3px 0'
    }
  },
  [`& .${outlinedInputClasses$1.root}`]: {
    padding: 9,
    [`.${autocompleteClasses$1.hasPopupIcon}&, .${autocompleteClasses$1.hasClearIcon}&`]: {
      paddingRight: 26 + 4 + 9
    },
    [`.${autocompleteClasses$1.hasPopupIcon}.${autocompleteClasses$1.hasClearIcon}&`]: {
      paddingRight: 52 + 4 + 9
    },
    [`& .${autocompleteClasses$1.input}`]: {
      padding: '7.5px 4px 7.5px 5px'
    },
    [`& .${autocompleteClasses$1.endAdornment}`]: {
      right: 9
    }
  },
  [`& .${outlinedInputClasses$1.root}.${inputBaseClasses$1.sizeSmall}`]: {
    // Don't specify paddingRight, as it overrides the default value set when there is only
    // one of the popup or clear icon as the specificity is equal so the latter one wins
    paddingTop: 6,
    paddingBottom: 6,
    paddingLeft: 6,
    [`& .${autocompleteClasses$1.input}`]: {
      padding: '2.5px 4px 2.5px 8px'
    }
  },
  [`& .${filledInputClasses$1.root}`]: {
    paddingTop: 19,
    paddingLeft: 8,
    [`.${autocompleteClasses$1.hasPopupIcon}&, .${autocompleteClasses$1.hasClearIcon}&`]: {
      paddingRight: 26 + 4 + 9
    },
    [`.${autocompleteClasses$1.hasPopupIcon}.${autocompleteClasses$1.hasClearIcon}&`]: {
      paddingRight: 52 + 4 + 9
    },
    [`& .${filledInputClasses$1.input}`]: {
      padding: '7px 4px'
    },
    [`& .${autocompleteClasses$1.endAdornment}`]: {
      right: 9
    }
  },
  [`& .${filledInputClasses$1.root}.${inputBaseClasses$1.sizeSmall}`]: {
    paddingBottom: 1,
    [`& .${filledInputClasses$1.input}`]: {
      padding: '2.5px 4px'
    }
  },
  [`& .${inputBaseClasses$1.hiddenLabel}`]: {
    paddingTop: 8
  },
  [`& .${filledInputClasses$1.root}.${inputBaseClasses$1.hiddenLabel}`]: {
    paddingTop: 0,
    paddingBottom: 0,
    [`& .${autocompleteClasses$1.input}`]: {
      paddingTop: 16,
      paddingBottom: 17
    }
  },
  [`& .${filledInputClasses$1.root}.${inputBaseClasses$1.hiddenLabel}.${inputBaseClasses$1.sizeSmall}`]: {
    [`& .${autocompleteClasses$1.input}`]: {
      paddingTop: 8,
      paddingBottom: 9
    }
  },
  [`& .${autocompleteClasses$1.input}`]: _extends({
    flexGrow: 1,
    textOverflow: 'ellipsis',
    opacity: 0
  }, ownerState.inputFocused && {
    opacity: 1
  })
}));
const AutocompleteEndAdornment = styled$1('div', {
  name: 'MuiAutocomplete',
  slot: 'EndAdornment',
  overridesResolver: (props, styles) => styles.endAdornment
})({
  // We use a position absolute to support wrapping tags.
  position: 'absolute',
  right: 0,
  top: 'calc(50% - 14px)' // Center vertically
});

const AutocompleteClearIndicator = styled$1(IconButton$2, {
  name: 'MuiAutocomplete',
  slot: 'ClearIndicator',
  overridesResolver: (props, styles) => styles.clearIndicator
})({
  marginRight: -2,
  padding: 4,
  visibility: 'hidden'
});
const AutocompletePopupIndicator = styled$1(IconButton$2, {
  name: 'MuiAutocomplete',
  slot: 'PopupIndicator',
  overridesResolver: ({
    ownerState
  }, styles) => _extends({}, styles.popupIndicator, ownerState.popupOpen && styles.popupIndicatorOpen)
})(({
  ownerState
}) => _extends({
  padding: 2,
  marginRight: -2
}, ownerState.popupOpen && {
  transform: 'rotate(180deg)'
}));
const AutocompletePopper = styled$1(Popper$1, {
  name: 'MuiAutocomplete',
  slot: 'Popper',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${autocompleteClasses$1.option}`]: styles.option
    }, styles.popper, ownerState.disablePortal && styles.popperDisablePortal];
  }
})(({
  theme,
  ownerState
}) => _extends({
  zIndex: (theme.vars || theme).zIndex.modal
}, ownerState.disablePortal && {
  position: 'absolute'
}));
const AutocompletePaper = styled$1(Paper$1, {
  name: 'MuiAutocomplete',
  slot: 'Paper',
  overridesResolver: (props, styles) => styles.paper
})(({
  theme
}) => _extends({}, theme.typography.body1, {
  overflow: 'auto'
}));
const AutocompleteLoading = styled$1('div', {
  name: 'MuiAutocomplete',
  slot: 'Loading',
  overridesResolver: (props, styles) => styles.loading
})(({
  theme
}) => ({
  color: (theme.vars || theme).palette.text.secondary,
  padding: '14px 16px'
}));
const AutocompleteNoOptions = styled$1('div', {
  name: 'MuiAutocomplete',
  slot: 'NoOptions',
  overridesResolver: (props, styles) => styles.noOptions
})(({
  theme
}) => ({
  color: (theme.vars || theme).palette.text.secondary,
  padding: '14px 16px'
}));
const AutocompleteListbox = styled$1('div', {
  name: 'MuiAutocomplete',
  slot: 'Listbox',
  overridesResolver: (props, styles) => styles.listbox
})(({
  theme
}) => ({
  listStyle: 'none',
  margin: 0,
  padding: '8px 0',
  maxHeight: '40vh',
  overflow: 'auto',
  position: 'relative',
  [`& .${autocompleteClasses$1.option}`]: {
    minHeight: 48,
    display: 'flex',
    overflow: 'hidden',
    justifyContent: 'flex-start',
    alignItems: 'center',
    cursor: 'pointer',
    paddingTop: 6,
    boxSizing: 'border-box',
    outline: '0',
    WebkitTapHighlightColor: 'transparent',
    paddingBottom: 6,
    paddingLeft: 16,
    paddingRight: 16,
    [theme.breakpoints.up('sm')]: {
      minHeight: 'auto'
    },
    [`&.${autocompleteClasses$1.focused}`]: {
      backgroundColor: (theme.vars || theme).palette.action.hover,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    },
    '&[aria-disabled="true"]': {
      opacity: (theme.vars || theme).palette.action.disabledOpacity,
      pointerEvents: 'none'
    },
    [`&.${autocompleteClasses$1.focusVisible}`]: {
      backgroundColor: (theme.vars || theme).palette.action.focus
    },
    '&[aria-selected="true"]': {
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
      [`&.${autocompleteClasses$1.focused}`]: {
        backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: (theme.vars || theme).palette.action.selected
        }
      },
      [`&.${autocompleteClasses$1.focusVisible}`]: {
        backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
      }
    }
  }
}));
const AutocompleteGroupLabel = styled$1(ListSubheader$1, {
  name: 'MuiAutocomplete',
  slot: 'GroupLabel',
  overridesResolver: (props, styles) => styles.groupLabel
})(({
  theme
}) => ({
  backgroundColor: (theme.vars || theme).palette.background.paper,
  top: -8
}));
const AutocompleteGroupUl = styled$1('ul', {
  name: 'MuiAutocomplete',
  slot: 'GroupUl',
  overridesResolver: (props, styles) => styles.groupUl
})({
  padding: 0,
  [`& .${autocompleteClasses$1.option}`]: {
    paddingLeft: 24
  }
});
const Autocomplete = /*#__PURE__*/reactExports$1.forwardRef(function Autocomplete(inProps, ref) {
  var _slotProps$clearIndic, _slotProps$paper, _slotProps$popper, _slotProps$popupIndic;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAutocomplete'
  });
  /* eslint-disable @typescript-eslint/no-unused-vars */
  const {
      autoComplete = false,
      autoHighlight = false,
      autoSelect = false,
      blurOnSelect = false,
      ChipProps,
      className,
      clearIcon = _ClearIcon || (_ClearIcon = /*#__PURE__*/jsxRuntimeExports.jsx(CloseIcon, {
        fontSize: "small"
      })),
      clearOnBlur = !props.freeSolo,
      clearOnEscape = false,
      clearText = 'Clear',
      closeText = 'Close',
      componentsProps = {},
      defaultValue = props.multiple ? [] : null,
      disableClearable = false,
      disableCloseOnSelect = false,
      disabled = false,
      disabledItemsFocusable = false,
      disableListWrap = false,
      disablePortal = false,
      filterSelectedOptions = false,
      forcePopupIcon = 'auto',
      freeSolo = false,
      fullWidth = false,
      getLimitTagsText = more => `+${more}`,
      getOptionLabel = option => {
        var _option$label;
        return (_option$label = option.label) != null ? _option$label : option;
      },
      groupBy,
      handleHomeEndKeys = !props.freeSolo,
      includeInputInList = false,
      limitTags = -1,
      ListboxComponent = 'ul',
      ListboxProps,
      loading = false,
      loadingText = 'Loading…',
      multiple = false,
      noOptionsText = 'No options',
      openOnFocus = false,
      openText = 'Open',
      PaperComponent = Paper$1,
      PopperComponent = Popper$1,
      popupIcon = _ArrowDropDownIcon || (_ArrowDropDownIcon = /*#__PURE__*/jsxRuntimeExports.jsx(ArrowDropDownIcon, {})),
      readOnly = false,
      renderGroup: renderGroupProp,
      renderInput,
      renderOption: renderOptionProp,
      renderTags,
      selectOnFocus = !props.freeSolo,
      size = 'medium',
      slotProps = {}
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$t);
  /* eslint-enable @typescript-eslint/no-unused-vars */

  const {
    getRootProps,
    getInputProps,
    getInputLabelProps,
    getPopupIndicatorProps,
    getClearProps,
    getTagProps,
    getListboxProps,
    getOptionProps,
    value,
    dirty,
    expanded,
    id,
    popupOpen,
    focused,
    focusedTag,
    anchorEl,
    setAnchorEl,
    inputValue,
    groupedOptions
  } = useAutocomplete(_extends({}, props, {
    componentName: 'Autocomplete'
  }));
  const hasClearIcon = !disableClearable && !disabled && dirty && !readOnly;
  const hasPopupIcon = (!freeSolo || forcePopupIcon === true) && forcePopupIcon !== false;
  const {
    onMouseDown: handleInputMouseDown
  } = getInputProps();
  const {
    ref: externalListboxRef
  } = ListboxProps != null ? ListboxProps : {};
  const _getListboxProps = getListboxProps(),
    {
      ref: listboxRef
    } = _getListboxProps,
    otherListboxProps = _objectWithoutPropertiesLoose$2(_getListboxProps, _excluded2$1);
  const combinedListboxRef = useForkRef(listboxRef, externalListboxRef);

  // If you modify this, make sure to keep the `AutocompleteOwnerState` type in sync.
  const ownerState = _extends({}, props, {
    disablePortal,
    expanded,
    focused,
    fullWidth,
    hasClearIcon,
    hasPopupIcon,
    inputFocused: focusedTag === -1,
    popupOpen,
    size
  });
  const classes = useUtilityClasses$q(ownerState);
  let startAdornment;
  if (multiple && value.length > 0) {
    const getCustomizedTagProps = params => _extends({
      className: classes.tag,
      disabled
    }, getTagProps(params));
    if (renderTags) {
      startAdornment = renderTags(value, getCustomizedTagProps, ownerState);
    } else {
      startAdornment = value.map((option, index) => /*#__PURE__*/jsxRuntimeExports.jsx(Chip$2, _extends({
        label: getOptionLabel(option),
        size: size
      }, getCustomizedTagProps({
        index
      }), ChipProps)));
    }
  }
  if (limitTags > -1 && Array.isArray(startAdornment)) {
    const more = startAdornment.length - limitTags;
    if (!focused && more > 0) {
      startAdornment = startAdornment.splice(0, limitTags);
      startAdornment.push( /*#__PURE__*/jsxRuntimeExports.jsx("span", {
        className: classes.tag,
        children: getLimitTagsText(more)
      }, startAdornment.length));
    }
  }
  const defaultRenderGroup = params => /*#__PURE__*/jsxRuntimeExports.jsxs("li", {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteGroupLabel, {
      className: classes.groupLabel,
      ownerState: ownerState,
      component: "div",
      children: params.group
    }), /*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteGroupUl, {
      className: classes.groupUl,
      ownerState: ownerState,
      children: params.children
    })]
  }, params.key);
  const renderGroup = renderGroupProp || defaultRenderGroup;
  const defaultRenderOption = (props2, option) => /*#__PURE__*/jsxRuntimeExports.jsx("li", _extends({}, props2, {
    children: getOptionLabel(option)
  }));
  const renderOption = renderOptionProp || defaultRenderOption;
  const renderListOption = (option, index) => {
    const optionProps = getOptionProps({
      option,
      index
    });
    return renderOption(_extends({}, optionProps, {
      className: classes.option
    }), option, {
      selected: optionProps['aria-selected'],
      index,
      inputValue
    });
  };
  const clearIndicatorSlotProps = (_slotProps$clearIndic = slotProps.clearIndicator) != null ? _slotProps$clearIndic : componentsProps.clearIndicator;
  const paperSlotProps = (_slotProps$paper = slotProps.paper) != null ? _slotProps$paper : componentsProps.paper;
  const popperSlotProps = (_slotProps$popper = slotProps.popper) != null ? _slotProps$popper : componentsProps.popper;
  const popupIndicatorSlotProps = (_slotProps$popupIndic = slotProps.popupIndicator) != null ? _slotProps$popupIndic : componentsProps.popupIndicator;
  return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports$1.Fragment, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteRoot, _extends({
      ref: ref,
      className: clsx(classes.root, className),
      ownerState: ownerState
    }, getRootProps(other), {
      children: renderInput({
        id,
        disabled,
        fullWidth: true,
        size: size === 'small' ? 'small' : undefined,
        InputLabelProps: getInputLabelProps(),
        InputProps: _extends({
          ref: setAnchorEl,
          className: classes.inputRoot,
          startAdornment,
          onClick: event => {
            if (event.target === event.currentTarget) {
              handleInputMouseDown(event);
            }
          }
        }, (hasClearIcon || hasPopupIcon) && {
          endAdornment: /*#__PURE__*/jsxRuntimeExports.jsxs(AutocompleteEndAdornment, {
            className: classes.endAdornment,
            ownerState: ownerState,
            children: [hasClearIcon ? /*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteClearIndicator, _extends({}, getClearProps(), {
              "aria-label": clearText,
              title: clearText,
              ownerState: ownerState
            }, clearIndicatorSlotProps, {
              className: clsx(classes.clearIndicator, clearIndicatorSlotProps == null ? void 0 : clearIndicatorSlotProps.className),
              children: clearIcon
            })) : null, hasPopupIcon ? /*#__PURE__*/jsxRuntimeExports.jsx(AutocompletePopupIndicator, _extends({}, getPopupIndicatorProps(), {
              disabled: disabled,
              "aria-label": popupOpen ? closeText : openText,
              title: popupOpen ? closeText : openText,
              ownerState: ownerState
            }, popupIndicatorSlotProps, {
              className: clsx(classes.popupIndicator, popupIndicatorSlotProps == null ? void 0 : popupIndicatorSlotProps.className),
              children: popupIcon
            })) : null]
          })
        }),
        inputProps: _extends({
          className: classes.input,
          disabled,
          readOnly
        }, getInputProps())
      })
    })), anchorEl ? /*#__PURE__*/jsxRuntimeExports.jsx(AutocompletePopper, _extends({
      as: PopperComponent,
      disablePortal: disablePortal,
      style: {
        width: anchorEl ? anchorEl.clientWidth : null
      },
      ownerState: ownerState,
      role: "presentation",
      anchorEl: anchorEl,
      open: popupOpen
    }, popperSlotProps, {
      className: clsx(classes.popper, popperSlotProps == null ? void 0 : popperSlotProps.className),
      children: /*#__PURE__*/jsxRuntimeExports.jsxs(AutocompletePaper, _extends({
        ownerState: ownerState,
        as: PaperComponent
      }, paperSlotProps, {
        className: clsx(classes.paper, paperSlotProps == null ? void 0 : paperSlotProps.className),
        children: [loading && groupedOptions.length === 0 ? /*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteLoading, {
          className: classes.loading,
          ownerState: ownerState,
          children: loadingText
        }) : null, groupedOptions.length === 0 && !freeSolo && !loading ? /*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteNoOptions, {
          className: classes.noOptions,
          ownerState: ownerState,
          role: "presentation",
          onMouseDown: event => {
            // Prevent input blur when interacting with the "no options" content
            event.preventDefault();
          },
          children: noOptionsText
        }) : null, groupedOptions.length > 0 ? /*#__PURE__*/jsxRuntimeExports.jsx(AutocompleteListbox, _extends({
          as: ListboxComponent,
          className: classes.listbox,
          ownerState: ownerState
        }, otherListboxProps, ListboxProps, {
          ref: combinedListboxRef,
          children: groupedOptions.map((option, index) => {
            if (groupBy) {
              return renderGroup({
                key: option.key,
                group: option.group,
                children: option.options.map((option2, index2) => renderListOption(option2, option.index + index2))
              });
            }
            return renderListOption(option, index);
          })
        })) : null]
      }))
    })) : null]
  });
});
Autocomplete.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the portion of the selected suggestion that has not been typed by the user,
   * known as the completion string, appears inline after the input cursor in the textbox.
   * The inline completion string is visually highlighted and has a selected state.
   * @default false
   */
  autoComplete: PropTypes.bool,
  /**
   * If `true`, the first option is automatically highlighted.
   * @default false
   */
  autoHighlight: PropTypes.bool,
  /**
   * If `true`, the selected option becomes the value of the input
   * when the Autocomplete loses focus unless the user chooses
   * a different option or changes the character string in the input.
   *
   * When using `freeSolo` mode, the typed value will be the input value
   * if the Autocomplete loses focus without highlighting an option.
   * @default false
   */
  autoSelect: PropTypes.bool,
  /**
   * Control if the input should be blurred when an option is selected:
   *
   * - `false` the input is not blurred.
   * - `true` the input is always blurred.
   * - `touch` the input is blurred after a touch event.
   * - `mouse` the input is blurred after a mouse event.
   * @default false
   */
  blurOnSelect: PropTypes.oneOfType([PropTypes.oneOf(['mouse', 'touch']), PropTypes.bool]),
  /**
   * Props applied to the [`Chip`](/material-ui/api/chip/) element.
   */
  ChipProps: PropTypes.object,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The icon to display in place of the default clear icon.
   * @default <ClearIcon fontSize="small" />
   */
  clearIcon: PropTypes.node,
  /**
   * If `true`, the input's text is cleared on blur if no value is selected.
   *
   * Set to `true` if you want to help the user enter a new value.
   * Set to `false` if you want to help the user resume their search.
   * @default !props.freeSolo
   */
  clearOnBlur: PropTypes.bool,
  /**
   * If `true`, clear all values when the user presses escape and the popup is closed.
   * @default false
   */
  clearOnEscape: PropTypes.bool,
  /**
   * Override the default text for the *clear* icon button.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Clear'
   */
  clearText: PropTypes.string,
  /**
   * Override the default text for the *close popup* icon button.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Close'
   */
  closeText: PropTypes.string,
  /**
   * The props used for each slot inside.
   * @default {}
   */
  componentsProps: PropTypes.shape({
    clearIndicator: PropTypes.object,
    paper: PropTypes.object,
    popper: PropTypes.object,
    popupIndicator: PropTypes.object
  }),
  /**
   * The default value. Use when the component is not controlled.
   * @default props.multiple ? [] : null
   */
  defaultValue: chainPropTypes(PropTypes.any, props => {
    if (props.multiple && props.defaultValue !== undefined && !Array.isArray(props.defaultValue)) {
      return new Error(['MUI: The Autocomplete expects the `defaultValue` prop to be an array when `multiple={true}` or undefined.', `However, ${props.defaultValue} was provided.`].join('\n'));
    }
    return null;
  }),
  /**
   * If `true`, the input can't be cleared.
   * @default false
   */
  disableClearable: PropTypes.bool,
  /**
   * If `true`, the popup won't close when a value is selected.
   * @default false
   */
  disableCloseOnSelect: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, will allow focus on disabled items.
   * @default false
   */
  disabledItemsFocusable: PropTypes.bool,
  /**
   * If `true`, the list box in the popup will not wrap focus.
   * @default false
   */
  disableListWrap: PropTypes.bool,
  /**
   * If `true`, the `Popper` content will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: PropTypes.bool,
  /**
   * A function that determines the filtered options to be rendered on search.
   *
   * @default createFilterOptions()
   * @param {T[]} options The options to render.
   * @param {object} state The state of the component.
   * @returns {T[]}
   */
  filterOptions: PropTypes.func,
  /**
   * If `true`, hide the selected options from the list box.
   * @default false
   */
  filterSelectedOptions: PropTypes.bool,
  /**
   * Force the visibility display of the popup icon.
   * @default 'auto'
   */
  forcePopupIcon: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.bool]),
  /**
   * If `true`, the Autocomplete is free solo, meaning that the user input is not bound to provided options.
   * @default false
   */
  freeSolo: PropTypes.bool,
  /**
   * If `true`, the input will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * The label to display when the tags are truncated (`limitTags`).
   *
   * @param {number} more The number of truncated tags.
   * @returns {ReactNode}
   * @default (more) => `+${more}`
   */
  getLimitTagsText: PropTypes.func,
  /**
   * Used to determine the disabled state for a given option.
   *
   * @param {T} option The option to test.
   * @returns {boolean}
   */
  getOptionDisabled: PropTypes.func,
  /**
   * Used to determine the string value for a given option.
   * It's used to fill the input (and the list box options if `renderOption` is not provided).
   *
   * If used in free solo mode, it must accept both the type of the options and a string.
   *
   * @param {T} option
   * @returns {string}
   * @default (option) => option.label ?? option
   */
  getOptionLabel: PropTypes.func,
  /**
   * If provided, the options will be grouped under the returned string.
   * The groupBy value is also used as the text for group headings when `renderGroup` is not provided.
   *
   * @param {T} options The options to group.
   * @returns {string}
   */
  groupBy: PropTypes.func,
  /**
   * If `true`, the component handles the "Home" and "End" keys when the popup is open.
   * It should move focus to the first option and last option, respectively.
   * @default !props.freeSolo
   */
  handleHomeEndKeys: PropTypes.bool,
  /**
   * This prop is used to help implement the accessibility logic.
   * If you don't provide an id it will fall back to a randomly generated one.
   */
  id: PropTypes.string,
  /**
   * If `true`, the highlight can move to the input.
   * @default false
   */
  includeInputInList: PropTypes.bool,
  /**
   * The input value.
   */
  inputValue: PropTypes.string,
  /**
   * Used to determine if the option represents the given value.
   * Uses strict equality by default.
   * ⚠️ Both arguments need to be handled, an option can only match with one value.
   *
   * @param {T} option The option to test.
   * @param {T} value The value to test against.
   * @returns {boolean}
   */
  isOptionEqualToValue: PropTypes.func,
  /**
   * The maximum number of tags that will be visible when not focused.
   * Set `-1` to disable the limit.
   * @default -1
   */
  limitTags: integerPropType,
  /**
   * The component used to render the listbox.
   * @default 'ul'
   */
  ListboxComponent: PropTypes.elementType,
  /**
   * Props applied to the Listbox element.
   */
  ListboxProps: PropTypes.object,
  /**
   * If `true`, the component is in a loading state.
   * This shows the `loadingText` in place of suggestions (only if there are no suggestions to show, e.g. `options` are empty).
   * @default false
   */
  loading: PropTypes.bool,
  /**
   * Text to display when in a loading state.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Loading…'
   */
  loadingText: PropTypes.node,
  /**
   * If `true`, `value` must be an array and the menu will support multiple selections.
   * @default false
   */
  multiple: PropTypes.bool,
  /**
   * Text to display when there are no options.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'No options'
   */
  noOptionsText: PropTypes.node,
  /**
   * Callback fired when the value changes.
   *
   * @param {React.SyntheticEvent} event The event source of the callback.
   * @param {T|T[]} value The new value of the component.
   * @param {string} reason One of "createOption", "selectOption", "removeOption", "blur" or "clear".
   * @param {string} [details]
   */
  onChange: PropTypes.func,
  /**
   * Callback fired when the popup requests to be closed.
   * Use in controlled mode (see open).
   *
   * @param {React.SyntheticEvent} event The event source of the callback.
   * @param {string} reason Can be: `"toggleInput"`, `"escape"`, `"selectOption"`, `"removeOption"`, `"blur"`.
   */
  onClose: PropTypes.func,
  /**
   * Callback fired when the highlight option changes.
   *
   * @param {React.SyntheticEvent} event The event source of the callback.
   * @param {T} option The highlighted option.
   * @param {string} reason Can be: `"keyboard"`, `"auto"`, `"mouse"`, `"touch"`.
   */
  onHighlightChange: PropTypes.func,
  /**
   * Callback fired when the input value changes.
   *
   * @param {React.SyntheticEvent} event The event source of the callback.
   * @param {string} value The new value of the text input.
   * @param {string} reason Can be: `"input"` (user input), `"reset"` (programmatic change), `"clear"`.
   */
  onInputChange: PropTypes.func,
  /**
   * Callback fired when the popup requests to be opened.
   * Use in controlled mode (see open).
   *
   * @param {React.SyntheticEvent} event The event source of the callback.
   */
  onOpen: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool,
  /**
   * If `true`, the popup will open on input focus.
   * @default false
   */
  openOnFocus: PropTypes.bool,
  /**
   * Override the default text for the *open popup* icon button.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Open'
   */
  openText: PropTypes.string,
  /**
   * Array of options.
   */
  options: PropTypes.array.isRequired,
  /**
   * The component used to render the body of the popup.
   * @default Paper
   */
  PaperComponent: PropTypes.elementType,
  /**
   * The component used to position the popup.
   * @default Popper
   */
  PopperComponent: PropTypes.elementType,
  /**
   * The icon to display in place of the default popup icon.
   * @default <ArrowDropDownIcon />
   */
  popupIcon: PropTypes.node,
  /**
   * If `true`, the component becomes readonly. It is also supported for multiple tags where the tag cannot be deleted.
   * @default false
   */
  readOnly: PropTypes.bool,
  /**
   * Render the group.
   *
   * @param {AutocompleteRenderGroupParams} params The group to render.
   * @returns {ReactNode}
   */
  renderGroup: PropTypes.func,
  /**
   * Render the input.
   *
   * @param {object} params
   * @returns {ReactNode}
   */
  renderInput: PropTypes.func.isRequired,
  /**
   * Render the option, use `getOptionLabel` by default.
   *
   * @param {object} props The props to apply on the li element.
   * @param {T} option The option to render.
   * @param {object} state The state of the component.
   * @returns {ReactNode}
   */
  renderOption: PropTypes.func,
  /**
   * Render the selected value.
   *
   * @param {T[]} value The `value` provided to the component.
   * @param {function} getTagProps A tag props getter.
   * @param {object} ownerState The state of the Autocomplete component.
   * @returns {ReactNode}
   */
  renderTags: PropTypes.func,
  /**
   * If `true`, the input's text is selected on focus.
   * It helps the user clear the selected value.
   * @default !props.freeSolo
   */
  selectOnFocus: PropTypes.bool,
  /**
   * The size of the component.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium']), PropTypes.string]),
  /**
   * The props used for each slot inside.
   * @default {}
   */
  slotProps: PropTypes.shape({
    clearIndicator: PropTypes.object,
    paper: PropTypes.object,
    popper: PropTypes.object,
    popupIndicator: PropTypes.object
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the autocomplete.
   *
   * The value must have reference equality with the option in order to be selected.
   * You can customize the equality behavior with the `isOptionEqualToValue` prop.
   */
  value: chainPropTypes(PropTypes.any, props => {
    if (props.multiple && props.value !== undefined && !Array.isArray(props.value)) {
      return new Error(['MUI: The Autocomplete expects the `value` prop to be an array when `multiple={true}` or undefined.', `However, ${props.value} was provided.`].join('\n'));
    }
    return null;
  })
} ;
var Autocomplete$1 = Autocomplete;

function fieldToCheckbox(_a) {
  var disabled = _a.disabled,
    _b = _a.field,
    fieldOnBlur = _b.onBlur,
    field = __rest(_b, ["onBlur"]),
    isSubmitting = _a.form.isSubmitting,
    type = _a.type,
    onBlur = _a.onBlur,
    props = __rest(_a, ["disabled", "field", "form", "type", "onBlur"]);
  var indeterminate = !Array.isArray(field.value) && field.value == null;
  {
    warning$1(type === 'checkbox', "property type=checkbox is missing from field " + field.name + ", this can caused unexpected behaviour");
  }
  return __assign(__assign({
    disabled: disabled !== null && disabled !== void 0 ? disabled : isSubmitting,
    indeterminate: indeterminate,
    onBlur: onBlur !== null && onBlur !== void 0 ? onBlur : function (e) {
      fieldOnBlur(e !== null && e !== void 0 ? e : field.name);
    }
  }, field), props);
}

function getFormControlUtilityClasses(slot) {
  return generateUtilityClass('MuiFormControl', slot);
}
generateUtilityClasses('MuiFormControl', ['root', 'marginNone', 'marginNormal', 'marginDense', 'fullWidth', 'disabled']);

const _excluded$s = ["children", "className", "color", "component", "disabled", "error", "focused", "fullWidth", "hiddenLabel", "margin", "required", "size", "variant"];
const useUtilityClasses$p = ownerState => {
  const {
    classes,
    margin,
    fullWidth
  } = ownerState;
  const slots = {
    root: ['root', margin !== 'none' && `margin${capitalize(margin)}`, fullWidth && 'fullWidth']
  };
  return composeClasses(slots, getFormControlUtilityClasses, classes);
};
const FormControlRoot = styled$1('div', {
  name: 'MuiFormControl',
  slot: 'Root',
  overridesResolver: ({
    ownerState
  }, styles) => {
    return _extends({}, styles.root, styles[`margin${capitalize(ownerState.margin)}`], ownerState.fullWidth && styles.fullWidth);
  }
})(({
  ownerState
}) => _extends({
  display: 'inline-flex',
  flexDirection: 'column',
  position: 'relative',
  // Reset fieldset default style.
  minWidth: 0,
  padding: 0,
  margin: 0,
  border: 0,
  verticalAlign: 'top'
}, ownerState.margin === 'normal' && {
  marginTop: 16,
  marginBottom: 8
}, ownerState.margin === 'dense' && {
  marginTop: 8,
  marginBottom: 4
}, ownerState.fullWidth && {
  width: '100%'
}));

/**
 * Provides context such as filled/focused/error/required for form inputs.
 * Relying on the context provides high flexibility and ensures that the state always stays
 * consistent across the children of the `FormControl`.
 * This context is used by the following components:
 *
 *  - FormLabel
 *  - FormHelperText
 *  - Input
 *  - InputLabel
 *
 * You can find one composition example below and more going to [the demos](/material-ui/react-text-field/#components).
 *
 * ```jsx
 * <FormControl>
 *   <InputLabel htmlFor="my-input">Email address</InputLabel>
 *   <Input id="my-input" aria-describedby="my-helper-text" />
 *   <FormHelperText id="my-helper-text">We'll never share your email.</FormHelperText>
 * </FormControl>
 * ```
 *
 * ⚠️ Only one `InputBase` can be used within a FormControl because it creates visual inconsistencies.
 * For instance, only one input can be focused at the same time, the state shouldn't be shared.
 */
const FormControl = /*#__PURE__*/reactExports$1.forwardRef(function FormControl(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFormControl'
  });
  const {
      children,
      className,
      color = 'primary',
      component = 'div',
      disabled = false,
      error = false,
      focused: visuallyFocused,
      fullWidth = false,
      hiddenLabel = false,
      margin = 'none',
      required = false,
      size = 'medium',
      variant = 'outlined'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$s);
  const ownerState = _extends({}, props, {
    color,
    component,
    disabled,
    error,
    fullWidth,
    hiddenLabel,
    margin,
    required,
    size,
    variant
  });
  const classes = useUtilityClasses$p(ownerState);
  const [adornedStart, setAdornedStart] = reactExports$1.useState(() => {
    // We need to iterate through the children and find the Input in order
    // to fully support server-side rendering.
    let initialAdornedStart = false;
    if (children) {
      reactExports$1.Children.forEach(children, child => {
        if (!isMuiElement(child, ['Input', 'Select'])) {
          return;
        }
        const input = isMuiElement(child, ['Select']) ? child.props.input : child;
        if (input && isAdornedStart(input.props)) {
          initialAdornedStart = true;
        }
      });
    }
    return initialAdornedStart;
  });
  const [filled, setFilled] = reactExports$1.useState(() => {
    // We need to iterate through the children and find the Input in order
    // to fully support server-side rendering.
    let initialFilled = false;
    if (children) {
      reactExports$1.Children.forEach(children, child => {
        if (!isMuiElement(child, ['Input', 'Select'])) {
          return;
        }
        if (isFilled(child.props, true) || isFilled(child.props.inputProps, true)) {
          initialFilled = true;
        }
      });
    }
    return initialFilled;
  });
  const [focusedState, setFocused] = reactExports$1.useState(false);
  if (disabled && focusedState) {
    setFocused(false);
  }
  const focused = visuallyFocused !== undefined && !disabled ? visuallyFocused : focusedState;
  let registerEffect;
  {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const registeredInput = reactExports$1.useRef(false);
    registerEffect = () => {
      if (registeredInput.current) {
        console.error(['MUI: There are multiple `InputBase` components inside a FormControl.', 'This creates visual inconsistencies, only use one `InputBase`.'].join('\n'));
      }
      registeredInput.current = true;
      return () => {
        registeredInput.current = false;
      };
    };
  }
  const childContext = reactExports$1.useMemo(() => {
    return {
      adornedStart,
      setAdornedStart,
      color,
      disabled,
      error,
      filled,
      focused,
      fullWidth,
      hiddenLabel,
      size,
      onBlur: () => {
        setFocused(false);
      },
      onEmpty: () => {
        setFilled(false);
      },
      onFilled: () => {
        setFilled(true);
      },
      onFocus: () => {
        setFocused(true);
      },
      registerEffect,
      required,
      variant
    };
  }, [adornedStart, color, disabled, error, filled, focused, fullWidth, hiddenLabel, registerEffect, required, size, variant]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(FormControlContext$1.Provider, {
    value: childContext,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(FormControlRoot, _extends({
      as: component,
      ownerState: ownerState,
      className: clsx(classes.root, className),
      ref: ref
    }, other, {
      children: children
    }))
  });
});
FormControl.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the label, input and helper text should be displayed in a disabled state.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the label is displayed in an error state.
   * @default false
   */
  error: PropTypes.bool,
  /**
   * If `true`, the component is displayed in focused state.
   */
  focused: PropTypes.bool,
  /**
   * If `true`, the component will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * If `true`, the label is hidden.
   * This is used to increase density for a `FilledInput`.
   * Be sure to add `aria-label` to the `input` element.
   * @default false
   */
  hiddenLabel: PropTypes.bool,
  /**
   * If `dense` or `normal`, will adjust vertical spacing of this and contained components.
   * @default 'none'
   */
  margin: PropTypes.oneOf(['dense', 'none', 'normal']),
  /**
   * If `true`, the label will indicate that the `input` is required.
   * @default false
   */
  required: PropTypes.bool,
  /**
   * The size of the component.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'outlined'
   */
  variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} ;
var FormControl$1 = FormControl;

function getFormControlLabelUtilityClasses(slot) {
  return generateUtilityClass('MuiFormControlLabel', slot);
}
const formControlLabelClasses = generateUtilityClasses('MuiFormControlLabel', ['root', 'labelPlacementStart', 'labelPlacementTop', 'labelPlacementBottom', 'disabled', 'label', 'error', 'required', 'asterisk']);
var formControlLabelClasses$1 = formControlLabelClasses;

const _excluded$r = ["checked", "className", "componentsProps", "control", "disabled", "disableTypography", "inputRef", "label", "labelPlacement", "name", "onChange", "required", "slotProps", "value"];
const useUtilityClasses$o = ownerState => {
  const {
    classes,
    disabled,
    labelPlacement,
    error,
    required
  } = ownerState;
  const slots = {
    root: ['root', disabled && 'disabled', `labelPlacement${capitalize(labelPlacement)}`, error && 'error', required && 'required'],
    label: ['label', disabled && 'disabled'],
    asterisk: ['asterisk', error && 'error']
  };
  return composeClasses(slots, getFormControlLabelUtilityClasses, classes);
};
const FormControlLabelRoot = styled$1('label', {
  name: 'MuiFormControlLabel',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${formControlLabelClasses$1.label}`]: styles.label
    }, styles.root, styles[`labelPlacement${capitalize(ownerState.labelPlacement)}`]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  display: 'inline-flex',
  alignItems: 'center',
  cursor: 'pointer',
  // For correct alignment with the text.
  verticalAlign: 'middle',
  WebkitTapHighlightColor: 'transparent',
  marginLeft: -11,
  marginRight: 16,
  // used for row presentation of radio/checkbox
  [`&.${formControlLabelClasses$1.disabled}`]: {
    cursor: 'default'
  }
}, ownerState.labelPlacement === 'start' && {
  flexDirection: 'row-reverse',
  marginLeft: 16,
  // used for row presentation of radio/checkbox
  marginRight: -11
}, ownerState.labelPlacement === 'top' && {
  flexDirection: 'column-reverse',
  marginLeft: 16
}, ownerState.labelPlacement === 'bottom' && {
  flexDirection: 'column',
  marginLeft: 16
}, {
  [`& .${formControlLabelClasses$1.label}`]: {
    [`&.${formControlLabelClasses$1.disabled}`]: {
      color: (theme.vars || theme).palette.text.disabled
    }
  }
}));
const AsteriskComponent$1 = styled$1('span', {
  name: 'MuiFormControlLabel',
  slot: 'Asterisk',
  overridesResolver: (props, styles) => styles.asterisk
})(({
  theme
}) => ({
  [`&.${formControlLabelClasses$1.error}`]: {
    color: (theme.vars || theme).palette.error.main
  }
}));

/**
 * Drop-in replacement of the `Radio`, `Switch` and `Checkbox` component.
 * Use this component if you want to display an extra label.
 */
const FormControlLabel = /*#__PURE__*/reactExports$1.forwardRef(function FormControlLabel(inProps, ref) {
  var _ref, _slotProps$typography;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFormControlLabel'
  });
  const {
      className,
      componentsProps = {},
      control,
      disabled: disabledProp,
      disableTypography,
      label: labelProp,
      labelPlacement = 'end',
      required: requiredProp,
      slotProps = {}
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$r);
  const muiFormControl = useFormControl();
  const disabled = (_ref = disabledProp != null ? disabledProp : control.props.disabled) != null ? _ref : muiFormControl == null ? void 0 : muiFormControl.disabled;
  const required = requiredProp != null ? requiredProp : control.props.required;
  const controlProps = {
    disabled,
    required
  };
  ['checked', 'name', 'onChange', 'value', 'inputRef'].forEach(key => {
    if (typeof control.props[key] === 'undefined' && typeof props[key] !== 'undefined') {
      controlProps[key] = props[key];
    }
  });
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['error']
  });
  const ownerState = _extends({}, props, {
    disabled,
    labelPlacement,
    required,
    error: fcs.error
  });
  const classes = useUtilityClasses$o(ownerState);
  const typographySlotProps = (_slotProps$typography = slotProps.typography) != null ? _slotProps$typography : componentsProps.typography;
  let label = labelProp;
  if (label != null && label.type !== Typography$1 && !disableTypography) {
    label = /*#__PURE__*/jsxRuntimeExports.jsx(Typography$1, _extends({
      component: "span"
    }, typographySlotProps, {
      className: clsx(classes.label, typographySlotProps == null ? void 0 : typographySlotProps.className),
      children: label
    }));
  }
  return /*#__PURE__*/jsxRuntimeExports.jsxs(FormControlLabelRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other, {
    children: [/*#__PURE__*/reactExports$1.cloneElement(control, controlProps), label, required && /*#__PURE__*/jsxRuntimeExports.jsxs(AsteriskComponent$1, {
      ownerState: ownerState,
      "aria-hidden": true,
      className: classes.asterisk,
      children: ["\u2009", '*']
    })]
  }));
});
FormControlLabel.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * If `true`, the component appears selected.
   */
  checked: PropTypes.bool,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The props used for each slot inside.
   * @default {}
   */
  componentsProps: PropTypes.shape({
    typography: PropTypes.object
  }),
  /**
   * A control element. For instance, it can be a `Radio`, a `Switch` or a `Checkbox`.
   */
  control: PropTypes.element.isRequired,
  /**
   * If `true`, the control is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the label is rendered as it is passed without an additional typography node.
   */
  disableTypography: PropTypes.bool,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * A text or an element to be used in an enclosing label element.
   */
  label: PropTypes.node,
  /**
   * The position of the label.
   * @default 'end'
   */
  labelPlacement: PropTypes.oneOf(['bottom', 'end', 'start', 'top']),
  /**
   * @ignore
   */
  name: PropTypes.string,
  /**
   * Callback fired when the state is changed.
   *
   * @param {React.SyntheticEvent} event The event source of the callback.
   * You can pull out the new checked state by accessing `event.target.checked` (boolean).
   */
  onChange: PropTypes.func,
  /**
   * If `true`, the label will indicate that the `input` is required.
   */
  required: PropTypes.bool,
  /**
   * The props used for each slot inside.
   * @default {}
   */
  slotProps: PropTypes.shape({
    typography: PropTypes.object
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the component.
   */
  value: PropTypes.any
} ;
var FormControlLabel$1 = FormControlLabel;

function CheckboxWithLabel(_a) {
  var Label = _a.Label,
    props = __rest(_a, ["Label"]);
  return reactExports$1.createElement(FormControlLabel$1, __assign({
    control: reactExports$1.createElement(Checkbox$1, __assign({}, fieldToCheckbox(props)))
  }, Label));
}
CheckboxWithLabel.displayName = 'FormikMaterialUICheckboxWithLabel';

function getFormGroupUtilityClass(slot) {
  return generateUtilityClass('MuiFormGroup', slot);
}
generateUtilityClasses('MuiFormGroup', ['root', 'row', 'error']);

const _excluded$q = ["className", "row"];
const useUtilityClasses$n = ownerState => {
  const {
    classes,
    row,
    error
  } = ownerState;
  const slots = {
    root: ['root', row && 'row', error && 'error']
  };
  return composeClasses(slots, getFormGroupUtilityClass, classes);
};
const FormGroupRoot = styled$1('div', {
  name: 'MuiFormGroup',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.row && styles.row];
  }
})(({
  ownerState
}) => _extends({
  display: 'flex',
  flexDirection: 'column',
  flexWrap: 'wrap'
}, ownerState.row && {
  flexDirection: 'row'
}));

/**
 * `FormGroup` wraps controls such as `Checkbox` and `Switch`.
 * It provides compact row layout.
 * For the `Radio`, you should be using the `RadioGroup` component instead of this one.
 */
const FormGroup = /*#__PURE__*/reactExports$1.forwardRef(function FormGroup(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFormGroup'
  });
  const {
      className,
      row = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$q);
  const muiFormControl = useFormControl();
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['error']
  });
  const ownerState = _extends({}, props, {
    row,
    error: fcs.error
  });
  const classes = useUtilityClasses$n(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(FormGroupRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other));
});
FormGroup.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Display group of elements in a compact row.
   * @default false
   */
  row: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var FormGroup$1 = FormGroup;

const _excluded$p = ["actions", "children", "defaultValue", "name", "onChange", "value"];
const RadioGroup$1 = /*#__PURE__*/reactExports$1.forwardRef(function RadioGroup(props, ref) {
  const {
      // private
      // eslint-disable-next-line react/prop-types
      actions,
      children,
      defaultValue,
      name: nameProp,
      onChange,
      value: valueProp
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$p);
  const rootRef = reactExports$1.useRef(null);
  const [value, setValueState] = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: 'RadioGroup'
  });
  reactExports$1.useImperativeHandle(actions, () => ({
    focus: () => {
      let input = rootRef.current.querySelector('input:not(:disabled):checked');
      if (!input) {
        input = rootRef.current.querySelector('input:not(:disabled)');
      }
      if (input) {
        input.focus();
      }
    }
  }), []);
  const handleRef = useForkRef(ref, rootRef);
  const name = useId(nameProp);
  const contextValue = reactExports$1.useMemo(() => ({
    name,
    onChange(event) {
      setValueState(event.target.value);
      if (onChange) {
        onChange(event, event.target.value);
      }
    },
    value
  }), [name, onChange, setValueState, value]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(RadioGroupContext$1.Provider, {
    value: contextValue,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(FormGroup$1, _extends({
      role: "radiogroup",
      ref: handleRef
    }, other, {
      children: children
    }))
  });
});
RadioGroup$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * The name used to reference the value of the control.
   * If you don't provide this prop, it falls back to a randomly generated name.
   */
  name: PropTypes.string,
  /**
   * Callback fired when a radio button is selected.
   *
   * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
   * @param {string} value The value of the selected radio button.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * Value of the selected radio button. The DOM API casts this to a string.
   */
  value: PropTypes.any
} ;
var MuiRadioGroup = RadioGroup$1;

function fieldToRadioGroup(_a) {
  var _b = _a.field,
    fieldOnBlur = _b.onBlur,
    field = __rest(_b, ["onBlur"]);
  _a.form;
  var onBlur = _a.onBlur,
    props = __rest(_a, ["field", "form", "onBlur"]);
  return __assign(__assign({
    onBlur: onBlur !== null && onBlur !== void 0 ? onBlur : function (e) {
      fieldOnBlur(e !== null && e !== void 0 ? e : field.name);
    }
  }, field), props);
}
function RadioGroup(props) {
  return reactExports$1.createElement(MuiRadioGroup, __assign({}, fieldToRadioGroup(props)));
}
RadioGroup.displayName = 'FormikMaterialUIRadioGroup';

function getFormLabelUtilityClasses(slot) {
  return generateUtilityClass('MuiFormLabel', slot);
}
const formLabelClasses = generateUtilityClasses('MuiFormLabel', ['root', 'colorSecondary', 'focused', 'disabled', 'error', 'filled', 'required', 'asterisk']);
var formLabelClasses$1 = formLabelClasses;

const _excluded$o = ["children", "className", "color", "component", "disabled", "error", "filled", "focused", "required"];
const useUtilityClasses$m = ownerState => {
  const {
    classes,
    color,
    focused,
    disabled,
    error,
    filled,
    required
  } = ownerState;
  const slots = {
    root: ['root', `color${capitalize(color)}`, disabled && 'disabled', error && 'error', filled && 'filled', focused && 'focused', required && 'required'],
    asterisk: ['asterisk', error && 'error']
  };
  return composeClasses(slots, getFormLabelUtilityClasses, classes);
};
const FormLabelRoot = styled$1('label', {
  name: 'MuiFormLabel',
  slot: 'Root',
  overridesResolver: ({
    ownerState
  }, styles) => {
    return _extends({}, styles.root, ownerState.color === 'secondary' && styles.colorSecondary, ownerState.filled && styles.filled);
  }
})(({
  theme,
  ownerState
}) => _extends({
  color: (theme.vars || theme).palette.text.secondary
}, theme.typography.body1, {
  lineHeight: '1.4375em',
  padding: 0,
  position: 'relative',
  [`&.${formLabelClasses$1.focused}`]: {
    color: (theme.vars || theme).palette[ownerState.color].main
  },
  [`&.${formLabelClasses$1.disabled}`]: {
    color: (theme.vars || theme).palette.text.disabled
  },
  [`&.${formLabelClasses$1.error}`]: {
    color: (theme.vars || theme).palette.error.main
  }
}));
const AsteriskComponent = styled$1('span', {
  name: 'MuiFormLabel',
  slot: 'Asterisk',
  overridesResolver: (props, styles) => styles.asterisk
})(({
  theme
}) => ({
  [`&.${formLabelClasses$1.error}`]: {
    color: (theme.vars || theme).palette.error.main
  }
}));
const FormLabel = /*#__PURE__*/reactExports$1.forwardRef(function FormLabel(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiFormLabel'
  });
  const {
      children,
      className,
      component = 'label'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$o);
  const muiFormControl = useFormControl();
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['color', 'required', 'focused', 'disabled', 'error', 'filled']
  });
  const ownerState = _extends({}, props, {
    color: fcs.color || 'primary',
    component,
    disabled: fcs.disabled,
    error: fcs.error,
    filled: fcs.filled,
    focused: fcs.focused,
    required: fcs.required
  });
  const classes = useUtilityClasses$m(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(FormLabelRoot, _extends({
    as: component,
    ownerState: ownerState,
    className: clsx(classes.root, className),
    ref: ref
  }, other, {
    children: [children, fcs.required && /*#__PURE__*/jsxRuntimeExports.jsxs(AsteriskComponent, {
      ownerState: ownerState,
      "aria-hidden": true,
      className: classes.asterisk,
      children: ["\u2009", '*']
    })]
  }));
});
FormLabel.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['error', 'info', 'primary', 'secondary', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the label should be displayed in a disabled state.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the label is displayed in an error state.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the label should use filled classes key.
   */
  filled: PropTypes.bool,
  /**
   * If `true`, the input of this label is focused (used by `FormGroup` components).
   */
  focused: PropTypes.bool,
  /**
   * If `true`, the label will indicate that the `input` is required.
   */
  required: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var FormLabel$1 = FormLabel;

function getInputLabelUtilityClasses(slot) {
  return generateUtilityClass('MuiInputLabel', slot);
}
generateUtilityClasses('MuiInputLabel', ['root', 'focused', 'disabled', 'error', 'required', 'asterisk', 'formControl', 'sizeSmall', 'shrink', 'animated', 'standard', 'filled', 'outlined']);

const _excluded$n = ["disableAnimation", "margin", "shrink", "variant", "className"];
const useUtilityClasses$l = ownerState => {
  const {
    classes,
    formControl,
    size,
    shrink,
    disableAnimation,
    variant,
    required
  } = ownerState;
  const slots = {
    root: ['root', formControl && 'formControl', !disableAnimation && 'animated', shrink && 'shrink', size === 'small' && 'sizeSmall', variant],
    asterisk: [required && 'asterisk']
  };
  const composedClasses = composeClasses(slots, getInputLabelUtilityClasses, classes);
  return _extends({}, classes, composedClasses);
};
const InputLabelRoot = styled$1(FormLabel$1, {
  shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
  name: 'MuiInputLabel',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${formLabelClasses$1.asterisk}`]: styles.asterisk
    }, styles.root, ownerState.formControl && styles.formControl, ownerState.size === 'small' && styles.sizeSmall, ownerState.shrink && styles.shrink, !ownerState.disableAnimation && styles.animated, styles[ownerState.variant]];
  }
})(({
  theme,
  ownerState
}) => _extends({
  display: 'block',
  transformOrigin: 'top left',
  whiteSpace: 'nowrap',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  maxWidth: '100%'
}, ownerState.formControl && {
  position: 'absolute',
  left: 0,
  top: 0,
  // slight alteration to spec spacing to match visual spec result
  transform: 'translate(0, 20px) scale(1)'
}, ownerState.size === 'small' && {
  // Compensation for the `Input.inputSizeSmall` style.
  transform: 'translate(0, 17px) scale(1)'
}, ownerState.shrink && {
  transform: 'translate(0, -1.5px) scale(0.75)',
  transformOrigin: 'top left',
  maxWidth: '133%'
}, !ownerState.disableAnimation && {
  transition: theme.transitions.create(['color', 'transform', 'max-width'], {
    duration: theme.transitions.duration.shorter,
    easing: theme.transitions.easing.easeOut
  })
}, ownerState.variant === 'filled' && _extends({
  // Chrome's autofill feature gives the input field a yellow background.
  // Since the input field is behind the label in the HTML tree,
  // the input field is drawn last and hides the label with an opaque background color.
  // zIndex: 1 will raise the label above opaque background-colors of input.
  zIndex: 1,
  pointerEvents: 'none',
  transform: 'translate(12px, 16px) scale(1)',
  maxWidth: 'calc(100% - 24px)'
}, ownerState.size === 'small' && {
  transform: 'translate(12px, 13px) scale(1)'
}, ownerState.shrink && _extends({
  userSelect: 'none',
  pointerEvents: 'auto',
  transform: 'translate(12px, 7px) scale(0.75)',
  maxWidth: 'calc(133% - 24px)'
}, ownerState.size === 'small' && {
  transform: 'translate(12px, 4px) scale(0.75)'
})), ownerState.variant === 'outlined' && _extends({
  // see comment above on filled.zIndex
  zIndex: 1,
  pointerEvents: 'none',
  transform: 'translate(14px, 16px) scale(1)',
  maxWidth: 'calc(100% - 24px)'
}, ownerState.size === 'small' && {
  transform: 'translate(14px, 9px) scale(1)'
}, ownerState.shrink && {
  userSelect: 'none',
  pointerEvents: 'auto',
  // Theoretically, we should have (8+5)*2/0.75 = 34px
  // but it feels a better when it bleeds a bit on the left, so 32px.
  maxWidth: 'calc(133% - 32px)',
  transform: 'translate(14px, -9px) scale(0.75)'
})));
const InputLabel = /*#__PURE__*/reactExports$1.forwardRef(function InputLabel(inProps, ref) {
  const props = useThemeProps({
    name: 'MuiInputLabel',
    props: inProps
  });
  const {
      disableAnimation = false,
      shrink: shrinkProp,
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$n);
  const muiFormControl = useFormControl();
  let shrink = shrinkProp;
  if (typeof shrink === 'undefined' && muiFormControl) {
    shrink = muiFormControl.filled || muiFormControl.focused || muiFormControl.adornedStart;
  }
  const fcs = formControlState({
    props,
    muiFormControl,
    states: ['size', 'variant', 'required']
  });
  const ownerState = _extends({}, props, {
    disableAnimation,
    formControl: muiFormControl,
    shrink,
    size: fcs.size,
    variant: fcs.variant,
    required: fcs.required
  });
  const classes = useUtilityClasses$l(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(InputLabelRoot, _extends({
    "data-shrink": shrink,
    ownerState: ownerState,
    ref: ref,
    className: clsx(classes.root, className)
  }, other, {
    classes: classes
  }));
});
InputLabel.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['error', 'info', 'primary', 'secondary', 'success', 'warning']), PropTypes.string]),
  /**
   * If `true`, the transition animation is disabled.
   * @default false
   */
  disableAnimation: PropTypes.bool,
  /**
   * If `true`, the component is disabled.
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the label is displayed in an error state.
   */
  error: PropTypes.bool,
  /**
   * If `true`, the `input` of this label is focused.
   */
  focused: PropTypes.bool,
  /**
   * If `dense`, will adjust vertical spacing. This is normally obtained via context from
   * FormControl.
   */
  margin: PropTypes.oneOf(['dense']),
  /**
   * if `true`, the label will indicate that the `input` is required.
   */
  required: PropTypes.bool,
  /**
   * If `true`, the label is shrunk.
   */
  shrink: PropTypes.bool,
  /**
   * The size of the component.
   * @default 'normal'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['normal', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   */
  variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} ;
var InputLabel$1 = InputLabel;

function fieldToSelect(_a) {
  var _this = this;
  var disabled = _a.disabled,
    _b = _a.field;
  _b.onBlur;
  var fieldOnChange = _b.onChange,
    field = __rest(_b, ["onBlur", "onChange"]),
    _c = _a.form,
    isSubmitting = _c.isSubmitting,
    touched = _c.touched,
    errors = _c.errors,
    setFieldTouched = _c.setFieldTouched,
    setFieldValue = _c.setFieldValue,
    onClose = _a.onClose,
    props = __rest(_a, ["disabled", "field", "form", "onClose"]);
  var fieldError = getIn(errors, field.name);
  var showError = getIn(touched, field.name) && !!fieldError;
  return __assign(__assign({
    disabled: disabled !== null && disabled !== void 0 ? disabled : isSubmitting,
    error: showError,
    formError: showError ? fieldError : undefined,
    onBlur: function () {},
    onChange: fieldOnChange !== null && fieldOnChange !== void 0 ? fieldOnChange : function () {},
    onClose: onClose !== null && onClose !== void 0 ? onClose : function (e) {
      return __awaiter$1(_this, void 0, void 0, function () {
        var dataset;
        return __generator$1(this, function (_a) {
          switch (_a.label) {
            case 0:
              dataset = e.target.dataset;
              if (!(dataset && dataset.value)) return [3, 2];
              return [4, setFieldValue(field.name, dataset.value, false)];
            case 1:
              _a.sent();
              _a.label = 2;
            case 2:
              setFieldTouched(field.name, true, true);
              return [2];
          }
        });
      });
    }
  }, field), props);
}
function Select$1(_a) {
  var formControl = _a.formControl,
    inputLabel = _a.inputLabel,
    formHelperText = _a.formHelperText,
    selectProps = __rest(_a, ["formControl", "inputLabel", "formHelperText"]);
  var _b = fieldToSelect(selectProps),
    error = _b.error,
    formError = _b.formError,
    disabled = _b.disabled,
    selectFieldProps = __rest(_b, ["error", "formError", "disabled"]);
  var _c = formHelperText || {},
    formHelperTextChildren = _c.children,
    formHelperTextProps = __rest(_c, ["children"]);
  var shouldDisplayFormHelperText = error || formHelperTextChildren;
  return reactExports$1.createElement(FormControl$1, __assign({
    disabled: disabled,
    error: error
  }, formControl), reactExports$1.createElement(InputLabel$1, __assign({
    id: selectFieldProps.labelId
  }, inputLabel), selectFieldProps.label), reactExports$1.createElement(Select$3, __assign({}, selectFieldProps)), shouldDisplayFormHelperText && reactExports$1.createElement(FormHelperText$1, __assign({}, formHelperTextProps), error ? formError : formHelperTextChildren));
}
Select$1.displayName = 'FormikMaterialUISelect';

function getTextFieldUtilityClass(slot) {
  return generateUtilityClass('MuiTextField', slot);
}
generateUtilityClasses('MuiTextField', ['root']);

const _excluded$m = ["autoComplete", "autoFocus", "children", "className", "color", "defaultValue", "disabled", "error", "FormHelperTextProps", "fullWidth", "helperText", "id", "InputLabelProps", "inputProps", "InputProps", "inputRef", "label", "maxRows", "minRows", "multiline", "name", "onBlur", "onChange", "onClick", "onFocus", "placeholder", "required", "rows", "select", "SelectProps", "type", "value", "variant"];
const variantComponent = {
  standard: Input$3,
  filled: FilledInput$1,
  outlined: OutlinedInput$1
};
const useUtilityClasses$k = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getTextFieldUtilityClass, classes);
};
const TextFieldRoot = styled$1(FormControl$1, {
  name: 'MuiTextField',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({});

/**
 * The `TextField` is a convenience wrapper for the most common cases (80%).
 * It cannot be all things to all people, otherwise the API would grow out of control.
 *
 * ## Advanced Configuration
 *
 * It's important to understand that the text field is a simple abstraction
 * on top of the following components:
 *
 * - [FormControl](/material-ui/api/form-control/)
 * - [InputLabel](/material-ui/api/input-label/)
 * - [FilledInput](/material-ui/api/filled-input/)
 * - [OutlinedInput](/material-ui/api/outlined-input/)
 * - [Input](/material-ui/api/input/)
 * - [FormHelperText](/material-ui/api/form-helper-text/)
 *
 * If you wish to alter the props applied to the `input` element, you can do so as follows:
 *
 * ```jsx
 * const inputProps = {
 *   step: 300,
 * };
 *
 * return <TextField id="time" type="time" inputProps={inputProps} />;
 * ```
 *
 * For advanced cases, please look at the source of TextField by clicking on the
 * "Edit this page" button above. Consider either:
 *
 * - using the upper case props for passing values directly to the components
 * - using the underlying components directly as shown in the demos
 */
const TextField$1 = /*#__PURE__*/reactExports$1.forwardRef(function TextField(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiTextField'
  });
  const {
      autoComplete,
      autoFocus = false,
      children,
      className,
      color = 'primary',
      defaultValue,
      disabled = false,
      error = false,
      FormHelperTextProps,
      fullWidth = false,
      helperText,
      id: idOverride,
      InputLabelProps,
      inputProps,
      InputProps,
      inputRef,
      label,
      maxRows,
      minRows,
      multiline = false,
      name,
      onBlur,
      onChange,
      onClick,
      onFocus,
      placeholder,
      required = false,
      rows,
      select = false,
      SelectProps,
      type,
      value,
      variant = 'outlined'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$m);
  const ownerState = _extends({}, props, {
    autoFocus,
    color,
    disabled,
    error,
    fullWidth,
    multiline,
    required,
    select,
    variant
  });
  const classes = useUtilityClasses$k(ownerState);
  {
    if (select && !children) {
      console.error('MUI: `children` must be passed when using the `TextField` component with `select`.');
    }
  }
  const InputMore = {};
  if (variant === 'outlined') {
    if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {
      InputMore.notched = InputLabelProps.shrink;
    }
    InputMore.label = label;
  }
  if (select) {
    // unset defaults from textbox inputs
    if (!SelectProps || !SelectProps.native) {
      InputMore.id = undefined;
    }
    InputMore['aria-describedby'] = undefined;
  }
  const id = useId(idOverride);
  const helperTextId = helperText && id ? `${id}-helper-text` : undefined;
  const inputLabelId = label && id ? `${id}-label` : undefined;
  const InputComponent = variantComponent[variant];
  const InputElement = /*#__PURE__*/jsxRuntimeExports.jsx(InputComponent, _extends({
    "aria-describedby": helperTextId,
    autoComplete: autoComplete,
    autoFocus: autoFocus,
    defaultValue: defaultValue,
    fullWidth: fullWidth,
    multiline: multiline,
    name: name,
    rows: rows,
    maxRows: maxRows,
    minRows: minRows,
    type: type,
    value: value,
    id: id,
    inputRef: inputRef,
    onBlur: onBlur,
    onChange: onChange,
    onFocus: onFocus,
    onClick: onClick,
    placeholder: placeholder,
    inputProps: inputProps
  }, InputMore, InputProps));
  return /*#__PURE__*/jsxRuntimeExports.jsxs(TextFieldRoot, _extends({
    className: clsx(classes.root, className),
    disabled: disabled,
    error: error,
    fullWidth: fullWidth,
    ref: ref,
    required: required,
    color: color,
    variant: variant,
    ownerState: ownerState
  }, other, {
    children: [label != null && label !== '' && /*#__PURE__*/jsxRuntimeExports.jsx(InputLabel$1, _extends({
      htmlFor: id,
      id: inputLabelId
    }, InputLabelProps, {
      children: label
    })), select ? /*#__PURE__*/jsxRuntimeExports.jsx(Select$3, _extends({
      "aria-describedby": helperTextId,
      id: id,
      labelId: inputLabelId,
      value: value,
      input: InputElement
    }, SelectProps, {
      children: children
    })) : InputElement, helperText && /*#__PURE__*/jsxRuntimeExports.jsx(FormHelperText$1, _extends({
      id: helperTextId
    }, FormHelperTextProps, {
      children: helperText
    }))]
  }));
});
TextField$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: PropTypes.string,
  /**
   * If `true`, the `input` element is focused during the first mount.
   * @default false
   */
  autoFocus: PropTypes.bool,
  /**
   * @ignore
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: PropTypes.any,
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the label is displayed in an error state.
   * @default false
   */
  error: PropTypes.bool,
  /**
   * Props applied to the [`FormHelperText`](/material-ui/api/form-helper-text/) element.
   */
  FormHelperTextProps: PropTypes.object,
  /**
   * If `true`, the input will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * The helper text content.
   */
  helperText: PropTypes.node,
  /**
   * The id of the `input` element.
   * Use this prop to make `label` and `helperText` accessible for screen readers.
   */
  id: PropTypes.string,
  /**
   * Props applied to the [`InputLabel`](/material-ui/api/input-label/) element.
   * Pointer events like `onClick` are enabled if and only if `shrink` is `true`.
   */
  InputLabelProps: PropTypes.object,
  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: PropTypes.object,
  /**
   * Props applied to the Input element.
   * It will be a [`FilledInput`](/material-ui/api/filled-input/),
   * [`OutlinedInput`](/material-ui/api/outlined-input/) or [`Input`](/material-ui/api/input/)
   * component depending on the `variant` prop value.
   */
  InputProps: PropTypes.object,
  /**
   * Pass a ref to the `input` element.
   */
  inputRef: refType$1,
  /**
   * The label content.
   */
  label: PropTypes.node,
  /**
   * If `dense` or `normal`, will adjust vertical spacing of this and contained components.
   * @default 'none'
   */
  margin: PropTypes.oneOf(['dense', 'none', 'normal']),
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Minimum number of rows to display when multiline option is set to true.
   */
  minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * If `true`, a `textarea` element is rendered instead of an input.
   * @default false
   */
  multiline: PropTypes.bool,
  /**
   * Name attribute of the `input` element.
   */
  name: PropTypes.string,
  /**
   * @ignore
   */
  onBlur: PropTypes.func,
  /**
   * Callback fired when the value is changed.
   *
   * @param {object} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: PropTypes.func,
  /**
   * @ignore
   */
  onClick: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * The short hint displayed in the `input` before the user enters a value.
   */
  placeholder: PropTypes.string,
  /**
   * If `true`, the label is displayed as required and the `input` element is required.
   * @default false
   */
  required: PropTypes.bool,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Render a [`Select`](/material-ui/api/select/) element while passing the Input element to `Select` as `input` parameter.
   * If this option is set you must pass the options of the select as children.
   * @default false
   */
  select: PropTypes.bool,
  /**
   * Props applied to the [`Select`](/material-ui/api/select/) element.
   */
  SelectProps: PropTypes.object,
  /**
   * The size of the component.
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   */
  type: PropTypes /* @typescript-to-proptypes-ignore */.string,
  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: PropTypes.any,
  /**
   * The variant to use.
   * @default 'outlined'
   */
  variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} ;
var TextField$2 = TextField$1;

function fieldToTextField(_a) {
  var disabled = _a.disabled,
    _b = _a.field,
    fieldOnBlur = _b.onBlur,
    field = __rest(_b, ["onBlur"]),
    _c = _a.form,
    isSubmitting = _c.isSubmitting,
    touched = _c.touched,
    errors = _c.errors,
    onBlur = _a.onBlur,
    helperText = _a.helperText,
    props = __rest(_a, ["disabled", "field", "form", "onBlur", "helperText"]);
  var fieldError = getIn(errors, field.name);
  var showError = getIn(touched, field.name) && !!fieldError;
  return __assign(__assign({
    error: showError,
    helperText: showError ? fieldError : helperText,
    disabled: disabled !== null && disabled !== void 0 ? disabled : isSubmitting,
    onBlur: onBlur !== null && onBlur !== void 0 ? onBlur : function (e) {
      fieldOnBlur(e !== null && e !== void 0 ? e : field.name);
    }
  }, field), props);
}
function TextField(_a) {
  var children = _a.children,
    props = __rest(_a, ["children"]);
  return reactExports$1.createElement(TextField$2, __assign({}, fieldToTextField(props)), children);
}
TextField.displayName = 'FormikMaterialUITextField';

// Determine if the toggle button value matches, or is contained in, the
// candidate group value.
function isValueSelected(value, candidate) {
  if (candidate === undefined || value === undefined) {
    return false;
  }
  if (Array.isArray(candidate)) {
    return candidate.indexOf(value) >= 0;
  }
  return value === candidate;
}

function getToggleButtonGroupUtilityClass(slot) {
  return generateUtilityClass('MuiToggleButtonGroup', slot);
}
const toggleButtonGroupClasses = generateUtilityClasses('MuiToggleButtonGroup', ['root', 'selected', 'vertical', 'disabled', 'grouped', 'groupedHorizontal', 'groupedVertical']);
var toggleButtonGroupClasses$1 = toggleButtonGroupClasses;

const _excluded$l = ["children", "className", "color", "disabled", "exclusive", "fullWidth", "onChange", "orientation", "size", "value"];
const useUtilityClasses$j = ownerState => {
  const {
    classes,
    orientation,
    fullWidth,
    disabled
  } = ownerState;
  const slots = {
    root: ['root', orientation === 'vertical' && 'vertical', fullWidth && 'fullWidth'],
    grouped: ['grouped', `grouped${capitalize(orientation)}`, disabled && 'disabled']
  };
  return composeClasses(slots, getToggleButtonGroupUtilityClass, classes);
};
const ToggleButtonGroupRoot = styled$1('div', {
  name: 'MuiToggleButtonGroup',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${toggleButtonGroupClasses$1.grouped}`]: styles.grouped
    }, {
      [`& .${toggleButtonGroupClasses$1.grouped}`]: styles[`grouped${capitalize(ownerState.orientation)}`]
    }, styles.root, ownerState.orientation === 'vertical' && styles.vertical, ownerState.fullWidth && styles.fullWidth];
  }
})(({
  ownerState,
  theme
}) => _extends({
  display: 'inline-flex',
  borderRadius: (theme.vars || theme).shape.borderRadius
}, ownerState.orientation === 'vertical' && {
  flexDirection: 'column'
}, ownerState.fullWidth && {
  width: '100%'
}, {
  [`& .${toggleButtonGroupClasses$1.grouped}`]: _extends({}, ownerState.orientation === 'horizontal' ? {
    '&:not(:first-of-type)': {
      marginLeft: -1,
      borderLeft: '1px solid transparent',
      borderTopLeftRadius: 0,
      borderBottomLeftRadius: 0
    },
    '&:not(:last-of-type)': {
      borderTopRightRadius: 0,
      borderBottomRightRadius: 0
    },
    [`&.${toggleButtonGroupClasses$1.selected} + .${toggleButtonGroupClasses$1.grouped}.${toggleButtonGroupClasses$1.selected}`]: {
      borderLeft: 0,
      marginLeft: 0
    }
  } : {
    '&:not(:first-of-type)': {
      marginTop: -1,
      borderTop: '1px solid transparent',
      borderTopLeftRadius: 0,
      borderTopRightRadius: 0
    },
    '&:not(:last-of-type)': {
      borderBottomLeftRadius: 0,
      borderBottomRightRadius: 0
    },
    [`&.${toggleButtonGroupClasses$1.selected} + .${toggleButtonGroupClasses$1.grouped}.${toggleButtonGroupClasses$1.selected}`]: {
      borderTop: 0,
      marginTop: 0
    }
  })
}));
const ToggleButtonGroup$1 = /*#__PURE__*/reactExports$1.forwardRef(function ToggleButtonGroup(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiToggleButtonGroup'
  });
  const {
      children,
      className,
      color = 'standard',
      disabled = false,
      exclusive = false,
      fullWidth = false,
      onChange,
      orientation = 'horizontal',
      size = 'medium',
      value
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$l);
  const ownerState = _extends({}, props, {
    disabled,
    fullWidth,
    orientation,
    size
  });
  const classes = useUtilityClasses$j(ownerState);
  const handleChange = (event, buttonValue) => {
    if (!onChange) {
      return;
    }
    const index = value && value.indexOf(buttonValue);
    let newValue;
    if (value && index >= 0) {
      newValue = value.slice();
      newValue.splice(index, 1);
    } else {
      newValue = value ? value.concat(buttonValue) : [buttonValue];
    }
    onChange(event, newValue);
  };
  const handleExclusiveChange = (event, buttonValue) => {
    if (!onChange) {
      return;
    }
    onChange(event, value === buttonValue ? null : buttonValue);
  };
  return /*#__PURE__*/jsxRuntimeExports.jsx(ToggleButtonGroupRoot, _extends({
    role: "group",
    className: clsx(classes.root, className),
    ref: ref,
    ownerState: ownerState
  }, other, {
    children: reactExports$1.Children.map(children, child => {
      if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
        return null;
      }
      {
        if (reactIsExports$1.isFragment(child)) {
          console.error(["MUI: The ToggleButtonGroup component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
        }
      }
      return /*#__PURE__*/reactExports$1.cloneElement(child, {
        className: clsx(classes.grouped, child.props.className),
        onChange: exclusive ? handleExclusiveChange : handleChange,
        selected: child.props.selected === undefined ? isValueSelected(child.props.value, value) : child.props.selected,
        size: child.props.size || size,
        fullWidth,
        color: child.props.color || color,
        disabled: child.props.disabled || disabled
      });
    })
  }));
});
ToggleButtonGroup$1.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the button when it is selected.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'standard'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['standard', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * If `true`, the component is disabled. This implies that all ToggleButton children will be disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, only allow one of the child ToggleButton values to be selected.
   * @default false
   */
  exclusive: PropTypes.bool,
  /**
   * If `true`, the button group will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * Callback fired when the value changes.
   *
   * @param {React.MouseEvent<HTMLElement>} event The event source of the callback.
   * @param {any} value of the selected buttons. When `exclusive` is true
   * this is a single value; when false an array of selected values. If no value
   * is selected and `exclusive` is true the value is null; when false an empty array.
   */
  onChange: PropTypes.func,
  /**
   * The component orientation (layout flow direction).
   * @default 'horizontal'
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']),
  /**
   * The size of the component.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The currently selected value within the group or an array of selected
   * values when `exclusive` is false.
   *
   * The value must have reference equality with the option in order to be selected.
   */
  value: PropTypes.any
} ;
var ToggleButtonGroup$2 = ToggleButtonGroup$1;

function fieldToToggleButtonGroup(_a) {
  var _b = _a.field;
  _b.onChange;
  var fieldOnBlur = _b.onBlur,
    field = __rest(_b, ["onChange", "onBlur"]),
    type = _a.type,
    onChange = _a.onChange,
    onBlur = _a.onBlur,
    form = _a.form,
    props = __rest(_a, ["field", "type", "onChange", "onBlur", "form"]);
  {
    warning$1(type === 'checkbox', "property type=checkbox is missing from field " + field.name + ", this can caused unexpected behaviour");
    if (!props.exclusive) {
      warning$1(Array.isArray(field.value), "value for " + field.name + " is not an array, this can caused unexpected behaviour");
    }
  }
  return __assign(__assign({
    onBlur: onBlur !== null && onBlur !== void 0 ? onBlur : function () {
      fieldOnBlur(field.name);
    },
    onChange: onChange !== null && onChange !== void 0 ? onChange : function (_event, newValue) {
      form.setFieldValue(field.name, newValue);
    }
  }, field), props);
}
function ToggleButtonGroup(props) {
  return reactExports$1.createElement(ToggleButtonGroup$2, __assign({}, fieldToToggleButtonGroup(props)));
}
ToggleButtonGroup.displayName = 'FormikMaterialUIToggleButtonGroup';

function Input$1({
  hint,
  inputProps,
  ...rest
}) {
  const {
    name,
    type,
    maxLength
  } = useHtmlInput(rest);
  return /*#__PURE__*/React.createElement(Field, {
    name: name,
    fullWidth: true,
    margin: "dense",
    component: TextField,
    helperText: hint,
    inputProps: {
      maxLength,
      ...inputProps
    },
    ...rest,
    type: type
  });
}
Input$1.propTypes = {
  name: PropTypes.string,
  hint: PropTypes.string,
  inputProps: PropTypes.object
};

function HelperText({
  name,
  hint
}) {
  const {
      errors,
      touched
    } = useFormikContext(),
    error = getIn(errors, name),
    showError = !!error && !!getIn(touched, name);
  if (showError) {
    hint = error;
  }
  if (!hint) {
    return null;
  }
  return /*#__PURE__*/React.createElement(FormHelperText$1, {
    error: !!showError
  }, hint);
}
HelperText.propTypes = {
  name: PropTypes.string,
  hint: PropTypes.string
};

function Input({
  label,
  ...props
}) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Field, {
    component: CheckboxWithLabel,
    Label: {
      label
    },
    ...props,
    type: "checkbox"
  }), /*#__PURE__*/React.createElement(HelperText, {
    name: props.name,
    hint: props.hint
  }));
}
Input.propTypes = {
  name: PropTypes.string,
  label: PropTypes.string,
  hint: PropTypes.string
};

function DateTime({
  InputLabelProps: overrides,
  ...rest
}) {
  const InputLabelProps = {
    shrink: true,
    ...overrides
  };
  return /*#__PURE__*/React.createElement(Input$1, {
    InputLabelProps: InputLabelProps,
    ...rest
  });
}

function _defineProperty$1(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 _toPrimitive(input, hint) {
  if (typeof input !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (typeof 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 key === "symbol" ? key : String(key);
}

function isImage(file) {
  if (file.type.split("/")[0] === "image") {
    return true;
  }
}
const bytesInKiloB = 1024; // 2 ** 10;
const bytesInMegaB = 1048576; // bytesInKiloB ** 2;

function convertBytesToMbsOrKbs(filesize) {
  let size = "";
  if (filesize >= bytesInMegaB) {
    size = filesize / bytesInMegaB + " megabytes";
  } else if (filesize >= bytesInKiloB) {
    size = filesize / bytesInKiloB + " kilobytes";
  } else {
    size = filesize + " bytes";
  }
  return size;
}
async function createFileFromUrl(url) {
  const response = await fetch(url);
  const data = await response?.blob();
  const metadata = {
    type: data.type
  };
  const filename = url.replace(/\?.+/, "").split("/").pop();
  return new File([data], filename, metadata);
}
function readFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = event => {
      resolve(event?.target?.result);
    };
    reader.onerror = event => {
      reader.abort();
      reject(event);
    };
    reader.readAsDataURL(file);
  });
}

var AttachFile = {};

var createSvgIcon = {};

var require$$0 = /*@__PURE__*/getAugmentedNamespace(muiMaterialUtils);

var hasRequiredCreateSvgIcon;

function requireCreateSvgIcon () {
	if (hasRequiredCreateSvgIcon) return createSvgIcon;
	hasRequiredCreateSvgIcon = 1;
	(function (exports) {

		Object.defineProperty(exports, "__esModule", {
		  value: true
		});
		Object.defineProperty(exports, "default", {
		  enumerable: true,
		  get: function () {
		    return _utils.createSvgIcon;
		  }
		});
		var _utils = require$$0; 
	} (createSvgIcon));
	return createSvgIcon;
}

var _interopRequireDefault$7 = interopRequireDefaultExports;
Object.defineProperty(AttachFile, "__esModule", {
  value: true
});
var default_1$7 = AttachFile.default = void 0;
var _createSvgIcon$7 = _interopRequireDefault$7(requireCreateSvgIcon());
var _jsxRuntime$7 = jsxRuntimeExports;
var _default$8 = (0, _createSvgIcon$7.default)( /*#__PURE__*/(0, _jsxRuntime$7.jsx)("path", {
  d: "M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6h-1.5z"
}), 'AttachFile');
default_1$7 = AttachFile.default = _default$8;

var CloudUpload = {};

var _interopRequireDefault$6 = interopRequireDefaultExports;
Object.defineProperty(CloudUpload, "__esModule", {
  value: true
});
var default_1$6 = CloudUpload.default = void 0;
var _createSvgIcon$6 = _interopRequireDefault$6(requireCreateSvgIcon());
var _jsxRuntime$6 = jsxRuntimeExports;
var _default$7 = (0, _createSvgIcon$6.default)( /*#__PURE__*/(0, _jsxRuntime$6.jsx)("path", {
  d: "M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"
}), 'CloudUpload');
default_1$6 = CloudUpload.default = _default$7;

function getSnackbarContentUtilityClass(slot) {
  return generateUtilityClass('MuiSnackbarContent', slot);
}
generateUtilityClasses('MuiSnackbarContent', ['root', 'message', 'action']);

const _excluded$k = ["action", "className", "message", "role"];
const useUtilityClasses$i = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root'],
    action: ['action'],
    message: ['message']
  };
  return composeClasses(slots, getSnackbarContentUtilityClass, classes);
};
const SnackbarContentRoot = styled$1(Paper$1, {
  name: 'MuiSnackbarContent',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => {
  const emphasis = theme.palette.mode === 'light' ? 0.8 : 0.98;
  const backgroundColor = emphasize(theme.palette.background.default, emphasis);
  return _extends({}, theme.typography.body2, {
    color: theme.vars ? theme.vars.palette.SnackbarContent.color : theme.palette.getContrastText(backgroundColor),
    backgroundColor: theme.vars ? theme.vars.palette.SnackbarContent.bg : backgroundColor,
    display: 'flex',
    alignItems: 'center',
    flexWrap: 'wrap',
    padding: '6px 16px',
    borderRadius: (theme.vars || theme).shape.borderRadius,
    flexGrow: 1,
    [theme.breakpoints.up('sm')]: {
      flexGrow: 'initial',
      minWidth: 288
    }
  });
});
const SnackbarContentMessage = styled$1('div', {
  name: 'MuiSnackbarContent',
  slot: 'Message',
  overridesResolver: (props, styles) => styles.message
})({
  padding: '8px 0'
});
const SnackbarContentAction = styled$1('div', {
  name: 'MuiSnackbarContent',
  slot: 'Action',
  overridesResolver: (props, styles) => styles.action
})({
  display: 'flex',
  alignItems: 'center',
  marginLeft: 'auto',
  paddingLeft: 16,
  marginRight: -8
});
const SnackbarContent = /*#__PURE__*/reactExports$1.forwardRef(function SnackbarContent(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiSnackbarContent'
  });
  const {
      action,
      className,
      message,
      role = 'alert'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$k);
  const ownerState = props;
  const classes = useUtilityClasses$i(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(SnackbarContentRoot, _extends({
    role: role,
    square: true,
    elevation: 6,
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsx(SnackbarContentMessage, {
      className: classes.message,
      ownerState: ownerState,
      children: message
    }), action ? /*#__PURE__*/jsxRuntimeExports.jsx(SnackbarContentAction, {
      className: classes.action,
      ownerState: ownerState,
      children: action
    }) : null]
  }));
});
SnackbarContent.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display. It renders after the message, at the end of the snackbar.
   */
  action: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The message to display.
   */
  message: PropTypes.node,
  /**
   * The ARIA role attribute of the element.
   * @default 'alert'
   */
  role: PropTypes /* @typescript-to-proptypes-ignore */.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var SnackbarContent$1 = SnackbarContent;

function getSnackbarUtilityClass(slot) {
  return generateUtilityClass('MuiSnackbar', slot);
}
generateUtilityClasses('MuiSnackbar', ['root', 'anchorOriginTopCenter', 'anchorOriginBottomCenter', 'anchorOriginTopRight', 'anchorOriginBottomRight', 'anchorOriginTopLeft', 'anchorOriginBottomLeft']);

const _excluded$j = ["onEnter", "onExited"],
  _excluded2 = ["action", "anchorOrigin", "autoHideDuration", "children", "className", "ClickAwayListenerProps", "ContentProps", "disableWindowBlurListener", "message", "onBlur", "onClose", "onFocus", "onMouseEnter", "onMouseLeave", "open", "resumeHideDuration", "TransitionComponent", "transitionDuration", "TransitionProps"];
const useUtilityClasses$h = ownerState => {
  const {
    classes,
    anchorOrigin
  } = ownerState;
  const slots = {
    root: ['root', `anchorOrigin${capitalize(anchorOrigin.vertical)}${capitalize(anchorOrigin.horizontal)}`]
  };
  return composeClasses(slots, getSnackbarUtilityClass, classes);
};
const SnackbarRoot = styled$1('div', {
  name: 'MuiSnackbar',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`anchorOrigin${capitalize(ownerState.anchorOrigin.vertical)}${capitalize(ownerState.anchorOrigin.horizontal)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  const center = {
    left: '50%',
    right: 'auto',
    transform: 'translateX(-50%)'
  };
  return _extends({
    zIndex: (theme.vars || theme).zIndex.snackbar,
    position: 'fixed',
    display: 'flex',
    left: 8,
    right: 8,
    justifyContent: 'center',
    alignItems: 'center'
  }, ownerState.anchorOrigin.vertical === 'top' ? {
    top: 8
  } : {
    bottom: 8
  }, ownerState.anchorOrigin.horizontal === 'left' && {
    justifyContent: 'flex-start'
  }, ownerState.anchorOrigin.horizontal === 'right' && {
    justifyContent: 'flex-end'
  }, {
    [theme.breakpoints.up('sm')]: _extends({}, ownerState.anchorOrigin.vertical === 'top' ? {
      top: 24
    } : {
      bottom: 24
    }, ownerState.anchorOrigin.horizontal === 'center' && center, ownerState.anchorOrigin.horizontal === 'left' && {
      left: 24,
      right: 'auto'
    }, ownerState.anchorOrigin.horizontal === 'right' && {
      right: 24,
      left: 'auto'
    })
  });
});
const Snackbar = /*#__PURE__*/reactExports$1.forwardRef(function Snackbar(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiSnackbar'
  });
  const theme = useTheme();
  const defaultTransitionDuration = {
    enter: theme.transitions.duration.enteringScreen,
    exit: theme.transitions.duration.leavingScreen
  };
  const {
      action,
      anchorOrigin: {
        vertical,
        horizontal
      } = {
        vertical: 'bottom',
        horizontal: 'left'
      },
      autoHideDuration = null,
      children,
      className,
      ClickAwayListenerProps,
      ContentProps,
      disableWindowBlurListener = false,
      message,
      open,
      TransitionComponent = Grow$1,
      transitionDuration = defaultTransitionDuration,
      TransitionProps: {
        onEnter,
        onExited
      } = {}
    } = props,
    TransitionProps = _objectWithoutPropertiesLoose$2(props.TransitionProps, _excluded$j),
    other = _objectWithoutPropertiesLoose$2(props, _excluded2);
  const ownerState = _extends({}, props, {
    anchorOrigin: {
      vertical,
      horizontal
    },
    autoHideDuration,
    disableWindowBlurListener,
    TransitionComponent,
    transitionDuration
  });
  const classes = useUtilityClasses$h(ownerState);
  const {
    getRootProps,
    onClickAway
  } = useSnackbar(_extends({}, ownerState));
  const [exited, setExited] = reactExports$1.useState(true);
  const rootProps = useSlotProps({
    elementType: SnackbarRoot,
    getSlotProps: getRootProps,
    externalForwardedProps: other,
    ownerState,
    additionalProps: {
      ref
    },
    className: [classes.root, className]
  });
  const handleExited = node => {
    setExited(true);
    if (onExited) {
      onExited(node);
    }
  };
  const handleEnter = (node, isAppearing) => {
    setExited(false);
    if (onEnter) {
      onEnter(node, isAppearing);
    }
  };

  // So we only render active snackbars.
  if (!open && exited) {
    return null;
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(ClickAwayListener, _extends({
    onClickAway: onClickAway
  }, ClickAwayListenerProps, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(SnackbarRoot, _extends({}, rootProps, {
      children: /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
        appear: true,
        in: open,
        timeout: transitionDuration,
        direction: vertical === 'top' ? 'down' : 'up',
        onEnter: handleEnter,
        onExited: handleExited
      }, TransitionProps, {
        children: children || /*#__PURE__*/jsxRuntimeExports.jsx(SnackbarContent$1, _extends({
          message: message,
          action: action
        }, ContentProps))
      }))
    }))
  }));
});
Snackbar.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display. It renders after the message, at the end of the snackbar.
   */
  action: PropTypes.node,
  /**
   * The anchor of the `Snackbar`.
   * On smaller screens, the component grows to occupy all the available width,
   * the horizontal alignment is ignored.
   * @default { vertical: 'bottom', horizontal: 'left' }
   */
  anchorOrigin: PropTypes.shape({
    horizontal: PropTypes.oneOf(['center', 'left', 'right']).isRequired,
    vertical: PropTypes.oneOf(['bottom', 'top']).isRequired
  }),
  /**
   * The number of milliseconds to wait before automatically calling the
   * `onClose` function. `onClose` should then set the state of the `open`
   * prop to hide the Snackbar. This behavior is disabled by default with
   * the `null` value.
   * @default null
   */
  autoHideDuration: PropTypes.number,
  /**
   * Replace the `SnackbarContent` component.
   */
  children: PropTypes.element,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Props applied to the `ClickAwayListener` element.
   */
  ClickAwayListenerProps: PropTypes.object,
  /**
   * Props applied to the [`SnackbarContent`](/material-ui/api/snackbar-content/) element.
   */
  ContentProps: PropTypes.object,
  /**
   * If `true`, the `autoHideDuration` timer will expire even if the window is not focused.
   * @default false
   */
  disableWindowBlurListener: PropTypes.bool,
  /**
   * When displaying multiple consecutive Snackbars from a parent rendering a single
   * <Snackbar/>, add the key prop to ensure independent treatment of each message.
   * e.g. <Snackbar key={message} />, otherwise, the message may update-in-place and
   * features such as autoHideDuration may be canceled.
   */
  key: () => null,
  /**
   * The message to display.
   */
  message: PropTypes.node,
  /**
   * @ignore
   */
  onBlur: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   * Typically `onClose` is used to set state in the parent component,
   * which is used to control the `Snackbar` `open` prop.
   * The `reason` parameter can optionally be used to control the response to `onClose`,
   * for example ignoring `clickaway`.
   *
   * @param {React.SyntheticEvent<any> | Event} event The event source of the callback.
   * @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`, or `"escapeKeyDown"`.
   */
  onClose: PropTypes.func,
  /**
   * @ignore
   */
  onFocus: PropTypes.func,
  /**
   * @ignore
   */
  onMouseEnter: PropTypes.func,
  /**
   * @ignore
   */
  onMouseLeave: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool,
  /**
   * The number of milliseconds to wait before dismissing after user interaction.
   * If `autoHideDuration` prop isn't specified, it does nothing.
   * If `autoHideDuration` prop is specified but `resumeHideDuration` isn't,
   * we default to `autoHideDuration / 2` ms.
   */
  resumeHideDuration: PropTypes.number,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The component used for the transition.
   * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   * @default Grow
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default {
   *   enter: theme.transitions.duration.enteringScreen,
   *   exit: theme.transitions.duration.leavingScreen,
   * }
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })]),
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition/) component.
   * @default {}
   */
  TransitionProps: PropTypes.object
} ;
var Snackbar$1 = Snackbar;

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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
    };
  }
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o),
    r,
    ar = [],
    e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  } catch (error) {
    e = {
      error: error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"])) m.call(i);
    } finally {
      if (e) throw e.error;
    }
  }
  return ar;
}

/** @deprecated */
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
  return ar;
}

var COMMON_MIME_TYPES = new Map([['avi', 'video/avi'], ['gif', 'image/gif'], ['ico', 'image/x-icon'], ['jpeg', 'image/jpeg'], ['jpg', 'image/jpeg'], ['mkv', 'video/x-matroska'], ['mov', 'video/quicktime'], ['mp4', 'video/mp4'], ['pdf', 'application/pdf'], ['png', 'image/png'], ['zip', 'application/zip'], ['doc', 'application/msword'], ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']]);
function toFileWithPath(file, path) {
  var f = withMimeType(file);
  if (typeof f.path !== 'string') {
    // on electron, path is already set to the absolute path
    var webkitRelativePath = file.webkitRelativePath;
    Object.defineProperty(f, 'path', {
      value: typeof path === 'string' ? path
      // If <input webkitdirectory> is set,
      // the File will have a {webkitRelativePath} property
      // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
      : typeof webkitRelativePath === 'string' && webkitRelativePath.length > 0 ? webkitRelativePath : file.name,
      writable: false,
      configurable: false,
      enumerable: true
    });
  }
  return f;
}
function withMimeType(file) {
  var name = file.name;
  var hasExtension = name && name.lastIndexOf('.') !== -1;
  if (hasExtension && !file.type) {
    var ext = name.split('.').pop().toLowerCase();
    var type = COMMON_MIME_TYPES.get(ext);
    if (type) {
      Object.defineProperty(file, 'type', {
        value: type,
        writable: false,
        configurable: false,
        enumerable: true
      });
    }
  }
  return file;
}

var FILES_TO_IGNORE = [
// Thumbnail cache files for macOS and Windows
'.DS_Store', 'Thumbs.db' // Windows
];
/**
 * Convert a DragEvent's DataTrasfer object to a list of File objects
 * NOTE: If some of the items are folders,
 * everything will be flattened and placed in the same list but the paths will be kept as a {path} property.
 * @param evt
 */
function fromEvent(evt) {
  return __awaiter(this, void 0, void 0, function () {
    return __generator(this, function (_a) {
      return [2 /*return*/, isDragEvt(evt) && evt.dataTransfer ? getDataTransferFiles(evt.dataTransfer, evt.type) : getInputFiles(evt)];
    });
  });
}
function isDragEvt(value) {
  return !!value.dataTransfer;
}
function getInputFiles(evt) {
  var files = isInput(evt.target) ? evt.target.files ? fromList(evt.target.files) : [] : [];
  return files.map(function (file) {
    return toFileWithPath(file);
  });
}
function isInput(value) {
  return value !== null;
}
function getDataTransferFiles(dt, type) {
  return __awaiter(this, void 0, void 0, function () {
    var items, files;
    return __generator(this, function (_a) {
      switch (_a.label) {
        case 0:
          if (!dt.items) return [3 /*break*/, 2];
          items = fromList(dt.items).filter(function (item) {
            return item.kind === 'file';
          });
          // According to https://html.spec.whatwg.org/multipage/dnd.html#dndevents,
          // only 'dragstart' and 'drop' has access to the data (source node)
          if (type !== 'drop') {
            return [2 /*return*/, items];
          }
          return [4 /*yield*/, Promise.all(items.map(toFilePromises))];
        case 1:
          files = _a.sent();
          return [2 /*return*/, noIgnoredFiles(flatten(files))];
        case 2:
          return [2 /*return*/, noIgnoredFiles(fromList(dt.files).map(function (file) {
            return toFileWithPath(file);
          }))];
      }
    });
  });
}
function noIgnoredFiles(files) {
  return files.filter(function (file) {
    return FILES_TO_IGNORE.indexOf(file.name) === -1;
  });
}
// IE11 does not support Array.from()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList
function fromList(items) {
  var files = [];
  // tslint:disable: prefer-for-of
  for (var i = 0; i < items.length; i++) {
    var file = items[i];
    files.push(file);
  }
  return files;
}
// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem
function toFilePromises(item) {
  if (typeof item.webkitGetAsEntry !== 'function') {
    return fromDataTransferItem(item);
  }
  var entry = item.webkitGetAsEntry();
  // Safari supports dropping an image node from a different window and can be retrieved using
  // the DataTransferItem.getAsFile() API
  // NOTE: FileSystemEntry.file() throws if trying to get the file
  if (entry && entry.isDirectory) {
    return fromDirEntry(entry);
  }
  return fromDataTransferItem(item);
}
function flatten(items) {
  return items.reduce(function (acc, files) {
    return __spread(acc, Array.isArray(files) ? flatten(files) : [files]);
  }, []);
}
function fromDataTransferItem(item) {
  var file = item.getAsFile();
  if (!file) {
    return Promise.reject(item + " is not a File");
  }
  var fwp = toFileWithPath(file);
  return Promise.resolve(fwp);
}
// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry
function fromEntry(entry) {
  return __awaiter(this, void 0, void 0, function () {
    return __generator(this, function (_a) {
      return [2 /*return*/, entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry)];
    });
  });
}
// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry
function fromDirEntry(entry) {
  var reader = entry.createReader();
  return new Promise(function (resolve, reject) {
    var entries = [];
    function readEntries() {
      var _this = this;
      // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry/createReader
      // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries
      reader.readEntries(function (batch) {
        return __awaiter(_this, void 0, void 0, function () {
          var files, err_1, items;
          return __generator(this, function (_a) {
            switch (_a.label) {
              case 0:
                if (!!batch.length) return [3 /*break*/, 5];
                _a.label = 1;
              case 1:
                _a.trys.push([1, 3,, 4]);
                return [4 /*yield*/, Promise.all(entries)];
              case 2:
                files = _a.sent();
                resolve(files);
                return [3 /*break*/, 4];
              case 3:
                err_1 = _a.sent();
                reject(err_1);
                return [3 /*break*/, 4];
              case 4:
                return [3 /*break*/, 6];
              case 5:
                items = Promise.all(batch.map(fromEntry));
                entries.push(items);
                // Continue reading
                readEntries();
                _a.label = 6;
              case 6:
                return [2 /*return*/];
            }
          });
        });
      }, function (err) {
        reject(err);
      });
    }
    readEntries();
  });
}
// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry
function fromFileEntry(entry) {
  return __awaiter(this, void 0, void 0, function () {
    return __generator(this, function (_a) {
      return [2 /*return*/, new Promise(function (resolve, reject) {
        entry.file(function (file) {
          var fwp = toFileWithPath(file, entry.fullPath);
          resolve(fwp);
        }, function (err) {
          reject(err);
        });
      })];
    });
  });
}

var _default$6 = function (file, acceptedFiles) {
  if (file && acceptedFiles) {
    var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(',');
    var fileName = file.name || '';
    var mimeType = (file.type || '').toLowerCase();
    var baseMimeType = mimeType.replace(/\/.*$/, '');
    return acceptedFilesArray.some(function (type) {
      var validType = type.trim().toLowerCase();
      if (validType.charAt(0) === '.') {
        return fileName.toLowerCase().endsWith(validType);
      } else if (validType.endsWith('/*')) {
        // This is something like a image/* mime type
        return baseMimeType === validType.replace(/\/.*$/, '');
      }
      return mimeType === validType;
    });
  }
  return true;
};

// that MIME type will always be accepted

function fileAccepted(file, accept) {
  return file.type === 'application/x-moz-file' || _default$6(file, accept);
}
function fileMatchSize(file, minSize, maxSize) {
  if (isDefined(file.size)) {
    if (isDefined(minSize) && isDefined(maxSize)) return file.size >= minSize && file.size <= maxSize;else if (isDefined(minSize)) return file.size >= minSize;else if (isDefined(maxSize)) return file.size <= maxSize;
  }
  return true;
}
function isDefined(value) {
  return value !== undefined && value !== null;
}
function allFilesAccepted(_ref) {
  var files = _ref.files,
    accept = _ref.accept,
    minSize = _ref.minSize,
    maxSize = _ref.maxSize,
    multiple = _ref.multiple;
  if (!multiple && files.length > 1) {
    return false;
  }
  return files.every(function (file) {
    return fileAccepted(file, accept) && fileMatchSize(file, minSize, maxSize);
  });
} // React's synthetic events has event.isPropagationStopped,
// but to remain compatibility with other libs (Preact) fall back
// to check event.cancelBubble

function isPropagationStopped(event) {
  if (typeof event.isPropagationStopped === 'function') {
    return event.isPropagationStopped();
  } else if (typeof event.cancelBubble !== 'undefined') {
    return event.cancelBubble;
  }
  return false;
}
function isEvtWithFiles(event) {
  if (!event.dataTransfer) {
    return !!event.target && !!event.target.files;
  } // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types
  // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file

  return Array.prototype.some.call(event.dataTransfer.types, function (type) {
    return type === 'Files' || type === 'application/x-moz-file';
  });
}

function onDocumentDragOver(event) {
  event.preventDefault();
}
function isIe(userAgent) {
  return userAgent.indexOf('MSIE') !== -1 || userAgent.indexOf('Trident/') !== -1;
}
function isEdge(userAgent) {
  return userAgent.indexOf('Edge/') !== -1;
}
function isIeOrEdge() {
  var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.navigator.userAgent;
  return isIe(userAgent) || isEdge(userAgent);
}
/**
 * This is intended to be used to compose event handlers
 * They are executed in order until one of them calls `event.isPropagationStopped()`.
 * Note that the check is done on the first invoke too,
 * meaning that if propagation was stopped before invoking the fns,
 * no handlers will be executed.
 *
 * @param {Function} fns the event hanlder functions
 * @return {Function} the event handler to add to an element
 */

function composeEventHandlers() {
  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return function (event) {
    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }
    return fns.some(function (fn) {
      if (!isPropagationStopped(event) && fn) {
        fn.apply(void 0, [event].concat(args));
      }
      return isPropagationStopped(event);
    });
  };
}

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _arrayWithoutHoles(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 _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _iterableToArrayLimit(arr, i) {
  if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
    return;
  }
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;
  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }
  return _arr;
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function ownKeys(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(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys(source, true).forEach(function (key) {
        _defineProperty(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys(source).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(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(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;
}
/**
 * Convenience wrapper component for the `useDropzone` hook
 *
 * ```jsx
 * <Dropzone>
 *   {({getRootProps, getInputProps}) => (
 *     <div {...getRootProps()}>
 *       <input {...getInputProps()} />
 *       <p>Drag 'n' drop some files here, or click to select files</p>
 *     </div>
 *   )}
 * </Dropzone>
 * ```
 */

var Dropzone = reactExports$1.forwardRef(function (_ref, ref) {
  var children = _ref.children,
    params = _objectWithoutProperties(_ref, ["children"]);
  var _useDropzone = useDropzone(params),
    open = _useDropzone.open,
    props = _objectWithoutProperties(_useDropzone, ["open"]);
  reactExports$1.useImperativeHandle(ref, function () {
    return {
      open: open
    };
  }, [open]); // TODO: Figure out why react-styleguidist cannot create docs if we don't return a jsx element

  return React.createElement(reactExports$1.Fragment, null, children(_objectSpread({}, props, {
    open: open
  })));
});
Dropzone.displayName = 'Dropzone';
Dropzone.propTypes = {
  /**
   * Render function that exposes the dropzone state and prop getter fns
   *
   * @param {object} params
   * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render
   * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render
   * @param {Function} params.open Open the native file selection dialog
   * @param {boolean} params.isFocused Dropzone area is in focus
   * @param {boolean} params.isFileDialogActive File dialog is opened
   * @param {boolean} params.isDragActive Active drag is in progress
   * @param {boolean} params.isDragAccept Dragged files are accepted
   * @param {boolean} params.isDragReject Some dragged files are rejected
   * @param {File[]} params.draggedFiles Files in active drag
   * @param {File[]} params.acceptedFiles Accepted files
   * @param {File[]} params.rejectedFiles Rejected files
   */
  children: PropTypes.func,
  /**
   * Set accepted file types.
   * See https://github.com/okonet/attr-accept for more information.
   * Keep in mind that mime type determination is not reliable across platforms. CSV files,
   * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
   * Windows. In some cases there might not be a mime type set at all.
   * See: https://github.com/react-dropzone/react-dropzone/issues/276
   */
  accept: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  /**
   * Allow drag 'n' drop (or selection from the file dialog) of multiple files
   */
  multiple: PropTypes.bool,
  /**
   * If false, allow dropped items to take over the current browser window
   */
  preventDropOnDocument: PropTypes.bool,
  /**
   * If true, disables click to open the native file selection dialog
   */
  noClick: PropTypes.bool,
  /**
   * If true, disables SPACE/ENTER to open the native file selection dialog.
   * Note that it also stops tracking the focus state.
   */
  noKeyboard: PropTypes.bool,
  /**
   * If true, disables drag 'n' drop
   */
  noDrag: PropTypes.bool,
  /**
   * If true, stops drag event propagation to parents
   */
  noDragEventsBubbling: PropTypes.bool,
  /**
   * Minimum file size (in bytes)
   */
  minSize: PropTypes.number,
  /**
   * Maximum file size (in bytes)
   */
  maxSize: PropTypes.number,
  /**
   * Enable/disable the dropzone
   */
  disabled: PropTypes.bool,
  /**
   * Use this to provide a custom file aggregator
   *
   * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
   */
  getFilesFromEvent: PropTypes.func,
  /**
   * Cb for when closing the file dialog with no selection
   */
  onFileDialogCancel: PropTypes.func,
  /**
   * Cb for when the `dragenter` event occurs.
   *
   * @param {DragEvent} event
   */
  onDragEnter: PropTypes.func,
  /**
   * Cb for when the `dragleave` event occurs
   *
   * @param {DragEvent} event
   */
  onDragLeave: PropTypes.func,
  /**
   * Cb for when the `dragover` event occurs
   *
   * @param {DragEvent} event
   */
  onDragOver: PropTypes.func,
  /**
   * Cb for when the `drop` event occurs.
   * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
   *
   * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
   * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension.
   * If `multiple` is set to false and additional files are droppped,
   * all files besides the first will be rejected.
   * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
   *
   * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
   * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
   *
   * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.
   * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
   *
   * ```js
   * function onDrop(acceptedFiles) {
   *   const req = request.post('/upload')
   *   acceptedFiles.forEach(file => {
   *     req.attach(file.name, file)
   *   })
   *   req.end(callback)
   * }
   * ```
   *
   * @param {File[]} acceptedFiles
   * @param {File[]} rejectedFiles
   * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
   */
  onDrop: PropTypes.func,
  /**
   * Cb for when the `drop` event occurs.
   * Note that if no files are accepted, this callback is not invoked.
   *
   * @param {File[]} files
   * @param {(DragEvent|Event)} event
   */
  onDropAccepted: PropTypes.func,
  /**
   * Cb for when the `drop` event occurs.
   * Note that if no files are rejected, this callback is not invoked.
   *
   * @param {object[]} files
   * @param {(DragEvent|Event)} event
   */
  onDropRejected: PropTypes.func
};
/**
 * A function that is invoked for the `dragenter`,
 * `dragover` and `dragleave` events.
 * It is not invoked if the items are not files (such as link, text, etc.).
 *
 * @callback dragCb
 * @param {DragEvent} event
 */

/**
 * A function that is invoked for the `drop` or input change event.
 * It is not invoked if the items are not files (such as link, text, etc.).
 *
 * @callback dropCb
 * @param {File[]} acceptedFiles List of accepted files
 * @param {File[]} rejectedFiles List of rejected files
 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
 */

/**
 * A function that is invoked for the `drop` or input change event.
 * It is not invoked if the items are files (such as link, text, etc.).
 *
 * @callback dropAcceptedCb
 * @param {File[]} files List of accepted files that meet the given criteria
 * (`accept`, `multiple`, `minSize`, `maxSize`)
 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
 */

/**
 * A function that is invoked for the `drop` or input change event.
 *
 * @callback dropRejectedCb
 * @param {File[]} files List of rejected files that do not meet the given criteria
 * (`accept`, `multiple`, `minSize`, `maxSize`)
 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
 */

/**
 * A function that is used aggregate files,
 * in a asynchronous fashion, from drag or input change events.
 *
 * @callback getFilesFromEvent
 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
 * @returns {(File[]|Promise<File[]>)}
 */

/**
 * An object with the current dropzone state and some helper functions.
 *
 * @typedef {object} DropzoneState
 * @property {Function} getRootProps Returns the props you should apply to the root drop container you render
 * @property {Function} getInputProps Returns the props you should apply to hidden file input you render
 * @property {Function} open Open the native file selection dialog
 * @property {boolean} isFocused Dropzone area is in focus
 * @property {boolean} isFileDialogActive File dialog is opened
 * @property {boolean} isDragActive Active drag is in progress
 * @property {boolean} isDragAccept Dragged files are accepted
 * @property {boolean} isDragReject Some dragged files are rejected
 * @property {File[]} draggedFiles Files in active drag
 * @property {File[]} acceptedFiles Accepted files
 * @property {File[]} rejectedFiles Rejected files
 */

var initialState = {
  isFocused: false,
  isFileDialogActive: false,
  isDragActive: false,
  isDragAccept: false,
  isDragReject: false,
  draggedFiles: [],
  acceptedFiles: [],
  rejectedFiles: []
};
/**
 * A React hook that creates a drag 'n' drop area.
 *
 * ```jsx
 * function MyDropzone(props) {
 *   const {getRootProps, getInputProps} = useDropzone({
 *     onDrop: acceptedFiles => {
 *       // do something with the File objects, e.g. upload to some server
 *     }
 *   });
 *   return (
 *     <div {...getRootProps()}>
 *       <input {...getInputProps()} />
 *       <p>Drag and drop some files here, or click to select files</p>
 *     </div>
 *   )
 * }
 * ```
 *
 * @function useDropzone
 *
 * @param {object} props
 * @param {string|string[]} [props.accept] Set accepted file types.
 * See https://github.com/okonet/attr-accept for more information.
 * Keep in mind that mime type determination is not reliable across platforms. CSV files,
 * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
 * Windows. In some cases there might not be a mime type set at all.
 * See: https://github.com/react-dropzone/react-dropzone/issues/276
 * @param {boolean} [props.multiple=true] Allow drag 'n' drop (or selection from the file dialog) of multiple files
 * @param {boolean} [props.preventDropOnDocument=true] If false, allow dropped items to take over the current browser window
 * @param {boolean} [props.noClick=false] If true, disables click to open the native file selection dialog
 * @param {boolean} [props.noKeyboard=false] If true, disables SPACE/ENTER to open the native file selection dialog.
 * Note that it also stops tracking the focus state.
 * @param {boolean} [props.noDrag=false] If true, disables drag 'n' drop
 * @param {boolean} [props.noDragEventsBubbling=false] If true, stops drag event propagation to parents
 * @param {number} [props.minSize=0] Minimum file size (in bytes)
 * @param {number} [props.maxSize=Infinity] Maximum file size (in bytes)
 * @param {boolean} [props.disabled=false] Enable/disable the dropzone
 * @param {getFilesFromEvent} [props.getFilesFromEvent] Use this to provide a custom file aggregator
 * @param {Function} [props.onFileDialogCancel] Cb for when closing the file dialog with no selection
 * @param {dragCb} [props.onDragEnter] Cb for when the `dragenter` event occurs.
 * @param {dragCb} [props.onDragLeave] Cb for when the `dragleave` event occurs
 * @param {dragCb} [props.onDragOver] Cb for when the `dragover` event occurs
 * @param {dropCb} [props.onDrop] Cb for when the `drop` event occurs.
 * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
 *
 * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
 * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension.
 * If `multiple` is set to false and additional files are droppped,
 * all files besides the first will be rejected.
 * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
 *
 * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
 * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
 *
 * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.
 * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
 *
 * ```js
 * function onDrop(acceptedFiles) {
 *   const req = request.post('/upload')
 *   acceptedFiles.forEach(file => {
 *     req.attach(file.name, file)
 *   })
 *   req.end(callback)
 * }
 * ```
 * @param {dropAcceptedCb} [props.onDropAccepted]
 * @param {dropRejectedCb} [props.onDropRejected]
 *
 * @returns {DropzoneState}
 */

function useDropzone() {
  var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
    accept = _ref2.accept,
    _ref2$disabled = _ref2.disabled,
    disabled = _ref2$disabled === void 0 ? false : _ref2$disabled,
    _ref2$getFilesFromEve = _ref2.getFilesFromEvent,
    getFilesFromEvent = _ref2$getFilesFromEve === void 0 ? fromEvent : _ref2$getFilesFromEve,
    _ref2$maxSize = _ref2.maxSize,
    maxSize = _ref2$maxSize === void 0 ? Infinity : _ref2$maxSize,
    _ref2$minSize = _ref2.minSize,
    minSize = _ref2$minSize === void 0 ? 0 : _ref2$minSize,
    _ref2$multiple = _ref2.multiple,
    multiple = _ref2$multiple === void 0 ? true : _ref2$multiple,
    onDragEnter = _ref2.onDragEnter,
    onDragLeave = _ref2.onDragLeave,
    onDragOver = _ref2.onDragOver,
    onDrop = _ref2.onDrop,
    onDropAccepted = _ref2.onDropAccepted,
    onDropRejected = _ref2.onDropRejected,
    onFileDialogCancel = _ref2.onFileDialogCancel,
    _ref2$preventDropOnDo = _ref2.preventDropOnDocument,
    preventDropOnDocument = _ref2$preventDropOnDo === void 0 ? true : _ref2$preventDropOnDo,
    _ref2$noClick = _ref2.noClick,
    noClick = _ref2$noClick === void 0 ? false : _ref2$noClick,
    _ref2$noKeyboard = _ref2.noKeyboard,
    noKeyboard = _ref2$noKeyboard === void 0 ? false : _ref2$noKeyboard,
    _ref2$noDrag = _ref2.noDrag,
    noDrag = _ref2$noDrag === void 0 ? false : _ref2$noDrag,
    _ref2$noDragEventsBub = _ref2.noDragEventsBubbling,
    noDragEventsBubbling = _ref2$noDragEventsBub === void 0 ? false : _ref2$noDragEventsBub;
  var rootRef = reactExports$1.useRef(null);
  var inputRef = reactExports$1.useRef(null);
  var _useReducer = reactExports$1.useReducer(reducer$1, initialState),
    _useReducer2 = _slicedToArray(_useReducer, 2),
    state = _useReducer2[0],
    dispatch = _useReducer2[1];
  var isFocused = state.isFocused,
    isFileDialogActive = state.isFileDialogActive,
    draggedFiles = state.draggedFiles; // Fn for opening the file dialog programmatically

  var openFileDialog = reactExports$1.useCallback(function () {
    if (inputRef.current) {
      dispatch({
        type: 'openDialog'
      });
      inputRef.current.value = null;
      inputRef.current.click();
    }
  }, [dispatch]); // Update file dialog active state when the window is focused on

  var onWindowFocus = function onWindowFocus() {
    // Execute the timeout only if the file dialog is opened in the browser
    if (isFileDialogActive) {
      setTimeout(function () {
        if (inputRef.current) {
          var files = inputRef.current.files;
          if (!files.length) {
            dispatch({
              type: 'closeDialog'
            });
            if (typeof onFileDialogCancel === 'function') {
              onFileDialogCancel();
            }
          }
        }
      }, 300);
    }
  };
  reactExports$1.useEffect(function () {
    window.addEventListener('focus', onWindowFocus, false);
    return function () {
      window.removeEventListener('focus', onWindowFocus, false);
    };
  }, [inputRef, isFileDialogActive, onFileDialogCancel]); // Cb to open the file dialog when SPACE/ENTER occurs on the dropzone

  var onKeyDownCb = reactExports$1.useCallback(function (event) {
    // Ignore keyboard events bubbling up the DOM tree
    if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {
      return;
    }
    if (event.keyCode === 32 || event.keyCode === 13) {
      event.preventDefault();
      openFileDialog();
    }
  }, [rootRef, inputRef]); // Update focus state for the dropzone

  var onFocusCb = reactExports$1.useCallback(function () {
    dispatch({
      type: 'focus'
    });
  }, []);
  var onBlurCb = reactExports$1.useCallback(function () {
    dispatch({
      type: 'blur'
    });
  }, []); // Cb to open the file dialog when click occurs on the dropzone

  var onClickCb = reactExports$1.useCallback(function () {
    if (noClick) {
      return;
    } // In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout()
    // to ensure React can handle state changes
    // See: https://github.com/react-dropzone/react-dropzone/issues/450

    if (isIeOrEdge()) {
      setTimeout(openFileDialog, 0);
    } else {
      openFileDialog();
    }
  }, [inputRef, noClick]);
  var dragTargetsRef = reactExports$1.useRef([]);
  var onDocumentDrop = function onDocumentDrop(event) {
    if (rootRef.current && rootRef.current.contains(event.target)) {
      // If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
      return;
    }
    event.preventDefault();
    dragTargetsRef.current = [];
  };
  reactExports$1.useEffect(function () {
    if (preventDropOnDocument) {
      document.addEventListener('dragover', onDocumentDragOver, false);
      document.addEventListener('drop', onDocumentDrop, false);
    }
    return function () {
      if (preventDropOnDocument) {
        document.removeEventListener('dragover', onDocumentDragOver);
        document.removeEventListener('drop', onDocumentDrop);
      }
    };
  }, [rootRef, preventDropOnDocument]);
  var onDragEnterCb = reactExports$1.useCallback(function (event) {
    event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done

    event.persist();
    stopPropagation(event); // Count the dropzone and any children that are entered.

    if (dragTargetsRef.current.indexOf(event.target) === -1) {
      dragTargetsRef.current = [].concat(_toConsumableArray(dragTargetsRef.current), [event.target]);
    }
    if (isEvtWithFiles(event)) {
      Promise.resolve(getFilesFromEvent(event)).then(function (draggedFiles) {
        if (isPropagationStopped(event) && !noDragEventsBubbling) {
          return;
        }
        dispatch({
          draggedFiles: draggedFiles,
          isDragActive: true,
          type: 'setDraggedFiles'
        });
        if (onDragEnter) {
          onDragEnter(event);
        }
      });
    }
  }, [getFilesFromEvent, onDragEnter, noDragEventsBubbling]);
  var onDragOverCb = reactExports$1.useCallback(function (event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    if (event.dataTransfer) {
      try {
        event.dataTransfer.dropEffect = 'copy';
      } catch (_unused) {}
      /* eslint-disable-line no-empty */
    }

    if (isEvtWithFiles(event) && onDragOver) {
      onDragOver(event);
    }
    return false;
  }, [onDragOver, noDragEventsBubbling]);
  var onDragLeaveCb = reactExports$1.useCallback(function (event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event); // Only deactivate once the dropzone and all children have been left

    var targets = dragTargetsRef.current.filter(function (target) {
      return target !== event.target && rootRef.current && rootRef.current.contains(target);
    });
    dragTargetsRef.current = targets;
    if (targets.length > 0) {
      return;
    }
    dispatch({
      isDragActive: false,
      type: 'setDraggedFiles',
      draggedFiles: []
    });
    if (isEvtWithFiles(event) && onDragLeave) {
      onDragLeave(event);
    }
  }, [rootRef, onDragLeave, noDragEventsBubbling]);
  var onDropCb = reactExports$1.useCallback(function (event) {
    event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done

    event.persist();
    stopPropagation(event);
    dragTargetsRef.current = [];
    if (isEvtWithFiles(event)) {
      Promise.resolve(getFilesFromEvent(event)).then(function (files) {
        if (isPropagationStopped(event) && !noDragEventsBubbling) {
          return;
        }
        var acceptedFiles = [];
        var rejectedFiles = [];
        files.forEach(function (file) {
          if (fileAccepted(file, accept) && fileMatchSize(file, minSize, maxSize)) {
            acceptedFiles.push(file);
          } else {
            rejectedFiles.push(file);
          }
        });
        if (!multiple && acceptedFiles.length > 1) {
          rejectedFiles.push.apply(rejectedFiles, _toConsumableArray(acceptedFiles.splice(0))); // Reject everything and empty accepted files
        }

        dispatch({
          acceptedFiles: acceptedFiles,
          rejectedFiles: rejectedFiles,
          type: 'setFiles'
        });
        if (onDrop) {
          onDrop(acceptedFiles, rejectedFiles, event);
        }
        if (rejectedFiles.length > 0 && onDropRejected) {
          onDropRejected(rejectedFiles, event);
        }
        if (acceptedFiles.length > 0 && onDropAccepted) {
          onDropAccepted(acceptedFiles, event);
        }
      });
    }
    dispatch({
      type: 'reset'
    });
  }, [multiple, accept, minSize, maxSize, getFilesFromEvent, onDrop, onDropAccepted, onDropRejected, noDragEventsBubbling]);
  var composeHandler = function composeHandler(fn) {
    return disabled ? null : fn;
  };
  var composeKeyboardHandler = function composeKeyboardHandler(fn) {
    return noKeyboard ? null : composeHandler(fn);
  };
  var composeDragHandler = function composeDragHandler(fn) {
    return noDrag ? null : composeHandler(fn);
  };
  var stopPropagation = function stopPropagation(event) {
    if (noDragEventsBubbling) {
      event.stopPropagation();
    }
  };
  var getRootProps = reactExports$1.useMemo(function () {
    return function () {
      var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref3$refKey = _ref3.refKey,
        refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey,
        onKeyDown = _ref3.onKeyDown,
        onFocus = _ref3.onFocus,
        onBlur = _ref3.onBlur,
        onClick = _ref3.onClick,
        onDragEnter = _ref3.onDragEnter,
        onDragOver = _ref3.onDragOver,
        onDragLeave = _ref3.onDragLeave,
        onDrop = _ref3.onDrop,
        rest = _objectWithoutProperties(_ref3, ["refKey", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"]);
      return _objectSpread(_defineProperty({
        onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)),
        onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)),
        onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),
        onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),
        onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter, onDragEnterCb)),
        onDragOver: composeDragHandler(composeEventHandlers(onDragOver, onDragOverCb)),
        onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave, onDragLeaveCb)),
        onDrop: composeDragHandler(composeEventHandlers(onDrop, onDropCb))
      }, refKey, rootRef), !disabled && !noKeyboard ? {
        tabIndex: 0
      } : {}, {}, rest);
    };
  }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]);
  var onInputElementClick = reactExports$1.useCallback(function (event) {
    event.stopPropagation();
  }, []);
  var getInputProps = reactExports$1.useMemo(function () {
    return function () {
      var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref4$refKey = _ref4.refKey,
        refKey = _ref4$refKey === void 0 ? 'ref' : _ref4$refKey,
        onChange = _ref4.onChange,
        onClick = _ref4.onClick,
        rest = _objectWithoutProperties(_ref4, ["refKey", "onChange", "onClick"]);
      var inputProps = _defineProperty({
        accept: accept,
        multiple: multiple,
        type: 'file',
        style: {
          display: 'none'
        },
        onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),
        onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)),
        autoComplete: 'off',
        tabIndex: -1
      }, refKey, inputRef);
      return _objectSpread({}, inputProps, {}, rest);
    };
  }, [inputRef, accept, multiple, onDropCb, disabled]);
  var fileCount = draggedFiles.length;
  var isDragAccept = fileCount > 0 && allFilesAccepted({
    files: draggedFiles,
    accept: accept,
    minSize: minSize,
    maxSize: maxSize,
    multiple: multiple
  });
  var isDragReject = fileCount > 0 && !isDragAccept;
  return _objectSpread({}, state, {
    isDragAccept: isDragAccept,
    isDragReject: isDragReject,
    isFocused: isFocused && !disabled,
    getRootProps: getRootProps,
    getInputProps: getInputProps,
    rootRef: rootRef,
    inputRef: inputRef,
    open: composeHandler(openFileDialog)
  });
}
function reducer$1(state, action) {
  /* istanbul ignore next */
  switch (action.type) {
    case 'focus':
      return _objectSpread({}, state, {
        isFocused: true
      });
    case 'blur':
      return _objectSpread({}, state, {
        isFocused: false
      });
    case 'openDialog':
      return _objectSpread({}, state, {
        isFileDialogActive: true
      });
    case 'closeDialog':
      return _objectSpread({}, state, {
        isFileDialogActive: false
      });
    case 'setDraggedFiles':
      /* eslint no-case-declarations: 0 */
      var isDragActive = action.isDragActive,
        draggedFiles = action.draggedFiles;
      return _objectSpread({}, state, {
        draggedFiles: draggedFiles,
        isDragActive: isDragActive
      });
    case 'setFiles':
      return _objectSpread({}, state, {
        acceptedFiles: action.acceptedFiles,
        rejectedFiles: action.rejectedFiles
      });
    case 'reset':
      return _objectSpread({}, state, {
        isFileDialogActive: false,
        isDragActive: false,
        draggedFiles: [],
        acceptedFiles: [],
        rejectedFiles: []
      });
    default:
      return state;
  }
}

function withTheme(Component) {
  return reactExports$1.forwardRef(function ComponentWithTheme(props, ref) {
    const theme = useTheme();
    const combinedProps = {
      ...props,
      theme
    };
    return /*#__PURE__*/React.createElement(Component, {
      ref: ref,
      ...combinedProps
    });
  });
}

var Delete$1 = {};

var _interopRequireDefault$5 = interopRequireDefaultExports;
Object.defineProperty(Delete$1, "__esModule", {
  value: true
});
var default_1$5 = Delete$1.default = void 0;
var _createSvgIcon$5 = _interopRequireDefault$5(requireCreateSvgIcon());
var _jsxRuntime$5 = jsxRuntimeExports;
var _default$5 = (0, _createSvgIcon$5.default)( /*#__PURE__*/(0, _jsxRuntime$5.jsx)("path", {
  d: "M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"
}), 'Delete');
default_1$5 = Delete$1.default = _default$5;

function PreviewList(props) {
  const {
    fileObjects,
    handleRemove,
    showFileNames,
    useChipsForPreview,
    previewChipProps,
    previewGridClasses,
    previewGridProps,
    classes,
    getPreviewIcon
  } = props;
  const sxGridContainer = reactExports$1.useMemo(() => ({
    display: "flex",
    flexWrap: "wrap",
    width: "100%",
    gap: useChipsForPreview ? 1 : 8
  }), [useChipsForPreview]);
  const sxImageContainer = reactExports$1.useMemo(() => ({
    position: "relative",
    zIndex: 10,
    textAlign: "center",
    "& img": {
      height: 100,
      width: "initial",
      maxWidth: "100%",
      color: "text.primary",
      transition: "all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms",
      boxSizing: "border-box",
      boxShadow: "rgba(0, 0, 0, 0.12) 0 1px 6px, rgba(0, 0, 0, 0.12) 0 1px 4px",
      borderRadius: 1,
      zIndex: 5,
      opacity: 1
    },
    "&:hover svg": {
      opacity: 0.3
    },
    "&:hover button": {
      opacity: 1
    }
  }), []);
  const sxRemoveButton = reactExports$1.useMemo(() => ({
    transition: ".5s ease",
    position: "absolute",
    opacity: 0,
    top: -16,
    right: -16,
    width: 40,
    height: 40,
    "&:focus": {
      opacity: 1
    }
  }), []);
  if (useChipsForPreview) {
    return /*#__PURE__*/React.createElement(Box$1, {
      sx: sxGridContainer,
      ...previewGridProps?.container,
      className: clsx(classes?.root, previewGridClasses?.container)
    }, fileObjects.map((fileObject, i) => {
      return /*#__PURE__*/React.createElement(Box$1, {
        ...previewGridProps?.item,
        key: i,
        sx: sxImageContainer,
        className: classes?.imageContainer
      }, /*#__PURE__*/React.createElement(Chip$2, {
        variant: "outlined",
        ...previewChipProps,
        label: fileObject.file.name,
        onDelete: handleRemove(i)
      }));
    }));
  }
  return /*#__PURE__*/React.createElement(Box$1, {
    sx: sxGridContainer,
    ...previewGridProps?.container,
    className: clsx(classes?.root, previewGridClasses?.container)
  }, fileObjects.map((fileObject, i) => {
    return /*#__PURE__*/React.createElement(Box$1, {
      ...previewGridProps?.item,
      key: i,
      sx: sxImageContainer,
      className: clsx(classes?.imageContainer, previewGridClasses?.item)
    }, getPreviewIcon(fileObject, classes), showFileNames ? /*#__PURE__*/React.createElement(Typography$1, {
      component: "p"
    }, fileObject.file.name) : null, /*#__PURE__*/React.createElement(Fab$2, {
      onClick: handleRemove(i),
      "aria-label": "Delete",
      sx: sxRemoveButton,
      className: classes?.removeButton
    }, /*#__PURE__*/React.createElement(default_1$5, null)));
  }));
}
PreviewList.propTypes = {
  classes: PropTypes.object,
  fileObjects: PropTypes.arrayOf(PropTypes.object).isRequired,
  getPreviewIcon: PropTypes.func.isRequired,
  handleRemove: PropTypes.func.isRequired,
  previewChipProps: PropTypes.object,
  previewGridClasses: PropTypes.object,
  previewGridProps: PropTypes.object,
  showFileNames: PropTypes.bool,
  useChipsForPreview: PropTypes.bool
};

var CheckCircle = {};

var _interopRequireDefault$4 = interopRequireDefaultExports;
Object.defineProperty(CheckCircle, "__esModule", {
  value: true
});
var default_1$4 = CheckCircle.default = void 0;
var _createSvgIcon$4 = _interopRequireDefault$4(requireCreateSvgIcon());
var _jsxRuntime$4 = jsxRuntimeExports;
var _default$4 = (0, _createSvgIcon$4.default)( /*#__PURE__*/(0, _jsxRuntime$4.jsx)("path", {
  d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
}), 'CheckCircle');
default_1$4 = CheckCircle.default = _default$4;

var Close$1 = {};

var _interopRequireDefault$3 = interopRequireDefaultExports;
Object.defineProperty(Close$1, "__esModule", {
  value: true
});
var default_1$3 = Close$1.default = void 0;
var _createSvgIcon$3 = _interopRequireDefault$3(requireCreateSvgIcon());
var _jsxRuntime$3 = jsxRuntimeExports;
var _default$3 = (0, _createSvgIcon$3.default)( /*#__PURE__*/(0, _jsxRuntime$3.jsx)("path", {
  d: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), 'Close');
default_1$3 = Close$1.default = _default$3;

var _Error = {};

var _interopRequireDefault$2 = interopRequireDefaultExports;
Object.defineProperty(_Error, "__esModule", {
  value: true
});
var default_1$2 = _Error.default = void 0;
var _createSvgIcon$2 = _interopRequireDefault$2(requireCreateSvgIcon());
var _jsxRuntime$2 = jsxRuntimeExports;
var _default$2 = (0, _createSvgIcon$2.default)( /*#__PURE__*/(0, _jsxRuntime$2.jsx)("path", {
  d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"
}), 'Error');
default_1$2 = _Error.default = _default$2;

var Info$1 = {};

var _interopRequireDefault$1 = interopRequireDefaultExports;
Object.defineProperty(Info$1, "__esModule", {
  value: true
});
var default_1$1 = Info$1.default = void 0;
var _createSvgIcon$1 = _interopRequireDefault$1(requireCreateSvgIcon());
var _jsxRuntime$1 = jsxRuntimeExports;
var _default$1 = (0, _createSvgIcon$1.default)( /*#__PURE__*/(0, _jsxRuntime$1.jsx)("path", {
  d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"
}), 'Info');
default_1$1 = Info$1.default = _default$1;

var Warning = {};

var _interopRequireDefault = interopRequireDefaultExports;
Object.defineProperty(Warning, "__esModule", {
  value: true
});
var default_1 = Warning.default = void 0;
var _createSvgIcon = _interopRequireDefault(requireCreateSvgIcon());
var _jsxRuntime = jsxRuntimeExports;
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"
}), 'Warning');
default_1 = Warning.default = _default;

const variantIcon = {
  error: default_1$2,
  info: default_1$1,
  success: default_1$4,
  warning: default_1
};
const SnackbarContentWrapper = reactExports$1.forwardRef(function SnackbarContentWrapper(props, ref) {
  const {
    classes,
    className,
    message,
    onClose,
    variant = "info",
    ...other
  } = props;
  const Icon = variantIcon[variant];
  const sx = reactExports$1.useMemo(() => ({
    icon: {
      fontSize: 20,
      opacity: 0.9
    },
    message: {
      display: "flex",
      alignItems: "center",
      "& > svg": {
        marginRight: 1
      }
    }
  }), []);
  const sxVariant = reactExports$1.useMemo(() => ({
    backgroundColor: `${variant}.main`
  }), [variant]);
  return /*#__PURE__*/React.createElement(SnackbarContent$1, {
    ref: ref,
    sx: sxVariant,
    className: clsx(classes?.[variant], className),
    "aria-describedby": "client-snackbar",
    message: /*#__PURE__*/React.createElement(Box$1, {
      component: "span",
      id: "client-snackbar",
      sx: sx.message,
      className: classes?.message
    }, /*#__PURE__*/React.createElement(Icon, {
      sx: sx.icon,
      className: classes?.icon
    }), message),
    action: /*#__PURE__*/React.createElement(IconButton$2, {
      key: "close",
      "aria-label": "Close",
      color: "inherit",
      className: classes?.closeButton,
      onClick: onClose
    }, /*#__PURE__*/React.createElement(default_1$3, {
      sx: sx.icon,
      className: classes?.icon
    })),
    ...other
  });
});
SnackbarContentWrapper.propTypes = {
  classes: PropTypes.object,
  className: PropTypes.string,
  message: PropTypes.node,
  onClose: PropTypes.func,
  variant: PropTypes.oneOf(["success", "warning", "error", "info"])
};

const defaultSnackbarAnchorOrigin = {
  horizontal: "left",
  vertical: "bottom"
};
const defaultGetPreviewIcon = (fileObject, classes) => {
  const {
    data,
    file
  } = fileObject || {};
  if (isImage(file)) {
    const src = typeof data === "string" ? data : undefined;
    return /*#__PURE__*/React.createElement("img", {
      className: classes?.image,
      role: "presentation",
      src: src
    });
  }
  return /*#__PURE__*/React.createElement(default_1$7, {
    sx: {
      height: 100,
      width: "initial",
      maxWidth: "100%",
      color: "text.primary",
      transition: "all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms",
      boxSizing: "border-box",
      boxShadow: "rgba(0, 0, 0, 0.12) 0 1px 6px, rgba(0, 0, 0, 0.12) 0 1px 4px",
      borderRadius: 1,
      zIndex: 5,
      opacity: 1
    },
    className: classes?.image
  });
};
const FileObjectShape = PropTypes.shape({
  file: PropTypes.object,
  data: PropTypes.any
});
/**
 * This components creates a Material-UI Dropzone, with previews and snackbar notifications.
 */
class DropzoneAreaBase extends reactExports$1.PureComponent {
  constructor(...args) {
    super(...args);
    _defineProperty$1(this, "state", {
      openSnackBar: false,
      snackbarMessage: "",
      snackbarVariant: "success"
    });
    _defineProperty$1(this, "handleDropAccepted", async (acceptedFiles, evt) => {
      const {
        fileObjects,
        filesLimit = DropzoneAreaBase.defaultProps.filesLimit,
        getFileAddedMessage = DropzoneAreaBase.defaultProps.getFileAddedMessage,
        getFileLimitExceedMessage = DropzoneAreaBase.defaultProps.getFileLimitExceedMessage,
        onAdd,
        onDrop
      } = this.props;
      if (filesLimit > 1 && fileObjects.length + acceptedFiles.length > filesLimit) {
        this.setState({
          openSnackBar: true,
          snackbarMessage: getFileLimitExceedMessage(filesLimit),
          snackbarVariant: "error"
        }, this.notifyAlert);
        return;
      }

      // Notify Drop event
      if (onDrop) {
        onDrop(acceptedFiles, evt);
      }

      // Retrieve fileObjects data
      const fileObjs = await Promise.all(acceptedFiles.map(async file => {
        const data = await readFile(file);
        return {
          file,
          data
        };
      }));

      // Notify added files
      if (onAdd) {
        onAdd(fileObjs);
      }

      // Display message
      const message = fileObjs.reduce((msg, fileObj) => msg + getFileAddedMessage(fileObj.file.name), "");
      this.setState({
        openSnackBar: true,
        snackbarMessage: message,
        snackbarVariant: "success"
      }, this.notifyAlert);
    });
    _defineProperty$1(this, "handleDropRejected", (rejectedFiles, evt) => {
      const {
        acceptedFiles,
        filesLimit = DropzoneAreaBase.defaultProps.filesLimit,
        fileObjects,
        getDropRejectMessage = DropzoneAreaBase.defaultProps.getDropRejectMessage,
        getFileLimitExceedMessage = DropzoneAreaBase.defaultProps.getFileLimitExceedMessage,
        maxFileSize = DropzoneAreaBase.defaultProps.maxFileSize,
        onDropRejected
      } = this.props;
      let message = "";
      if (fileObjects.length + rejectedFiles.length > filesLimit) {
        message = getFileLimitExceedMessage(filesLimit);
      } else {
        rejectedFiles.forEach(rejectedFile => {
          message = getDropRejectMessage(rejectedFile, acceptedFiles || [], maxFileSize);
        });
      }
      if (onDropRejected) {
        onDropRejected(rejectedFiles, evt);
      }
      this.setState({
        openSnackBar: true,
        snackbarMessage: message,
        snackbarVariant: "error"
      }, this.notifyAlert);
    });
    _defineProperty$1(this, "handleRemove", fileIndex => event => {
      event.stopPropagation();
      const {
        fileObjects,
        getFileRemovedMessage = DropzoneAreaBase.defaultProps.getFileRemovedMessage,
        onDelete
      } = this.props;

      // Find removed fileObject
      const removedFileObj = fileObjects[fileIndex];

      // Notify removed file
      if (onDelete) {
        onDelete(removedFileObj, fileIndex);
      }
      this.setState({
        openSnackBar: true,
        snackbarMessage: getFileRemovedMessage(removedFileObj.file.name),
        snackbarVariant: "info"
      }, this.notifyAlert);
    });
    _defineProperty$1(this, "handleCloseSnackbar", () => {
      this.setState({
        openSnackBar: false
      });
    });
    _defineProperty$1(this, "defaultSx", {
      root: {
        "@keyframes progress": {
          "0%": {
            backgroundPosition: "0 0"
          },
          "100%": {
            backgroundPosition: "-70px 0"
          }
        },
        position: "relative",
        width: "100%",
        minHeight: "250px",
        backgroundColor: "background.paper",
        border: "dashed",
        borderColor: "divider",
        borderRadius: 1,
        boxSizing: "border-box",
        cursor: "pointer",
        overflow: "hidden"
      },
      active: {
        animation: "$progress 2s linear infinite !important",
        backgroundImage: `repeating-linear-gradient(-45deg, ${this.props.theme.palette.background.paper}, ${this.props.theme.palette.background.paper} 25px, ${this.props.theme.palette.divider} 25px, ${this.props.theme.palette.divider} 50px)`,
        backgroundSize: "150% 100%",
        border: "solid",
        borderColor: "primary.light"
      },
      invalid: {
        backgroundImage: `repeating-linear-gradient(-45deg, ${this.props.theme.palette.error.light}, ${this.props.theme.palette.error.light} 25px, ${this.props.theme.palette.error.dark} 25px, ${this.props.theme.palette.error.dark} 50px)`,
        borderColor: "error.main"
      },
      textContainer: {
        textAlign: "center"
      },
      text: {
        marginBottom: 3,
        marginTop: 3
      },
      icon: {
        width: 51,
        height: 51,
        color: "text.primary"
      }
    });
  }
  notifyAlert() {
    const {
      onAlert
    } = this.props;
    const {
      openSnackBar,
      snackbarMessage,
      snackbarVariant
    } = this.state;
    if (openSnackBar && onAlert) {
      onAlert(snackbarMessage, snackbarVariant);
    }
  }
  render() {
    const {
      acceptedFiles,
      alertSnackbarProps,
      classes = {},
      disableRejectionFeedback,
      dropzoneClass,
      dropzoneParagraphClass,
      dropzoneProps,
      dropzoneText,
      fileObjects,
      filesLimit = DropzoneAreaBase.defaultProps.filesLimit,
      getPreviewIcon = DropzoneAreaBase.defaultProps.getPreviewIcon,
      Icon,
      inputProps,
      maxFileSize,
      previewChipProps,
      previewGridClasses,
      previewGridProps,
      previewText,
      showAlerts,
      showFileNames,
      showFileNamesInPreview,
      showPreviews,
      showPreviewsInDropzone,
      useChipsForPreview
    } = this.props;
    const {
      openSnackBar,
      snackbarMessage,
      snackbarVariant
    } = this.state;
    const acceptFiles = acceptedFiles?.join(",");
    const isMultiple = filesLimit > 1;
    const previewsVisible = showPreviews && fileObjects.length > 0;
    const previewsInDropzoneVisible = showPreviewsInDropzone && fileObjects.length > 0;
    return /*#__PURE__*/React.createElement(reactExports$1.Fragment, null, /*#__PURE__*/React.createElement(Dropzone, {
      ...dropzoneProps,
      accept: acceptFiles,
      onDropAccepted: this.handleDropAccepted,
      onDropRejected: this.handleDropRejected,
      maxSize: maxFileSize,
      multiple: isMultiple
    }, ({
      getRootProps,
      getInputProps,
      isDragActive,
      isDragReject
    }) => {
      const isActive = isDragActive;
      const isInvalid = !disableRejectionFeedback && isDragReject;
      return /*#__PURE__*/React.createElement(Box$1, {
        sx: {
          ...this.defaultSx.root,
          ...(isActive ? this.defaultSx.active : {}),
          ...(isInvalid ? this.defaultSx.invalid : {})
        },
        ...getRootProps({
          className: clsx(classes.root, dropzoneClass, isActive && classes.active, isInvalid && classes.invalid)
        })
      }, /*#__PURE__*/React.createElement("input", {
        ...getInputProps(inputProps)
      }), /*#__PURE__*/React.createElement(Box$1, {
        sx: this.defaultSx.textContainer,
        className: classes.textContainer
      }, /*#__PURE__*/React.createElement(Typography$1, {
        variant: "h5",
        component: "p",
        sx: this.defaultSx.text,
        className: clsx(classes.text, dropzoneParagraphClass)
      }, dropzoneText), Icon ? /*#__PURE__*/React.createElement(Icon, {
        sx: this.defaultSx.icon,
        className: classes.icon
      }) : /*#__PURE__*/React.createElement(default_1$6, {
        sx: this.defaultSx.icon,
        className: classes.icon
      })), previewsInDropzoneVisible ? /*#__PURE__*/React.createElement(PreviewList, {
        fileObjects: fileObjects,
        handleRemove: this.handleRemove,
        getPreviewIcon: getPreviewIcon,
        showFileNames: showFileNames,
        useChipsForPreview: useChipsForPreview,
        previewChipProps: previewChipProps,
        previewGridClasses: previewGridClasses,
        previewGridProps: previewGridProps
      }) : null);
    }), previewsVisible ? /*#__PURE__*/React.createElement(reactExports$1.Fragment, null, /*#__PURE__*/React.createElement(Typography$1, {
      variant: "subtitle1",
      component: "span"
    }, previewText), /*#__PURE__*/React.createElement(PreviewList, {
      fileObjects: fileObjects,
      handleRemove: this.handleRemove,
      getPreviewIcon: getPreviewIcon,
      showFileNames: showFileNamesInPreview,
      useChipsForPreview: useChipsForPreview,
      previewChipProps: previewChipProps,
      previewGridClasses: previewGridClasses,
      previewGridProps: previewGridProps
    })) : null, typeof showAlerts === "boolean" && showAlerts || Array.isArray(showAlerts) && showAlerts.includes(snackbarVariant) ? /*#__PURE__*/React.createElement(Snackbar$1, {
      anchorOrigin: defaultSnackbarAnchorOrigin,
      autoHideDuration: 6000,
      ...alertSnackbarProps,
      open: openSnackBar,
      onClose: this.handleCloseSnackbar
    }, /*#__PURE__*/React.createElement(SnackbarContentWrapper, {
      onClose: this.handleCloseSnackbar,
      variant: snackbarVariant,
      message: snackbarMessage
    })) : null);
  }
}

// @ts-expect-error
_defineProperty$1(DropzoneAreaBase, "propTypes", {
  classes: PropTypes.object,
  acceptedFiles: PropTypes.arrayOf(PropTypes.string),
  filesLimit: PropTypes.number,
  Icon: PropTypes.elementType,
  fileObjects: PropTypes.arrayOf(FileObjectShape),
  maxFileSize: PropTypes.number,
  dropzoneText: PropTypes.string,
  dropzoneClass: PropTypes.string,
  dropzoneParagraphClass: PropTypes.string,
  disableRejectionFeedback: PropTypes.bool,
  showPreviews: PropTypes.bool,
  showPreviewsInDropzone: PropTypes.bool,
  showFileNames: PropTypes.bool,
  showFileNamesInPreview: PropTypes.bool,
  useChipsForPreview: PropTypes.bool,
  previewChipProps: PropTypes.object,
  previewGridClasses: PropTypes.object,
  previewGridProps: PropTypes.object,
  previewText: PropTypes.string,
  showAlerts: PropTypes.oneOfType([PropTypes.bool, PropTypes.arrayOf(PropTypes.oneOf(["error", "success", "info", "warning"]))]),
  alertSnackbarProps: PropTypes.object,
  dropzoneProps: PropTypes.object,
  inputProps: PropTypes.object,
  getFileLimitExceedMessage: PropTypes.func,
  getFileAddedMessage: PropTypes.func,
  getFileRemovedMessage: PropTypes.func,
  getDropRejectMessage: PropTypes.func,
  getPreviewIcon: PropTypes.func,
  onAdd: PropTypes.func,
  onDelete: PropTypes.func,
  onDrop: PropTypes.func,
  onDropRejected: PropTypes.func,
  onAlert: PropTypes.func
});
_defineProperty$1(DropzoneAreaBase, "defaultProps", {
  acceptedFiles: [],
  filesLimit: 3,
  fileObjects: [],
  maxFileSize: 3000000,
  dropzoneText: "Drag and drop a file here or click",
  previewText: "Preview:",
  disableRejectionFeedback: false,
  showPreviews: false,
  // By default previews show up under in the dialog and inside in the standalone
  showPreviewsInDropzone: true,
  showFileNames: false,
  showFileNamesInPreview: false,
  useChipsForPreview: false,
  previewChipProps: {},
  previewGridClasses: {},
  previewGridProps: {},
  showAlerts: true,
  alertSnackbarProps: {
    anchorOrigin: {
      horizontal: "left",
      vertical: "bottom"
    },
    autoHideDuration: 6000
  },
  getFileLimitExceedMessage: filesLimit => `Maximum allowed number of files exceeded. Only ${filesLimit} allowed`,
  getFileAddedMessage: fileName => `File ${fileName} successfully added.`,
  getPreviewIcon: defaultGetPreviewIcon,
  getFileRemovedMessage: fileName => `File ${fileName} removed.`,
  getDropRejectMessage: (rejectedFile, acceptedFiles, maxFileSize) => {
    let message = `File ${rejectedFile.name} was rejected. `;
    if (!acceptedFiles.includes(rejectedFile.type)) {
      message += "File type not supported. ";
    }
    if (rejectedFile.size > maxFileSize) {
      message += "File is too big. Size limit is " + convertBytesToMbsOrKbs(maxFileSize) + ". ";
    }
    return message;
  }
});
const ThemedDropzoneAreaBase = withTheme(DropzoneAreaBase);

const splitDropzoneAreaProps = props => {
  const {
    clearOnUnmount,
    initialFiles,
    onChange,
    onDelete,
    ...dropzoneAreaBaseProps
  } = props;
  const dropzoneAreaProps = {
    clearOnUnmount,
    initialFiles,
    onChange,
    onDelete
  };
  const splitProps = [dropzoneAreaProps, dropzoneAreaBaseProps];
  return splitProps;
};
/**
 * This components creates an uncontrolled Material-UI Dropzone, with previews and snackbar notifications.
 *
 * It supports all props of `DropzoneAreaBase` but keeps the files state internally.
 *
 * **Note** To listen to file changes use `onChange` event handler and notice that `onDelete` returns a `File` instance instead of `FileObject`.
 */
let DropzoneArea$2 = class DropzoneArea extends reactExports$1.PureComponent {
  constructor(...args) {
    super(...args);
    _defineProperty$1(this, "state", {
      fileObjects: []
    });
    _defineProperty$1(this, "notifyFileChange", () => {
      const {
        onChange
      } = this.props;
      const {
        fileObjects
      } = this.state;
      if (onChange) {
        onChange(fileObjects.map(fileObject => fileObject.file));
      }
    });
    _defineProperty$1(this, "loadInitialFiles", async () => {
      const {
        initialFiles = DropzoneArea.defaultProps.initialFiles
      } = this.props;
      try {
        const fileObjs = await Promise.all(initialFiles.map(async initialFile => {
          let file;
          if (typeof initialFile === "string") {
            file = await createFileFromUrl(initialFile);
          } else {
            file = initialFile;
          }
          const data = await readFile(file);
          const fileObj = {
            file,
            data
          };
          return fileObj;
        }));
        this.setState(prevState => ({
          fileObjects: [...prevState.fileObjects, ...fileObjs]
        }), this.notifyFileChange);
      } catch (err) {
        // eslint-disable-next-line no-console
        console.log(err);
      }
    });
    _defineProperty$1(this, "addFiles", async newFileObjects => {
      const {
        filesLimit = DropzoneArea.defaultProps.filesLimit
      } = this.props;

      // Update component state
      this.setState(prevState => {
        // Handle a single file
        if (filesLimit <= 1) {
          return {
            fileObjects: [newFileObjects[0]]
          };
        }

        // Handle multiple files
        return {
          fileObjects: [...prevState.fileObjects, ...newFileObjects]
        };
      }, this.notifyFileChange);
    });
    _defineProperty$1(this, "deleteFile", (removedFileObj, removedFileObjIdx) => {
      event?.stopPropagation();
      const {
        onDelete
      } = this.props;
      const {
        fileObjects
      } = this.state;

      // Calculate remaining fileObjects array
      const remainingFileObjs = fileObjects.filter((fileObject, i) => {
        return i !== removedFileObjIdx;
      });

      // Notify removed file
      if (onDelete) {
        onDelete(removedFileObj.file);
      }

      // Update local state
      this.setState({
        fileObjects: remainingFileObjs
      }, this.notifyFileChange);
    });
  }
  componentDidMount() {
    this.loadInitialFiles();
  }
  componentWillUnmount() {
    const {
      clearOnUnmount
    } = this.props;
    if (clearOnUnmount) {
      this.setState({
        fileObjects: []
      }, this.notifyFileChange);
    }
  }
  render() {
    const [, dropzoneAreaBaseProps] = splitDropzoneAreaProps(this.props);
    const {
      fileObjects
    } = this.state;
    return /*#__PURE__*/React.createElement(ThemedDropzoneAreaBase, {
      ...dropzoneAreaBaseProps,
      fileObjects: fileObjects,
      onAdd: this.addFiles,
      onDelete: this.deleteFile
    });
  }
};
_defineProperty$1(DropzoneArea$2, "propTypes", {
  // @ts-ignore
  ...ThemedDropzoneAreaBase.propTypes,
  clearOnUnmount: PropTypes.bool,
  initialFiles: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.any])),
  filesLimit: PropTypes.number,
  onChange: PropTypes.func,
  onDelete: PropTypes.func
});
_defineProperty$1(DropzoneArea$2, "defaultProps", {
  clearOnUnmount: true,
  filesLimit: 3,
  initialFiles: []
});

function getDialogUtilityClass(slot) {
  return generateUtilityClass('MuiDialog', slot);
}
const dialogClasses = generateUtilityClasses('MuiDialog', ['root', 'scrollPaper', 'scrollBody', 'container', 'paper', 'paperScrollPaper', 'paperScrollBody', 'paperWidthFalse', 'paperWidthXs', 'paperWidthSm', 'paperWidthMd', 'paperWidthLg', 'paperWidthXl', 'paperFullWidth', 'paperFullScreen']);
var dialogClasses$1 = dialogClasses;

const DialogContext = /*#__PURE__*/reactExports$1.createContext({});
{
  DialogContext.displayName = 'DialogContext';
}
var DialogContext$1 = DialogContext;

const _excluded$i = ["aria-describedby", "aria-labelledby", "BackdropComponent", "BackdropProps", "children", "className", "disableEscapeKeyDown", "fullScreen", "fullWidth", "maxWidth", "onBackdropClick", "onClose", "open", "PaperComponent", "PaperProps", "scroll", "TransitionComponent", "transitionDuration", "TransitionProps"];
const DialogBackdrop = styled$1(Backdrop$1, {
  name: 'MuiDialog',
  slot: 'Backdrop',
  overrides: (props, styles) => styles.backdrop
})({
  // Improve scrollable dialog support.
  zIndex: -1
});
const useUtilityClasses$g = ownerState => {
  const {
    classes,
    scroll,
    maxWidth,
    fullWidth,
    fullScreen
  } = ownerState;
  const slots = {
    root: ['root'],
    container: ['container', `scroll${capitalize(scroll)}`],
    paper: ['paper', `paperScroll${capitalize(scroll)}`, `paperWidth${capitalize(String(maxWidth))}`, fullWidth && 'paperFullWidth', fullScreen && 'paperFullScreen']
  };
  return composeClasses(slots, getDialogUtilityClass, classes);
};
const DialogRoot = styled$1(Modal$1, {
  name: 'MuiDialog',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  '@media print': {
    // Use !important to override the Modal inline-style.
    position: 'absolute !important'
  }
});
const DialogContainer = styled$1('div', {
  name: 'MuiDialog',
  slot: 'Container',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.container, styles[`scroll${capitalize(ownerState.scroll)}`]];
  }
})(({
  ownerState
}) => _extends({
  height: '100%',
  '@media print': {
    height: 'auto'
  },
  // We disable the focus ring for mouse, touch and keyboard users.
  outline: 0
}, ownerState.scroll === 'paper' && {
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center'
}, ownerState.scroll === 'body' && {
  overflowY: 'auto',
  overflowX: 'hidden',
  textAlign: 'center',
  '&:after': {
    content: '""',
    display: 'inline-block',
    verticalAlign: 'middle',
    height: '100%',
    width: '0'
  }
}));
const DialogPaper = styled$1(Paper$1, {
  name: 'MuiDialog',
  slot: 'Paper',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.paper, styles[`scrollPaper${capitalize(ownerState.scroll)}`], styles[`paperWidth${capitalize(String(ownerState.maxWidth))}`], ownerState.fullWidth && styles.paperFullWidth, ownerState.fullScreen && styles.paperFullScreen];
  }
})(({
  theme,
  ownerState
}) => _extends({
  margin: 32,
  position: 'relative',
  overflowY: 'auto',
  // Fix IE11 issue, to remove at some point.
  '@media print': {
    overflowY: 'visible',
    boxShadow: 'none'
  }
}, ownerState.scroll === 'paper' && {
  display: 'flex',
  flexDirection: 'column',
  maxHeight: 'calc(100% - 64px)'
}, ownerState.scroll === 'body' && {
  display: 'inline-block',
  verticalAlign: 'middle',
  textAlign: 'left' // 'initial' doesn't work on IE11
}, !ownerState.maxWidth && {
  maxWidth: 'calc(100% - 64px)'
}, ownerState.maxWidth === 'xs' && {
  maxWidth: theme.breakpoints.unit === 'px' ? Math.max(theme.breakpoints.values.xs, 444) : `max(${theme.breakpoints.values.xs}${theme.breakpoints.unit}, 444px)`,
  [`&.${dialogClasses$1.paperScrollBody}`]: {
    [theme.breakpoints.down(Math.max(theme.breakpoints.values.xs, 444) + 32 * 2)]: {
      maxWidth: 'calc(100% - 64px)'
    }
  }
}, ownerState.maxWidth && ownerState.maxWidth !== 'xs' && {
  maxWidth: `${theme.breakpoints.values[ownerState.maxWidth]}${theme.breakpoints.unit}`,
  [`&.${dialogClasses$1.paperScrollBody}`]: {
    [theme.breakpoints.down(theme.breakpoints.values[ownerState.maxWidth] + 32 * 2)]: {
      maxWidth: 'calc(100% - 64px)'
    }
  }
}, ownerState.fullWidth && {
  width: 'calc(100% - 64px)'
}, ownerState.fullScreen && {
  margin: 0,
  width: '100%',
  maxWidth: '100%',
  height: '100%',
  maxHeight: 'none',
  borderRadius: 0,
  [`&.${dialogClasses$1.paperScrollBody}`]: {
    margin: 0,
    maxWidth: '100%'
  }
}));

/**
 * Dialogs are overlaid modal paper based components with a backdrop.
 */
const Dialog = /*#__PURE__*/reactExports$1.forwardRef(function Dialog(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiDialog'
  });
  const theme = useTheme();
  const defaultTransitionDuration = {
    enter: theme.transitions.duration.enteringScreen,
    exit: theme.transitions.duration.leavingScreen
  };
  const {
      'aria-describedby': ariaDescribedby,
      'aria-labelledby': ariaLabelledbyProp,
      BackdropComponent,
      BackdropProps,
      children,
      className,
      disableEscapeKeyDown = false,
      fullScreen = false,
      fullWidth = false,
      maxWidth = 'sm',
      onBackdropClick,
      onClose,
      open,
      PaperComponent = Paper$1,
      PaperProps = {},
      scroll = 'paper',
      TransitionComponent = Fade$1,
      transitionDuration = defaultTransitionDuration,
      TransitionProps
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$i);
  const ownerState = _extends({}, props, {
    disableEscapeKeyDown,
    fullScreen,
    fullWidth,
    maxWidth,
    scroll
  });
  const classes = useUtilityClasses$g(ownerState);
  const backdropClick = reactExports$1.useRef();
  const handleMouseDown = event => {
    // We don't want to close the dialog when clicking the dialog content.
    // Make sure the event starts and ends on the same DOM element.
    backdropClick.current = event.target === event.currentTarget;
  };
  const handleBackdropClick = event => {
    // Ignore the events not coming from the "backdrop".
    if (!backdropClick.current) {
      return;
    }
    backdropClick.current = null;
    if (onBackdropClick) {
      onBackdropClick(event);
    }
    if (onClose) {
      onClose(event, 'backdropClick');
    }
  };
  const ariaLabelledby = useId(ariaLabelledbyProp);
  const dialogContextValue = reactExports$1.useMemo(() => {
    return {
      titleId: ariaLabelledby
    };
  }, [ariaLabelledby]);
  return /*#__PURE__*/jsxRuntimeExports.jsx(DialogRoot, _extends({
    className: clsx(classes.root, className),
    closeAfterTransition: true,
    components: {
      Backdrop: DialogBackdrop
    },
    componentsProps: {
      backdrop: _extends({
        transitionDuration,
        as: BackdropComponent
      }, BackdropProps)
    },
    disableEscapeKeyDown: disableEscapeKeyDown,
    onClose: onClose,
    open: open,
    ref: ref,
    onClick: handleBackdropClick,
    ownerState: ownerState
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, _extends({
      appear: true,
      in: open,
      timeout: transitionDuration,
      role: "presentation"
    }, TransitionProps, {
      children: /*#__PURE__*/jsxRuntimeExports.jsx(DialogContainer, {
        className: clsx(classes.container),
        onMouseDown: handleMouseDown,
        ownerState: ownerState,
        children: /*#__PURE__*/jsxRuntimeExports.jsx(DialogPaper, _extends({
          as: PaperComponent,
          elevation: 24,
          role: "dialog",
          "aria-describedby": ariaDescribedby,
          "aria-labelledby": ariaLabelledby
        }, PaperProps, {
          className: clsx(classes.paper, PaperProps.className),
          ownerState: ownerState,
          children: /*#__PURE__*/jsxRuntimeExports.jsx(DialogContext$1.Provider, {
            value: dialogContextValue,
            children: children
          })
        }))
      })
    }))
  }));
});
Dialog.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The id(s) of the element(s) that describe the dialog.
   */
  'aria-describedby': PropTypes.string,
  /**
   * The id(s) of the element(s) that label the dialog.
   */
  'aria-labelledby': PropTypes.string,
  /**
   * A backdrop component. This prop enables custom backdrop rendering.
   * @deprecated Use `slots.backdrop` instead. While this prop currently works, it will be removed in the next major version.
   * Use the `slots.backdrop` prop to make your application ready for the next version of Material UI.
   * @default styled(Backdrop, {
   *   name: 'MuiModal',
   *   slot: 'Backdrop',
   *   overridesResolver: (props, styles) => {
   *     return styles.backdrop;
   *   },
   * })({
   *   zIndex: -1,
   * })
   */
  BackdropComponent: PropTypes.elementType,
  /**
   * @ignore
   */
  BackdropProps: PropTypes.object,
  /**
   * Dialog children, usually the included sub-components.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, hitting escape will not fire the `onClose` callback.
   * @default false
   */
  disableEscapeKeyDown: PropTypes.bool,
  /**
   * If `true`, the dialog is full-screen.
   * @default false
   */
  fullScreen: PropTypes.bool,
  /**
   * If `true`, the dialog stretches to `maxWidth`.
   *
   * Notice that the dialog width grow is limited by the default margin.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * Determine the max-width of the dialog.
   * The dialog width grows with the size of the screen.
   * Set to `false` to disable `maxWidth`.
   * @default 'sm'
   */
  maxWidth: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl', false]), PropTypes.string]),
  /**
   * Callback fired when the backdrop is clicked.
   * @deprecated Use the `onClose` prop with the `reason` argument to handle the `backdropClick` events.
   */
  onBackdropClick: PropTypes.func,
  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
   */
  onClose: PropTypes.func,
  /**
   * If `true`, the component is shown.
   */
  open: PropTypes.bool.isRequired,
  /**
   * The component used to render the body of the dialog.
   * @default Paper
   */
  PaperComponent: PropTypes.elementType,
  /**
   * Props applied to the [`Paper`](/material-ui/api/paper/) element.
   * @default {}
   */
  PaperProps: PropTypes.object,
  /**
   * Determine the container for scrolling the dialog.
   * @default 'paper'
   */
  scroll: PropTypes.oneOf(['body', 'paper']),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The component used for the transition.
   * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   * @default Fade
   */
  TransitionComponent: PropTypes.elementType,
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default {
   *   enter: theme.transitions.duration.enteringScreen,
   *   exit: theme.transitions.duration.leavingScreen,
   * }
   */
  transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })]),
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition/) component.
   */
  TransitionProps: PropTypes.object
} ;
var Dialog$1 = Dialog;

function getDialogActionsUtilityClass(slot) {
  return generateUtilityClass('MuiDialogActions', slot);
}
generateUtilityClasses('MuiDialogActions', ['root', 'spacing']);

const _excluded$h = ["className", "disableSpacing"];
const useUtilityClasses$f = ownerState => {
  const {
    classes,
    disableSpacing
  } = ownerState;
  const slots = {
    root: ['root', !disableSpacing && 'spacing']
  };
  return composeClasses(slots, getDialogActionsUtilityClass, classes);
};
const DialogActionsRoot = styled$1('div', {
  name: 'MuiDialogActions',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, !ownerState.disableSpacing && styles.spacing];
  }
})(({
  ownerState
}) => _extends({
  display: 'flex',
  alignItems: 'center',
  padding: 8,
  justifyContent: 'flex-end',
  flex: '0 0 auto'
}, !ownerState.disableSpacing && {
  '& > :not(:first-of-type)': {
    marginLeft: 8
  }
}));
const DialogActions = /*#__PURE__*/reactExports$1.forwardRef(function DialogActions(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiDialogActions'
  });
  const {
      className,
      disableSpacing = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$h);
  const ownerState = _extends({}, props, {
    disableSpacing
  });
  const classes = useUtilityClasses$f(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(DialogActionsRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other));
});
DialogActions.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the actions do not have additional margin.
   * @default false
   */
  disableSpacing: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var DialogActions$1 = DialogActions;

function getDialogContentUtilityClass(slot) {
  return generateUtilityClass('MuiDialogContent', slot);
}
generateUtilityClasses('MuiDialogContent', ['root', 'dividers']);

function getDialogTitleUtilityClass(slot) {
  return generateUtilityClass('MuiDialogTitle', slot);
}
const dialogTitleClasses = generateUtilityClasses('MuiDialogTitle', ['root']);
var dialogTitleClasses$1 = dialogTitleClasses;

const _excluded$g = ["className", "dividers"];
const useUtilityClasses$e = ownerState => {
  const {
    classes,
    dividers
  } = ownerState;
  const slots = {
    root: ['root', dividers && 'dividers']
  };
  return composeClasses(slots, getDialogContentUtilityClass, classes);
};
const DialogContentRoot = styled$1('div', {
  name: 'MuiDialogContent',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.dividers && styles.dividers];
  }
})(({
  theme,
  ownerState
}) => _extends({
  flex: '1 1 auto',
  // Add iOS momentum scrolling for iOS < 13.0
  WebkitOverflowScrolling: 'touch',
  overflowY: 'auto',
  padding: '20px 24px'
}, ownerState.dividers ? {
  padding: '16px 24px',
  borderTop: `1px solid ${(theme.vars || theme).palette.divider}`,
  borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`
} : {
  [`.${dialogTitleClasses$1.root} + &`]: {
    paddingTop: 0
  }
}));
const DialogContent = /*#__PURE__*/reactExports$1.forwardRef(function DialogContent(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiDialogContent'
  });
  const {
      className,
      dividers = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$g);
  const ownerState = _extends({}, props, {
    dividers
  });
  const classes = useUtilityClasses$e(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(DialogContentRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other));
});
DialogContent.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Display the top and bottom dividers.
   * @default false
   */
  dividers: PropTypes.bool,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var DialogContent$1 = DialogContent;

const _excluded$f = ["className", "id"];
const useUtilityClasses$d = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getDialogTitleUtilityClass, classes);
};
const DialogTitleRoot = styled$1(Typography$1, {
  name: 'MuiDialogTitle',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  padding: '16px 24px',
  flex: '0 0 auto'
});
const DialogTitle = /*#__PURE__*/reactExports$1.forwardRef(function DialogTitle(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiDialogTitle'
  });
  const {
      className,
      id: idProp
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$f);
  const ownerState = props;
  const classes = useUtilityClasses$d(ownerState);
  const {
    titleId = idProp
  } = reactExports$1.useContext(DialogContext$1);
  return /*#__PURE__*/jsxRuntimeExports.jsx(DialogTitleRoot, _extends({
    component: "h2",
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref,
    variant: "h6",
    id: idProp != null ? idProp : titleId
  }, other));
});
DialogTitle.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * @ignore
   */
  id: PropTypes.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var DialogTitle$1 = DialogTitle;

// Split props related to DropzoneDialog from DropzoneArea ones
function splitDropzoneDialogProps(allProps) {
  const defaults = DropzoneDialogBase.defaultProps;
  const {
    cancelButtonText = defaults.cancelButtonText,
    dialogProps = defaults.dialogProps,
    dialogTitle = defaults.dialogTitle,
    fullWidth = defaults.fullWidth,
    maxWidth = defaults.maxWidth,
    onClose,
    onSave,
    open = defaults.open,
    submitButtonText = defaults.submitButtonText,
    ...dropzoneAreaProps
  } = allProps;
  const dropzoneDialogProps = {
    cancelButtonText,
    dialogProps,
    dialogTitle,
    fullWidth,
    maxWidth,
    onClose,
    onSave,
    open,
    submitButtonText
  };
  const splitProps = [dropzoneDialogProps, dropzoneAreaProps];
  return splitProps;
}

/**
 * This component provides the DropzoneArea inside of a Material-UI Dialog.
 *
 * It supports all the Props and Methods from `DropzoneAreaBase`.
 */
class DropzoneDialogBase extends reactExports$1.PureComponent {
  constructor(...args) {
    super(...args);
    _defineProperty$1(this, "handlePressClose", e => {
      const {
        onClose
      } = this.props;
      onClose?.(e, "backdropClick");
    });
  }
  render() {
    const [dropzoneDialogProps, dropzoneAreaProps] = splitDropzoneDialogProps(this.props);
    const {
      cancelButtonText,
      dialogProps,
      dialogTitle,
      fullWidth,
      maxWidth,
      onClose,
      onSave,
      open,
      submitButtonText
    } = dropzoneDialogProps;

    // Submit button state
    const submitDisabled = dropzoneAreaProps.fileObjects.length === 0;
    return /*#__PURE__*/React.createElement(Dialog$1, {
      ...dialogProps,
      fullWidth: fullWidth,
      maxWidth: maxWidth,
      onClose: onClose,
      open: open
    }, /*#__PURE__*/React.createElement(DialogTitle$1, null, dialogTitle), /*#__PURE__*/React.createElement(DialogContent$1, null, /*#__PURE__*/React.createElement(ThemedDropzoneAreaBase, {
      ...dropzoneAreaProps
    })), /*#__PURE__*/React.createElement(DialogActions$1, null, /*#__PURE__*/React.createElement(Button$2, {
      onClick: this.handlePressClose
    }, cancelButtonText), /*#__PURE__*/React.createElement(Button$2, {
      variant: "contained",
      disabled: submitDisabled,
      onClick: onSave
    }, submitButtonText)));
  }
}
_defineProperty$1(DropzoneDialogBase, "propTypes", {
  // @ts-ignore
  ...ThemedDropzoneAreaBase.propTypes,
  open: PropTypes.bool,
  dialogTitle: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  dialogProps: PropTypes.object,
  fullWidth: PropTypes.bool,
  maxWidth: PropTypes.string,
  cancelButtonText: PropTypes.string,
  submitButtonText: PropTypes.string,
  onClose: PropTypes.func,
  onSave: PropTypes.func,
  showPreviews: PropTypes.bool,
  showPreviewsInDropzone: PropTypes.bool,
  showFileNamesInPreview: PropTypes.bool
});
_defineProperty$1(DropzoneDialogBase, "defaultProps", {
  open: false,
  dialogTitle: "Upload file",
  dialogProps: {},
  fullWidth: true,
  maxWidth: "sm",
  cancelButtonText: "Cancel",
  submitButtonText: "Submit",
  showPreviews: true,
  showPreviewsInDropzone: false,
  showFileNamesInPreview: true
});

/**
 * This component provides an uncontrolled version of the DropzoneDialogBase component.
 *
 * It supports all the Props and Methods from `DropzoneDialogBase` but keeps the files state internally.
 *
 * **Note** The `onSave` handler also returns `File[]` with all the accepted files.
 */
class DropzoneDialog extends reactExports$1.PureComponent {
  constructor(...args) {
    super(...args);
    _defineProperty$1(this, "state", {
      fileObjects: []
    });
    _defineProperty$1(this, "notifyFileChange", () => {
      const {
        onChange
      } = this.props;
      const {
        fileObjects
      } = this.state;
      if (onChange) {
        onChange(fileObjects.map(fileObject => fileObject.file));
      }
    });
    _defineProperty$1(this, "loadInitialFiles", async () => {
      const {
        initialFiles = DropzoneDialog.defaultProps.initialFiles
      } = this.props;
      try {
        const fileObjs = await Promise.all(initialFiles.map(async initialFile => {
          let file;
          if (typeof initialFile === "string") {
            file = await createFileFromUrl(initialFile);
          } else {
            file = initialFile;
          }
          const data = await readFile(file);
          const fileObj = {
            file,
            data
          };
          return fileObj;
        }));
        this.setState(state => ({
          fileObjects: [...state.fileObjects, ...fileObjs]
        }), this.notifyFileChange);
      } catch (err) {
        // eslint-disable-next-line no-console
        console.log(err);
      }
    });
    _defineProperty$1(this, "addFiles", async newFileObjects => {
      const {
        filesLimit = DropzoneDialog.defaultProps.filesLimit
      } = this.props;

      // Update component state
      this.setState(state => {
        // Handle a single file
        if (filesLimit <= 1) {
          return {
            fileObjects: [newFileObjects[0]]
          };
        }

        // Handle multiple files
        return {
          fileObjects: [...state.fileObjects, ...newFileObjects]
        };
      }, this.notifyFileChange);
    });
    _defineProperty$1(this, "deleteFile", (removedFileObj, removedFileObjIdx) => {
      event?.stopPropagation();
      const {
        onDelete
      } = this.props;
      const {
        fileObjects
      } = this.state;

      // Calculate remaining fileObjects array
      const remainingFileObjs = fileObjects.filter((fileObject, i) => {
        return i !== removedFileObjIdx;
      });

      // Notify removed file
      if (onDelete) {
        onDelete(removedFileObj.file);
      }

      // Update local state
      this.setState({
        fileObjects: remainingFileObjs
      }, this.notifyFileChange);
    });
    _defineProperty$1(this, "handleClose", (evt, reason) => {
      const {
        clearOnUnmount,
        onClose
      } = this.props;
      if (onClose) {
        onClose(evt, reason);
      }
      if (clearOnUnmount) {
        this.setState({
          fileObjects: []
        }, this.notifyFileChange);
      }
    });
    _defineProperty$1(this, "handleSave", evt => {
      const {
        clearOnUnmount,
        onSave
      } = this.props;
      const {
        fileObjects
      } = this.state;
      if (onSave) {
        onSave(fileObjects.map(fileObject => fileObject.file), evt);
      }
      if (clearOnUnmount) {
        this.setState({
          fileObjects: []
        }, this.notifyFileChange);
      }
    });
  }
  componentDidMount() {
    this.loadInitialFiles();
  }
  componentWillUnmount() {
    const {
      clearOnUnmount
    } = this.props;
    if (clearOnUnmount) {
      this.setState({
        fileObjects: []
      }, this.notifyFileChange);
    }
  }
  render() {
    const {
      fileObjects
    } = this.state;
    return /*#__PURE__*/React.createElement(DropzoneDialogBase, {
      ...this.props,
      fileObjects: fileObjects,
      onAdd: this.addFiles,
      onDelete: this.deleteFile,
      onClose: this.handleClose,
      onSave: this.handleSave
    });
  }
}
_defineProperty$1(DropzoneDialog, "propTypes", {
  ...DropzoneDialogBase.propTypes,
  clearOnUnmount: PropTypes.bool,
  filesLimit: PropTypes.number,
  initialFiles: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.any])),
  onSave: PropTypes.func
});
_defineProperty$1(DropzoneDialog, "defaultProps", {
  clearOnUnmount: true,
  filesLimit: 3,
  initialFiles: []
});

var MuiFileDropzone = /*#__PURE__*/Object.freeze({
  __proto__: null,
  DropzoneArea: DropzoneArea$2,
  DropzoneAreaBase: ThemedDropzoneAreaBase,
  DropzoneDialog: DropzoneDialog,
  DropzoneDialogBase: DropzoneDialogBase,
  FileObjectShape: FileObjectShape,
  convertBytesToMbsOrKbs: convertBytesToMbsOrKbs,
  createFileFromUrl: createFileFromUrl,
  isImage: isImage,
  readFile: readFile,
  withTheme: withTheme
});

const {
  DropzoneArea: DropzoneArea$1
} = MuiFileDropzone;
function File$1({
  name,
  accept,
  hint,
  label
}) {
  const [, {
      initialValue
    }, {
      setValue
    }] = useField(name),
    loadedRef = reactExports$1.useRef(null);
  const initialFiles = reactExports$1.useMemo(() => {
      if (!initialValue || initialValue === "__clear__") {
        return [];
      } else if (initialValue.type && initialValue.body) {
        return [initialValue.body];
      } else if (typeof initialValue === "string") {
        return [initialValue];
      }
    }, [initialValue]),
    acceptedFiles = reactExports$1.useMemo(() => accept ? accept.split(",") : null, [accept]),
    setFile = reactExports$1.useCallback(files => {
      if (!loadedRef.current) {
        // initialFiles loaded
        loadedRef.current = files && files.length ? files[0] : true;
        return;
      }
      if (files && files.length) {
        if (files[0] !== loadedRef.current) {
          const {
            name,
            type
          } = files[0];
          setValue({
            name,
            type,
            body: files[0]
          });
        }
      } else if (initialValue) {
        setValue("__clear__");
      } else {
        setValue(null);
      }
    }, [initialValue]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(InputLabel$1, {
    shrink: true
  }, label), /*#__PURE__*/React.createElement(DropzoneArea$1, {
    initialFiles: initialFiles,
    acceptedFiles: acceptedFiles,
    onChange: setFile,
    filesLimit: 1,
    maxFileSize: 100000000
  }), /*#__PURE__*/React.createElement(HelperText, {
    name: name,
    hint: hint
  }));
}
File$1.propTypes = {
  name: PropTypes.string,
  accept: PropTypes.string,
  label: PropTypes.string,
  hint: PropTypes.string
};

function Image(props) {
  return /*#__PURE__*/React.createElement(File$1, {
    accept: "image/*",
    ...props
  });
}

function ContextCheckbox({
  value,
  field
}) {
  const {
    values
  } = useFormikContext();
  const checked = (getIn(values, field) || []).some(val => val === value);
  return /*#__PURE__*/React.createElement(Checkbox$1, {
    checked: checked
  });
}
ContextCheckbox.propTypes = {
  value: PropTypes.string,
  field: PropTypes.string
};
function Select({
  choices,
  label,
  required,
  native,
  placeholder,
  renderValue,
  InputLabelProps,
  ...rest
}) {
  const {
      name: fieldName,
      type,
      hint
    } = rest,
    {
      errors,
      touched
    } = useFormikContext(),
    showError = !!getIn(errors, fieldName) && getIn(touched, fieldName),
    multiple = type === "select";
  if (multiple && !renderValue) {
    renderValue = sel => sel.map(getLabel).join(", ");
  }
  if (placeholder && !renderValue) {
    renderValue = sel => getLabel(sel) || sel || placeholder;
  }
  const getLabel = reactExports$1.useMemo(() => {
    const labels = {};
    choices.forEach(({
      name,
      label
    }) => {
      labels[name] = label;
    });
    return name => labels[name];
  }, [choices]);
  const choiceGroups = reactExports$1.useMemo(() => {
    const choiceGroups = {};
    choices.forEach(choice => {
      const group = choice.group || "";
      if (!choiceGroups[group]) {
        choiceGroups[group] = [];
      }
      choiceGroups[group].push(choice);
    });
    return choiceGroups;
  }, [choices]);
  const Option = reactExports$1.useMemo(() => native ? ({
    value,
    children
  }) => /*#__PURE__*/React.createElement("option", {
    value: value
  }, children) : ({
    children,
    ...rest
  }) => /*#__PURE__*/React.createElement(MenuItem$1, {
    ...rest
  }, multiple && /*#__PURE__*/React.createElement(ContextCheckbox, {
    value: rest["data-value"],
    field: fieldName
  }), /*#__PURE__*/React.createElement(ListItemText$1, {
    primary: children,
    "data-value": rest["data-value"],
    primaryTypographyProps: {
      "data-value": rest["data-value"]
    }
  })), [native, multiple, fieldName]);
  const renderChoices = choices => choices.map(({
    name,
    label
  }) => /*#__PURE__*/React.createElement(Option, {
    key: name,
    value: name
  }, label));
  const renderGroups = native ? choiceGroups => Object.entries(choiceGroups).map(([group, choices]) => group ? /*#__PURE__*/React.createElement("optgroup", {
    key: group,
    label: group
  }, renderChoices(choices)) : /*#__PURE__*/React.createElement(React.Fragment, null, renderChoices(choices))) : choiceGroups => {
    const flattened = [];
    Object.entries(choiceGroups).forEach(([group, choices]) => {
      if (group) {
        flattened.push( /*#__PURE__*/React.createElement(ListSubheader$1, {
          style: {
            backgroundColor: "white"
          }
        }, group));
      }
      flattened.push(...renderChoices(choices));
    });
    return flattened;
  };
  return /*#__PURE__*/React.createElement(Field, {
    component: Select$1,
    formControl: {
      fullWidth: true,
      margin: "dense"
    },
    inputLabel: {
      required,
      error: showError,
      ...InputLabelProps
    },
    formHelperText: {
      children: hint
    },
    multiple: multiple,
    required: required,
    native: native,
    label: label,
    renderValue: renderValue,
    displayEmpty: !!placeholder,
    ...(InputLabelProps && InputLabelProps.shrink ? {
      notched: true
    } : {}),
    ...rest
  }, !multiple && /*#__PURE__*/React.createElement(Option, {
    value: "",
    disabled: !!required
  }, required ? "Select one..." : "(No Selection)"), renderGroups(choiceGroups));
}
Select.propTypes = {
  choices: PropTypes.arrayOf(PropTypes.object),
  label: PropTypes.string,
  placeholder: PropTypes.string,
  required: PropTypes.bool,
  native: PropTypes.bool,
  renderValue: PropTypes.func,
  InputLabelProps: PropTypes.object
};

function Radio({
  choices,
  label,
  ...rest
}) {
  return /*#__PURE__*/React.createElement(FormControl$1, {
    component: "fieldset",
    fullWidth: true,
    margin: "dense"
  }, /*#__PURE__*/React.createElement(FormLabel$1, {
    component: "legend"
  }, label), /*#__PURE__*/React.createElement(Field, {
    component: RadioGroup,
    ...rest
  }, choices.map(({
    name,
    label
  }) => /*#__PURE__*/React.createElement(FormControlLabel$1, {
    key: name,
    value: name,
    label: label,
    control: /*#__PURE__*/React.createElement(Radio$2, null)
  }))), /*#__PURE__*/React.createElement(HelperText, {
    name: rest.name,
    hint: rest.hint
  }));
}
Radio.propTypes = {
  choices: PropTypes.arrayOf(PropTypes.object),
  label: PropTypes.string
};

function getToggleButtonUtilityClass(slot) {
  return generateUtilityClass('MuiToggleButton', slot);
}
const toggleButtonClasses = generateUtilityClasses('MuiToggleButton', ['root', 'disabled', 'selected', 'standard', 'primary', 'secondary', 'sizeSmall', 'sizeMedium', 'sizeLarge']);
var toggleButtonClasses$1 = toggleButtonClasses;

const _excluded$e = ["children", "className", "color", "disabled", "disableFocusRipple", "fullWidth", "onChange", "onClick", "selected", "size", "value"];
const useUtilityClasses$c = ownerState => {
  const {
    classes,
    fullWidth,
    selected,
    disabled,
    size,
    color
  } = ownerState;
  const slots = {
    root: ['root', selected && 'selected', disabled && 'disabled', fullWidth && 'fullWidth', `size${capitalize(size)}`, color]
  };
  return composeClasses(slots, getToggleButtonUtilityClass, classes);
};
const ToggleButtonRoot = styled$1(ButtonBase$1, {
  name: 'MuiToggleButton',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`size${capitalize(ownerState.size)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  let selectedColor = ownerState.color === 'standard' ? theme.palette.text.primary : theme.palette[ownerState.color].main;
  let selectedColorChannel;
  if (theme.vars) {
    selectedColor = ownerState.color === 'standard' ? theme.vars.palette.text.primary : theme.vars.palette[ownerState.color].main;
    selectedColorChannel = ownerState.color === 'standard' ? theme.vars.palette.text.primaryChannel : theme.vars.palette[ownerState.color].mainChannel;
  }
  return _extends({}, theme.typography.button, {
    borderRadius: (theme.vars || theme).shape.borderRadius,
    padding: 11,
    border: `1px solid ${(theme.vars || theme).palette.divider}`,
    color: (theme.vars || theme).palette.action.active
  }, ownerState.fullWidth && {
    width: '100%'
  }, {
    [`&.${toggleButtonClasses$1.disabled}`]: {
      color: (theme.vars || theme).palette.action.disabled,
      border: `1px solid ${(theme.vars || theme).palette.action.disabledBackground}`
    },
    '&:hover': {
      textDecoration: 'none',
      // Reset on mouse devices
      backgroundColor: theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity),
      '@media (hover: none)': {
        backgroundColor: 'transparent'
      }
    },
    [`&.${toggleButtonClasses$1.selected}`]: {
      color: selectedColor,
      backgroundColor: theme.vars ? `rgba(${selectedColorChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(selectedColor, theme.palette.action.selectedOpacity),
      '&:hover': {
        backgroundColor: theme.vars ? `rgba(${selectedColorChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(selectedColor, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: theme.vars ? `rgba(${selectedColorChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(selectedColor, theme.palette.action.selectedOpacity)
        }
      }
    }
  }, ownerState.size === 'small' && {
    padding: 7,
    fontSize: theme.typography.pxToRem(13)
  }, ownerState.size === 'large' && {
    padding: 15,
    fontSize: theme.typography.pxToRem(15)
  });
});
const ToggleButton = /*#__PURE__*/reactExports$1.forwardRef(function ToggleButton(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiToggleButton'
  });
  const {
      children,
      className,
      color = 'standard',
      disabled = false,
      disableFocusRipple = false,
      fullWidth = false,
      onChange,
      onClick,
      selected,
      size = 'medium',
      value
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$e);
  const ownerState = _extends({}, props, {
    color,
    disabled,
    disableFocusRipple,
    fullWidth,
    size
  });
  const classes = useUtilityClasses$c(ownerState);
  const handleChange = event => {
    if (onClick) {
      onClick(event, value);
      if (event.defaultPrevented) {
        return;
      }
    }
    if (onChange) {
      onChange(event, value);
    }
  };
  return /*#__PURE__*/jsxRuntimeExports.jsx(ToggleButtonRoot, _extends({
    className: clsx(classes.root, className),
    disabled: disabled,
    focusRipple: !disableFocusRipple,
    ref: ref,
    onClick: handleChange,
    onChange: onChange,
    value: value,
    ownerState: ownerState,
    "aria-pressed": selected
  }, other, {
    children: children
  }));
});
ToggleButton.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the button when it is in an active state.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'standard'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['standard', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: PropTypes.bool,
  /**
   * If `true`, the  keyboard focus ripple is disabled.
   * @default false
   */
  disableFocusRipple: PropTypes.bool,
  /**
   * If `true`, the ripple effect is disabled.
   *
   * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
   * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.
   * @default false
   */
  disableRipple: PropTypes.bool,
  /**
   * If `true`, the button will take up the full width of its container.
   * @default false
   */
  fullWidth: PropTypes.bool,
  /**
   * Callback fired when the state changes.
   *
   * @param {React.MouseEvent<HTMLElement>} event The event source of the callback.
   * @param {any} value of the selected button.
   */
  onChange: PropTypes.func,
  /**
   * Callback fired when the button is clicked.
   *
   * @param {React.MouseEvent<HTMLElement>} event The event source of the callback.
   * @param {any} value of the selected button.
   */
  onClick: PropTypes.func,
  /**
   * If `true`, the button is rendered in an active state.
   */
  selected: PropTypes.bool,
  /**
   * The size of the component.
   * The prop defaults to the value inherited from the parent ToggleButtonGroup component.
   * @default 'medium'
   */
  size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value to associate with the button when selected in a
   * ToggleButtonGroup.
   */
  value: PropTypes /* @typescript-to-proptypes-ignore */.any.isRequired
} ;
var ToggleButton$1 = ToggleButton;

function Toggle({
  choices,
  label,
  ...rest
}) {
  return /*#__PURE__*/React.createElement(FormControl$1, {
    component: "fieldset",
    fullWidth: true,
    margin: "dense"
  }, /*#__PURE__*/React.createElement(FormLabel$1, {
    component: "legend"
  }, label), /*#__PURE__*/React.createElement(Field, {
    component: ToggleButtonGroup,
    exclusive: true,
    ...rest,
    type: "checkbox"
  }, choices.map(({
    name,
    label
  }) => /*#__PURE__*/React.createElement(ToggleButton$1, {
    key: name,
    value: name
  }, label))), /*#__PURE__*/React.createElement(HelperText, {
    name: rest.name,
    hint: rest.hint
  }));
}
Toggle.propTypes = {
  choices: PropTypes.arrayOf(PropTypes.object),
  label: PropTypes.string
};

function Hidden$1(props) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Field, {
    ...props,
    type: "hidden"
  }), /*#__PURE__*/React.createElement(HelperText, {
    name: props.name,
    hint: props.hint
  }));
}
Hidden$1.propTypes = {
  name: PropTypes.string,
  hint: PropTypes.string
};

function getCardUtilityClass(slot) {
  return generateUtilityClass('MuiCard', slot);
}
generateUtilityClasses('MuiCard', ['root']);

const _excluded$d = ["className", "raised"];
const useUtilityClasses$b = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getCardUtilityClass, classes);
};
const CardRoot = styled$1(Paper$1, {
  name: 'MuiCard',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => {
  return {
    overflow: 'hidden'
  };
});
const Card = /*#__PURE__*/reactExports$1.forwardRef(function Card(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiCard'
  });
  const {
      className,
      raised = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$d);
  const ownerState = _extends({}, props, {
    raised
  });
  const classes = useUtilityClasses$b(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(CardRoot, _extends({
    className: clsx(classes.root, className),
    elevation: raised ? 8 : undefined,
    ref: ref,
    ownerState: ownerState
  }, other));
});
Card.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * If `true`, the card will use raised styling.
   * @default false
   */
  raised: chainPropTypes(PropTypes.bool, props => {
    if (props.raised && props.variant === 'outlined') {
      return new Error('MUI: Combining `raised={true}` with `variant="outlined"` has no effect.');
    }
    return null;
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var Card$1 = Card;

function getCardContentUtilityClass(slot) {
  return generateUtilityClass('MuiCardContent', slot);
}
generateUtilityClasses('MuiCardContent', ['root']);

const _excluded$c = ["className", "component"];
const useUtilityClasses$a = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getCardContentUtilityClass, classes);
};
const CardContentRoot = styled$1('div', {
  name: 'MuiCardContent',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => {
  return {
    padding: 16,
    '&:last-child': {
      paddingBottom: 24
    }
  };
});
const CardContent = /*#__PURE__*/reactExports$1.forwardRef(function CardContent(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiCardContent'
  });
  const {
      className,
      component = 'div'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$c);
  const ownerState = _extends({}, props, {
    component
  });
  const classes = useUtilityClasses$a(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(CardContentRoot, _extends({
    as: component,
    className: clsx(classes.root, className),
    ownerState: ownerState,
    ref: ref
  }, other));
});
CardContent.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var CardContent$1 = CardContent;

function Fieldset({
  label,
  children
}) {
  return /*#__PURE__*/React.createElement(Card$1, {
    sx: {
      mb: 2
    }
  }, /*#__PURE__*/React.createElement(CardContent$1, null, label && /*#__PURE__*/React.createElement(Typography$1, {
    color: "textSecondary"
  }, label), children));
}
Fieldset.propTypes = {
  label: PropTypes.string,
  children: PropTypes.node
};

function FlatFieldset({
  label,
  children
}) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Typography$1, {
    color: "textSecondary"
  }, label), children);
}
FlatFieldset.propTypes = {
  label: PropTypes.string,
  children: PropTypes.node
};

function FieldsetArray({
  label,
  children,
  addRow
}) {
  const {
    View,
    Button
  } = useComponents();
  return /*#__PURE__*/React.createElement(View, null, children, addRow && /*#__PURE__*/React.createElement(Button, {
    onClick: () => addRow()
  }, `Add ${label}`));
}
FieldsetArray.propTypes = {
  label: PropTypes.string,
  children: PropTypes.node,
  addRow: PropTypes.func
};

const {
  DropzoneArea
} = MuiFileDropzone;
function FileArray({
  name,
  label,
  subform,
  hint,
  maxRows
}) {
  const [, {
      initialValue = []
    }, {
      setValue
    }] = useField(name),
    fileField = subform.find(field => field.type === "file" || field.type === "image") || {
      name: "file",
      type: "file"
    },
    accept = fileField.type === "image" ? "image/*" : null,
    loadedRef = reactExports$1.useRef(null);
  const initialFiles = reactExports$1.useMemo(() => {
      if (!initialValue || initialValue.length === 0) {
        return [];
      }
      return initialValue.filter(row => {
        if (!row[fileField.name] || row[fileField.name] === "__clear__") {
          return false;
        }
        return true;
      }).map(row => {
        const value = row[fileField.name];
        if (value.type && value.body) {
          return value.body;
        } else if (typeof value === "string") {
          return value;
        }
      });
    }, [initialValue]),
    acceptedFiles = reactExports$1.useMemo(() => accept ? accept.split(",") : null, [accept]),
    setFiles = reactExports$1.useCallback(files => {
      if (!loadedRef.current) {
        // initialFiles loaded
        let fileIndex = 0;
        loadedRef.current = initialValue.map(row => {
          let file;
          if (row[fileField.name] && row[fileField.name] !== "__clear__") {
            file = files[fileIndex];
            fileIndex++;
          }
          return {
            row,
            file
          };
        });
        return;
      }
      const nextValue = files.map((file, i) => {
        const {
          row,
          file: initialFile
        } = loadedRef.current[i] || {
          row: {},
          file: null
        };
        if (initialFile === file) {
          return row;
        } else {
          return {
            ...row,
            [fileField.name]: {
              name: file.name,
              type: file.type,
              body: file
            }
          };
        }
      });
      if (initialValue && nextValue.length < initialValue.length) {
        initialValue.slice(nextValue.length).forEach(row => {
          nextValue.push({
            ...row,
            [fileField.name]: "__clear__"
          });
        });
      }
      setValue(nextValue);
    }, [initialValue]);
  return /*#__PURE__*/React.createElement(Fieldset, {
    label: label
  }, /*#__PURE__*/React.createElement(DropzoneArea, {
    initialFiles: initialFiles,
    acceptedFiles: acceptedFiles,
    onChange: setFiles,
    filesLimit: maxRows
  }), /*#__PURE__*/React.createElement(HelperText, {
    name: name,
    hint: hint
  }));
}
FileArray.Fieldset = function EmptyFieldset() {
  return null;
};
FileArray.propTypes = {
  name: PropTypes.string,
  accept: PropTypes.string,
  label: PropTypes.string,
  subform: PropTypes.arrayOf(PropTypes.object),
  hint: PropTypes.string,
  maxRows: PropTypes.number
};

const Date$1 = DateTime;
const Time = DateTime;
const dateTime = DateTime;

var inputs = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Checkbox: Input,
  Date: Date$1,
  DateTime: DateTime,
  Fieldset: Fieldset,
  FieldsetArray: FieldsetArray,
  File: File$1,
  FileArray: FileArray,
  FlatFieldset: FlatFieldset,
  HelperText: HelperText,
  Hidden: Hidden$1,
  Image: Image,
  Input: Input$1,
  Radio: Radio,
  Select: Select,
  Time: Time,
  Toggle: Toggle,
  dateTime: dateTime
});

var Add = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"
}), 'Add');

var Edit = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
}), 'Edit');

var Delete = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"
}), 'Delete');

var Done = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M9 16.2 4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"
}), 'Done');

var Error$1 = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"
}), 'Error');

var Sync = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"
}), 'Sync');

var Close = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), 'Close');

var ExpandMore = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"
}), 'ExpandMore');

var ExpandLess = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"
}), 'ExpandLess');

var ChevronRight = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"
}), 'ChevronRight');

var ChevronLeft = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"
}), 'ChevronLeft');

var GpsFixed = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"
}), 'GpsFixed');

var GpsOff = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"
}), 'GpsOff');

var Search = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
}), 'Search');

var ListAlt = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 5v14H5V5h14m1.1-2H3.9c-.5 0-.9.4-.9.9v16.2c0 .4.4.9.9.9h16.2c.4 0 .9-.5.9-.9V3.9c0-.5-.5-.9-.9-.9zM11 7h6v2h-6V7zm0 4h6v2h-6v-2zm0 4h6v2h-6zM7 7h2v2H7zm0 4h2v2H7zm0 4h2v2H7z"
}), 'ListAlt');

var Info = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"
}), 'Info');

var Map$4 = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "m20.5 3-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5zM15 19l-6-2.11V5l6 2.11V19z"
}), 'Map');

var Home = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"
}), 'Home');

var NavigateNext = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"
}), 'NavigateNext');

var Menu = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"
}), 'Menu');

var Login = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M11 7 9.6 8.4l2.6 2.6H2v2h10.2l-2.6 2.6L11 17l5-5-5-5zm9 12h-8v2h8c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-8v2h8v14z"
}), 'Login');

var Logout = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "m17 7-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"
}), 'Logout');

var Settings = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"
}), 'Settings');

var OpenInNew = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"
}), 'OpenInNew');

var icons = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Add: Add,
  BreadcrumbSeparator: NavigateNext,
  Close: Close,
  Collapse: ExpandLess,
  Config: Settings,
  Delete: Delete,
  Detail: Info,
  Edit: Edit,
  Error: Error$1,
  Expand: ExpandMore,
  External: OpenInNew,
  GpsStart: GpsFixed,
  GpsStop: GpsOff,
  Home: Home,
  List: ListAlt,
  Login: Login,
  Logout: Logout,
  Map: Map$4,
  Menu: Menu,
  PanelClose: ChevronLeft,
  PanelOpen: ChevronRight,
  Pending: Sync,
  Search: Search,
  Success: Done
});

function toInteger(dirtyNumber) {
  if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
    return NaN;
  }
  var number = Number(dirtyNumber);
  if (isNaN(number)) {
    return number;
  }
  return number < 0 ? Math.ceil(number) : Math.floor(number);
}

function requiredArgs(required, args) {
  if (args.length < required) {
    throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
  }
}

/**
 * @name toDate
 * @category Common Helpers
 * @summary Convert the given argument to an instance of Date.
 *
 * @description
 * Convert the given argument to an instance of Date.
 *
 * If the argument is an instance of Date, the function returns its clone.
 *
 * If the argument is a number, it is treated as a timestamp.
 *
 * If the argument is none of the above, the function returns Invalid Date.
 *
 * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
 *
 * @param {Date|Number} argument - the value to convert
 * @returns {Date} the parsed date in the local time zone
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // Clone the date:
 * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
 * //=> Tue Feb 11 2014 11:30:30
 *
 * @example
 * // Convert the timestamp to date:
 * const result = toDate(1392098430000)
 * //=> Tue Feb 11 2014 11:30:30
 */
function toDate(argument) {
  requiredArgs(1, arguments);
  var argStr = Object.prototype.toString.call(argument);

  // Clone the date
  if (argument instanceof Date || _typeof$c(argument) === 'object' && argStr === '[object Date]') {
    // Prevent the date to lose the milliseconds when passed to new Date() in IE10
    return new Date(argument.getTime());
  } else if (typeof argument === 'number' || argStr === '[object Number]') {
    return new Date(argument);
  } else {
    if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
      // eslint-disable-next-line no-console
      console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
      // eslint-disable-next-line no-console
      console.warn(new Error().stack);
    }
    return new Date(NaN);
  }
}

/**
 * Days in 1 week.
 *
 * @name daysInWeek
 * @constant
 * @type {number}
 * @default
 */

/**
 * Milliseconds in 1 minute
 *
 * @name millisecondsInMinute
 * @constant
 * @type {number}
 * @default
 */
var millisecondsInMinute = 60000;

/**
 * Milliseconds in 1 hour
 *
 * @name millisecondsInHour
 * @constant
 * @type {number}
 * @default
 */
var millisecondsInHour = 3600000;

/**
 * @name isDate
 * @category Common Helpers
 * @summary Is the given value a date?
 *
 * @description
 * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
 *
 * @param {*} value - the value to check
 * @returns {boolean} true if the given value is a date
 * @throws {TypeError} 1 arguments required
 *
 * @example
 * // For a valid date:
 * const result = isDate(new Date())
 * //=> true
 *
 * @example
 * // For an invalid date:
 * const result = isDate(new Date(NaN))
 * //=> true
 *
 * @example
 * // For some value:
 * const result = isDate('2014-02-31')
 * //=> false
 *
 * @example
 * // For an object:
 * const result = isDate({})
 * //=> false
 */
function isDate(value) {
  requiredArgs(1, arguments);
  return value instanceof Date || _typeof$c(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
}

/**
 * @name isValid
 * @category Common Helpers
 * @summary Is the given date valid?
 *
 * @description
 * Returns false if argument is Invalid Date and true otherwise.
 * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
 * Invalid Date is a Date, whose time value is NaN.
 *
 * Time value of Date: http://es5.github.io/#x15.9.1.1
 *
 * @param {*} date - the date to check
 * @returns {Boolean} the date is valid
 * @throws {TypeError} 1 argument required
 *
 * @example
 * // For the valid date:
 * const result = isValid(new Date(2014, 1, 31))
 * //=> true
 *
 * @example
 * // For the value, convertable into a date:
 * const result = isValid(1393804800000)
 * //=> true
 *
 * @example
 * // For the invalid date:
 * const result = isValid(new Date(''))
 * //=> false
 */
function isValid(dirtyDate) {
  requiredArgs(1, arguments);
  if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
    return false;
  }
  var date = toDate(dirtyDate);
  return !isNaN(Number(date));
}

function addLeadingZeros(number, targetLength) {
  var sign = number < 0 ? '-' : '';
  var output = Math.abs(number).toString();
  while (output.length < targetLength) {
    output = '0' + output;
  }
  return sign + output;
}

/**
 * @name formatISO9075
 * @category Common Helpers
 * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format).
 *
 * @description
 * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date.
 *
 * @param {Date|Number} date - the original date
 * @param {Object} [options] - an object with options.
 * @param {'extended'|'basic'} [options.format='extended'] - if 'basic', hide delimiters between date and time values.
 * @param {'complete'|'date'|'time'} [options.representation='complete'] - format date, time, or both.
 * @returns {String} the formatted date string
 * @throws {TypeError} 1 argument required
 * @throws {RangeError} `date` must not be Invalid Date
 * @throws {RangeError} `options.format` must be 'extended' or 'basic'
 * @throws {RangeError} `options.representation` must be 'date', 'time' or 'complete'
 *
 * @example
 * // Represent 18 September 2019 in ISO 9075 format:
 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52))
 * //=> '2019-09-18 19:00:52'
 *
 * @example
 * // Represent 18 September 2019 in ISO 9075, short format:
 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })
 * //=> '20190918 190052'
 *
 * @example
 * // Represent 18 September 2019 in ISO 9075 format, date only:
 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })
 * //=> '2019-09-18'
 *
 * @example
 * // Represent 18 September 2019 in ISO 9075 format, time only:
 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })
 * //=> '19:00:52'
 */
function formatISO9075(dirtyDate, options) {
  var _options$format, _options$representati;
  if (arguments.length < 1) {
    throw new TypeError("1 argument required, but only ".concat(arguments.length, " present"));
  }
  var originalDate = toDate(dirtyDate);
  if (!isValid(originalDate)) {
    throw new RangeError('Invalid time value');
  }
  var format = String((_options$format = options === null || options === void 0 ? void 0 : options.format) !== null && _options$format !== void 0 ? _options$format : 'extended');
  var representation = String((_options$representati = options === null || options === void 0 ? void 0 : options.representation) !== null && _options$representati !== void 0 ? _options$representati : 'complete');
  if (format !== 'extended' && format !== 'basic') {
    throw new RangeError("format must be 'extended' or 'basic'");
  }
  if (representation !== 'date' && representation !== 'time' && representation !== 'complete') {
    throw new RangeError("representation must be 'date', 'time', or 'complete'");
  }
  var result = '';
  var dateDelimiter = format === 'extended' ? '-' : '';
  var timeDelimiter = format === 'extended' ? ':' : '';

  // Representation is either 'date' or 'complete'
  if (representation !== 'time') {
    var day = addLeadingZeros(originalDate.getDate(), 2);
    var month = addLeadingZeros(originalDate.getMonth() + 1, 2);
    var year = addLeadingZeros(originalDate.getFullYear(), 4);

    // yyyyMMdd or yyyy-MM-dd.
    result = "".concat(year).concat(dateDelimiter).concat(month).concat(dateDelimiter).concat(day);
  }

  // Representation is either 'time' or 'complete'
  if (representation !== 'date') {
    var hour = addLeadingZeros(originalDate.getHours(), 2);
    var minute = addLeadingZeros(originalDate.getMinutes(), 2);
    var second = addLeadingZeros(originalDate.getSeconds(), 2);

    // If there's also date, separate it with time with a space
    var separator = result === '' ? '' : ' ';

    // HHmmss or HH:mm:ss.
    result = "".concat(result).concat(separator).concat(hour).concat(timeDelimiter).concat(minute).concat(timeDelimiter).concat(second);
  }
  return result;
}

/**
 * @name parseISO
 * @category Common Helpers
 * @summary Parse ISO string
 *
 * @description
 * Parse the given string in ISO 8601 format and return an instance of Date.
 *
 * Function accepts complete ISO 8601 formats as well as partial implementations.
 * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
 *
 * If the argument isn't a string, the function cannot parse the string or
 * the values are invalid, it returns Invalid Date.
 *
 * @param {String} argument - the value to convert
 * @param {Object} [options] - an object with options.
 * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format
 * @returns {Date} the parsed date in the local time zone
 * @throws {TypeError} 1 argument required
 * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
 *
 * @example
 * // Convert string '2014-02-11T11:30:30' to date:
 * const result = parseISO('2014-02-11T11:30:30')
 * //=> Tue Feb 11 2014 11:30:30
 *
 * @example
 * // Convert string '+02014101' to date,
 * // if the additional number of digits in the extended year format is 1:
 * const result = parseISO('+02014101', { additionalDigits: 1 })
 * //=> Fri Apr 11 2014 00:00:00
 */
function parseISO(argument, options) {
  var _options$additionalDi;
  requiredArgs(1, arguments);
  var additionalDigits = toInteger((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2);
  if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
    throw new RangeError('additionalDigits must be 0, 1 or 2');
  }
  if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) {
    return new Date(NaN);
  }
  var dateStrings = splitDateString(argument);
  var date;
  if (dateStrings.date) {
    var parseYearResult = parseYear(dateStrings.date, additionalDigits);
    date = parseDate(parseYearResult.restDateString, parseYearResult.year);
  }
  if (!date || isNaN(date.getTime())) {
    return new Date(NaN);
  }
  var timestamp = date.getTime();
  var time = 0;
  var offset;
  if (dateStrings.time) {
    time = parseTime(dateStrings.time);
    if (isNaN(time)) {
      return new Date(NaN);
    }
  }
  if (dateStrings.timezone) {
    offset = parseTimezone(dateStrings.timezone);
    if (isNaN(offset)) {
      return new Date(NaN);
    }
  } else {
    var dirtyDate = new Date(timestamp + time);
    // js parsed string assuming it's in UTC timezone
    // but we need it to be parsed in our timezone
    // so we use utc values to build date in our timezone.
    // Year values from 0 to 99 map to the years 1900 to 1999
    // so set year explicitly with setFullYear.
    var result = new Date(0);
    result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate());
    result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
    return result;
  }
  return new Date(timestamp + time + offset);
}
var patterns = {
  dateTimeDelimiter: /[T ]/,
  timeZoneDelimiter: /[Z ]/i,
  timezone: /([Z+-].*)$/
};
var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
function splitDateString(dateString) {
  var dateStrings = {};
  var array = dateString.split(patterns.dateTimeDelimiter);
  var timeString;

  // The regex match should only return at maximum two array elements.
  // [date], [time], or [date, time].
  if (array.length > 2) {
    return dateStrings;
  }
  if (/:/.test(array[0])) {
    timeString = array[0];
  } else {
    dateStrings.date = array[0];
    timeString = array[1];
    if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
      dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
      timeString = dateString.substr(dateStrings.date.length, dateString.length);
    }
  }
  if (timeString) {
    var token = patterns.timezone.exec(timeString);
    if (token) {
      dateStrings.time = timeString.replace(token[1], '');
      dateStrings.timezone = token[1];
    } else {
      dateStrings.time = timeString;
    }
  }
  return dateStrings;
}
function parseYear(dateString, additionalDigits) {
  var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)');
  var captures = dateString.match(regex);
  // Invalid ISO-formatted year
  if (!captures) return {
    year: NaN,
    restDateString: ''
  };
  var year = captures[1] ? parseInt(captures[1]) : null;
  var century = captures[2] ? parseInt(captures[2]) : null;

  // either year or century is null, not both
  return {
    year: century === null ? year : century * 100,
    restDateString: dateString.slice((captures[1] || captures[2]).length)
  };
}
function parseDate(dateString, year) {
  // Invalid ISO-formatted year
  if (year === null) return new Date(NaN);
  var captures = dateString.match(dateRegex);
  // Invalid ISO-formatted string
  if (!captures) return new Date(NaN);
  var isWeekDate = !!captures[4];
  var dayOfYear = parseDateUnit(captures[1]);
  var month = parseDateUnit(captures[2]) - 1;
  var day = parseDateUnit(captures[3]);
  var week = parseDateUnit(captures[4]);
  var dayOfWeek = parseDateUnit(captures[5]) - 1;
  if (isWeekDate) {
    if (!validateWeekDate(year, week, dayOfWeek)) {
      return new Date(NaN);
    }
    return dayOfISOWeekYear(year, week, dayOfWeek);
  } else {
    var date = new Date(0);
    if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
      return new Date(NaN);
    }
    date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
    return date;
  }
}
function parseDateUnit(value) {
  return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
  var captures = timeString.match(timeRegex);
  if (!captures) return NaN; // Invalid ISO-formatted time

  var hours = parseTimeUnit(captures[1]);
  var minutes = parseTimeUnit(captures[2]);
  var seconds = parseTimeUnit(captures[3]);
  if (!validateTime(hours, minutes, seconds)) {
    return NaN;
  }
  return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000;
}
function parseTimeUnit(value) {
  return value && parseFloat(value.replace(',', '.')) || 0;
}
function parseTimezone(timezoneString) {
  if (timezoneString === 'Z') return 0;
  var captures = timezoneString.match(timezoneRegex);
  if (!captures) return 0;
  var sign = captures[1] === '+' ? -1 : 1;
  var hours = parseInt(captures[2]);
  var minutes = captures[3] && parseInt(captures[3]) || 0;
  if (!validateTimezone(hours, minutes)) {
    return NaN;
  }
  return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
  var date = new Date(0);
  date.setUTCFullYear(isoWeekYear, 0, 4);
  var fourthOfJanuaryDay = date.getUTCDay() || 7;
  var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
  date.setUTCDate(date.getUTCDate() + diff);
  return date;
}

// Validation functions

// February is null to handle the leap year (using ||)
var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function validateDate(year, month, date) {
  return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
}
function validateDayOfYearDate(year, dayOfYear) {
  return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
}
function validateWeekDate(_year, week, day) {
  return week >= 1 && week <= 53 && day >= 0 && day <= 6;
}
function validateTime(hours, minutes, seconds) {
  if (hours === 24) {
    return minutes === 0 && seconds === 0;
  }
  return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
}
function validateTimezone(_hours, minutes) {
  return minutes >= 0 && minutes <= 59;
}

const format = {
  date: value => tryFormat(value, {
    representation: "date"
  }),
  time: value => tryFormat(value, {
    representation: "time"
  }),
  datetime: value => tryFormat(value)
};
function tryFormat(value, options) {
  try {
    return formatISO9075(value, options);
  } catch (e) {
    return value;
  }
}
const parse = {
  date: value => value ? parseISO(value) : null,
  time: value => value ? parseISO("9999-01-01 " + value) : null,
  datetime: value => value ? parseISO(value) : null
};

var material = {
  name: "material",
  dependencies: [react],
  config: {
    theme: {
      primary: "#7500ae",
      secondary: "#0088bd"
    },
    inputFormat: {
      date: "yyyy-MM-dd",
      time: "HH:mm",
      datetime: "yyyy-MM-dd HH:mm"
    }
  },
  components: {
    App,
    ...components
  },
  inputs: {
    ...inputs
  },
  icons: {
    ...icons
  },
  init(config) {
    if (!config) {
      return;
    }
    if (config.theme) {
      if (config.theme.palette) {
        this.config.theme = config.theme;
      } else {
        Object.assign(this.config.theme, config.theme);
      }
    }
    if (config.inputFormat) {
      Object.assign(this.config.inputFormat, config.inputFormat);
    }
  }
};

var materialExports = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Accordion: Accordion,
  App: App,
  BottomNavigation: BottomNavigation$1,
  BottomNavigationAction: BottomNavigationAction,
  Breadcrumbs: Breadcrumbs,
  Button: Button,
  ButtonLink: ButtonLink,
  CancelButton: ButtonLink,
  Checkbox: Input,
  CheckboxButton: Checkbox$1,
  Chip: Chip,
  Container: Container,
  Date: Date$1,
  DateTime: DateTime,
  DeleteForm: DeleteForm,
  Divider: Divider$1,
  ExpandableListItem: ExpandableListItem,
  ExpansionPanel: Accordion,
  Fab: Fab,
  Fieldset: Fieldset,
  FieldsetArray: FieldsetArray,
  File: File$1,
  FileArray: FileArray,
  FlatFieldset: FlatFieldset,
  Footer: Footer,
  FooterContent: FooterContent,
  FormError: FormError,
  FormRoot: FormRoot,
  FormatJson: FormatJson,
  Header: Header,
  HelperText: HelperText,
  Hidden: Hidden$1,
  HomeLink: HomeLink,
  HorizontalView: HorizontalView,
  IconButton: IconButton,
  IconSubmitButton: IconSubmitButton,
  Image: Image,
  Input: Input$1,
  Link: Link,
  List: List,
  ListItem: ListItem,
  ListItemLink: ListItemLink,
  ListSubheader: ListSubheader$1,
  Main: Main,
  NavMenuFixed: NavMenuFixed,
  NavMenuPopup: NavMenuPopup,
  Pagination: Pagination,
  Popup: Popup$2,
  Radio: Radio,
  RadioButton: Radio$2,
  ScrollView: ScrollView,
  Select: Select,
  SidePanel: SidePanel,
  Spinner: Spinner,
  SubmitButton: SubmitButton,
  Switch: Switch$1,
  TabGroup: TabGroup,
  TabItem: TabItem,
  Table: Table$1,
  TableBody: TableBody$1,
  TableCell: TableCell$1,
  TableContainer: TableContainer$1,
  TableHead: TableHead$1,
  TablePagination: TablePagination$1,
  TableRow: TableRow$1,
  TableTitle: TableCell$1,
  Text: Fragment,
  Time: Time,
  Toggle: Toggle,
  Typography: Typography$1,
  View: View,
  dateTime: dateTime,
  default: material,
  format: format,
  parse: parse,
  useMinWidth: useMinWidth
});

const TYPE_MAP = {
  geopoint: "point",
  geotrace: "line_string",
  geoshape: "polygon"
};
function useBasemapComponents() {
  return usePluginComponentMap("map", "basemaps");
}
function useOverlayComponents() {
  return usePluginComponentMap("map", "overlays");
}
function useGeoTools(name, type, mapId) {
  const {
      zoomToLocation
    } = usePlugin("map").config,
    tools = usePluginComponentMap("map", "geotools", true),
    toggleName = `${name}_method`,
    mapState = useMapState(),
    {
      useMapInstance
    } = useComponents(),
    instance = useMapInstance(mapId),
    [, {
      value
    }, {
      setValue
    }] = useField(name),
    [,, {
      setValue: setAccuracy
    }] = useField(`${name}_accuracy`),
    [, {
      value: activeTool
    }, {
      setValue: setActiveTool
    }] = useField(toggleName);
  const [defaultTool, DefaultTool] = Object.entries(tools).find(([, Tool]) => Tool.toolDefault) || (() => null),
    ActiveTool = tools[activeTool] || DefaultTool;
  const setLocation = reactExports$1.useCallback(({
    geometry = null,
    latitude = 0,
    longitude = 0,
    accuracy = null,
    zoom = true,
    save = false
  }) => {
    if (!geometry) {
      geometry = {
        type: "Point",
        coordinates: [longitude, latitude]
      };
    }
    if (save) {
      setValue(geometry);
      setAccuracy(accuracy);
    }
    if (zoom && zoomToLocation) {
      zoomToLocation(instance, geometry, {
        name,
        type,
        activeTool,
        mapState
      });
    }
  }, [instance]);
  reactExports$1.useEffect(() => {
    if (!activeTool && defaultTool && ActiveTool == DefaultTool && DefaultTool.toolLabel) {
      setActiveTool(defaultTool);
    }
  }, [activeTool, ActiveTool]);
  return reactExports$1.useMemo(() => ({
    toggleProps: {
      name: toggleName,
      choices: Object.entries(tools).filter(([, Tool]) => Tool.toolLabel).map(([key, Tool]) => ({
        name: key,
        label: Tool.toolLabel
      }))
    },
    setLocation,
    ActiveTool,
    value
  }), [toggleName, tools, setLocation, ActiveTool, value]);
}
function useMapState() {
  const state = usePluginState("map"),
    routeName = useRouteInfo().name,
    routeState = state && state.routes && state.routes[routeName];
  if (routeState) {
    return routeState;
  } else {
    return null;
  }
}
function useMapInstance$1() {
  throw new Error("@wq/map's useMapInstance() export is deprecated." + " Load useMapInstance() via useComponents()," + " or import it directly from @wq/map-gl");
}
function checkGroupLayers(layerconf) {
  const {
    type,
    layers = []
  } = layerconf;
  if (type !== "group") {
    return layerconf;
  }
  return {
    ...layerconf,
    layers: layers.map((layer, i) => {
      if (layer.name) {
        return layer;
      }
      return {
        ...layer,
        name: `${layerconf.name}-${i}`
      };
    })
  };
}
function routeMapConf(config, routeInfo, context = {}) {
  const {
      page,
      mode,
      path,
      params,
      item_id,
      page_config
    } = routeInfo,
    conf = config.maps[page === "outbox" ? page_config.name : page];
  if (!conf) {
    return null;
  }
  // FIXME: custom mapname
  const mapname = "main";

  // Start with defaults, override with mode-specific options
  var mapconf = {
    ...(conf.defaults.maps[mapname] || {}),
    ...((conf[mode] || {
      maps: {}
    }).maps[mapname] || {}),
    basemaps: config.basemaps.map(checkGroupLayers),
    bounds: config.bounds
  };
  if (config.mapProps) {
    mapconf.mapProps = config.mapProps;
  }
  if (typeof mapconf.autoZoom === "undefined") {
    mapconf.autoZoom = {
      ...config.autoZoom
    };
  }
  if (mapconf.autoZoom === true) {
    mapconf.autoZoom = {};
  }
  if (typeof mapconf.autoZoom.wait === "undefined") {
    mapconf.autoZoom.wait = 0.5;
  }
  if (typeof mapconf.autoZoom.maxZoom === "undefined") {
    mapconf.autoZoom.maxZoom = 13;
  }
  if (typeof mapconf.autoZoom.animate === "undefined") {
    mapconf.autoZoom.animate = true;
  }

  // Combine (rather than overwrite) defaults + mode-specific layers
  if (mode && mode !== "defaults" && conf.defaults.maps[mapname] && conf.defaults.maps[mapname].layers) {
    mapconf.layers = conf.defaults.maps[mapname].layers.concat(mapconf.layers || []);
  }
  if (!mapconf.name) {
    mapconf.name = conf.name;
  }
  if (!mapconf.url) {
    mapconf.url = conf.url;
  }
  if (!mapconf.layers) {
    mapconf.layers = [];
  }

  // Compute default layer configuration for wq REST API
  if (mapconf.autoLayers && mode !== "edit") {
    const geometryFields = getGeometryFields((page_config || {}).form);
    geometryFields.forEach(field => {
      let name = page_config && page_config.label || mapconf.name;
      if (field.label) {
        name += ` - ${field.label}`;
      }
      const defaultLayer = {
        name,
        type: "geojson"
      };
      if (!mode || mode === "list") {
        Object.assign(defaultLayer, {
          data: ["context_feature_collection", field.name],
          popup: page,
          cluster: true
        });
      } else {
        Object.assign(defaultLayer, {
          data: ["context_feature", field.name],
          popup: page
        });
      }
      mapconf.layers.push(defaultLayer);
    });
  }
  mapconf.layers = mapconf.layers.map(checkGroupLayers).map(layerconf => {
    // FIXME: recalculate
    const baseurl = path.replace(/\/$/, "");
    layerconf = {
      active: true,
      ...layerconf
    };
    if (layerconf.url && layerconf.url.indexOf("{{") > -1) {
      layerconf.url = mustache.render(layerconf.url, {
        ...context,
        id: item_id,
        url: baseurl
      });
      if (params) {
        const pstr = new URLSearchParams(params).toString();
        if (layerconf.url.indexOf("?") > -1) {
          layerconf.url += "&" + pstr;
        } else {
          layerconf.url += "?" + pstr;
        }
      }
    }
    return layerconf;
  });
  return mapconf;
}
function getGeometryFields(form, prefix = "") {
  const geometryFields = [];
  (form || []).forEach(field => {
    if (field.type.startsWith("geo")) {
      geometryFields.push({
        name: prefix + field.name,
        label: field.label || field.name
      });
    } else if (field.type === "group") {
      geometryFields.push(...getGeometryFields(field.children, prefix = `${field.name}.`));
    } else if (field.type === "repeat") {
      geometryFields.push(...getGeometryFields(field.children, prefix = `${field.name}[].`));
    }
  });
  if (geometryFields.length === 0 && !prefix) {
    geometryFields.push({
      name: "geometry",
      label: ""
    });
  }
  return geometryFields;
}
function contextFeatureCollection(context, fieldName) {
  return {
    type: "FeatureCollection",
    features: (context && context.list || []).map(obj => {
      return contextFeature(obj, fieldName);
    }).filter(obj => !!obj)
  };
}
function contextFeature(context, fieldName) {
  const geometry = contextGeometry(context, fieldName);
  if (!geometry) {
    return null;
  }
  return {
    type: "Feature",
    id: context.id,
    geometry,
    properties: {
      ...context
    }
  };
}
function contextGeometry(context, fieldName) {
  const [prefix, ...rest] = fieldName.split(".");
  if (!context) {
    return null;
  } else if (prefix.endsWith("[]")) {
    const list = context[prefix.slice(0, prefix.length - 2)];
    if (Array.isArray(list)) {
      return {
        type: "GeometryCollection",
        geometries: list.map(row => contextGeometry(row, rest.join(".")))
      };
    } else {
      return null;
    }
  } else {
    const obj = context[prefix];
    if (rest.length) {
      return contextGeometry(obj, rest.join("."));
    } else if (obj && obj.type && (obj.coordinates || obj.geometries)) {
      return obj;
    } else {
      return null;
    }
  }
}
function useDataProps(data, context) {
  return reactExports$1.useMemo(() => {
    const dataProps = {};
    if (Array.isArray(data)) {
      const [dataType, fieldName] = data;
      if (dataType === "context_feature_collection") {
        dataProps.data = contextFeatureCollection(context, fieldName);
      } else if (dataType === "context_feature") {
        dataProps.data = contextFeature(context, fieldName) || {
          type: "Feature",
          geometry: {
            type: "GeometryCollection",
            geometries: []
          }
        };
      } else {
        console.error("Unexpected data context array", data);
      }
    } else if (data) {
      dataProps.data = data;
    }
    return dataProps;
  }, [data, context]);
}
const _cache = {};
function useGeoJSON(url, data) {
  const app = useApp(),
    [geojson, setGeojson] = reactExports$1.useState();
  if (url && !(url.indexOf("/") === 0 || url.indexOf("http") === 0)) {
    console.warn(new Error(`Use "{{{rt}}}/${url}" instead of relative URL`));
    url = app.service + "/" + url;
  }
  reactExports$1.useEffect(() => {
    if (data) {
      setGeojson(data);
      return;
    }
    if (_cache[url]) {
      setGeojson(_cache[url]);
      return;
    }
    if (url.match(/\/(new)?(\/edit)?\.geojson$/)) {
      // Ignore requests for "new.geojson"
      setGeojson(null);
      return;
    }
    app.spin.start();
    app.store.ajax(url).then(function (data) {
      app.spin.stop();
      _cache[url] = data;
      setGeojson(data);
    }, function () {
      app.spin.stop();
      setGeojson(null);
    });
  }, [url, data, app]);
  return geojson;
}
function useGeometry(value, maxGeometries) {
  return reactExports$1.useMemo(() => {
    return asGeometry(value, maxGeometries);
  }, [value]);
}
function useFeatureCollection(value) {
  return reactExports$1.useMemo(() => {
    return asFeatureCollection$1(value);
  }, [value]);
}
function asGeometry(geojson, maxGeometries) {
  var geoms = [];
  if (geojson.type === "FeatureCollection") {
    geojson.features.forEach(function (feature) {
      addGeometry(feature.geometry);
    });
  } else if (geojson.type === "Feature") {
    addGeometry(geojson.geometry);
  } else {
    addGeometry(geojson);
  }
  if (geoms.length == 0) {
    return null;
  } else if (geoms.length == 1) {
    return geoms[0];
  } else if (maxGeometries === 1) {
    return geoms[geoms.length - 1];
  } else if (maxGeometries && geoms.length > maxGeometries) {
    return {
      type: "GeometryCollection",
      geometries: geoms.slice(-maxGeometries)
    };
  } else {
    return {
      type: "GeometryCollection",
      geometries: geoms
    };
  }
  function addGeometry(geometry) {
    if (geometry.type == "GeometryCollection") {
      geometry.geometries.forEach(addGeometry);
    } else {
      geoms.push(geometry);
    }
  }
}
function asFeatureCollection$1(geojson) {
  if (typeof geojson === "string") {
    try {
      geojson = JSON.parse(geojson);
    } catch (e) {
      geojson = null;
    }
  }
  if (!geojson || !geojson.type) {
    return geojson;
  }
  const geometry = asGeometry(geojson);
  if (!geometry) {
    return null;
  }
  let features;
  if (geometry.type === "GeometryCollection") {
    features = geometry.geometries.map(geometry => ({
      type: "Feature",
      properties: {},
      geometry
    }));
  } else {
    features = [{
      type: "Feature",
      properties: {},
      geometry
    }];
  }
  return {
    type: "FeatureCollection",
    features
  };
}
function computeBounds(features) {
  let hasBounds = false,
    minx,
    miny,
    maxx,
    maxy;
  features.forEach(feature => {
    const geometry = feature.geometry;
    if (geometry.type === "GeometryCollection") {
      geometry.geometries.forEach(addCoordinates);
    } else {
      addCoordinates(geometry.coordinates);
    }
  });
  function addCoordinates(coordinates) {
    if (!Array.isArray(coordinates)) {
      return;
    }
    if (Array.isArray(coordinates[0])) {
      coordinates.forEach(addCoordinates);
      return;
    }
    const [x, y] = coordinates;
    if (typeof x !== "number" || typeof y !== "number") {
      return;
    }
    if (hasBounds) {
      minx = Math.min(minx, x);
      miny = Math.min(miny, y);
      maxx = Math.max(maxx, x);
      maxy = Math.max(maxy, y);
    } else {
      hasBounds = true;
      minx = maxx = x;
      miny = maxy = y;
    }
  }
  if (hasBounds) {
    return [[minx, miny], [maxx, maxy]];
  } else {
    return null;
  }
}
function useGeolocation() {
  return {
    supported: typeof navigator !== "undefined" && "geolocation" in navigator,
    watchPosition(onPosition, onError, options) {
      return navigator.geolocation.watchPosition(onPosition, onError, options);
    },
    clearWatch(watchId) {
      return navigator.geolocation.clearWatch(watchId);
    }
  };
}

function AutoMap({
  name,
  mapId,
  toolbar = true,
  toolbarAnchor = "top-right",
  containerStyle,
  context,
  state,
  children
}) {
  const mapState = useMapState(),
    {
      showOverlay,
      hideOverlay,
      setBasemap
    } = usePlugin("map"),
    {
      MapContainer,
      MapToolbar,
      Map,
      MapInteraction,
      MapAutoZoom,
      MapIdentify,
      MapLayers,
      AutoBasemap,
      AutoOverlay
    } = useComponents(),
    {
      Highlight
    } = useOverlayComponents();
  if (!state) {
    state = mapState;
  }
  if (!state) {
    return null;
  }
  const {
    basemaps,
    overlays,
    initBounds,
    mapProps,
    autoZoom,
    highlight
  } = state;
  const identify = overlays.some(overlay => !!overlay.popup);
  if (toolbar === true) {
    toolbar = /*#__PURE__*/React.createElement(MapToolbar, {
      name: name,
      mapId: mapId,
      basemaps: basemaps,
      overlays: overlays,
      showOverlay: showOverlay,
      hideOverlay: hideOverlay,
      setBasemap: setBasemap,
      context: context,
      anchor: toolbarAnchor
    });
  } else if (!toolbar) {
    toolbar = false;
  }
  return /*#__PURE__*/React.createElement(MapContainer, {
    name: name,
    mapId: mapId
  }, toolbarAnchor.endsWith("left") && toolbar, /*#__PURE__*/React.createElement(Map, {
    name: name,
    mapId: mapId,
    initBounds: initBounds,
    mapProps: mapProps,
    containerStyle: containerStyle
  }, /*#__PURE__*/React.createElement(MapInteraction, {
    name: name,
    mapId: mapId
  }), !!autoZoom && /*#__PURE__*/React.createElement(MapAutoZoom, {
    name: name,
    mapId: mapId,
    context: context,
    ...autoZoom
  }), identify && /*#__PURE__*/React.createElement(MapIdentify, {
    name: name,
    mapId: mapId,
    context: context
  }), /*#__PURE__*/React.createElement(MapLayers, null, basemaps.map(conf => /*#__PURE__*/React.createElement(AutoBasemap, {
    key: conf.name,
    ...conf
  })), overlays.map(conf => /*#__PURE__*/React.createElement(AutoOverlay, {
    key: conf.name,
    ...conf,
    context: context
  }))), highlight && /*#__PURE__*/React.createElement(Highlight, {
    data: highlight
  }), children), toolbarAnchor.endsWith("right") && toolbar);
}
AutoMap.propTypes = {
  name: PropTypes.string,
  mapId: PropTypes.string,
  toolbar: PropTypes.bool,
  toolbarAnchor: PropTypes.string,
  containerStyle: PropTypes.object,
  context: PropTypes.object,
  state: PropTypes.object,
  children: PropTypes.node
};

function AutoBasemap({
  type,
  ...conf
}) {
  const basemaps = useBasemapComponents(),
    Basemap = basemaps[type];
  if (type === "empty") {
    return Basemap ? /*#__PURE__*/React.createElement(Basemap, {
      active: conf.active
    }) : null;
  } else if (type === "group") {
    const Group = Basemap || React.Fragment;
    return /*#__PURE__*/React.createElement(Group, null, conf.layers.map(layer => /*#__PURE__*/React.createElement(AutoBasemap, {
      key: layer.name,
      active: conf.active,
      ...layer
    })));
  } else if (!Basemap) {
    console.warn(`Skipping unrecognized layer type "${type}"`);
    return null;
  }
  return /*#__PURE__*/React.createElement(Basemap, {
    ...conf
  });
}
AutoBasemap.propTypes = {
  type: PropTypes.string.isRequired
};
AutoBasemap.isAutoBasemap = true;

function AutoOverlay({
  type,
  data,
  context,
  ...conf
}) {
  const overlays = useOverlayComponents(),
    Overlay = overlays[type],
    dataProps = useDataProps(data, context);
  if (type === "empty") {
    return Overlay ? /*#__PURE__*/React.createElement(Overlay, {
      active: conf.active
    }) : null;
  } else if (type === "group") {
    const Group = Overlay || React.Fragment;
    return /*#__PURE__*/React.createElement(Group, null, conf.layers.map(layer => /*#__PURE__*/React.createElement(AutoOverlay, {
      key: layer.name,
      active: conf.active,
      context: context,
      ...layer
    })));
  } else if (!Overlay) {
    console.warn(`Skipping unrecognized layer type "${type}"`);
    return null;
  }
  return /*#__PURE__*/React.createElement(Overlay, {
    ...conf,
    ...dataProps
  });
}
AutoOverlay.propTypes = {
  type: PropTypes.string.isRequired,
  data: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.string)]),
  context: PropTypes.object
};

function HighlightPopup$1({
  inMap
}) {
  const {
      Popup,
      View,
      ScrollView,
      IconButton
    } = useComponents(),
    [{
      highlight
    }, {
      clearHighlight
    }] = usePluginReducer("map"),
    features = highlight && highlight.features || [];
  if (inMap) {
    return null;
  }
  return /*#__PURE__*/React.createElement(View, {
    style: {
      position: "absolute",
      bottom: 0
    }
  }, /*#__PURE__*/React.createElement(Popup, {
    open: features.length > 0,
    onClose: clearHighlight,
    variant: "persistent"
  }, /*#__PURE__*/React.createElement(IconButton, {
    icon: "close",
    onClick: clearHighlight,
    style: {
      position: "absolute",
      right: 0,
      top: 0,
      zIndex: 1
    }
  }), /*#__PURE__*/React.createElement(ScrollView, {
    style: {
      maxHeight: "33vh"
    }
  }, features.map(feature => /*#__PURE__*/React.createElement(HighlightContent, {
    key: feature.id,
    feature: feature
  })))));
}
function HighlightContent({
  feature,
  inMap
}) {
  const popupName = feature.popup ? `${feature.popup}-popup` : "default-popup",
    views = useViewComponents();
  let View = views[popupName];
  if (!View) {
    console.warn(`No popup view named ${popupName}, using default.`);
    View = views["default-popup"];
    if (!View) {
      throw new Error("No popup view named default-popup!");
    }
  }
  return /*#__PURE__*/React.createElement(View, {
    feature: feature,
    inMap: inMap
  });
}
HighlightContent.propTypes = {
  feature: PropTypes.object,
  inMap: PropTypes.bool
};

function PropertyTableWithoutGeometry({
  form,
  values
}) {
  return /*#__PURE__*/React.createElement(PropertyTable, {
    form: withoutGeometry(form),
    values: values
  });
}
function withoutGeometry(form) {
  const nform = [];
  form.forEach(field => {
    if (field.type && field.type.startsWith("geo")) {
      return;
    }
    if (field.type === "repeat" || field.type === "group") {
      field = {
        ...field,
        children: withoutGeometry(field.children)
      };
    }
    nform.push(field);
  });
  return nform;
}
PropertyTableWithoutGeometry.propTypes = {
  form: PropTypes.arrayOf(PropTypes.object),
  values: PropTypes.object
};

var MapProvider$1 = reactExports$1.Fragment;

function MapContainer({
  children
}) {
  const {
    View
  } = useComponents();
  return /*#__PURE__*/React.createElement(View, {
    style: {
      flex: 1,
      display: "flex",
      flexDirection: "row",
      position: "relative"
    }
  }, children);
}
MapContainer.propTypes = {
  children: PropTypes.node
};

function MapToolbar({
  overlays,
  basemaps,
  showOverlay,
  hideOverlay,
  setBasemap,
  children,
  anchor
}) {
  const {
      SidePanel,
      List,
      ListSubheader,
      OverlayToggle,
      BasemapToggle
    } = useComponents(),
    hasMultipleOverlays = overlays && (overlays.length > 1 || overlays.some(conf => conf.legend)),
    hasMultipleBasemaps = basemaps && basemaps.length > 1;
  if (!hasMultipleOverlays && !hasMultipleBasemaps) {
    return null;
  }
  return /*#__PURE__*/React.createElement(SidePanel, {
    anchor: anchor
  }, children, /*#__PURE__*/React.createElement(List, {
    dense: true
  }, hasMultipleOverlays && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ListSubheader, null, "Layers"), overlays.map(conf => /*#__PURE__*/React.createElement(OverlayToggle, {
    key: conf.name,
    name: conf.name,
    legend: conf.legend,
    active: conf.active,
    setActive: active => active ? showOverlay(conf.name) : hideOverlay(conf.name)
  }))), hasMultipleBasemaps && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ListSubheader, null, "Basemap"), basemaps.map(conf => /*#__PURE__*/React.createElement(BasemapToggle, {
    key: conf.name,
    name: conf.name,
    active: conf.active,
    setActive: active => active && setBasemap(conf.name)
  })))));
}
MapToolbar.propTypes = {
  mapId: PropTypes.string,
  overlays: PropTypes.arrayOf(PropTypes.object),
  basemaps: PropTypes.arrayOf(PropTypes.object),
  showOverlay: PropTypes.func,
  hideOverlay: PropTypes.func,
  setBasemap: PropTypes.func,
  children: PropTypes.node,
  anchor: PropTypes.string
};

function Map$3({
  children
}) {
  return /*#__PURE__*/React.createElement("div", {
    style: {
      flex: "1",
      minHeight: 200
    }
  }, /*#__PURE__*/React.createElement("p", null, "No map integration library loaded - install @wq/map-gl."), children);
}
Map$3.propTypes = {
  children: PropTypes.node
};

function MapLayers$1({
  children
}) {
  return /*#__PURE__*/React.createElement("table", null, /*#__PURE__*/React.createElement("thead", null, /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("th", null, "Group"), /*#__PURE__*/React.createElement("th", null, "Name"), /*#__PURE__*/React.createElement("th", null, "Active"), /*#__PURE__*/React.createElement("th", null, "Detail"))), /*#__PURE__*/React.createElement("tbody", null, React.Children.map(children, element => /*#__PURE__*/React.createElement(MapLayer, {
    element: element
  }))));
}
MapLayers$1.propTypes = {
  children: PropTypes.node
};
function MapLayer({
  element
}) {
  const type = element.type.isAutoBasemap ? "Basemap" : "Overlay",
    {
      name,
      active
    } = element.props;
  return /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("td", null, type), /*#__PURE__*/React.createElement("td", null, name), /*#__PURE__*/React.createElement("td", null, active ? "Y" : "N"), /*#__PURE__*/React.createElement("td", null, element));
}
MapLayer.propTypes = {
  element: PropTypes.node
};

function BasemapToggle({
  name,
  active,
  setActive
}) {
  const {
    ListItem,
    RadioButton
  } = useComponents();
  return /*#__PURE__*/React.createElement(ListItem, {
    button: true,
    dense: true,
    disableGutters: true,
    onClick: () => setActive(true),
    icon: () => /*#__PURE__*/React.createElement(RadioButton, {
      style: {
        marginLeft: 9
      },
      color: "primary",
      checked: active,
      onPress: setActive
    })
  }, name);
}
BasemapToggle.propTypes = {
  name: PropTypes.string,
  active: PropTypes.bool,
  setActive: PropTypes.func
};

function OverlayToggle({
  name,
  legend,
  active,
  setActive
}) {
  const {
    ListItem,
    Switch,
    Legend
  } = useComponents();
  return /*#__PURE__*/React.createElement(ListItem, {
    button: true,
    dense: true,
    disableGutters: true,
    style: {
      alignItems: "start"
    },
    onClick: () => setActive(!active),
    icon: () => /*#__PURE__*/React.createElement(Switch, {
      color: "primary",
      checked: active,
      onValueChange: setActive
    }),
    description: active && legend ? () => /*#__PURE__*/React.createElement(Legend, {
      legend: legend
    }) : null
  }, name);
}
OverlayToggle.propTypes = {
  name: PropTypes.string,
  legend: PropTypes.object,
  active: PropTypes.bool,
  setActive: PropTypes.func
};

function Legend({
  legend
}) {
  const {
    View,
    Typography,
    LegendIcon
  } = useComponents();
  return /*#__PURE__*/React.createElement(View, null, Object.entries(legend).map(([label, icon]) => /*#__PURE__*/React.createElement(View, {
    style: {
      display: "flex",
      flexDirection: "row",
      alignItems: "center"
    },
    key: label
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "caption",
    style: {
      flex: 1
    }
  }, label), /*#__PURE__*/React.createElement(View, {
    style: {
      width: 48
    }
  }, /*#__PURE__*/React.createElement(LegendIcon, {
    name: icon,
    label: label
  })))));
}
Legend.propTypes = {
  legend: PropTypes.object
};

function LegendIcon({
  name,
  label
}) {
  const {
    Img
  } = useComponents();
  return /*#__PURE__*/React.createElement(Img, {
    src: name,
    alt: label
  });
}
LegendIcon.propTypes = {
  name: PropTypes.string,
  label: PropTypes.string
};

function GeoTools({
  name,
  type,
  mapId
}) {
  const {
      toggleProps,
      setLocation,
      ActiveTool,
      value
    } = useGeoTools(name, type, mapId),
    {
      View
    } = useComponents(),
    {
      Toggle
    } = useInputComponents(),
    singleRow = useMinWidth(600);
  if (singleRow) {
    return /*#__PURE__*/React.createElement(View, {
      style: {
        display: "flex",
        flexDirection: "row",
        alignItems: "center"
      }
    }, /*#__PURE__*/React.createElement(View, {
      style: {
        marginRight: 8,
        minWidth: 200
      }
    }, /*#__PURE__*/React.createElement(Toggle, {
      ...toggleProps
    })), /*#__PURE__*/React.createElement(ActiveTool, {
      name: name,
      value: value,
      type: type,
      setLocation: setLocation
    }));
  } else {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Toggle, {
      label: "Location Mode",
      ...toggleProps
    })), /*#__PURE__*/React.createElement(View, {
      style: {
        display: "flex",
        flexDirection: "row",
        alignItems: "center",
        padding: 8,
        width: "100%"
      }
    }, /*#__PURE__*/React.createElement(ActiveTool, {
      name: name,
      value: value,
      type: type,
      setLocation: setLocation
    })));
  }
}
GeoTools.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  mapId: PropTypes.string
};

function GeoHelpIcon$1({
  name
}) {
  return `{${name}}`;
}
GeoHelpIcon$1.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string
};

function Geo({
  name,
  type,
  mapId = undefined,
  required,
  label,
  hint,
  inset = true,
  children
}) {
  const {
      MapProvider,
      AutoMap,
      GeoTools
    } = useComponents(),
    {
      Fieldset: DefaultFieldset,
      FlatFieldset,
      HelperText
    } = useInputComponents(),
    {
      Draw,
      Accuracy
    } = useOverlayComponents(),
    [, {
      value
    }, {
      setValue
    }] = useField(name),
    [, {
      value: accuracy
    }, {
      setValue: setAccuracy
    }] = useField(`${name}_accuracy`),
    maxGeometries = 1; // FIXME;

  const geojson = useFeatureCollection(value),
    drawType = TYPE_MAP[type] || "all",
    Fieldset = inset ? DefaultFieldset : FlatFieldset;
  function handleChange(geojson) {
    setValue(asGeometry(geojson, maxGeometries));
    if (accuracy) {
      setAccuracy(null);
    }
  }
  return /*#__PURE__*/React.createElement(MapProvider, null, /*#__PURE__*/React.createElement(Fieldset, {
    label: label
  }, /*#__PURE__*/React.createElement(GeoTools, {
    name: name,
    type: type,
    mapId: mapId
  }), /*#__PURE__*/React.createElement(AutoMap, {
    name: name,
    mapId: mapId,
    containerStyle: {
      minHeight: 400
    },
    context: emptyContext,
    toolbarAnchor: "bottom-right"
  }, children, /*#__PURE__*/React.createElement(Accuracy, {
    accuracy: accuracy,
    data: geojson
  }), /*#__PURE__*/React.createElement(Draw, {
    name: name,
    type: drawType,
    required: required,
    data: geojson,
    setData: handleChange
  })), /*#__PURE__*/React.createElement(HelperText, {
    name: name,
    hint: hint
  })));
}
Geo.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  mapId: PropTypes.string,
  required: PropTypes.bool,
  label: PropTypes.string,
  hint: PropTypes.string,
  inset: PropTypes.bool,
  children: PropTypes.node
};
const emptyContext = {};

function GeoHelp({
  value,
  type
}) {
  const drawType = TYPE_MAP[type] || type,
    {
      Typography,
      GeoHelpIcon
    } = useComponents(),
    messageId = `GEO_${drawType.toUpperCase()}_${value ? "EDIT" : "NEW"}`,
    {
      [messageId]: messageTemplate
    } = useMessages(),
    message = [];
  if (messageTemplate) {
    messageTemplate.split("{").forEach(part => {
      if (message.length === 0) {
        message.push(part);
        return;
      }
      const [iconName, ...rest] = part.split("}");
      message.push( /*#__PURE__*/React.createElement(GeoHelpIcon, {
        name: iconName,
        type: drawType
      }));
      message.push(rest.join("}"));
    });
  }
  return /*#__PURE__*/React.createElement(Typography, {
    color: "textSecondary",
    style: {
      flex: 1,
      textAlign: "right"
    }
  }, message);
}
GeoHelp.toolLabel = false;
GeoHelp.toolDefault = true;
GeoHelp.propTypes = {
  value: PropTypes.object,
  type: PropTypes.string
};

function GeoLocate({
  type,
  setLocation
}) {
  const {
      Button,
      Typography,
      useGeolocation
    } = useComponents(),
    geolocation = useGeolocation(),
    [gpsStatus, setGpsStatus] = reactExports$1.useState(""),
    gpsWatch = reactExports$1.useRef();
  async function startGps() {
    if (gpsWatch.current) {
      return;
    }
    if (!geolocation.supported) {
      setGpsStatus("Geolocation not supported");
      return;
    }
    const watchId = await geolocation.watchPosition(onPosition, onError, {
      enableHighAccuracy: true,
      timeout: 60 * 1000
    });
    gpsWatch.current = watchId;
    setGpsStatus("Determining location...");
  }
  function onPosition(evt) {
    const lat = +evt.coords.latitude.toFixed(6),
      lng = +evt.coords.longitude.toFixed(6),
      acc = +evt.coords.accuracy.toFixed(3);
    setLocation({
      longitude: lng,
      latitude: lat,
      accuracy: acc,
      zoom: true,
      save: type === "geopoint"
    });
    const latFmt = lat > 0 ? lat + "°N" : -lat + "°S",
      lngFmt = lng > 0 ? lng + "°E" : -lng + "°W",
      accFmt = acc > 1000 ? "~" + Math.round(acc / 1000) + "km" : acc > 1 ? "~" + Math.round(acc) + "m" : acc + "m";
    setGpsStatus(`${latFmt} ${lngFmt} (${accFmt})`);
  }
  function onError(error) {
    setGpsStatus(error.message);
    stopGps();
  }
  function stopGps() {
    if (gpsWatch.current) {
      geolocation.clearWatch(gpsWatch.current);
    }
    gpsWatch.current = null;
  }
  function resetGps() {
    stopGps();
    setGpsStatus("");
  }
  reactExports$1.useEffect(() => {
    return () => stopGps();
  }, []);
  const gpsActive = !!gpsWatch.current;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Typography, {
    style: {
      marginRight: 8,
      flex: 1,
      textAlign: "center"
    },
    color: "textSecondary"
  }, gpsStatus), /*#__PURE__*/React.createElement(Button, {
    icon: gpsActive ? "gps-stop" : "gps-start",
    style: {
      minWidth: 140
    },
    variant: gpsActive ? "contained" : "outlined",
    color: "secondary",
    onClick: gpsActive ? resetGps : startGps
  }, gpsActive ? "Stop GPS" : "Start GPS"));
}
GeoLocate.toolLabel = "Current";
GeoLocate.propTypes = {
  type: PropTypes.string,
  setLocation: PropTypes.func
};

function GeoCode({
  name,
  type,
  setLocation
}) {
  const {
      IconButton
    } = useComponents(),
    {
      Input
    } = useInputComponents(),
    [, {
      value: address
    }, {
      setValue: setAddress,
      setError: setAddressError
    }] = useField(name + "_address"),
    [geocodeStatus, setGeocodeStatus] = reactExports$1.useState(null),
    {
      geocoder,
      geocoderAddress
    } = usePlugin("map").config,
    {
      values
    } = useFormikContext();
  async function geocode() {
    if (!geocoder) {
      setAddressError("No geocoder plugin registered!");
      return;
    }
    setAddressError(null);
    setGeocodeStatus("Looking up location...");
    try {
      const result = await geocoder(address),
        {
          label,
          geometry
        } = result;
      if (geometry) {
        setLocation({
          latitude: geometry.coordinates[1],
          longitude: geometry.coordinates[0],
          zoom: true,
          save: type === "geopoint"
        });
        setGeocodeStatus(label || "Location found!");
      } else {
        setGeocodeStatus(label || "Not found");
      }
    } catch (e) {
      setAddressError(e.message || "" + e);
      setGeocodeStatus(null);
    }
  }
  reactExports$1.useEffect(() => {
    if (address === undefined && geocoderAddress) {
      setDefaultAddress();
    }
    async function setDefaultAddress() {
      setAddress(await geocoderAddress(values));
    }
  }, [address, values]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Input, {
    name: name + "_address",
    label: "Address",
    helperText: geocodeStatus || "Enter address or city name",
    style: {
      flex: 1
    }
  }), /*#__PURE__*/React.createElement(IconButton, {
    onClick: geocode,
    icon: "search",
    color: "secondary"
  }));
}
GeoCode.toolLabel = "Address";
GeoCode.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string,
  setLocation: PropTypes.func
};

function GeoCoords({
  name,
  value,
  type,
  setLocation
}) {
  const {
      IconButton
    } = useComponents(),
    {
      Input
    } = useInputComponents(),
    longitudeName = `${name}_longitude`,
    latitudeName = `${name}_latitude`,
    [, {
      value: longitude
    }, {
      setValue: setLongitude
    }] = useField(longitudeName),
    [, {
      value: latitude
    }, {
      setValue: setLatitude
    }] = useField(latitudeName);
  reactExports$1.useEffect(() => {
    if (type !== "geopoint") {
      return;
    }
    if (!(value && value.type === "Point" && value.coordinates)) {
      return;
    }
    const [longitude, latitude] = value.coordinates;
    setLongitude(longitude);
    setLatitude(latitude);
  }, [type, value]);
  function saveLatLong() {
    if (!latitude || !longitude || Math.abs(latitude) > 90 || Math.abs(longitude) > 180) {
      return;
    }
    setLocation({
      longitude,
      latitude,
      zoom: true,
      save: type === "geopoint"
    });
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Input, {
    name: name + "_latitude",
    label: "Latitude",
    type: "decimal",
    inputProps: {
      step: 0.000001,
      min: -90,
      max: 90
    },
    InputLabelProps: {
      shrink: true
    },
    style: {
      marginRight: 4,
      flex: 1
    }
  }), /*#__PURE__*/React.createElement(Input, {
    name: name + "_longitude",
    label: "Longitude",
    type: "decimal",
    inputProps: {
      step: 0.000001,
      min: -180,
      max: 180
    },
    InputLabelProps: {
      shrink: true
    },
    style: {
      marginLeft: 4,
      flex: 1
    }
  }), /*#__PURE__*/React.createElement(IconButton, {
    onClick: saveLatLong,
    icon: "search",
    variant: "filled",
    color: "secondary"
  }));
}
GeoCoords.toolLabel = "Lat/Lng";
GeoCoords.propTypes = {
  name: PropTypes.str,
  value: PropTypes.object,
  type: PropTypes.str,
  setLocation: PropTypes.func
};

function DefaultListWithMap() {
  const mapState = useMapState(),
    {
      MapProvider,
      AutoMap,
      HighlightPopup,
      Divider,
      TabGroup,
      TabItem
    } = useComponents(),
    splitScreen = useMinWidth(900),
    context = useList();
  if (mapState) {
    const {
      mapId
    } = mapState;
    if (splitScreen) {
      return /*#__PURE__*/React.createElement(MapProvider, null, /*#__PURE__*/React.createElement(DefaultList, null), /*#__PURE__*/React.createElement(Divider, {
        orientation: "vertical"
      }), /*#__PURE__*/React.createElement(AutoMap, {
        mapId: mapId,
        context: context
      }, /*#__PURE__*/React.createElement(HighlightPopup, {
        inMap: true
      })), /*#__PURE__*/React.createElement(HighlightPopup, null));
    } else {
      return /*#__PURE__*/React.createElement(MapProvider, null, /*#__PURE__*/React.createElement(TabGroup, {
        sx: {
          minHeight: 72
        }
      }, /*#__PURE__*/React.createElement(TabItem, {
        label: "List",
        value: "list",
        icon: "list"
      }, /*#__PURE__*/React.createElement(DefaultList, null)), /*#__PURE__*/React.createElement(TabItem, {
        label: "Map",
        value: "map",
        icon: "map"
      }, /*#__PURE__*/React.createElement(AutoMap, {
        mapId: mapId,
        context: context
      }), /*#__PURE__*/React.createElement(HighlightPopup, null))));
    }
  } else {
    return /*#__PURE__*/React.createElement(DefaultList, null);
  }
}

function DefaultDetailWithMap() {
  const mapState = useMapState(),
    {
      MapProvider,
      AutoMap,
      Divider,
      TabGroup,
      TabItem
    } = useComponents(),
    splitScreen = useMinWidth(900),
    context = useRenderContext();
  if (mapState) {
    const {
      mapId
    } = mapState;
    if (splitScreen) {
      return /*#__PURE__*/React.createElement(MapProvider, null, /*#__PURE__*/React.createElement(DefaultDetail, null), /*#__PURE__*/React.createElement(Divider, {
        orientation: "vertical"
      }), /*#__PURE__*/React.createElement(AutoMap, {
        mapId: mapId,
        context: context
      }));
    } else {
      return /*#__PURE__*/React.createElement(MapProvider, null, /*#__PURE__*/React.createElement(TabGroup, {
        sx: {
          minHeight: 72
        }
      }, /*#__PURE__*/React.createElement(TabItem, {
        label: "Detail",
        value: "detail",
        icon: "detail"
      }, /*#__PURE__*/React.createElement(DefaultDetail, null)), /*#__PURE__*/React.createElement(TabItem, {
        label: "Map",
        value: "map",
        icon: "map"
      }, /*#__PURE__*/React.createElement(AutoMap, {
        mapId: mapId,
        context: context
      }))));
    }
  } else {
    return /*#__PURE__*/React.createElement(DefaultDetail, null);
  }
}

function DefaultPopup({
  feature
}) {
  const reverse = useReverse(),
    {
      PropertyTable,
      View,
      Fab
    } = useComponents(),
    config = useConfig(),
    authState = usePluginState("auth"),
    page_config = feature.popup ? config.pages[feature.popup] : null,
    perms = page_config && authState && authState.config && authState.config.pages && authState.config.pages[feature.popup];
  let form, editUrl;
  if (page_config) {
    form = page_config.form || [{
      name: "label"
    }];
    if (perms && perms.can_change) {
      editUrl = reverse(`${feature.popup}_edit`, feature.id);
    }
  } else {
    form = Object.keys(feature.properties).map(name => ({
      name
    }));
  }
  return /*#__PURE__*/React.createElement(View, {
    style: {
      maxWidth: "70em",
      position: "relative",
      marginLeft: "auto",
      marginRight: "auto"
    }
  }, /*#__PURE__*/React.createElement(PropertyTable, {
    form: form,
    values: feature.properties
  }), editUrl && /*#__PURE__*/React.createElement(Fab, {
    icon: "edit",
    to: editUrl
  }));
}
DefaultPopup.propTypes = {
  feature: PropTypes.object
};

const RENDER = "RENDER";
const MAP_SET_VIEW_STATE = "MAP_SET_VIEWSTATE",
  MAP_SHOW_OVERLAY = "MAP_SHOW_OVERLAY",
  MAP_HIDE_OVERLAY = "MAP_HIDE_OVERLAY",
  MAP_SET_BASEMAP = "MAP_SET_BASEMAP",
  MAP_SET_HIGHLIGHT = "MAP_SET_HIGHLIGHT",
  MAP_ADD_HIGHLIGHT = "MAP_ADD_HIGHLIGHT",
  MAP_TOGGLE_HIGHLIGHT = "MAP_TOGGLE_HIGHLIGHT",
  MAP_REMOVE_HIGHLIGHT = "MAP_REMOVE_HIGHLIGHT",
  MAP_CLEAR_HIGHLIGHT = "MAP_CLEAR_HIGHLIGHT";
var _lastRouteInfo = null;
function reducer(state = {}, action, config) {
  switch (action.type) {
    case RENDER:
      {
        const context = action.payload,
          {
            router_info: routeInfo
          } = context,
          conf = routeMapConf(config, routeInfo, context);
        if (routeInfo === _lastRouteInfo) {
          return state;
        } else {
          const isSameView = _lastRouteInfo && ["name", "mode", "variant", "item_id"].every(key => routeInfo[key] == _lastRouteInfo[key]);
          _lastRouteInfo = routeInfo;
          let nextState = {};
          const {
            routes,
            stickyMaps,
            activeBasemap,
            activeOverlays
          } = state;
          if (!conf) {
            nextState = {
              routes,
              stickyMaps,
              activeBasemap,
              activeOverlays
            };
          } else {
            const {
                mapId
              } = conf,
              {
                highlight = null,
                viewState = null
              } = mapId && stickyMaps && stickyMaps[mapId] || {};
            nextState = {
              routeName: routeInfo.name,
              basemaps: reduceBasemaps(state.basemaps, conf.basemaps, activeBasemap),
              overlays: reduceOverlays(state.overlays, conf.layers, activeOverlays, isSameView),
              viewState,
              initBounds: conf.bounds,
              autoZoom: conf.autoZoom,
              mapProps: conf.mapProps,
              highlight: isSameView ? highlight : null,
              mapId,
              routes,
              stickyMaps,
              activeBasemap,
              activeOverlays
            };
          }
          ["stickyMaps", "activeBasemap", "activeOverlays"].forEach(key => {
            if (!nextState[key]) {
              delete nextState[key];
            }
          });
          return reduceMapState(nextState);
        }
      }
    case MAP_SET_VIEW_STATE:
      return reduceMapState({
        ...state,
        viewState: action.payload
      });
    case MAP_SHOW_OVERLAY:
      return reduceMapState({
        ...state,
        activeOverlays: {
          ...state.activeOverlays,
          [action.payload]: true
        },
        overlays: state.overlays && state.overlays.map(overlay => {
          if (overlay.name === action.payload) {
            return {
              ...overlay,
              active: true
            };
          } else {
            return overlay;
          }
        })
      });
    case MAP_HIDE_OVERLAY:
      return reduceMapState({
        ...state,
        activeOverlays: {
          ...state.activeOverlays,
          [action.payload]: false
        },
        overlays: state.overlays && state.overlays.map(overlay => {
          if (overlay.name === action.payload) {
            return {
              ...overlay,
              active: false
            };
          } else {
            return overlay;
          }
        })
      });
    case MAP_SET_BASEMAP:
      return reduceMapState({
        ...state,
        activeBasemap: action.payload,
        basemaps: state.basemaps && state.basemaps.map(basemap => {
          if (basemap.name === action.payload) {
            return {
              ...basemap,
              active: true
            };
          } else if (basemap.active) {
            return {
              ...basemap,
              active: false
            };
          } else {
            return basemap;
          }
        })
      });
    case MAP_SET_HIGHLIGHT:
      return reduceMapState({
        ...state,
        highlight: action.payload
      });
    case MAP_ADD_HIGHLIGHT:
      {
        if (!state.highlight) {
          return reduceMapState({
            ...state,
            highlight: action.payload
          });
        }
        const features = {};
        let hasNew = false;
        state.highlight.features.forEach(feature => features[feature.id] = feature);
        action.payload.features.forEach(feature => {
          if (!features[feature.id]) {
            hasNew = true;
            features[feature.id] = feature;
          }
        });
        if (!hasNew) {
          return state;
        }
        return reduceMapState({
          ...state,
          highlight: {
            type: "FeatureCollection",
            features: Object.values(features)
          }
        });
      }
    case MAP_TOGGLE_HIGHLIGHT:
      {
        if (!state.highlight) {
          return reduceMapState({
            ...state,
            highlight: action.payload
          });
        }
        const features = {};
        state.highlight.features.forEach(feature => features[feature.id] = feature);
        action.payload.features.forEach(feature => {
          if (features[feature.id]) {
            delete features[feature.id];
          } else {
            features[feature.id] = feature;
          }
        });
        return reduceMapState({
          ...state,
          highlight: checkEmpty({
            type: "FeatureCollection",
            features: Object.values(features)
          })
        });
      }
    case MAP_REMOVE_HIGHLIGHT:
      {
        if (!state.highlight) {
          return state;
        }
        const remove = {};
        action.payload.features.forEach(feature => remove[feature.id] = true);
        return reduceMapState({
          ...state,
          highlight: checkEmpty({
            type: "FeatureCollection",
            features: state.highlight.features.filter(feature => !remove[feature.id])
          })
        });
      }
    case MAP_CLEAR_HIGHLIGHT:
      if (!state.highlight) {
        return state;
      } else {
        return reduceMapState({
          ...state,
          highlight: null
        });
      }
    default:
      return state;
  }
}
function reduceBasemaps(lastBasemaps, nextBasemaps, activeBasemap) {
  if (!nextBasemaps || nextBasemaps.length === 0) {
    return;
  }
  const basemaps = nextBasemaps.map(basemap => {
    if (activeBasemap && activeBasemap === basemap.name) {
      return {
        ...basemap,
        active: true
      };
    } else {
      return {
        ...basemap,
        active: false
      };
    }
  });
  if (!basemaps.some(basemap => basemap.active)) {
    basemaps[0].active = true;
  }
  if (sameLayers(basemaps, lastBasemaps)) {
    return lastBasemaps;
  } else {
    return basemaps;
  }
}
function reduceOverlays(lastOverlays, nextOverlays, activeOverlays, isSameView) {
  if (!nextOverlays || nextOverlays.length === 0) {
    return [];
  }
  const overlays = nextOverlays.map(overlay => {
    if (activeOverlays && activeOverlays[overlay.name]) {
      return {
        ...overlay,
        active: true
      };
    } else if (overlay.active) {
      return {
        ...overlay
      };
    } else {
      return {
        ...overlay,
        active: false
      };
    }
  });
  if (isSameView && sameLayers(overlays, lastOverlays)) {
    return lastOverlays;
  } else {
    return overlays;
  }
}
function sameLayers(arr1, arr2) {
  if (arr1.length !== (arr2 || []).length) {
    return false;
  }
  return arr1.every((layer, i) => layer.name === arr2[i].name && layer.active === arr2[i].active);
}
function checkEmpty(geojson) {
  if (geojson.features.length === 0) {
    return null;
  } else {
    return geojson;
  }
}
function reduceMapState(state) {
  const {
    routeName,
    basemaps,
    overlays,
    viewState,
    initBounds,
    autoZoom,
    mapProps,
    highlight,
    mapId
  } = state;
  state = {
    ...state,
    routes: {
      ...state.routes,
      [routeName]: {
        routeName,
        basemaps,
        overlays,
        viewState,
        initBounds,
        autoZoom,
        mapProps,
        highlight,
        mapId
      }
    }
  };
  if (mapId) {
    state = {
      ...state,
      stickyMaps: {
        ...state.stickyMaps,
        [mapId]: {
          highlight,
          viewState
        }
      }
    };
  }
  return state;
}

// module variable
const map = {
  name: "map",
  reducer(state, action) {
    return reducer(state, action, this.config);
  },
  persist({
    activeBasemap,
    activeOverlays
  }) {
    return {
      activeBasemap,
      activeOverlays
    };
  },
  restore({
    activeBasemap,
    activeOverlays
  }) {
    Object.keys(activeOverlays || {}).forEach(key => {
      if (!this.config.allOverlays[key]) {
        delete activeOverlays[key];
      }
    });
    return {
      activeBasemap,
      activeOverlays
    };
  },
  actions: {
    setViewState(viewState) {
      return {
        type: MAP_SET_VIEW_STATE,
        payload: viewState
      };
    },
    setBasemap(name) {
      return {
        type: MAP_SET_BASEMAP,
        payload: name
      };
    },
    showOverlay(name) {
      return {
        type: MAP_SHOW_OVERLAY,
        payload: name
      };
    },
    hideOverlay(name) {
      return {
        type: MAP_HIDE_OVERLAY,
        payload: name
      };
    },
    setHighlight(geojson) {
      return {
        type: MAP_SET_HIGHLIGHT,
        payload: asFeatureCollection(geojson)
      };
    },
    addHighlight(geojson) {
      return {
        type: MAP_ADD_HIGHLIGHT,
        payload: asFeatureCollection(geojson)
      };
    },
    toggleHighlight(geojson) {
      return {
        type: MAP_TOGGLE_HIGHLIGHT,
        payload: asFeatureCollection(geojson)
      };
    },
    removeHighlight(geojson) {
      return {
        type: MAP_REMOVE_HIGHLIGHT,
        payload: asFeatureCollection(geojson)
      };
    },
    clearHighlight() {
      return {
        type: MAP_CLEAR_HIGHLIGHT
      };
    }
  },
  components: {
    AutoMap,
    AutoBasemap,
    AutoOverlay,
    HighlightPopup: HighlightPopup$1,
    PropertyTable: PropertyTableWithoutGeometry,
    MapProvider: MapProvider$1,
    useMapInstance: () => null,
    MapContainer,
    MapToolbar,
    Map: Map$3,
    MapInteraction: () => null,
    MapAutoZoom: () => null,
    MapIdentify: () => null,
    MapLayers: MapLayers$1,
    BasemapToggle,
    OverlayToggle,
    Legend,
    LegendIcon,
    GeoTools,
    GeoHelpIcon: GeoHelpIcon$1,
    useGeolocation
  },
  inputs: {
    Geo,
    geopoint: Geo,
    geotrace: Geo,
    geoshape: Geo
  },
  views: {
    DefaultList: DefaultListWithMap,
    DefaultDetail: DefaultDetailWithMap,
    DefaultPopup
  },
  config: {
    maps: {},
    // Auto-populated from app.config.pages where map == true
    bounds: [[-4, -4], [4, 4]],
    autoZoom: {
      wait: 0.5,
      // How long to wait before triggering autoZoom

      // Settings for fitBounds
      maxZoom: 13,
      animate: true
    },
    basemaps: _defaultBasemaps()
  },
  registry: {
    basemaps: {
      Tile({
        url
      }) {
        return `Tile at ${url}`;
      }
    },
    overlays: {
      Geojson({
        url,
        data
      }) {
        if (data) {
          return `GeoJSON ${data.type}`;
        } else {
          return `GeoJSON at ${url}`;
        }
      },
      Highlight({
        data
      }) {
        return `Highlight ${data.type}`;
      },
      Draw({
        type,
        data
      }) {
        return `Draw ${data ? data.type : type}`;
      },
      Accuracy({
        accuracy
      }) {
        return `Accuracy ${accuracy}`;
      }
    },
    geotools: {
      GeoHelp,
      GeoLocate,
      GeoCode,
      GeoCoords
    }
  }
};

// This will be called by app.init()
map.init = function (config) {
  var app = this.app;
  Object.values(app.plugins).forEach(plugin => {
    if (plugin.basemaps) {
      Object.assign(this.registry.basemaps, plugin.basemaps);
    }
    if (plugin.overlays) {
      Object.assign(this.registry.overlays, plugin.overlays);
    }
    if (plugin.geotools) {
      Object.assign(this.registry.geotools, plugin.geotools);
    }
    if (plugin.geocoder) {
      this.config.geocoder = address => plugin.geocoder(address);
    }
    if (plugin.geocoderAddress) {
      this.config.geocoderAddress = values => plugin.geocoderAddress(values);
    }
    if (plugin.zoomToLocation) {
      this.config.zoomToLocation = (instance, geometry, meta) => plugin.zoomToLocation(instance, geometry, meta);
    }
  });
  if (!this.config.geocoder) {
    // No geocoder; disable default GeoCode unless it has been overridden
    if (this.registry.geotools.GeoCode === GeoCode) {
      delete this.registry.geotools.GeoCode;
    }
  }
  if (config) {
    Object.assign(this.config, config);
    if (config.maps && config.maps.basemaps) {
      // Compatibility with 1.3 alpha/beta; remove in 2.0
      this.config.basemaps = config.maps.basemaps;
    }
  }

  // Define map configuration for all app pages with map=True
  this.config.allOverlays = {};
  Object.keys(app.config.pages).forEach(page => {
    var pconf = app.config.pages[page],
      mconf = pconf.map;
    if (!mconf) {
      return;
    } else if (mconf === true) {
      mconf = [];
    } else if (!Array.isArray(mconf)) {
      mconf = [mconf];
    }
    const {
      mapId
    } = mconf[0] || {};
    var mapconf = {
      name: pconf.name,
      url: pconf.url,
      mapId,
      defaults: {
        maps: {
          main: {
            layers: []
          }
        }
      }
    };

    // Initialize map configurations for each page display mode
    mconf.forEach(conf => {
      var mode = conf.mode || "defaults",
        map = conf.map || "main";
      if (mode === "all") {
        mode = "defaults";
      }
      if (!mapconf[mode]) {
        mapconf[mode] = {
          maps: {}
        };
      }
      mapconf[mode].maps[map] = conf;
      if (conf.layers) {
        conf.layers.forEach(layer => this.config.allOverlays[layer.name] = true);
      }
    });

    // Ensure map configurations exist for all list page modes
    var modes = [];
    if (pconf.modes) {
      modes = pconf.modes;
    } else if (pconf.list) {
      modes = ["list", "detail", "edit"];
    }
    modes.forEach(mode => {
      if (mapconf[mode]) {
        if (mapconf[mode].maps && mapconf[mode].maps.main && mapconf[mode].maps.main.autoLayers && !mapconf[mode].maps.main.layers) {
          mapconf[mode].maps.main.layers = [];
        }
        return;
      }
      mapconf[mode] = {
        maps: {
          main: {
            autoLayers: true,
            layers: []
          }
        }
      };
    });
    map.config.maps[page] = mapconf;
  });
};

// Default base map configuration - override to customize
function _defaultBasemaps() {
  var cdn = "https://stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg";
  var attr = 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.';
  return [{
    name: "Stamen Terrain",
    type: "tile",
    url: cdn,
    attribution: attr
  }];
}
function asFeatureCollection(geojson) {
  if (!geojson) {
    geojson = [];
  } else if (geojson.type && geojson.type !== "FeatureCollection") {
    geojson = [geojson];
  }
  if (Array.isArray(geojson)) {
    geojson = {
      type: "FeatureCollection",
      features: geojson
    };
  } else if (!geojson.type) {
    throw new Error("Invalid GeoJSON");
  }
  return geojson;
}

var mapExports = /*#__PURE__*/Object.freeze({
  __proto__: null,
  AutoBasemap: AutoBasemap,
  AutoMap: AutoMap,
  AutoOverlay: AutoOverlay,
  DefaultDetail: DefaultDetailWithMap,
  DefaultList: DefaultListWithMap,
  Geo: Geo,
  GeoCode: GeoCode,
  GeoCoords: GeoCoords,
  GeoHelp: GeoHelp,
  GeoLocate: GeoLocate,
  GeoTools: GeoTools,
  HighlightContent: HighlightContent,
  HighlightPopup: HighlightPopup$1,
  Legend: Legend,
  LegendIcon: LegendIcon,
  MapToolbar: MapToolbar,
  PropertyTable: PropertyTableWithoutGeometry,
  asFeatureCollection: asFeatureCollection$1,
  asGeometry: asGeometry,
  computeBounds: computeBounds,
  default: map,
  useBasemapComponents: useBasemapComponents,
  useFeatureCollection: useFeatureCollection,
  useGeoJSON: useGeoJSON,
  useGeoTools: useGeoTools,
  useGeolocation: useGeolocation,
  useGeometry: useGeometry,
  useMapInstance: useMapInstance$1,
  useMapState: useMapState,
  useOverlayComponents: useOverlayComponents
});

const MountedMapsContext = reactExports$1.createContext(null);
const MapProvider = props => {
  const [maps, setMaps] = reactExports$1.useState({});
  const onMapMount = reactExports$1.useCallback((map, id = 'default') => {
    setMaps(currMaps => {
      if (id === 'current') {
        throw new Error("'current' cannot be used as map id");
      }
      if (currMaps[id]) {
        throw new Error(`Multiple maps with the same id: ${id}`);
      }
      return {
        ...currMaps,
        [id]: map
      };
    });
  }, []);
  const onMapUnmount = reactExports$1.useCallback((id = 'default') => {
    setMaps(currMaps => {
      if (currMaps[id]) {
        const nextMaps = {
          ...currMaps
        };
        delete nextMaps[id];
        return nextMaps;
      }
      return currMaps;
    });
  }, []);
  return reactExports$1.createElement(MountedMapsContext.Provider, {
    value: {
      maps,
      onMapMount,
      onMapUnmount
    }
  }, props.children);
};
function useMap() {
  var _a;
  const maps = (_a = reactExports$1.useContext(MountedMapsContext)) === null || _a === void 0 ? void 0 : _a.maps;
  const currentMap = reactExports$1.useContext(MapContext);
  const mapsWithCurrent = reactExports$1.useMemo(() => {
    return {
      ...maps,
      current: currentMap === null || currentMap === void 0 ? void 0 : currentMap.map
    };
  }, [maps, currentMap]);
  return mapsWithCurrent;
}

/**
 * Make a copy of a transform
 * @param tr
 */
function cloneTransform(tr) {
  const newTransform = tr.clone();
  // Work around mapbox bug - this value is not assigned in clone(), only in resize()
  newTransform.pixelsToGLUnits = tr.pixelsToGLUnits;
  return newTransform;
}
/**
 * Capture a transform's current state
 * @param transform
 * @returns descriptor of the view state
 */
function transformToViewState(tr) {
  return {
    longitude: tr.center.lng,
    latitude: tr.center.lat,
    zoom: tr.zoom,
    pitch: tr.pitch,
    bearing: tr.bearing,
    padding: tr.padding
  };
}
/* eslint-disable complexity */
/**
 * Mutate a transform to match the given view state
 * @param transform
 * @param viewState
 * @returns true if the transform has changed
 */
function applyViewStateToTransform(tr, props) {
  const v = props.viewState || props;
  let changed = false;
  if ('longitude' in v && 'latitude' in v) {
    const center = tr.center;
    // @ts-ignore
    tr.center = new center.constructor(v.longitude, v.latitude);
    changed = changed || center !== tr.center;
  }
  if ('zoom' in v) {
    const zoom = tr.zoom;
    tr.zoom = v.zoom;
    changed = changed || zoom !== tr.zoom;
  }
  if ('bearing' in v) {
    const bearing = tr.bearing;
    tr.bearing = v.bearing;
    changed = changed || bearing !== tr.bearing;
  }
  if ('pitch' in v) {
    const pitch = tr.pitch;
    tr.pitch = v.pitch;
    changed = changed || pitch !== tr.pitch;
  }
  if (v.padding && !tr.isPaddingEqual(v.padding)) {
    changed = true;
    tr.padding = v.padding;
  }
  return changed;
}

const refProps = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];
// Prepare a map style object for diffing
// If immutable - convert to plain object
// Work around some issues in older styles that would fail Mapbox's diffing
function normalizeStyle(style) {
  if (!style) {
    return null;
  }
  if (typeof style === 'string') {
    return style;
  }
  if ('toJS' in style) {
    style = style.toJS();
  }
  if (!style.layers) {
    return style;
  }
  const layerIndex = {};
  for (const layer of style.layers) {
    layerIndex[layer.id] = layer;
  }
  const layers = style.layers.map(layer => {
    // @ts-expect-error
    const layerRef = layerIndex[layer.ref];
    let normalizedLayer = null;
    if ('interactive' in layer) {
      normalizedLayer = {
        ...layer
      };
      // Breaks style diffing :(
      delete normalizedLayer.interactive;
    }
    // Style diffing doesn't work with refs so expand them out manually before diffing.
    if (layerRef) {
      normalizedLayer = normalizedLayer || {
        ...layer
      };
      delete normalizedLayer.ref;
      // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/deref.js
      for (const propName of refProps) {
        if (propName in layerRef) {
          normalizedLayer[propName] = layerRef[propName];
        }
      }
    }
    return normalizedLayer || layer;
  });
  // Do not mutate the style object provided by the user
  return {
    ...style,
    layers
  };
}

/**
 * Compare two points
 * @param a
 * @param b
 * @returns true if the points are equal
 */
function arePointsEqual(a, b) {
  const ax = Array.isArray(a) ? a[0] : a ? a.x : 0;
  const ay = Array.isArray(a) ? a[1] : a ? a.y : 0;
  const bx = Array.isArray(b) ? b[0] : b ? b.x : 0;
  const by = Array.isArray(b) ? b[1] : b ? b.y : 0;
  return ax === bx && ay === by;
}
/* eslint-disable complexity */
/**
 * Compare any two objects
 * @param a
 * @param b
 * @returns true if the objects are deep equal
 */
function deepEqual(a, b) {
  if (a === b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  if (Array.isArray(a)) {
    if (!Array.isArray(b) || a.length !== b.length) {
      return false;
    }
    for (let i = 0; i < a.length; i++) {
      if (!deepEqual(a[i], b[i])) {
        return false;
      }
    }
    return true;
  } else if (Array.isArray(b)) {
    return false;
  }
  if (typeof a === 'object' && typeof b === 'object') {
    const aKeys = Object.keys(a);
    const bKeys = Object.keys(b);
    if (aKeys.length !== bKeys.length) {
      return false;
    }
    for (const key of aKeys) {
      if (!b.hasOwnProperty(key)) {
        return false;
      }
      if (!deepEqual(a[key], b[key])) {
        return false;
      }
    }
    return true;
  }
  return false;
}

const pointerEvents = {
  mousedown: 'onMouseDown',
  mouseup: 'onMouseUp',
  mouseover: 'onMouseOver',
  mousemove: 'onMouseMove',
  click: 'onClick',
  dblclick: 'onDblClick',
  mouseenter: 'onMouseEnter',
  mouseleave: 'onMouseLeave',
  mouseout: 'onMouseOut',
  contextmenu: 'onContextMenu',
  touchstart: 'onTouchStart',
  touchend: 'onTouchEnd',
  touchmove: 'onTouchMove',
  touchcancel: 'onTouchCancel'
};
const cameraEvents = {
  movestart: 'onMoveStart',
  move: 'onMove',
  moveend: 'onMoveEnd',
  dragstart: 'onDragStart',
  drag: 'onDrag',
  dragend: 'onDragEnd',
  zoomstart: 'onZoomStart',
  zoom: 'onZoom',
  zoomend: 'onZoomEnd',
  rotatestart: 'onRotateStart',
  rotate: 'onRotate',
  rotateend: 'onRotateEnd',
  pitchstart: 'onPitchStart',
  pitch: 'onPitch',
  pitchend: 'onPitchEnd'
};
const otherEvents = {
  wheel: 'onWheel',
  boxzoomstart: 'onBoxZoomStart',
  boxzoomend: 'onBoxZoomEnd',
  boxzoomcancel: 'onBoxZoomCancel',
  resize: 'onResize',
  load: 'onLoad',
  render: 'onRender',
  idle: 'onIdle',
  remove: 'onRemove',
  data: 'onData',
  styledata: 'onStyleData',
  sourcedata: 'onSourceData',
  error: 'onError'
};
const settingNames = ['minZoom', 'maxZoom', 'minPitch', 'maxPitch', 'maxBounds', 'projection', 'renderWorldCopies'];
const handlerNames = ['scrollZoom', 'boxZoom', 'dragRotate', 'dragPan', 'keyboard', 'doubleClickZoom', 'touchZoomRotate', 'touchPitch'];
/**
 * A wrapper for mapbox-gl's Map class
 */
class Mapbox {
  constructor(MapClass, props, container) {
    // mapboxgl.Map instance. Not using type here because we are accessing
    // private members and methods
    this._map = null;
    // Internal states
    this._internalUpdate = false;
    this._inRender = false;
    this._hoveredFeatures = null;
    this._deferredEvents = {
      move: false,
      zoom: false,
      pitch: false,
      rotate: false
    };
    this._onEvent = e => {
      // @ts-ignore
      const cb = this.props[otherEvents[e.type]];
      if (cb) {
        cb(e);
      }
    };
    this._onPointerEvent = e => {
      if (e.type === 'mousemove' || e.type === 'mouseout') {
        this._updateHover(e);
      }
      // @ts-ignore
      const cb = this.props[pointerEvents[e.type]];
      if (cb) {
        if (this.props.interactiveLayerIds && e.type !== 'mouseover' && e.type !== 'mouseout') {
          e.features = this._hoveredFeatures || this._queryRenderedFeatures(e.point);
        }
        cb(e);
        delete e.features;
      }
    };
    this._onCameraEvent = e => {
      if (!this._internalUpdate) {
        // @ts-ignore
        const cb = this.props[cameraEvents[e.type]];
        if (cb) {
          cb(e);
        }
      }
      if (e.type in this._deferredEvents) {
        this._deferredEvents[e.type] = false;
      }
    };
    this._MapClass = MapClass;
    this.props = props;
    this._initialize(container);
  }
  get map() {
    return this._map;
  }
  get transform() {
    return this._renderTransform;
  }
  setProps(props) {
    const oldProps = this.props;
    this.props = props;
    const settingsChanged = this._updateSettings(props, oldProps);
    if (settingsChanged) {
      this._createShadowTransform(this._map);
    }
    const sizeChanged = this._updateSize(props);
    const viewStateChanged = this._updateViewState(props, true);
    this._updateStyle(props, oldProps);
    this._updateStyleComponents(props, oldProps);
    this._updateHandlers(props, oldProps);
    // If 1) view state has changed to match props and
    //    2) the props change is not triggered by map events,
    // it's driven by an external state change. Redraw immediately
    if (settingsChanged || sizeChanged || viewStateChanged && !this._map.isMoving()) {
      this.redraw();
    }
  }
  static reuse(props, container) {
    const that = Mapbox.savedMaps.pop();
    if (!that) {
      return null;
    }
    const map = that.map;
    // When reusing the saved map, we need to reparent the map(canvas) and other child nodes
    // intoto the new container from the props.
    // Step 1: reparenting child nodes from old container to new container
    const oldContainer = map.getContainer();
    container.className = oldContainer.className;
    while (oldContainer.childNodes.length > 0) {
      container.appendChild(oldContainer.childNodes[0]);
    }
    // Step 2: replace the internal container with new container from the react component
    // @ts-ignore
    map._container = container;
    // With maplibre-gl as mapLib, map uses ResizeObserver to observe when its container resizes.
    // When reusing the saved map, we need to disconnect the observer and observe the new container.
    // Step 3: telling the ResizeObserver to disconnect and observe the new container
    // @ts-ignore
    const resizeObserver = map._resizeObserver;
    if (resizeObserver) {
      resizeObserver.disconnect();
      resizeObserver.observe(container);
    }
    // Step 4: apply new props
    that.setProps({
      ...props,
      styleDiffing: false
    });
    map.resize();
    const {
      initialViewState
    } = props;
    if (initialViewState) {
      if (initialViewState.bounds) {
        map.fitBounds(initialViewState.bounds, {
          ...initialViewState.fitBoundsOptions,
          duration: 0
        });
      } else {
        that._updateViewState(initialViewState, false);
      }
    }
    // Simulate load event
    if (map.isStyleLoaded()) {
      map.fire('load');
    } else {
      map.once('styledata', () => map.fire('load'));
    }
    // Force reload
    // @ts-ignore
    map._update();
    return that;
  }
  /* eslint-disable complexity,max-statements */
  _initialize(container) {
    const {
      props
    } = this;
    const mapOptions = {
      ...props,
      ...props.initialViewState,
      accessToken: props.mapboxAccessToken || getAccessTokenFromEnv() || null,
      container,
      style: normalizeStyle(props.mapStyle)
    };
    const viewState = mapOptions.initialViewState || mapOptions.viewState || mapOptions;
    Object.assign(mapOptions, {
      center: [viewState.longitude || 0, viewState.latitude || 0],
      zoom: viewState.zoom || 0,
      pitch: viewState.pitch || 0,
      bearing: viewState.bearing || 0
    });
    if (props.gl) {
      // eslint-disable-next-line
      const getContext = HTMLCanvasElement.prototype.getContext;
      // Hijack canvas.getContext to return our own WebGLContext
      // This will be called inside the mapboxgl.Map constructor
      // @ts-expect-error
      HTMLCanvasElement.prototype.getContext = () => {
        // Unhijack immediately
        HTMLCanvasElement.prototype.getContext = getContext;
        return props.gl;
      };
    }
    const map = new this._MapClass(mapOptions);
    // Props that are not part of constructor options
    if (viewState.padding) {
      map.setPadding(viewState.padding);
    }
    if (props.cursor) {
      map.getCanvas().style.cursor = props.cursor;
    }
    this._createShadowTransform(map);
    // Hack
    // Insert code into map's render cycle
    const renderMap = map._render;
    map._render = arg => {
      this._inRender = true;
      renderMap.call(map, arg);
      this._inRender = false;
    };
    const runRenderTaskQueue = map._renderTaskQueue.run;
    map._renderTaskQueue.run = arg => {
      runRenderTaskQueue.call(map._renderTaskQueue, arg);
      this._onBeforeRepaint();
    };
    map.on('render', () => this._onAfterRepaint());
    // Insert code into map's event pipeline
    const fireEvent = map.fire;
    map.fire = this._fireEvent.bind(this, fireEvent);
    // add listeners
    map.on('resize', () => {
      this._renderTransform.resize(map.transform.width, map.transform.height);
    });
    map.on('styledata', () => this._updateStyleComponents(this.props, {}));
    map.on('sourcedata', () => this._updateStyleComponents(this.props, {}));
    for (const eventName in pointerEvents) {
      map.on(eventName, this._onPointerEvent);
    }
    for (const eventName in cameraEvents) {
      map.on(eventName, this._onCameraEvent);
    }
    for (const eventName in otherEvents) {
      map.on(eventName, this._onEvent);
    }
    this._map = map;
  }
  /* eslint-enable complexity,max-statements */
  recycle() {
    // Clean up unnecessary elements before storing for reuse.
    const container = this.map.getContainer();
    const children = container.querySelector('[mapboxgl-children]');
    children === null || children === void 0 ? void 0 : children.remove();
    Mapbox.savedMaps.push(this);
  }
  destroy() {
    this._map.remove();
  }
  // Force redraw the map now. Typically resize() and jumpTo() is reflected in the next
  // render cycle, which is managed by Mapbox's animation loop.
  // This removes the synchronization issue caused by requestAnimationFrame.
  redraw() {
    const map = this._map;
    // map._render will throw error if style does not exist
    // https://github.com/mapbox/mapbox-gl-js/blob/fb9fc316da14e99ff4368f3e4faa3888fb43c513
    //   /src/ui/map.js#L1834
    if (!this._inRender && map.style) {
      // cancel the scheduled update
      if (map._frame) {
        map._frame.cancel();
        map._frame = null;
      }
      // the order is important - render() may schedule another update
      map._render();
    }
  }
  _createShadowTransform(map) {
    const renderTransform = cloneTransform(map.transform);
    map.painter.transform = renderTransform;
    this._renderTransform = renderTransform;
  }
  /* Trigger map resize if size is controlled
     @param {object} nextProps
     @returns {bool} true if size has changed
   */
  _updateSize(nextProps) {
    // Check if size is controlled
    const {
      viewState
    } = nextProps;
    if (viewState) {
      const map = this._map;
      if (viewState.width !== map.transform.width || viewState.height !== map.transform.height) {
        map.resize();
        return true;
      }
    }
    return false;
  }
  // Adapted from map.jumpTo
  /* Update camera to match props
     @param {object} nextProps
     @param {bool} triggerEvents - should fire camera events
     @returns {bool} true if anything is changed
   */
  _updateViewState(nextProps, triggerEvents) {
    if (this._internalUpdate) {
      return false;
    }
    const map = this._map;
    const tr = this._renderTransform;
    // Take a snapshot of the transform before mutation
    const {
      zoom,
      pitch,
      bearing
    } = tr;
    const isMoving = map.isMoving();
    if (isMoving) {
      // All movement of the camera is done relative to the sea level
      tr.cameraElevationReference = 'sea';
    }
    const changed = applyViewStateToTransform(tr, {
      ...transformToViewState(map.transform),
      ...nextProps
    });
    if (isMoving) {
      // Reset camera reference
      tr.cameraElevationReference = 'ground';
    }
    if (changed && triggerEvents) {
      const deferredEvents = this._deferredEvents;
      // Delay DOM control updates to the next render cycle
      deferredEvents.move = true;
      deferredEvents.zoom || (deferredEvents.zoom = zoom !== tr.zoom);
      deferredEvents.rotate || (deferredEvents.rotate = bearing !== tr.bearing);
      deferredEvents.pitch || (deferredEvents.pitch = pitch !== tr.pitch);
    }
    // Avoid manipulating the real transform when interaction/animation is ongoing
    // as it would interfere with Mapbox's handlers
    if (!isMoving) {
      applyViewStateToTransform(map.transform, nextProps);
    }
    return changed;
  }
  /* Update camera constraints and projection settings to match props
     @param {object} nextProps
     @param {object} currProps
     @returns {bool} true if anything is changed
   */
  _updateSettings(nextProps, currProps) {
    const map = this._map;
    let changed = false;
    for (const propName of settingNames) {
      if (propName in nextProps && !deepEqual(nextProps[propName], currProps[propName])) {
        changed = true;
        map[`set${propName[0].toUpperCase()}${propName.slice(1)}`](nextProps[propName]);
      }
    }
    return changed;
  }
  /* Update map style to match props
     @param {object} nextProps
     @param {object} currProps
     @returns {bool} true if style is changed
   */
  _updateStyle(nextProps, currProps) {
    if (nextProps.cursor !== currProps.cursor) {
      this._map.getCanvas().style.cursor = nextProps.cursor;
    }
    if (nextProps.mapStyle !== currProps.mapStyle) {
      const options = {
        diff: nextProps.styleDiffing
      };
      if ('localIdeographFontFamily' in nextProps) {
        options.localIdeographFontFamily = nextProps.localIdeographFontFamily;
      }
      this._map.setStyle(normalizeStyle(nextProps.mapStyle), options);
      return true;
    }
    return false;
  }
  /* Update fog, light and terrain to match props
     @param {object} nextProps
     @param {object} currProps
     @returns {bool} true if anything is changed
   */
  _updateStyleComponents(nextProps, currProps) {
    const map = this._map;
    let changed = false;
    if (map.style.loaded()) {
      if ('light' in nextProps && !deepEqual(nextProps.light, currProps.light)) {
        changed = true;
        map.setLight(nextProps.light);
      }
      if ('fog' in nextProps && !deepEqual(nextProps.fog, currProps.fog)) {
        changed = true;
        map.setFog(nextProps.fog);
      }
      if ('terrain' in nextProps && !deepEqual(nextProps.terrain, currProps.terrain)) {
        if (!nextProps.terrain || map.getSource(nextProps.terrain.source)) {
          changed = true;
          map.setTerrain(nextProps.terrain);
        }
      }
    }
    return changed;
  }
  /* Update interaction handlers to match props
     @param {object} nextProps
     @param {object} currProps
     @returns {bool} true if anything is changed
   */
  _updateHandlers(nextProps, currProps) {
    const map = this._map;
    let changed = false;
    for (const propName of handlerNames) {
      const newValue = nextProps[propName];
      if (!deepEqual(newValue, currProps[propName])) {
        changed = true;
        if (newValue) {
          map[propName].enable(newValue);
        } else {
          map[propName].disable();
        }
      }
    }
    return changed;
  }
  _queryRenderedFeatures(point) {
    const map = this._map;
    const {
      interactiveLayerIds = []
    } = this.props;
    try {
      return map.queryRenderedFeatures(point, {
        layers: interactiveLayerIds.filter(map.getLayer.bind(map))
      });
    } catch (_a) {
      // May fail if style is not loaded
      return [];
    }
  }
  _updateHover(e) {
    var _a;
    const {
      props
    } = this;
    const shouldTrackHoveredFeatures = props.interactiveLayerIds && (props.onMouseMove || props.onMouseEnter || props.onMouseLeave);
    if (shouldTrackHoveredFeatures) {
      const eventType = e.type;
      const wasHovering = ((_a = this._hoveredFeatures) === null || _a === void 0 ? void 0 : _a.length) > 0;
      const features = this._queryRenderedFeatures(e.point);
      const isHovering = features.length > 0;
      if (!isHovering && wasHovering) {
        e.type = 'mouseleave';
        this._onPointerEvent(e);
      }
      this._hoveredFeatures = features;
      if (isHovering && !wasHovering) {
        e.type = 'mouseenter';
        this._onPointerEvent(e);
      }
      e.type = eventType;
    } else {
      this._hoveredFeatures = null;
    }
  }
  _fireEvent(baseFire, event, properties) {
    const map = this._map;
    const tr = map.transform;
    const eventType = typeof event === 'string' ? event : event.type;
    if (eventType === 'move') {
      this._updateViewState(this.props, false);
    }
    if (eventType in cameraEvents) {
      if (typeof event === 'object') {
        event.viewState = transformToViewState(tr);
      }
      if (this._map.isMoving()) {
        // Replace map.transform with ours during the callbacks
        map.transform = this._renderTransform;
        baseFire.call(map, event, properties);
        map.transform = tr;
        return map;
      }
    }
    baseFire.call(map, event, properties);
    return map;
  }
  // All camera manipulations are complete, ready to repaint
  _onBeforeRepaint() {
    const map = this._map;
    // If there are camera changes driven by props, invoke camera events so that DOM controls are synced
    this._internalUpdate = true;
    for (const eventType in this._deferredEvents) {
      if (this._deferredEvents[eventType]) {
        map.fire(eventType);
      }
    }
    this._internalUpdate = false;
    const tr = this._map.transform;
    // Make sure camera matches the current props
    this._map.transform = this._renderTransform;
    this._onAfterRepaint = () => {
      // Restores camera state before render/load events are fired
      this._map.transform = tr;
    };
  }
}
Mapbox.savedMaps = [];
/**
 * Access token can be provided via one of:
 *   mapboxAccessToken prop
 *   access_token query parameter
 *   MapboxAccessToken environment variable
 *   REACT_APP_MAPBOX_ACCESS_TOKEN environment variable
 * @returns access token
 */
function getAccessTokenFromEnv() {
  let accessToken = null;
  /* global location, process */
  if (typeof location !== 'undefined') {
    const match = /access_token=([^&\/]*)/.exec(location.search);
    accessToken = match && match[1];
  }
  // Note: This depends on bundler plugins (e.g. webpack) importing environment correctly
  try {
    accessToken = accessToken || process.env.MapboxAccessToken;
  } catch (_a) {
    // ignore
  }
  try {
    accessToken = accessToken || process.env.REACT_APP_MAPBOX_ACCESS_TOKEN;
  } catch (_b) {
    // ignore
  }
  return accessToken;
}

/** These methods may break the react binding if called directly */
const skipMethods = ['setMaxBounds', 'setMinZoom', 'setMaxZoom', 'setMinPitch', 'setMaxPitch', 'setRenderWorldCopies', 'setProjection', 'setStyle', 'addSource', 'removeSource', 'addLayer', 'removeLayer', 'setLayerZoomRange', 'setFilter', 'setPaintProperty', 'setLayoutProperty', 'setLight', 'setTerrain', 'setFog', 'remove'];
function createRef(mapInstance, mapLib) {
  if (!mapInstance) {
    return null;
  }
  const map = mapInstance.map;
  const result = {
    getMap: () => map,
    // Overwrite getters to use our shadow transform
    getCenter: () => mapInstance.transform.center,
    getZoom: () => mapInstance.transform.zoom,
    getBearing: () => mapInstance.transform.bearing,
    getPitch: () => mapInstance.transform.pitch,
    getPadding: () => mapInstance.transform.padding,
    getBounds: () => mapInstance.transform.getBounds(),
    project: lnglat => {
      return mapInstance.transform.locationPoint(mapLib.LngLat.convert(lnglat));
    },
    unproject: point => {
      return mapInstance.transform.pointLocation(mapLib.Point.convert(point));
    },
    queryTerrainElevation: (lnglat, options) => {
      // @ts-ignore transform not defined
      const tr = map.transform;
      // @ts-ignore transform not defined
      map.transform = mapInstance.transform;
      const result = map.queryTerrainElevation(lnglat, options);
      // @ts-ignore transform not defined
      map.transform = tr;
      return result;
    }
  };
  for (const key of getMethodNames(map)) {
    // @ts-expect-error
    if (!(key in result) && !skipMethods.includes(key)) {
      result[key] = map[key].bind(map);
    }
  }
  return result;
}
function getMethodNames(obj) {
  const result = new Set();
  let proto = obj;
  while (proto) {
    for (const key of Object.getOwnPropertyNames(proto)) {
      if (key[0] !== '_' && typeof obj[key] === 'function' && key !== 'fire' && key !== 'setEventedParent') {
        result.add(key);
      }
    }
    proto = Object.getPrototypeOf(proto);
  }
  return Array.from(result);
}

// From https://github.com/streamich/react-use/blob/master/src/useIsomorphicLayoutEffect.ts
// useLayoutEffect but does not trigger warning in server-side rendering
const useIsomorphicLayoutEffect = typeof document !== 'undefined' ? reactExports$1.useLayoutEffect : reactExports$1.useEffect;

const globalSettings = ['baseApiUrl', 'maxParallelImageRequests', 'workerClass', 'workerCount', 'workerUrl'];
function setGlobals(mapLib, props) {
  for (const key of globalSettings) {
    if (key in props) {
      mapLib[key] = props[key];
    }
  }
  if (props.RTLTextPlugin && mapLib.getRTLTextPluginStatus && mapLib.getRTLTextPluginStatus() === 'unavailable') {
    mapLib.setRTLTextPlugin(props.RTLTextPlugin, error => {
      if (error) {
        // eslint-disable-next-line
        console.error(error);
      }
    }, false);
  }
}

const MapContext = reactExports$1.createContext(null);
const defaultProps$2 = {
  // Constraints
  minZoom: 0,
  maxZoom: 22,
  minPitch: 0,
  maxPitch: 60,
  // Interaction handlers
  scrollZoom: true,
  boxZoom: true,
  dragRotate: true,
  dragPan: true,
  keyboard: true,
  doubleClickZoom: true,
  touchZoomRotate: true,
  touchPitch: true,
  // Style
  mapStyle: {
    version: 8,
    sources: {},
    layers: []
  },
  styleDiffing: true,
  projection: 'mercator',
  renderWorldCopies: true,
  // Callbacks
  onError: e => console.error(e.error),
  // Globals
  RTLTextPlugin: 'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js'
};
const Map$2 = reactExports$1.forwardRef((props, ref) => {
  const mountedMapsContext = reactExports$1.useContext(MountedMapsContext);
  const [mapInstance, setMapInstance] = reactExports$1.useState(null);
  const containerRef = reactExports$1.useRef();
  const {
    current: contextValue
  } = reactExports$1.useRef({
    mapLib: null,
    map: null
  });
  reactExports$1.useEffect(() => {
    const mapLib = props.mapLib;
    let isMounted = true;
    let mapbox;
    Promise.resolve(mapLib || Promise.resolve().then(function () { return index; })).then(mapboxgl => {
      if (!isMounted) {
        return;
      }
      if (!mapboxgl.Map) {
        // commonjs style
        mapboxgl = mapboxgl.default;
      }
      if (!mapboxgl || !mapboxgl.Map) {
        throw new Error('Invalid mapLib');
      }
      // workerUrl & workerClass may change the result of supported()
      // https://github.com/visgl/react-map-gl/discussions/2027
      setGlobals(mapboxgl, props);
      if (!mapboxgl.supported || mapboxgl.supported(props)) {
        if (props.reuseMaps) {
          mapbox = Mapbox.reuse(props, containerRef.current);
        }
        if (!mapbox) {
          mapbox = new Mapbox(mapboxgl.Map, props, containerRef.current);
        }
        contextValue.map = createRef(mapbox, mapboxgl);
        contextValue.mapLib = mapboxgl;
        setMapInstance(mapbox);
        mountedMapsContext === null || mountedMapsContext === void 0 ? void 0 : mountedMapsContext.onMapMount(contextValue.map, props.id);
      } else {
        throw new Error('Map is not supported by this browser');
      }
    }).catch(error => {
      props.onError({
        type: 'error',
        target: null,
        originalEvent: null,
        error
      });
    });
    return () => {
      isMounted = false;
      if (mapbox) {
        mountedMapsContext === null || mountedMapsContext === void 0 ? void 0 : mountedMapsContext.onMapUnmount(props.id);
        if (props.reuseMaps) {
          mapbox.recycle();
        } else {
          mapbox.destroy();
        }
      }
    };
  }, []);
  useIsomorphicLayoutEffect(() => {
    if (mapInstance) {
      mapInstance.setProps(props);
    }
  });
  reactExports$1.useImperativeHandle(ref, () => contextValue.map, [mapInstance]);
  const style = reactExports$1.useMemo(() => ({
    position: 'relative',
    width: '100%',
    height: '100%',
    ...props.style
  }), [props.style]);
  const CHILD_CONTAINER_STYLE = {
    height: '100%'
  };
  return reactExports$1.createElement("div", {
    id: props.id,
    ref: containerRef,
    style: style
  }, mapInstance && reactExports$1.createElement(MapContext.Provider, {
    value: contextValue
  }, reactExports$1.createElement("div", {
    "mapboxgl-children": "",
    style: CHILD_CONTAINER_STYLE
  }, props.children)));
});
Map$2.displayName = 'Map';
Map$2.defaultProps = defaultProps$2;

// This is a simplified version of
// https://github.com/facebook/react/blob/4131af3e4bf52f3a003537ec95a1655147c81270/src/renderers/dom/shared/CSSPropertyOperations.js#L62
const unitlessNumber = /box|flex|grid|column|lineHeight|fontWeight|opacity|order|tabSize|zIndex/;
function applyReactStyle(element, styles) {
  if (!element || !styles) {
    return;
  }
  const style = element.style;
  for (const key in styles) {
    const value = styles[key];
    if (Number.isFinite(value) && !unitlessNumber.test(key)) {
      style[key] = `${value}px`;
    } else {
      style[key] = value;
    }
  }
}

/* global document */
const defaultProps$1 = {
  draggable: false,
  popup: null,
  rotation: 0,
  rotationAlignment: 'auto',
  pitchAlignment: 'auto'
};
/* eslint-disable complexity,max-statements */
function Marker(props) {
  const {
    map,
    mapLib
  } = reactExports$1.useContext(MapContext);
  const thisRef = reactExports$1.useRef({
    props
  });
  thisRef.current.props = props;
  const marker = reactExports$1.useMemo(() => {
    let hasChildren = false;
    reactExports$1.Children.forEach(props.children, el => {
      if (el) {
        hasChildren = true;
      }
    });
    const options = {
      ...props,
      element: hasChildren ? document.createElement('div') : null
    };
    const mk = new mapLib.Marker(options).setLngLat([props.longitude, props.latitude]);
    mk.getElement().addEventListener('click', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onClick) === null || _b === void 0 ? void 0 : _b.call(_a, {
        type: 'click',
        target: mk,
        originalEvent: e
      });
    });
    mk.on('dragstart', e => {
      var _a, _b;
      const evt = e;
      evt.lngLat = marker.getLngLat();
      (_b = (_a = thisRef.current.props).onDragStart) === null || _b === void 0 ? void 0 : _b.call(_a, evt);
    });
    mk.on('drag', e => {
      var _a, _b;
      const evt = e;
      evt.lngLat = marker.getLngLat();
      (_b = (_a = thisRef.current.props).onDrag) === null || _b === void 0 ? void 0 : _b.call(_a, evt);
    });
    mk.on('dragend', e => {
      var _a, _b;
      const evt = e;
      evt.lngLat = marker.getLngLat();
      (_b = (_a = thisRef.current.props).onDragEnd) === null || _b === void 0 ? void 0 : _b.call(_a, evt);
    });
    return mk;
  }, []);
  reactExports$1.useEffect(() => {
    marker.addTo(map.getMap());
    return () => {
      marker.remove();
    };
  }, []);
  reactExports$1.useEffect(() => {
    applyReactStyle(marker.getElement(), props.style);
  }, [props.style]);
  if (marker.getLngLat().lng !== props.longitude || marker.getLngLat().lat !== props.latitude) {
    marker.setLngLat([props.longitude, props.latitude]);
  }
  if (props.offset && !arePointsEqual(marker.getOffset(), props.offset)) {
    marker.setOffset(props.offset);
  }
  if (marker.isDraggable() !== props.draggable) {
    marker.setDraggable(props.draggable);
  }
  if (marker.getRotation() !== props.rotation) {
    marker.setRotation(props.rotation);
  }
  if (marker.getRotationAlignment() !== props.rotationAlignment) {
    marker.setRotationAlignment(props.rotationAlignment);
  }
  if (marker.getPitchAlignment() !== props.pitchAlignment) {
    marker.setPitchAlignment(props.pitchAlignment);
  }
  if (marker.getPopup() !== props.popup) {
    marker.setPopup(props.popup);
  }
  return reactDomExports.createPortal(props.children, marker.getElement());
}
Marker.defaultProps = defaultProps$1;
// @ts-ignore
var marker = reactExports$1.memo(Marker);

/* global document */
// Adapted from https://github.com/mapbox/mapbox-gl-js/blob/v1.13.0/src/ui/popup.js
function getClassList(className) {
  return new Set(className ? className.trim().split(/\s+/) : []);
}
/* eslint-disable complexity,max-statements */
function Popup(props) {
  const {
    map,
    mapLib
  } = reactExports$1.useContext(MapContext);
  const container = reactExports$1.useMemo(() => {
    return document.createElement('div');
  }, []);
  const thisRef = reactExports$1.useRef({
    props
  });
  thisRef.current.props = props;
  const popup = reactExports$1.useMemo(() => {
    const options = {
      ...props
    };
    const pp = new mapLib.Popup(options).setLngLat([props.longitude, props.latitude]);
    pp.once('open', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onOpen) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    });
    return pp;
  }, []);
  reactExports$1.useEffect(() => {
    const onClose = e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onClose) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    };
    popup.on('close', onClose);
    popup.setDOMContent(container).addTo(map.getMap());
    return () => {
      // https://github.com/visgl/react-map-gl/issues/1825
      // onClose should not be fired if the popup is removed by unmounting
      // When using React strict mode, the component is mounted twice.
      // Firing the onClose callback here would be a false signal to remove the component.
      popup.off('close', onClose);
      if (popup.isOpen()) {
        popup.remove();
      }
    };
  }, []);
  reactExports$1.useEffect(() => {
    applyReactStyle(popup.getElement(), props.style);
  }, [props.style]);
  if (popup.isOpen()) {
    if (popup.getLngLat().lng !== props.longitude || popup.getLngLat().lat !== props.latitude) {
      popup.setLngLat([props.longitude, props.latitude]);
    }
    // @ts-ignore
    if (props.offset && !deepEqual(popup.options.offset, props.offset)) {
      popup.setOffset(props.offset);
    }
    // @ts-ignore
    if (popup.options.anchor !== props.anchor || popup.options.maxWidth !== props.maxWidth) {
      // @ts-ignore
      popup.options.anchor = props.anchor;
      popup.setMaxWidth(props.maxWidth);
    }
    // @ts-ignore
    if (popup.options.className !== props.className) {
      // @ts-ignore
      const prevClassList = getClassList(popup.options.className);
      const nextClassList = getClassList(props.className);
      for (const c of prevClassList) {
        if (!nextClassList.has(c)) {
          popup.removeClassName(c);
        }
      }
      for (const c of nextClassList) {
        if (!prevClassList.has(c)) {
          popup.addClassName(c);
        }
      }
      // @ts-ignore
      popup.options.className = props.className;
    }
  }
  return reactDomExports.createPortal(props.children, container);
}
// @ts-ignore
var Popup$1 = reactExports$1.memo(Popup);

function useControl(onCreate, arg1, arg2, arg3) {
  const context = reactExports$1.useContext(MapContext);
  const ctrl = reactExports$1.useMemo(() => onCreate(context), []);
  reactExports$1.useEffect(() => {
    const opts = arg3 || arg2 || arg1;
    const onAdd = typeof arg1 === 'function' && typeof arg2 === 'function' ? arg1 : null;
    const onRemove = typeof arg2 === 'function' ? arg2 : typeof arg1 === 'function' ? arg1 : null;
    const {
      map
    } = context;
    if (!map.hasControl(ctrl)) {
      map.addControl(ctrl, opts === null || opts === void 0 ? void 0 : opts.position);
      if (onAdd) {
        onAdd(context);
      }
    }
    return () => {
      if (onRemove) {
        onRemove(context);
      }
      // Map might have been removed (parent effects are destroyed before child ones)
      if (map.hasControl(ctrl)) {
        map.removeControl(ctrl);
      }
    };
  }, []);
  return ctrl;
}

function AttributionControl(props) {
  const ctrl = useControl(({
    mapLib
  }) => new mapLib.AttributionControl(props), {
    position: props.position
  });
  reactExports$1.useEffect(() => {
    // @ts-ignore
    applyReactStyle(ctrl._container, props.style);
  }, [props.style]);
  return null;
}
var attributionControl = reactExports$1.memo(AttributionControl);

/* global document */
function FullscreenControl(props) {
  const ctrl = useControl(({
    mapLib
  }) => new mapLib.FullscreenControl({
    container: props.containerId && document.getElementById(props.containerId)
  }), {
    position: props.position
  });
  reactExports$1.useEffect(() => {
    // @ts-ignore
    applyReactStyle(ctrl._controlContainer, props.style);
  }, [props.style]);
  return null;
}
var fullscreenControl = reactExports$1.memo(FullscreenControl);

const GeolocateControl = reactExports$1.forwardRef((props, ref) => {
  const thisRef = reactExports$1.useRef({
    props
  });
  const ctrl = useControl(({
    mapLib
  }) => {
    const gc = new mapLib.GeolocateControl(props);
    // Hack: fix GeolocateControl reuse
    // When using React strict mode, the component is mounted twice.
    // GeolocateControl's UI creation is asynchronous. Removing and adding it back causes the UI to be initialized twice.
    const setupUI = gc._setupUI;
    gc._setupUI = args => {
      if (!gc._container.hasChildNodes()) {
        setupUI(args);
      }
    };
    gc.on('geolocate', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onGeolocate) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    });
    gc.on('error', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onError) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    });
    gc.on('outofmaxbounds', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onOutOfMaxBounds) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    });
    gc.on('trackuserlocationstart', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onTrackUserLocationStart) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    });
    gc.on('trackuserlocationend', e => {
      var _a, _b;
      (_b = (_a = thisRef.current.props).onTrackUserLocationEnd) === null || _b === void 0 ? void 0 : _b.call(_a, e);
    });
    return gc;
  }, {
    position: props.position
  });
  thisRef.current.props = props;
  reactExports$1.useImperativeHandle(ref, () => ({
    trigger: () => ctrl.trigger()
  }), []);
  reactExports$1.useEffect(() => {
    // @ts-ignore
    applyReactStyle(ctrl._container, props.style);
  }, [props.style]);
  return null;
});
GeolocateControl.displayName = 'GeolocateControl';
var geolocateControl = reactExports$1.memo(GeolocateControl);

function NavigationControl(props) {
  const ctrl = useControl(({
    mapLib
  }) => new mapLib.NavigationControl(props), {
    position: props.position
  });
  reactExports$1.useEffect(() => {
    // @ts-ignore
    applyReactStyle(ctrl._container, props.style);
  }, [props.style]);
  return null;
}
var NavigationControl$1 = reactExports$1.memo(NavigationControl);

const defaultProps = {
  unit: 'metric',
  maxWidth: 100
};
function ScaleControl(props) {
  const ctrl = useControl(({
    mapLib
  }) => new mapLib.ScaleControl(props), {
    position: props.position
  });
  // @ts-ignore
  if (ctrl.options.unit !== props.unit || ctrl.options.maxWidth !== props.maxWidth) {
    // @ts-ignore
    ctrl.options.maxWidth = props.maxWidth;
    // This method will trigger an update
    ctrl.setUnit(props.unit);
  }
  reactExports$1.useEffect(() => {
    // @ts-ignore
    applyReactStyle(ctrl._container, props.style);
  }, [props.style]);
  return null;
}
ScaleControl.defaultProps = defaultProps;
var ScaleControl$1 = reactExports$1.memo(ScaleControl);

function assert(condition, message) {
  if (!condition) {
    throw new Error(message);
  }
}

let sourceCounter = 0;
function createSource(map, id, props) {
  // @ts-ignore
  if (map.style && map.style._loaded) {
    const options = {
      ...props
    };
    delete options.id;
    delete options.children;
    // @ts-ignore
    map.addSource(id, options);
    return map.getSource(id);
  }
  return null;
}
/* eslint-disable complexity */
function updateSource(source, props, prevProps) {
  assert(props.id === prevProps.id, 'source id changed');
  assert(props.type === prevProps.type, 'source type changed');
  let changedKey = '';
  let changedKeyCount = 0;
  for (const key in props) {
    if (key !== 'children' && key !== 'id' && !deepEqual(prevProps[key], props[key])) {
      changedKey = key;
      changedKeyCount++;
    }
  }
  if (!changedKeyCount) {
    return;
  }
  const type = props.type;
  if (type === 'geojson') {
    source.setData(props.data);
  } else if (type === 'image') {
    source.updateImage({
      url: props.url,
      coordinates: props.coordinates
    });
  } else if ((type === 'canvas' || type === 'video') && changedKeyCount === 1 && changedKey === 'coordinates') {
    source.setCoordinates(props.coordinates);
  } else if (type === 'vector' && 'setUrl' in source) {
    // Added in 1.12.0:
    // vectorTileSource.setTiles
    // vectorTileSource.setUrl
    switch (changedKey) {
      case 'url':
        source.setUrl(props.url);
        break;
      case 'tiles':
        source.setTiles(props.tiles);
        break;
    }
  } else {
    // eslint-disable-next-line
    console.warn(`Unable to update <Source> prop: ${changedKey}`);
  }
}
/* eslint-enable complexity */
function Source(props) {
  const map = reactExports$1.useContext(MapContext).map.getMap();
  const propsRef = reactExports$1.useRef(props);
  const [, setStyleLoaded] = reactExports$1.useState(0);
  const id = reactExports$1.useMemo(() => props.id || `jsx-source-${sourceCounter++}`, []);
  reactExports$1.useEffect(() => {
    if (map) {
      const forceUpdate = () => setTimeout(() => setStyleLoaded(version => version + 1), 0);
      map.on('styledata', forceUpdate);
      forceUpdate();
      return () => {
        var _a;
        map.off('styledata', forceUpdate);
        // @ts-ignore
        if (map.style && map.style._loaded && map.getSource(id)) {
          // Parent effects are destroyed before child ones, see
          // https://github.com/facebook/react/issues/16728
          // Source can only be removed after all child layers are removed
          const allLayers = (_a = map.getStyle()) === null || _a === void 0 ? void 0 : _a.layers;
          if (allLayers) {
            for (const layer of allLayers) {
              // @ts-ignore (2339) source does not exist on all layer types
              if (layer.source === id) {
                map.removeLayer(layer.id);
              }
            }
          }
          map.removeSource(id);
        }
      };
    }
    return undefined;
  }, [map]);
  // @ts-ignore
  let source = map && map.style && map.getSource(id);
  if (source) {
    updateSource(source, props, propsRef.current);
  } else {
    source = createSource(map, id, props);
  }
  propsRef.current = props;
  return source && reactExports$1.Children.map(props.children, child => child && reactExports$1.cloneElement(child, {
    source: id
  })) || null;
}

/* eslint-disable complexity, max-statements */
function updateLayer(map, id, props, prevProps) {
  assert(props.id === prevProps.id, 'layer id changed');
  assert(props.type === prevProps.type, 'layer type changed');
  if (props.type === 'custom' || prevProps.type === 'custom') {
    return;
  }
  const {
    layout = {},
    paint = {},
    filter,
    minzoom,
    maxzoom,
    beforeId
  } = props;
  if (beforeId !== prevProps.beforeId) {
    map.moveLayer(id, beforeId);
  }
  if (layout !== prevProps.layout) {
    const prevLayout = prevProps.layout || {};
    for (const key in layout) {
      if (!deepEqual(layout[key], prevLayout[key])) {
        map.setLayoutProperty(id, key, layout[key]);
      }
    }
    for (const key in prevLayout) {
      if (!layout.hasOwnProperty(key)) {
        map.setLayoutProperty(id, key, undefined);
      }
    }
  }
  if (paint !== prevProps.paint) {
    const prevPaint = prevProps.paint || {};
    for (const key in paint) {
      if (!deepEqual(paint[key], prevPaint[key])) {
        map.setPaintProperty(id, key, paint[key]);
      }
    }
    for (const key in prevPaint) {
      if (!paint.hasOwnProperty(key)) {
        map.setPaintProperty(id, key, undefined);
      }
    }
  }
  if (!deepEqual(filter, prevProps.filter)) {
    map.setFilter(id, filter);
  }
  if (minzoom !== prevProps.minzoom || maxzoom !== prevProps.maxzoom) {
    map.setLayerZoomRange(id, minzoom, maxzoom);
  }
}
function createLayer(map, id, props) {
  // @ts-ignore
  if (map.style && map.style._loaded && (!('source' in props) || map.getSource(props.source))) {
    const options = {
      ...props,
      id
    };
    delete options.beforeId;
    // @ts-ignore
    map.addLayer(options, props.beforeId);
  }
}
/* eslint-enable complexity, max-statements */
let layerCounter = 0;
function Layer(props) {
  const map = reactExports$1.useContext(MapContext).map.getMap();
  const propsRef = reactExports$1.useRef(props);
  const [, setStyleLoaded] = reactExports$1.useState(0);
  const id = reactExports$1.useMemo(() => props.id || `jsx-layer-${layerCounter++}`, []);
  reactExports$1.useEffect(() => {
    if (map) {
      const forceUpdate = () => setStyleLoaded(version => version + 1);
      map.on('styledata', forceUpdate);
      forceUpdate();
      return () => {
        map.off('styledata', forceUpdate);
        // @ts-ignore
        if (map.style && map.style._loaded && map.getLayer(id)) {
          map.removeLayer(id);
        }
      };
    }
    return undefined;
  }, [map]);
  // @ts-ignore
  const layer = map && map.style && map.getLayer(id);
  if (layer) {
    try {
      updateLayer(map, id, props, propsRef.current);
    } catch (error) {
      console.warn(error); // eslint-disable-line
    }
  } else {
    createLayer(map, id, props);
  }
  // Store last rendered props
  propsRef.current = props;
  return null;
}

var reactMapGlExports = /*#__PURE__*/Object.freeze({
  __proto__: null,
  AttributionControl: attributionControl,
  FullscreenControl: fullscreenControl,
  GeolocateControl: geolocateControl,
  Layer: Layer,
  Map: Map$2,
  MapProvider: MapProvider,
  Marker: marker,
  NavigationControl: NavigationControl$1,
  Popup: Popup$1,
  ScaleControl: ScaleControl$1,
  Source: Source,
  default: Map$2,
  useControl: useControl,
  useMap: useMap
});

function findBasemapStyle(children) {
  let style = null;
  React.Children.toArray(children).some(child => {
    if (!child || !child.props) {
      return false;
    }
    const {
      active,
      children
    } = child.props;
    let {
      type
    } = child;
    if (type && type.isAutoBasemap) {
      type = type(child.props).type;
    }
    if (active && type && type.asBasemapStyle) {
      style = type.asBasemapStyle(child.props);
    } else if (children) {
      style = findBasemapStyle(children);
    }
    return !!style;
  });
  return style;
}
function zoomToLocation(instance, geometry) {
  if (geometry.type == "Point") {
    instance.flyTo({
      center: geometry.coordinates,
      zoom: 18
    });
  }
}

function Map$1({
  mapId,
  initBounds,
  children,
  mapProps,
  containerStyle
}) {
  const {
      engine
    } = usePlugin("map-gl"),
    [{
      viewState: pluginViewState
    }, {
      setViewState: setPluginViewState
    }] = usePluginReducer("map"),
    [localViewState, setLocalViewState] = reactExports$1.useState(null),
    viewState = mapId ? pluginViewState : localViewState,
    setViewState = mapId ? setPluginViewState : setLocalViewState,
    onMove = reactExports$1.useCallback(evt => setViewState(evt.viewState), [setViewState]),
    style = findBasemapStyle(children);
  containerStyle = {
    flex: "1",
    minHeight: 200,
    ...containerStyle
  };
  if (!engine) {
    throw new Error("Must pass maplibre-gl or mapbox-gl to mapgl.setEngine()!  See https://wq.io/@wq/map-gl");
  }
  return /*#__PURE__*/React.createElement(Map$2, {
    mapLib: engine,
    id: mapId,
    reuseMaps: Boolean(mapId),
    mapStyle: style,
    initialViewState: !viewState && {
      bounds: initBounds
    },
    onMove: onMove,
    style: containerStyle,
    ...mapProps,
    ...viewState
  }, children);
}
Map$1.propTypes = {
  mapId: PropTypes.string,
  initBounds: PropTypes.array,
  children: PropTypes.node,
  mapProps: PropTypes.object,
  containerStyle: PropTypes.object
};

function MapInteraction() {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(NavigationControl$1, {
    position: "top-left"
  }), /*#__PURE__*/React.createElement(ScaleControl$1, null));
}

function useMapInstance(mapId) {
  const maps = useMap(),
    mapState = usePluginState("map");
  if (mapState && !mapId) {
    mapId = mapState.mapId;
  }
  return mapId && maps[mapId] || maps.current || maps.default;
}

function MapAutoZoom({
  mapId,
  context,
  wait,
  maxZoom,
  animate
}) {
  const map = useMapInstance(mapId);
  reactExports$1.useEffect(() => {
    if (!map || !context) {
      return;
    }
    const startTime = new Date();
    map.on("idle", autoZoom);
    async function autoZoom() {
      map.off("idle", autoZoom);
      const sources = map.getStyle().sources,
        allFeatures = [];
      for (const name in sources) {
        const source = sources[name];
        if (source.type !== "geojson") {
          continue;
        }
        let data;
        if (typeof source.data === "object") {
          data = source.data;
        } else {
          try {
            const response = await fetch(source.data);
            data = await response.json();
          } catch (e) {
            console.error(e);
            data = {
              type: "FeatureCollection",
              features: []
            };
          }
        }
        let features;
        if (data.type === "FeatureCollection") {
          features = data.features || [];
        } else if (data.type === "Feature") {
          features = [data];
        } else {
          features = [{
            type: "Feature",
            geometry: data
          }];
        }
        allFeatures.push(...features);
      }
      const bounds = computeBounds(allFeatures);
      if (bounds) {
        const elapsed = new Date() - startTime,
          timeout = Math.max(wait * 1000 - elapsed, 0);
        setTimeout(() => {
          map.fitBounds(bounds, {
            padding: 32,
            maxZoom,
            animate
          });
        }, timeout);
      }
    }
  }, [map, context]);
  return null;
}

function MapIdentify() {
  const map = useMapInstance(),
    [{
      overlays
    }, {
      setHighlight
    }] = usePluginReducer("map");
  reactExports$1.useEffect(() => {
    if (!map || map._alreadyConfiguredHandlers) {
      return;
    }
    map._alreadyConfiguredHandlers = true;
    overlays.forEach(overlay => {
      getIdentifyLayers(overlay).forEach(layer => {
        map.on("mouseenter", layer, onMouseEnter);
        map.on("mouseleave", layer, onMouseLeave);
        map.on("click", layer, evt => updateHighlight(evt, overlay));
      });
    });
    function onMouseEnter() {
      map.getCanvas().style.cursor = "pointer";
    }
    function onMouseLeave() {
      map.getCanvas().style.cursor = "";
    }
    function updateHighlight(evt, overlay) {
      const features = evt.features.map(feature => {
        feature.popup = overlay.popup;
        return feature;
      });
      setHighlight({
        type: "FeatureCollection",
        features
      });
    }
  }, [map, setHighlight]);
  return null;
}
function getIdentifyLayers(overlay) {
  if (overlay.identifyLayers) {
    return overlay.identifyLayers;
  }
  if (!overlay.popup) {
    return [];
  }
  if (overlay.type === "geojson") {
    return ["symbol", "line", "fill", "fill-extrusion", "circle"].map(type => `${overlay.name}-${type}`);
  } else if (overlay.type === "vector-tile") {
    return ((overlay.style || {}).layers || []).map(layer => layer.id);
  } else {
    return [];
  }
}

var MapLayers = reactExports$1.Fragment;

function GeoHelpIcon({
  name,
  type
}) {
  const iconClass = getIconClass(name, type);
  if (!iconClass) {
    return `{${name}}`;
  }
  return /*#__PURE__*/React.createElement("span", {
    className: iconClass,
    style: {
      display: "inline-block",
      width: 18,
      height: 18,
      verticalAlign: "middle"
    }
  });
}
GeoHelpIcon.propTypes = {
  name: PropTypes.string,
  type: PropTypes.string
};
const SHAPES = ["point", "line", "polygon"],
  ICONS = SHAPES.map(shape => `${shape.toUpperCase()}_ICON`);
function getIconClass(iconName, drawType) {
  let shape = null;
  if (iconName === "TOOL_ICON") {
    if (drawType === "line_string") {
      shape = "line";
    } else if (SHAPES.includes(drawType)) {
      shape = drawType;
    }
  } else if (ICONS.includes(iconName)) {
    shape = SHAPES[ICONS.indexOf(iconName)];
  }
  if (shape) {
    return `mapbox-gl-draw_${shape}`;
  } else {
    return null;
  }
}

function HighlightPopup({
  inMap
}) {
  const showInMap = useMinWidth(600);
  if (inMap && !showInMap) {
    return null;
  } else if (!inMap && showInMap) {
    return null;
  } else if (inMap) {
    return /*#__PURE__*/React.createElement(InMapPopup, null);
  } else {
    return /*#__PURE__*/React.createElement(HighlightPopup$1, null);
  }
}
function InMapPopup() {
  const [{
      highlight
    }, {
      clearHighlight
    }] = usePluginReducer("map"),
    [longitude, latitude] = reactExports$1.useMemo(() => findPoint(highlight), [highlight]);
  if (!highlight || latitude === null || longitude === null) {
    return null;
  }
  return /*#__PURE__*/React.createElement(Popup$1, {
    latitude: latitude,
    longitude: longitude,
    onClose: clearHighlight,
    maxWidth: "80vw"
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      maxHeight: "40vh",
      overflowY: "auto"
    }
  }, highlight.features.map(feature => /*#__PURE__*/React.createElement(HighlightContent, {
    key: feature.id,
    feature: feature,
    inMap: true
  }))));
}
function findPoint(highlight) {
  if (!highlight || !highlight.features || !highlight.features.length) {
    return [null, null];
  }
  const point = highlight.features.find(feature => feature.geometry && feature.geometry.type === "Point");
  if (point) {
    return point.geometry.coordinates;
  } else {
    const bounds = computeBounds(highlight.features);
    if (bounds) {
      const [[minx, miny], [maxx, maxy]] = bounds;
      return [(minx + maxx) / 2, (miny + maxy) / 2];
    } else {
      return [0, 0];
    }
  }
}

function VectorTile$1() {
  // Handled with style= prop in root Map
  return null;
}
function asBasemapStyle$1(basemap) {
  return basemap.style || basemap.url;
}
VectorTile$1.asBasemapStyle = asBasemapStyle$1;

function Tile$1() {
  // Handled with style= prop in root Map
  return null;
}
const styles = {};
function asBasemapStyle(basemap) {
  const key = makeBasemapKey(basemap);
  if (!styles[key]) {
    styles[key] = makeBasemapStyle(basemap);
  }
  return styles[key];
}
function makeBasemapKey(basemap) {
  return ["name", "url", "subdomains", "tileSize"].map(key => "" + (basemap[key] || "")).join("__");
}
function makeBasemapStyle(basemap) {
  const urls = [];
  if (basemap.url.match("{s}")) {
    (basemap.subdomains || ["a", "b", "c"]).forEach(s => urls.push(basemap.url.replace("{s}", s)));
  } else {
    urls.push(basemap.url);
  }
  return {
    version: 8,
    sources: {
      [basemap.name]: {
        type: "raster",
        tiles: urls,
        tileSize: basemap.tileSize || 256
      }
    },
    layers: [{
      id: basemap.name,
      type: "raster",
      source: basemap.name
    }]
  };
}
Tile$1.asBasemapStyle = asBasemapStyle;

const types = ["symbol", "line", "fill", "circle"];

// Same API as react-mapbox-gl's GeoJSONLayer but implemented via react-map-gl

function GeoJSONLayer({
  id,
  before,
  data,
  ...rest
}) {
  if (!id) {
    const ids = data && data.features ? data.features.map(feature => feature.id) : [];
    id = `_geojson_${ids.join("_")}`;
  }
  const {
    symbolLayout,
    symbolPaint,
    fillLayout,
    fillPaint,
    lineLayout,
    linePaint,
    circleLayout,
    circlePaint
  } = rest;
  const [source, layers] = reactExports$1.useMemo(() => {
    const source = {
      id,
      type: "geojson",
      data
    };
    const layers = types.map(type => ({
      id: `${id}-${type}`,
      type,
      paint: rest[`${type}Paint`] || {},
      layout: rest[`${type}Layout`] || {}
    }));
    return [source, layers];
  }, [id, before, data, symbolLayout, symbolPaint, fillLayout, fillPaint, lineLayout, linePaint, circleLayout, circlePaint]);
  return /*#__PURE__*/React.createElement(Source, {
    key: id,
    ...source
  }, layers.map(layer => /*#__PURE__*/React.createElement(Layer, {
    key: layer.id,
    ...layer
  })));
}
GeoJSONLayer.propTypes = {
  id: PropTypes.string,
  before: PropTypes.string,
  data: PropTypes.object
};

function Geojson({
  name,
  active,
  before,
  url,
  data,
  icon,
  symbol,
  color,
  fill,
  line,
  circle
}) {
  const {
    symbolLayout,
    symbolPaint,
    fillLayout,
    fillPaint,
    lineLayout,
    linePaint,
    circleLayout,
    circlePaint
  } = reactExports$1.useMemo(() => {
    let symbolLayout, symbolPaint, fillLayout, fillPaint, lineLayout, linePaint, circleLayout, circlePaint;
    if (symbol) {
      const {
        paint,
        ...layout
      } = symbol;
      symbolLayout = layout;
      symbolPaint = paint;
    } else if (icon) {
      symbolLayout = {
        "icon-image": icon,
        "icon-allow-overlap": true
      };
    } else if (fill || line || circle) {
      fillPaint = fill;
      linePaint = line;
      circlePaint = circle;
    } else {
      fillPaint = {
        "fill-color": color || "#3388ff",
        "fill-opacity": ["match", ["geometry-type"], ["Polygon", "MultiPolygon"], 0.2, 0]
      };
      linePaint = {
        "line-width": 3,
        "line-color": color || "#3388ff",
        "line-opacity": 1
      };
      circlePaint = {
        "circle-color": "white",
        "circle-radius": ["match", ["geometry-type"], ["Point", "MultiPoint"], 3, 0],
        "circle-stroke-color": color || "#3086cc",
        "circle-stroke-width": ["match", ["geometry-type"], ["Point", "MultiPoint"], 3, 0],
        "circle-opacity": ["match", ["geometry-type"], ["Point", "MultiPoint"], 1, 0]
      };
    }
    fillLayout = {
      visibility: active && fillPaint ? "visible" : "none"
    };
    lineLayout = {
      visibility: active && linePaint ? "visible" : "none"
    };
    circleLayout = {
      visibility: active && circlePaint ? "visible" : "none"
    };
    if (symbolLayout) {
      symbolLayout = {
        ...symbolLayout,
        visibility: active ? "visible" : "none"
      };
    }
    return {
      symbolLayout,
      symbolPaint,
      fillLayout,
      fillPaint,
      lineLayout,
      linePaint,
      circleLayout,
      circlePaint
    };
  }, [active, icon, symbol, color, fill, line, circle]);
  return /*#__PURE__*/React.createElement(GeoJSONLayer, {
    id: name,
    before: before,
    data: data || url,
    symbolLayout: symbolLayout,
    symbolPaint: symbolPaint,
    fillLayout: fillLayout,
    fillPaint: fillPaint,
    lineLayout: lineLayout,
    linePaint: linePaint,
    circleLayout: circleLayout,
    circlePaint: circlePaint
  });
}
Geojson.propTypes = {
  name: PropTypes.string,
  active: PropTypes.bool,
  before: PropTypes.string,
  url: PropTypes.string,
  data: PropTypes.object,
  icon: PropTypes.string,
  symbol: PropTypes.object,
  color: PropTypes.string,
  fill: PropTypes.object,
  line: PropTypes.object,
  circle: PropTypes.object,
  draw: PropTypes.object
};

function Highlight({
  data
}) {
  return /*#__PURE__*/React.createElement(GeoJSONLayer, {
    data: data,
    fillPaint: {
      "fill-color": "#0ff",
      "fill-opacity": ["match", ["geometry-type"], ["Polygon", "MultiPolygon"], 0.2, 0]
    },
    linePaint: {
      "line-width": 5,
      "line-color": "#0ff",
      "line-opacity": 1
    },
    circlePaint: {
      "circle-color": "#0ff",
      "circle-radius": ["match", ["geometry-type"], ["Point", "MultiPoint"], 9, 0],
      "circle-opacity": ["match", ["geometry-type"], ["Point", "MultiPoint"], 0.7, 0]
    }
  });
}
Highlight.propTypes = {
  data: PropTypes.object
};

var mapboxGlDraw = {exports: {}};

(function (module, exports) {
	!function (t, e) {
	  module.exports = e() ;
	}(commonjsGlobal, function () {

	  var t = function (t, e) {
	    var n = {
	        drag: [],
	        click: [],
	        mousemove: [],
	        mousedown: [],
	        mouseup: [],
	        mouseout: [],
	        keydown: [],
	        keyup: [],
	        touchstart: [],
	        touchmove: [],
	        touchend: [],
	        tap: []
	      },
	      o = {
	        on: function (t, e, o) {
	          if (void 0 === n[t]) throw new Error("Invalid event type: " + t);
	          n[t].push({
	            selector: e,
	            fn: o
	          });
	        },
	        render: function (t) {
	          e.store.featureChanged(t);
	        }
	      },
	      r = function (t, r) {
	        for (var i = n[t], a = i.length; a--;) {
	          var s = i[a];
	          if (s.selector(r)) {
	            s.fn.call(o, r) || e.store.render(), e.ui.updateMapClasses();
	            break;
	          }
	        }
	      };
	    return t.start.call(o), {
	      render: t.render,
	      stop: function () {
	        t.stop && t.stop();
	      },
	      trash: function () {
	        t.trash && (t.trash(), e.store.render());
	      },
	      combineFeatures: function () {
	        t.combineFeatures && t.combineFeatures();
	      },
	      uncombineFeatures: function () {
	        t.uncombineFeatures && t.uncombineFeatures();
	      },
	      drag: function (t) {
	        r("drag", t);
	      },
	      click: function (t) {
	        r("click", t);
	      },
	      mousemove: function (t) {
	        r("mousemove", t);
	      },
	      mousedown: function (t) {
	        r("mousedown", t);
	      },
	      mouseup: function (t) {
	        r("mouseup", t);
	      },
	      mouseout: function (t) {
	        r("mouseout", t);
	      },
	      keydown: function (t) {
	        r("keydown", t);
	      },
	      keyup: function (t) {
	        r("keyup", t);
	      },
	      touchstart: function (t) {
	        r("touchstart", t);
	      },
	      touchmove: function (t) {
	        r("touchmove", t);
	      },
	      touchend: function (t) {
	        r("touchend", t);
	      },
	      tap: function (t) {
	        r("tap", t);
	      }
	    };
	  };
	  function e(t) {
	    if (t.__esModule) return t;
	    var e = t.default;
	    if ("function" == typeof e) {
	      var n = function t() {
	        if (this instanceof t) {
	          var n = [null];
	          n.push.apply(n, arguments);
	          var o = Function.bind.apply(e, n);
	          return new o();
	        }
	        return e.apply(this, arguments);
	      };
	      n.prototype = e.prototype;
	    } else n = {};
	    return Object.defineProperty(n, "__esModule", {
	      value: !0
	    }), Object.keys(t).forEach(function (e) {
	      var o = Object.getOwnPropertyDescriptor(t, e);
	      Object.defineProperty(n, e, o.get ? o : {
	        enumerable: !0,
	        get: function () {
	          return t[e];
	        }
	      });
	    }), n;
	  }
	  var n = {},
	    o = {
	      RADIUS: 6378137,
	      FLATTENING: 1 / 298.257223563,
	      POLAR_RADIUS: 6356752.3142
	    },
	    r = o;
	  function i(t) {
	    var e = 0;
	    if (t && t.length > 0) {
	      e += Math.abs(a(t[0]));
	      for (var n = 1; n < t.length; n++) e -= Math.abs(a(t[n]));
	    }
	    return e;
	  }
	  function a(t) {
	    var e,
	      n,
	      o,
	      i,
	      a,
	      u,
	      c = 0,
	      l = t.length;
	    if (l > 2) {
	      for (u = 0; u < l; u++) u === l - 2 ? (o = l - 2, i = l - 1, a = 0) : u === l - 1 ? (o = l - 1, i = 0, a = 1) : (o = u, i = u + 1, a = u + 2), e = t[o], n = t[i], c += (s(t[a][0]) - s(e[0])) * Math.sin(s(n[1]));
	      c = c * r.RADIUS * r.RADIUS / 2;
	    }
	    return c;
	  }
	  function s(t) {
	    return t * Math.PI / 180;
	  }
	  n.geometry = function t(e) {
	    var n,
	      o = 0;
	    switch (e.type) {
	      case "Polygon":
	        return i(e.coordinates);
	      case "MultiPolygon":
	        for (n = 0; n < e.coordinates.length; n++) o += i(e.coordinates[n]);
	        return o;
	      case "Point":
	      case "MultiPoint":
	      case "LineString":
	      case "MultiLineString":
	        return 0;
	      case "GeometryCollection":
	        for (n = 0; n < e.geometries.length; n++) o += t(e.geometries[n]);
	        return o;
	    }
	  }, n.ring = a;
	  var u = {
	      CONTROL_BASE: "mapboxgl-ctrl",
	      CONTROL_PREFIX: "mapboxgl-ctrl-",
	      CONTROL_BUTTON: "mapbox-gl-draw_ctrl-draw-btn",
	      CONTROL_BUTTON_LINE: "mapbox-gl-draw_line",
	      CONTROL_BUTTON_POLYGON: "mapbox-gl-draw_polygon",
	      CONTROL_BUTTON_POINT: "mapbox-gl-draw_point",
	      CONTROL_BUTTON_TRASH: "mapbox-gl-draw_trash",
	      CONTROL_BUTTON_COMBINE_FEATURES: "mapbox-gl-draw_combine",
	      CONTROL_BUTTON_UNCOMBINE_FEATURES: "mapbox-gl-draw_uncombine",
	      CONTROL_GROUP: "mapboxgl-ctrl-group",
	      ATTRIBUTION: "mapboxgl-ctrl-attrib",
	      ACTIVE_BUTTON: "active",
	      BOX_SELECT: "mapbox-gl-draw_boxselect"
	    },
	    c = {
	      HOT: "mapbox-gl-draw-hot",
	      COLD: "mapbox-gl-draw-cold"
	    },
	    l = {
	      ADD: "add",
	      MOVE: "move",
	      DRAG: "drag",
	      POINTER: "pointer",
	      NONE: "none"
	    },
	    d = {
	      POLYGON: "polygon",
	      LINE: "line_string",
	      POINT: "point"
	    },
	    p = {
	      FEATURE: "Feature",
	      POLYGON: "Polygon",
	      LINE_STRING: "LineString",
	      POINT: "Point",
	      FEATURE_COLLECTION: "FeatureCollection",
	      MULTI_PREFIX: "Multi",
	      MULTI_POINT: "MultiPoint",
	      MULTI_LINE_STRING: "MultiLineString",
	      MULTI_POLYGON: "MultiPolygon"
	    },
	    f = {
	      DRAW_LINE_STRING: "draw_line_string",
	      DRAW_POLYGON: "draw_polygon",
	      DRAW_POINT: "draw_point",
	      SIMPLE_SELECT: "simple_select",
	      DIRECT_SELECT: "direct_select",
	      STATIC: "static"
	    },
	    h = {
	      CREATE: "draw.create",
	      DELETE: "draw.delete",
	      UPDATE: "draw.update",
	      SELECTION_CHANGE: "draw.selectionchange",
	      MODE_CHANGE: "draw.modechange",
	      ACTIONABLE: "draw.actionable",
	      RENDER: "draw.render",
	      COMBINE_FEATURES: "draw.combine",
	      UNCOMBINE_FEATURES: "draw.uncombine"
	    },
	    g = {
	      MOVE: "move",
	      CHANGE_COORDINATES: "change_coordinates"
	    },
	    y = {
	      FEATURE: "feature",
	      MIDPOINT: "midpoint",
	      VERTEX: "vertex"
	    },
	    v = {
	      ACTIVE: "true",
	      INACTIVE: "false"
	    },
	    m = ["scrollZoom", "boxZoom", "dragRotate", "dragPan", "keyboard", "doubleClickZoom", "touchZoomRotate"],
	    _ = -85,
	    b = Object.freeze({
	      __proto__: null,
	      classes: u,
	      sources: c,
	      cursors: l,
	      types: d,
	      geojsonTypes: p,
	      modes: f,
	      events: h,
	      updateActions: g,
	      meta: y,
	      activeStates: v,
	      interactions: m,
	      LAT_MIN: -90,
	      LAT_RENDERED_MIN: _,
	      LAT_MAX: 90,
	      LAT_RENDERED_MAX: 85,
	      LNG_MIN: -270,
	      LNG_MAX: 270
	    }),
	    E = {
	      Point: 0,
	      LineString: 1,
	      MultiLineString: 1,
	      Polygon: 2
	    };
	  function T(t, e) {
	    var n = E[t.geometry.type] - E[e.geometry.type];
	    return 0 === n && t.geometry.type === p.POLYGON ? t.area - e.area : n;
	  }
	  function C(t) {
	    return t.map(function (t) {
	      return t.geometry.type === p.POLYGON && (t.area = n.geometry({
	        type: p.FEATURE,
	        property: {},
	        geometry: t.geometry
	      })), t;
	    }).sort(T).map(function (t) {
	      return delete t.area, t;
	    });
	  }
	  function O(t, e) {
	    return void 0 === e && (e = 0), [[t.point.x - e, t.point.y - e], [t.point.x + e, t.point.y + e]];
	  }
	  function S(t) {
	    if (this._items = {}, this._nums = {}, this._length = t ? t.length : 0, t) for (var e = 0, n = t.length; e < n; e++) this.add(t[e]), void 0 !== t[e] && ("string" == typeof t[e] ? this._items[t[e]] = e : this._nums[t[e]] = e);
	  }
	  S.prototype.add = function (t) {
	    return this.has(t) || (this._length++, "string" == typeof t ? this._items[t] = this._length : this._nums[t] = this._length), this;
	  }, S.prototype.delete = function (t) {
	    return !1 === this.has(t) || (this._length--, delete this._items[t], delete this._nums[t]), this;
	  }, S.prototype.has = function (t) {
	    return ("string" == typeof t || "number" == typeof t) && (void 0 !== this._items[t] || void 0 !== this._nums[t]);
	  }, S.prototype.values = function () {
	    var t = this,
	      e = [];
	    return Object.keys(this._items).forEach(function (n) {
	      e.push({
	        k: n,
	        v: t._items[n]
	      });
	    }), Object.keys(this._nums).forEach(function (n) {
	      e.push({
	        k: JSON.parse(n),
	        v: t._nums[n]
	      });
	    }), e.sort(function (t, e) {
	      return t.v - e.v;
	    }).map(function (t) {
	      return t.k;
	    });
	  }, S.prototype.clear = function () {
	    return this._length = 0, this._items = {}, this._nums = {}, this;
	  };
	  var I = [y.FEATURE, y.MIDPOINT, y.VERTEX],
	    x = {
	      click: function (t, e, n) {
	        return M(t, e, n, n.options.clickBuffer);
	      },
	      touch: function (t, e, n) {
	        return M(t, e, n, n.options.touchBuffer);
	      }
	    };
	  function M(t, e, n, o) {
	    if (null === n.map) return [];
	    var r = t ? O(t, o) : e,
	      i = {};
	    n.options.styles && (i.layers = n.options.styles.map(function (t) {
	      return t.id;
	    }));
	    var a = n.map.queryRenderedFeatures(r, i).filter(function (t) {
	        return -1 !== I.indexOf(t.properties.meta);
	      }),
	      s = new S(),
	      u = [];
	    return a.forEach(function (t) {
	      var e = t.properties.id;
	      s.has(e) || (s.add(e), u.push(t));
	    }), C(u);
	  }
	  function L(t, e) {
	    var n = x.click(t, null, e),
	      o = {
	        mouse: l.NONE
	      };
	    return n[0] && (o.mouse = n[0].properties.active === v.ACTIVE ? l.MOVE : l.POINTER, o.feature = n[0].properties.meta), -1 !== e.events.currentModeName().indexOf("draw") && (o.mouse = l.ADD), e.ui.queueMapClasses(o), e.ui.updateMapClasses(), n[0];
	  }
	  function N(t, e) {
	    var n = t.x - e.x,
	      o = t.y - e.y;
	    return Math.sqrt(n * n + o * o);
	  }
	  function A(t, e, n) {
	    void 0 === n && (n = {});
	    var o = null != n.fineTolerance ? n.fineTolerance : 4,
	      r = null != n.grossTolerance ? n.grossTolerance : 12,
	      i = null != n.interval ? n.interval : 500;
	    t.point = t.point || e.point, t.time = t.time || e.time;
	    var a = N(t.point, e.point);
	    return a < o || a < r && e.time - t.time < i;
	  }
	  function P(t, e, n) {
	    void 0 === n && (n = {});
	    var o = null != n.tolerance ? n.tolerance : 25,
	      r = null != n.interval ? n.interval : 250;
	    return t.point = t.point || e.point, t.time = t.time || e.time, N(t.point, e.point) < o && e.time - t.time < r;
	  }
	  var F = {},
	    w = {
	      get exports() {
	        return F;
	      },
	      set exports(t) {
	        F = t;
	      }
	    }.exports = function (t, e) {
	      if (e || (e = 16), void 0 === t && (t = 128), t <= 0) return "0";
	      for (var n = Math.log(Math.pow(2, t)) / Math.log(e), o = 2; n === 1 / 0; o *= 2) n = Math.log(Math.pow(2, t / o)) / Math.log(e) * o;
	      var r = n - Math.floor(n),
	        i = "";
	      for (o = 0; o < Math.floor(n); o++) {
	        i = Math.floor(Math.random() * e).toString(e) + i;
	      }
	      if (r) {
	        var a = Math.pow(e, r);
	        i = Math.floor(Math.random() * a).toString(e) + i;
	      }
	      var s = parseInt(i, e);
	      return s !== 1 / 0 && s >= Math.pow(2, t) ? w(t, e) : i;
	    };
	  w.rack = function (t, e, n) {
	    var o = function (o) {
	        var i = 0;
	        do {
	          if (i++ > 10) {
	            if (!n) throw new Error("too many ID collisions, use more bits");
	            t += n;
	          }
	          var a = w(t, e);
	        } while (Object.hasOwnProperty.call(r, a));
	        return r[a] = o, a;
	      },
	      r = o.hats = {};
	    return o.get = function (t) {
	      return o.hats[t];
	    }, o.set = function (t, e) {
	      return o.hats[t] = e, o;
	    }, o.bits = t || 128, o.base = e || 16, o;
	  };
	  var R = function (t, e) {
	    this.ctx = t, this.properties = e.properties || {}, this.coordinates = e.geometry.coordinates, this.id = e.id || F(), this.type = e.geometry.type;
	  };
	  R.prototype.changed = function () {
	    this.ctx.store.featureChanged(this.id);
	  }, R.prototype.incomingCoords = function (t) {
	    this.setCoordinates(t);
	  }, R.prototype.setCoordinates = function (t) {
	    this.coordinates = t, this.changed();
	  }, R.prototype.getCoordinates = function () {
	    return JSON.parse(JSON.stringify(this.coordinates));
	  }, R.prototype.setProperty = function (t, e) {
	    this.properties[t] = e;
	  }, R.prototype.toGeoJSON = function () {
	    return JSON.parse(JSON.stringify({
	      id: this.id,
	      type: p.FEATURE,
	      properties: this.properties,
	      geometry: {
	        coordinates: this.getCoordinates(),
	        type: this.type
	      }
	    }));
	  }, R.prototype.internal = function (t) {
	    var e = {
	      id: this.id,
	      meta: y.FEATURE,
	      "meta:type": this.type,
	      active: v.INACTIVE,
	      mode: t
	    };
	    if (this.ctx.options.userProperties) for (var n in this.properties) e["user_" + n] = this.properties[n];
	    return {
	      type: p.FEATURE,
	      properties: e,
	      geometry: {
	        coordinates: this.getCoordinates(),
	        type: this.type
	      }
	    };
	  };
	  var D = function (t, e) {
	    R.call(this, t, e);
	  };
	  (D.prototype = Object.create(R.prototype)).isValid = function () {
	    return "number" == typeof this.coordinates[0] && "number" == typeof this.coordinates[1];
	  }, D.prototype.updateCoordinate = function (t, e, n) {
	    this.coordinates = 3 === arguments.length ? [e, n] : [t, e], this.changed();
	  }, D.prototype.getCoordinate = function () {
	    return this.getCoordinates();
	  };
	  var k = function (t, e) {
	    R.call(this, t, e);
	  };
	  (k.prototype = Object.create(R.prototype)).isValid = function () {
	    return this.coordinates.length > 1;
	  }, k.prototype.addCoordinate = function (t, e, n) {
	    this.changed();
	    var o = parseInt(t, 10);
	    this.coordinates.splice(o, 0, [e, n]);
	  }, k.prototype.getCoordinate = function (t) {
	    var e = parseInt(t, 10);
	    return JSON.parse(JSON.stringify(this.coordinates[e]));
	  }, k.prototype.removeCoordinate = function (t) {
	    this.changed(), this.coordinates.splice(parseInt(t, 10), 1);
	  }, k.prototype.updateCoordinate = function (t, e, n) {
	    var o = parseInt(t, 10);
	    this.coordinates[o] = [e, n], this.changed();
	  };
	  var U = function (t, e) {
	    R.call(this, t, e), this.coordinates = this.coordinates.map(function (t) {
	      return t.slice(0, -1);
	    });
	  };
	  (U.prototype = Object.create(R.prototype)).isValid = function () {
	    return 0 !== this.coordinates.length && this.coordinates.every(function (t) {
	      return t.length > 2;
	    });
	  }, U.prototype.incomingCoords = function (t) {
	    this.coordinates = t.map(function (t) {
	      return t.slice(0, -1);
	    }), this.changed();
	  }, U.prototype.setCoordinates = function (t) {
	    this.coordinates = t, this.changed();
	  }, U.prototype.addCoordinate = function (t, e, n) {
	    this.changed();
	    var o = t.split(".").map(function (t) {
	      return parseInt(t, 10);
	    });
	    this.coordinates[o[0]].splice(o[1], 0, [e, n]);
	  }, U.prototype.removeCoordinate = function (t) {
	    this.changed();
	    var e = t.split(".").map(function (t) {
	        return parseInt(t, 10);
	      }),
	      n = this.coordinates[e[0]];
	    n && (n.splice(e[1], 1), n.length < 3 && this.coordinates.splice(e[0], 1));
	  }, U.prototype.getCoordinate = function (t) {
	    var e = t.split(".").map(function (t) {
	        return parseInt(t, 10);
	      }),
	      n = this.coordinates[e[0]];
	    return JSON.parse(JSON.stringify(n[e[1]]));
	  }, U.prototype.getCoordinates = function () {
	    return this.coordinates.map(function (t) {
	      return t.concat([t[0]]);
	    });
	  }, U.prototype.updateCoordinate = function (t, e, n) {
	    this.changed();
	    var o = t.split("."),
	      r = parseInt(o[0], 10),
	      i = parseInt(o[1], 10);
	    void 0 === this.coordinates[r] && (this.coordinates[r] = []), this.coordinates[r][i] = [e, n];
	  };
	  var j = {
	      MultiPoint: D,
	      MultiLineString: k,
	      MultiPolygon: U
	    },
	    V = function (t, e, n, o, r) {
	      var i = n.split("."),
	        a = parseInt(i[0], 10),
	        s = i[1] ? i.slice(1).join(".") : null;
	      return t[a][e](s, o, r);
	    },
	    B = function (t, e) {
	      if (R.call(this, t, e), delete this.coordinates, this.model = j[e.geometry.type], void 0 === this.model) throw new TypeError(e.geometry.type + " is not a valid type");
	      this.features = this._coordinatesToFeatures(e.geometry.coordinates);
	    };
	  function G(t) {
	    this.map = t.map, this.drawConfig = JSON.parse(JSON.stringify(t.options || {})), this._ctx = t;
	  }
	  (B.prototype = Object.create(R.prototype))._coordinatesToFeatures = function (t) {
	    var e = this,
	      n = this.model.bind(this);
	    return t.map(function (t) {
	      return new n(e.ctx, {
	        id: F(),
	        type: p.FEATURE,
	        properties: {},
	        geometry: {
	          coordinates: t,
	          type: e.type.replace("Multi", "")
	        }
	      });
	    });
	  }, B.prototype.isValid = function () {
	    return this.features.every(function (t) {
	      return t.isValid();
	    });
	  }, B.prototype.setCoordinates = function (t) {
	    this.features = this._coordinatesToFeatures(t), this.changed();
	  }, B.prototype.getCoordinate = function (t) {
	    return V(this.features, "getCoordinate", t);
	  }, B.prototype.getCoordinates = function () {
	    return JSON.parse(JSON.stringify(this.features.map(function (t) {
	      return t.type === p.POLYGON ? t.getCoordinates() : t.coordinates;
	    })));
	  }, B.prototype.updateCoordinate = function (t, e, n) {
	    V(this.features, "updateCoordinate", t, e, n), this.changed();
	  }, B.prototype.addCoordinate = function (t, e, n) {
	    V(this.features, "addCoordinate", t, e, n), this.changed();
	  }, B.prototype.removeCoordinate = function (t) {
	    V(this.features, "removeCoordinate", t), this.changed();
	  }, B.prototype.getFeatures = function () {
	    return this.features;
	  }, G.prototype.setSelected = function (t) {
	    return this._ctx.store.setSelected(t);
	  }, G.prototype.setSelectedCoordinates = function (t) {
	    var e = this;
	    this._ctx.store.setSelectedCoordinates(t), t.reduce(function (t, n) {
	      return void 0 === t[n.feature_id] && (t[n.feature_id] = !0, e._ctx.store.get(n.feature_id).changed()), t;
	    }, {});
	  }, G.prototype.getSelected = function () {
	    return this._ctx.store.getSelected();
	  }, G.prototype.getSelectedIds = function () {
	    return this._ctx.store.getSelectedIds();
	  }, G.prototype.isSelected = function (t) {
	    return this._ctx.store.isSelected(t);
	  }, G.prototype.getFeature = function (t) {
	    return this._ctx.store.get(t);
	  }, G.prototype.select = function (t) {
	    return this._ctx.store.select(t);
	  }, G.prototype.deselect = function (t) {
	    return this._ctx.store.deselect(t);
	  }, G.prototype.deleteFeature = function (t, e) {
	    return void 0 === e && (e = {}), this._ctx.store.delete(t, e);
	  }, G.prototype.addFeature = function (t) {
	    return this._ctx.store.add(t);
	  }, G.prototype.clearSelectedFeatures = function () {
	    return this._ctx.store.clearSelected();
	  }, G.prototype.clearSelectedCoordinates = function () {
	    return this._ctx.store.clearSelectedCoordinates();
	  }, G.prototype.setActionableState = function (t) {
	    void 0 === t && (t = {});
	    var e = {
	      trash: t.trash || !1,
	      combineFeatures: t.combineFeatures || !1,
	      uncombineFeatures: t.uncombineFeatures || !1
	    };
	    return this._ctx.events.actionable(e);
	  }, G.prototype.changeMode = function (t, e, n) {
	    return void 0 === e && (e = {}), void 0 === n && (n = {}), this._ctx.events.changeMode(t, e, n);
	  }, G.prototype.updateUIClasses = function (t) {
	    return this._ctx.ui.queueMapClasses(t);
	  }, G.prototype.activateUIButton = function (t) {
	    return this._ctx.ui.setActiveButton(t);
	  }, G.prototype.featuresAt = function (t, e, n) {
	    if (void 0 === n && (n = "click"), "click" !== n && "touch" !== n) throw new Error("invalid buffer type");
	    return x[n](t, e, this._ctx);
	  }, G.prototype.newFeature = function (t) {
	    var e = t.geometry.type;
	    return e === p.POINT ? new D(this._ctx, t) : e === p.LINE_STRING ? new k(this._ctx, t) : e === p.POLYGON ? new U(this._ctx, t) : new B(this._ctx, t);
	  }, G.prototype.isInstanceOf = function (t, e) {
	    if (t === p.POINT) return e instanceof D;
	    if (t === p.LINE_STRING) return e instanceof k;
	    if (t === p.POLYGON) return e instanceof U;
	    if ("MultiFeature" === t) return e instanceof B;
	    throw new Error("Unknown feature class: " + t);
	  }, G.prototype.doRender = function (t) {
	    return this._ctx.store.featureChanged(t);
	  }, G.prototype.onSetup = function () {}, G.prototype.onDrag = function () {}, G.prototype.onClick = function () {}, G.prototype.onMouseMove = function () {}, G.prototype.onMouseDown = function () {}, G.prototype.onMouseUp = function () {}, G.prototype.onMouseOut = function () {}, G.prototype.onKeyUp = function () {}, G.prototype.onKeyDown = function () {}, G.prototype.onTouchStart = function () {}, G.prototype.onTouchMove = function () {}, G.prototype.onTouchEnd = function () {}, G.prototype.onTap = function () {}, G.prototype.onStop = function () {}, G.prototype.onTrash = function () {}, G.prototype.onCombineFeature = function () {}, G.prototype.onUncombineFeature = function () {}, G.prototype.toDisplayFeatures = function () {
	    throw new Error("You must overwrite toDisplayFeatures");
	  };
	  var J = {
	      drag: "onDrag",
	      click: "onClick",
	      mousemove: "onMouseMove",
	      mousedown: "onMouseDown",
	      mouseup: "onMouseUp",
	      mouseout: "onMouseOut",
	      keyup: "onKeyUp",
	      keydown: "onKeyDown",
	      touchstart: "onTouchStart",
	      touchmove: "onTouchMove",
	      touchend: "onTouchEnd",
	      tap: "onTap"
	    },
	    z = Object.keys(J);
	  function Y(t) {
	    var e = Object.keys(t);
	    return function (n, o) {
	      void 0 === o && (o = {});
	      var r = {},
	        i = e.reduce(function (e, n) {
	          return e[n] = t[n], e;
	        }, new G(n));
	      return {
	        start: function () {
	          var e = this;
	          r = i.onSetup(o), z.forEach(function (n) {
	            var o,
	              a = J[n],
	              s = function () {
	                return !1;
	              };
	            t[a] && (s = function () {
	              return !0;
	            }), e.on(n, s, (o = a, function (t) {
	              return i[o](r, t);
	            }));
	          });
	        },
	        stop: function () {
	          i.onStop(r);
	        },
	        trash: function () {
	          i.onTrash(r);
	        },
	        combineFeatures: function () {
	          i.onCombineFeatures(r);
	        },
	        uncombineFeatures: function () {
	          i.onUncombineFeatures(r);
	        },
	        render: function (t, e) {
	          i.toDisplayFeatures(r, t, e);
	        }
	      };
	    };
	  }
	  function $(t) {
	    return [].concat(t).filter(function (t) {
	      return void 0 !== t;
	    });
	  }
	  function q() {
	    var t = this;
	    if (!(t.ctx.map && void 0 !== t.ctx.map.getSource(c.HOT))) return u();
	    var e = t.ctx.events.currentModeName();
	    t.ctx.ui.queueMapClasses({
	      mode: e
	    });
	    var n = [],
	      o = [];
	    t.isDirty ? o = t.getAllIds() : (n = t.getChangedIds().filter(function (e) {
	      return void 0 !== t.get(e);
	    }), o = t.sources.hot.filter(function (e) {
	      return e.properties.id && -1 === n.indexOf(e.properties.id) && void 0 !== t.get(e.properties.id);
	    }).map(function (t) {
	      return t.properties.id;
	    })), t.sources.hot = [];
	    var r = t.sources.cold.length;
	    t.sources.cold = t.isDirty ? [] : t.sources.cold.filter(function (t) {
	      var e = t.properties.id || t.properties.parent;
	      return -1 === n.indexOf(e);
	    });
	    var i = r !== t.sources.cold.length || o.length > 0;
	    function a(n, o) {
	      var r = t.get(n).internal(e);
	      t.ctx.events.currentModeRender(r, function (e) {
	        t.sources[o].push(e);
	      });
	    }
	    if (n.forEach(function (t) {
	      return a(t, "hot");
	    }), o.forEach(function (t) {
	      return a(t, "cold");
	    }), i && t.ctx.map.getSource(c.COLD).setData({
	      type: p.FEATURE_COLLECTION,
	      features: t.sources.cold
	    }), t.ctx.map.getSource(c.HOT).setData({
	      type: p.FEATURE_COLLECTION,
	      features: t.sources.hot
	    }), t._emitSelectionChange && (t.ctx.map.fire(h.SELECTION_CHANGE, {
	      features: t.getSelected().map(function (t) {
	        return t.toGeoJSON();
	      }),
	      points: t.getSelectedCoordinates().map(function (t) {
	        return {
	          type: p.FEATURE,
	          properties: {},
	          geometry: {
	            type: p.POINT,
	            coordinates: t.coordinates
	          }
	        };
	      })
	    }), t._emitSelectionChange = !1), t._deletedFeaturesToEmit.length) {
	      var s = t._deletedFeaturesToEmit.map(function (t) {
	        return t.toGeoJSON();
	      });
	      t._deletedFeaturesToEmit = [], t.ctx.map.fire(h.DELETE, {
	        features: s
	      });
	    }
	    function u() {
	      t.isDirty = !1, t.clearChangedIds();
	    }
	    u(), t.ctx.map.fire(h.RENDER, {});
	  }
	  function H(t) {
	    var e,
	      n = this;
	    this._features = {}, this._featureIds = new S(), this._selectedFeatureIds = new S(), this._selectedCoordinates = [], this._changedFeatureIds = new S(), this._deletedFeaturesToEmit = [], this._emitSelectionChange = !1, this._mapInitialConfig = {}, this.ctx = t, this.sources = {
	      hot: [],
	      cold: []
	    }, this.render = function () {
	      e || (e = requestAnimationFrame(function () {
	        e = null, q.call(n);
	      }));
	    }, this.isDirty = !1;
	  }
	  function X(t, e) {
	    var n = t._selectedCoordinates.filter(function (e) {
	      return t._selectedFeatureIds.has(e.feature_id);
	    });
	    t._selectedCoordinates.length === n.length || e.silent || (t._emitSelectionChange = !0), t._selectedCoordinates = n;
	  }
	  H.prototype.createRenderBatch = function () {
	    var t = this,
	      e = this.render,
	      n = 0;
	    return this.render = function () {
	      n++;
	    }, function () {
	      t.render = e, n > 0 && t.render();
	    };
	  }, H.prototype.setDirty = function () {
	    return this.isDirty = !0, this;
	  }, H.prototype.featureChanged = function (t) {
	    return this._changedFeatureIds.add(t), this;
	  }, H.prototype.getChangedIds = function () {
	    return this._changedFeatureIds.values();
	  }, H.prototype.clearChangedIds = function () {
	    return this._changedFeatureIds.clear(), this;
	  }, H.prototype.getAllIds = function () {
	    return this._featureIds.values();
	  }, H.prototype.add = function (t) {
	    return this.featureChanged(t.id), this._features[t.id] = t, this._featureIds.add(t.id), this;
	  }, H.prototype.delete = function (t, e) {
	    var n = this;
	    return void 0 === e && (e = {}), $(t).forEach(function (t) {
	      n._featureIds.has(t) && (n._featureIds.delete(t), n._selectedFeatureIds.delete(t), e.silent || -1 === n._deletedFeaturesToEmit.indexOf(n._features[t]) && n._deletedFeaturesToEmit.push(n._features[t]), delete n._features[t], n.isDirty = !0);
	    }), X(this, e), this;
	  }, H.prototype.get = function (t) {
	    return this._features[t];
	  }, H.prototype.getAll = function () {
	    var t = this;
	    return Object.keys(this._features).map(function (e) {
	      return t._features[e];
	    });
	  }, H.prototype.select = function (t, e) {
	    var n = this;
	    return void 0 === e && (e = {}), $(t).forEach(function (t) {
	      n._selectedFeatureIds.has(t) || (n._selectedFeatureIds.add(t), n._changedFeatureIds.add(t), e.silent || (n._emitSelectionChange = !0));
	    }), this;
	  }, H.prototype.deselect = function (t, e) {
	    var n = this;
	    return void 0 === e && (e = {}), $(t).forEach(function (t) {
	      n._selectedFeatureIds.has(t) && (n._selectedFeatureIds.delete(t), n._changedFeatureIds.add(t), e.silent || (n._emitSelectionChange = !0));
	    }), X(this, e), this;
	  }, H.prototype.clearSelected = function (t) {
	    return void 0 === t && (t = {}), this.deselect(this._selectedFeatureIds.values(), {
	      silent: t.silent
	    }), this;
	  }, H.prototype.setSelected = function (t, e) {
	    var n = this;
	    return void 0 === e && (e = {}), t = $(t), this.deselect(this._selectedFeatureIds.values().filter(function (e) {
	      return -1 === t.indexOf(e);
	    }), {
	      silent: e.silent
	    }), this.select(t.filter(function (t) {
	      return !n._selectedFeatureIds.has(t);
	    }), {
	      silent: e.silent
	    }), this;
	  }, H.prototype.setSelectedCoordinates = function (t) {
	    return this._selectedCoordinates = t, this._emitSelectionChange = !0, this;
	  }, H.prototype.clearSelectedCoordinates = function () {
	    return this._selectedCoordinates = [], this._emitSelectionChange = !0, this;
	  }, H.prototype.getSelectedIds = function () {
	    return this._selectedFeatureIds.values();
	  }, H.prototype.getSelected = function () {
	    var t = this;
	    return this._selectedFeatureIds.values().map(function (e) {
	      return t.get(e);
	    });
	  }, H.prototype.getSelectedCoordinates = function () {
	    var t = this;
	    return this._selectedCoordinates.map(function (e) {
	      return {
	        coordinates: t.get(e.feature_id).getCoordinate(e.coord_path)
	      };
	    });
	  }, H.prototype.isSelected = function (t) {
	    return this._selectedFeatureIds.has(t);
	  }, H.prototype.setFeatureProperty = function (t, e, n) {
	    this.get(t).setProperty(e, n), this.featureChanged(t);
	  }, H.prototype.storeMapConfig = function () {
	    var t = this;
	    m.forEach(function (e) {
	      t.ctx.map[e] && (t._mapInitialConfig[e] = t.ctx.map[e].isEnabled());
	    });
	  }, H.prototype.restoreMapConfig = function () {
	    var t = this;
	    Object.keys(this._mapInitialConfig).forEach(function (e) {
	      t._mapInitialConfig[e] ? t.ctx.map[e].enable() : t.ctx.map[e].disable();
	    });
	  }, H.prototype.getInitialConfigValue = function (t) {
	    return void 0 === this._mapInitialConfig[t] || this._mapInitialConfig[t];
	  };
	  var W = function () {
	      for (var t = arguments, e = {}, n = 0; n < arguments.length; n++) {
	        var o = t[n];
	        for (var r in o) Z.call(o, r) && (e[r] = o[r]);
	      }
	      return e;
	    },
	    Z = Object.prototype.hasOwnProperty;
	  var K = ["mode", "feature", "mouse"];
	  function Q(e) {
	    var n = null,
	      o = null,
	      r = {
	        onRemove: function () {
	          return e.map.off("load", r.connect), clearInterval(o), r.removeLayers(), e.store.restoreMapConfig(), e.ui.removeButtons(), e.events.removeEventListeners(), e.ui.clearMapClasses(), e.map = null, e.container = null, e.store = null, n && n.parentNode && n.parentNode.removeChild(n), n = null, this;
	        },
	        connect: function () {
	          e.map.off("load", r.connect), clearInterval(o), r.addLayers(), e.store.storeMapConfig(), e.events.addEventListeners();
	        },
	        onAdd: function (i) {
	          var a = i.fire;
	          return i.fire = function (t, e) {
	            var n = arguments;
	            return 1 === a.length && 1 !== arguments.length && (n = [W({}, {
	              type: t
	            }, e)]), a.apply(i, n);
	          }, e.map = i, e.events = function (e) {
	            var n = Object.keys(e.options.modes).reduce(function (t, n) {
	                return t[n] = Y(e.options.modes[n]), t;
	              }, {}),
	              o = {},
	              r = {},
	              i = {},
	              a = null,
	              s = null;
	            i.drag = function (t, n) {
	              n({
	                point: t.point,
	                time: new Date().getTime()
	              }) ? (e.ui.queueMapClasses({
	                mouse: l.DRAG
	              }), s.drag(t)) : t.originalEvent.stopPropagation();
	            }, i.mousedrag = function (t) {
	              i.drag(t, function (t) {
	                return !A(o, t);
	              });
	            }, i.touchdrag = function (t) {
	              i.drag(t, function (t) {
	                return !P(r, t);
	              });
	            }, i.mousemove = function (t) {
	              if (1 === (void 0 !== t.originalEvent.buttons ? t.originalEvent.buttons : t.originalEvent.which)) return i.mousedrag(t);
	              var n = L(t, e);
	              t.featureTarget = n, s.mousemove(t);
	            }, i.mousedown = function (t) {
	              o = {
	                time: new Date().getTime(),
	                point: t.point
	              };
	              var n = L(t, e);
	              t.featureTarget = n, s.mousedown(t);
	            }, i.mouseup = function (t) {
	              var n = L(t, e);
	              t.featureTarget = n, A(o, {
	                point: t.point,
	                time: new Date().getTime()
	              }) ? s.click(t) : s.mouseup(t);
	            }, i.mouseout = function (t) {
	              s.mouseout(t);
	            }, i.touchstart = function (t) {
	              if (t.originalEvent.preventDefault(), e.options.touchEnabled) {
	                r = {
	                  time: new Date().getTime(),
	                  point: t.point
	                };
	                var n = x.touch(t, null, e)[0];
	                t.featureTarget = n, s.touchstart(t);
	              }
	            }, i.touchmove = function (t) {
	              if (t.originalEvent.preventDefault(), e.options.touchEnabled) return s.touchmove(t), i.touchdrag(t);
	            }, i.touchend = function (t) {
	              if (t.originalEvent.preventDefault(), e.options.touchEnabled) {
	                var n = x.touch(t, null, e)[0];
	                t.featureTarget = n, P(r, {
	                  time: new Date().getTime(),
	                  point: t.point
	                }) ? s.tap(t) : s.touchend(t);
	              }
	            };
	            var u = function (t) {
	              return !(8 === t || 46 === t || t >= 48 && t <= 57);
	            };
	            function c(o, r, i) {
	              void 0 === i && (i = {}), s.stop();
	              var u = n[o];
	              if (void 0 === u) throw new Error(o + " is not valid");
	              a = o;
	              var c = u(e, r);
	              s = t(c, e), i.silent || e.map.fire(h.MODE_CHANGE, {
	                mode: o
	              }), e.store.setDirty(), e.store.render();
	            }
	            i.keydown = function (t) {
	              "mapboxgl-canvas" === (t.srcElement || t.target).classList[0] && (8 !== t.keyCode && 46 !== t.keyCode || !e.options.controls.trash ? u(t.keyCode) ? s.keydown(t) : 49 === t.keyCode && e.options.controls.point ? c(f.DRAW_POINT) : 50 === t.keyCode && e.options.controls.line_string ? c(f.DRAW_LINE_STRING) : 51 === t.keyCode && e.options.controls.polygon && c(f.DRAW_POLYGON) : (t.preventDefault(), s.trash()));
	            }, i.keyup = function (t) {
	              u(t.keyCode) && s.keyup(t);
	            }, i.zoomend = function () {
	              e.store.changeZoom();
	            }, i.data = function (t) {
	              if ("style" === t.dataType) {
	                var n = e.setup,
	                  o = e.map,
	                  r = e.options,
	                  i = e.store;
	                r.styles.some(function (t) {
	                  return o.getLayer(t.id);
	                }) || (n.addLayers(), i.setDirty(), i.render());
	              }
	            };
	            var d = {
	              trash: !1,
	              combineFeatures: !1,
	              uncombineFeatures: !1
	            };
	            return {
	              start: function () {
	                a = e.options.defaultMode, s = t(n[a](e), e);
	              },
	              changeMode: c,
	              actionable: function (t) {
	                var n = !1;
	                Object.keys(t).forEach(function (e) {
	                  if (void 0 === d[e]) throw new Error("Invalid action type");
	                  d[e] !== t[e] && (n = !0), d[e] = t[e];
	                }), n && e.map.fire(h.ACTIONABLE, {
	                  actions: d
	                });
	              },
	              currentModeName: function () {
	                return a;
	              },
	              currentModeRender: function (t, e) {
	                return s.render(t, e);
	              },
	              fire: function (t, e) {
	                i[t] && i[t](e);
	              },
	              addEventListeners: function () {
	                e.map.on("mousemove", i.mousemove), e.map.on("mousedown", i.mousedown), e.map.on("mouseup", i.mouseup), e.map.on("data", i.data), e.map.on("touchmove", i.touchmove), e.map.on("touchstart", i.touchstart), e.map.on("touchend", i.touchend), e.container.addEventListener("mouseout", i.mouseout), e.options.keybindings && (e.container.addEventListener("keydown", i.keydown), e.container.addEventListener("keyup", i.keyup));
	              },
	              removeEventListeners: function () {
	                e.map.off("mousemove", i.mousemove), e.map.off("mousedown", i.mousedown), e.map.off("mouseup", i.mouseup), e.map.off("data", i.data), e.map.off("touchmove", i.touchmove), e.map.off("touchstart", i.touchstart), e.map.off("touchend", i.touchend), e.container.removeEventListener("mouseout", i.mouseout), e.options.keybindings && (e.container.removeEventListener("keydown", i.keydown), e.container.removeEventListener("keyup", i.keyup));
	              },
	              trash: function (t) {
	                s.trash(t);
	              },
	              combineFeatures: function () {
	                s.combineFeatures();
	              },
	              uncombineFeatures: function () {
	                s.uncombineFeatures();
	              },
	              getMode: function () {
	                return a;
	              }
	            };
	          }(e), e.ui = function (t) {
	            var e = {},
	              n = null,
	              o = {
	                mode: null,
	                feature: null,
	                mouse: null
	              },
	              r = {
	                mode: null,
	                feature: null,
	                mouse: null
	              };
	            function i(t) {
	              r = W(r, t);
	            }
	            function a() {
	              var e, n;
	              if (t.container) {
	                var i = [],
	                  a = [];
	                K.forEach(function (t) {
	                  r[t] !== o[t] && (i.push(t + "-" + o[t]), null !== r[t] && a.push(t + "-" + r[t]));
	                }), i.length > 0 && (e = t.container.classList).remove.apply(e, i), a.length > 0 && (n = t.container.classList).add.apply(n, a), o = W(o, r);
	              }
	            }
	            function s(t, e) {
	              void 0 === e && (e = {});
	              var o = document.createElement("button");
	              return o.className = u.CONTROL_BUTTON + " " + e.className, o.setAttribute("title", e.title), e.container.appendChild(o), o.addEventListener("click", function (o) {
	                if (o.preventDefault(), o.stopPropagation(), o.target === n) return c(), void e.onDeactivate();
	                l(t), e.onActivate();
	              }, !0), o;
	            }
	            function c() {
	              n && (n.classList.remove(u.ACTIVE_BUTTON), n = null);
	            }
	            function l(t) {
	              c();
	              var o = e[t];
	              o && o && "trash" !== t && (o.classList.add(u.ACTIVE_BUTTON), n = o);
	            }
	            return {
	              setActiveButton: l,
	              queueMapClasses: i,
	              updateMapClasses: a,
	              clearMapClasses: function () {
	                i({
	                  mode: null,
	                  feature: null,
	                  mouse: null
	                }), a();
	              },
	              addButtons: function () {
	                var n = t.options.controls,
	                  o = document.createElement("div");
	                return o.className = u.CONTROL_GROUP + " " + u.CONTROL_BASE, n ? (n[d.LINE] && (e[d.LINE] = s(d.LINE, {
	                  container: o,
	                  className: u.CONTROL_BUTTON_LINE,
	                  title: "LineString tool " + (t.options.keybindings ? "(l)" : ""),
	                  onActivate: function () {
	                    return t.events.changeMode(f.DRAW_LINE_STRING);
	                  },
	                  onDeactivate: function () {
	                    return t.events.trash();
	                  }
	                })), n[d.POLYGON] && (e[d.POLYGON] = s(d.POLYGON, {
	                  container: o,
	                  className: u.CONTROL_BUTTON_POLYGON,
	                  title: "Polygon tool " + (t.options.keybindings ? "(p)" : ""),
	                  onActivate: function () {
	                    return t.events.changeMode(f.DRAW_POLYGON);
	                  },
	                  onDeactivate: function () {
	                    return t.events.trash();
	                  }
	                })), n[d.POINT] && (e[d.POINT] = s(d.POINT, {
	                  container: o,
	                  className: u.CONTROL_BUTTON_POINT,
	                  title: "Marker tool " + (t.options.keybindings ? "(m)" : ""),
	                  onActivate: function () {
	                    return t.events.changeMode(f.DRAW_POINT);
	                  },
	                  onDeactivate: function () {
	                    return t.events.trash();
	                  }
	                })), n.trash && (e.trash = s("trash", {
	                  container: o,
	                  className: u.CONTROL_BUTTON_TRASH,
	                  title: "Delete",
	                  onActivate: function () {
	                    t.events.trash();
	                  }
	                })), n.combine_features && (e.combine_features = s("combineFeatures", {
	                  container: o,
	                  className: u.CONTROL_BUTTON_COMBINE_FEATURES,
	                  title: "Combine",
	                  onActivate: function () {
	                    t.events.combineFeatures();
	                  }
	                })), n.uncombine_features && (e.uncombine_features = s("uncombineFeatures", {
	                  container: o,
	                  className: u.CONTROL_BUTTON_UNCOMBINE_FEATURES,
	                  title: "Uncombine",
	                  onActivate: function () {
	                    t.events.uncombineFeatures();
	                  }
	                })), o) : o;
	              },
	              removeButtons: function () {
	                Object.keys(e).forEach(function (t) {
	                  var n = e[t];
	                  n.parentNode && n.parentNode.removeChild(n), delete e[t];
	                });
	              }
	            };
	          }(e), e.container = i.getContainer(), e.store = new H(e), n = e.ui.addButtons(), e.options.boxSelect && (i.boxZoom.disable(), i.dragPan.disable(), i.dragPan.enable()), i.loaded() ? r.connect() : (i.on("load", r.connect), o = setInterval(function () {
	            i.loaded() && r.connect();
	          }, 16)), e.events.start(), n;
	        },
	        addLayers: function () {
	          e.map.addSource(c.COLD, {
	            data: {
	              type: p.FEATURE_COLLECTION,
	              features: []
	            },
	            type: "geojson"
	          }), e.map.addSource(c.HOT, {
	            data: {
	              type: p.FEATURE_COLLECTION,
	              features: []
	            },
	            type: "geojson"
	          }), e.options.styles.forEach(function (t) {
	            e.map.addLayer(t);
	          }), e.store.setDirty(!0), e.store.render();
	        },
	        removeLayers: function () {
	          e.options.styles.forEach(function (t) {
	            e.map.getLayer(t.id) && e.map.removeLayer(t.id);
	          }), e.map.getSource(c.COLD) && e.map.removeSource(c.COLD), e.map.getSource(c.HOT) && e.map.removeSource(c.HOT);
	        }
	      };
	    return e.setup = r, r;
	  }
	  var tt = [{
	    id: "gl-draw-polygon-fill-inactive",
	    type: "fill",
	    filter: ["all", ["==", "active", "false"], ["==", "$type", "Polygon"], ["!=", "mode", "static"]],
	    paint: {
	      "fill-color": "#3bb2d0",
	      "fill-outline-color": "#3bb2d0",
	      "fill-opacity": .1
	    }
	  }, {
	    id: "gl-draw-polygon-fill-active",
	    type: "fill",
	    filter: ["all", ["==", "active", "true"], ["==", "$type", "Polygon"]],
	    paint: {
	      "fill-color": "#fbb03b",
	      "fill-outline-color": "#fbb03b",
	      "fill-opacity": .1
	    }
	  }, {
	    id: "gl-draw-polygon-midpoint",
	    type: "circle",
	    filter: ["all", ["==", "$type", "Point"], ["==", "meta", "midpoint"]],
	    paint: {
	      "circle-radius": 3,
	      "circle-color": "#fbb03b"
	    }
	  }, {
	    id: "gl-draw-polygon-stroke-inactive",
	    type: "line",
	    filter: ["all", ["==", "active", "false"], ["==", "$type", "Polygon"], ["!=", "mode", "static"]],
	    layout: {
	      "line-cap": "round",
	      "line-join": "round"
	    },
	    paint: {
	      "line-color": "#3bb2d0",
	      "line-width": 2
	    }
	  }, {
	    id: "gl-draw-polygon-stroke-active",
	    type: "line",
	    filter: ["all", ["==", "active", "true"], ["==", "$type", "Polygon"]],
	    layout: {
	      "line-cap": "round",
	      "line-join": "round"
	    },
	    paint: {
	      "line-color": "#fbb03b",
	      "line-dasharray": [.2, 2],
	      "line-width": 2
	    }
	  }, {
	    id: "gl-draw-line-inactive",
	    type: "line",
	    filter: ["all", ["==", "active", "false"], ["==", "$type", "LineString"], ["!=", "mode", "static"]],
	    layout: {
	      "line-cap": "round",
	      "line-join": "round"
	    },
	    paint: {
	      "line-color": "#3bb2d0",
	      "line-width": 2
	    }
	  }, {
	    id: "gl-draw-line-active",
	    type: "line",
	    filter: ["all", ["==", "$type", "LineString"], ["==", "active", "true"]],
	    layout: {
	      "line-cap": "round",
	      "line-join": "round"
	    },
	    paint: {
	      "line-color": "#fbb03b",
	      "line-dasharray": [.2, 2],
	      "line-width": 2
	    }
	  }, {
	    id: "gl-draw-polygon-and-line-vertex-stroke-inactive",
	    type: "circle",
	    filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"], ["!=", "mode", "static"]],
	    paint: {
	      "circle-radius": 5,
	      "circle-color": "#fff"
	    }
	  }, {
	    id: "gl-draw-polygon-and-line-vertex-inactive",
	    type: "circle",
	    filter: ["all", ["==", "meta", "vertex"], ["==", "$type", "Point"], ["!=", "mode", "static"]],
	    paint: {
	      "circle-radius": 3,
	      "circle-color": "#fbb03b"
	    }
	  }, {
	    id: "gl-draw-point-point-stroke-inactive",
	    type: "circle",
	    filter: ["all", ["==", "active", "false"], ["==", "$type", "Point"], ["==", "meta", "feature"], ["!=", "mode", "static"]],
	    paint: {
	      "circle-radius": 5,
	      "circle-opacity": 1,
	      "circle-color": "#fff"
	    }
	  }, {
	    id: "gl-draw-point-inactive",
	    type: "circle",
	    filter: ["all", ["==", "active", "false"], ["==", "$type", "Point"], ["==", "meta", "feature"], ["!=", "mode", "static"]],
	    paint: {
	      "circle-radius": 3,
	      "circle-color": "#3bb2d0"
	    }
	  }, {
	    id: "gl-draw-point-stroke-active",
	    type: "circle",
	    filter: ["all", ["==", "$type", "Point"], ["==", "active", "true"], ["!=", "meta", "midpoint"]],
	    paint: {
	      "circle-radius": 7,
	      "circle-color": "#fff"
	    }
	  }, {
	    id: "gl-draw-point-active",
	    type: "circle",
	    filter: ["all", ["==", "$type", "Point"], ["!=", "meta", "midpoint"], ["==", "active", "true"]],
	    paint: {
	      "circle-radius": 5,
	      "circle-color": "#fbb03b"
	    }
	  }, {
	    id: "gl-draw-polygon-fill-static",
	    type: "fill",
	    filter: ["all", ["==", "mode", "static"], ["==", "$type", "Polygon"]],
	    paint: {
	      "fill-color": "#404040",
	      "fill-outline-color": "#404040",
	      "fill-opacity": .1
	    }
	  }, {
	    id: "gl-draw-polygon-stroke-static",
	    type: "line",
	    filter: ["all", ["==", "mode", "static"], ["==", "$type", "Polygon"]],
	    layout: {
	      "line-cap": "round",
	      "line-join": "round"
	    },
	    paint: {
	      "line-color": "#404040",
	      "line-width": 2
	    }
	  }, {
	    id: "gl-draw-line-static",
	    type: "line",
	    filter: ["all", ["==", "mode", "static"], ["==", "$type", "LineString"]],
	    layout: {
	      "line-cap": "round",
	      "line-join": "round"
	    },
	    paint: {
	      "line-color": "#404040",
	      "line-width": 2
	    }
	  }, {
	    id: "gl-draw-point-static",
	    type: "circle",
	    filter: ["all", ["==", "mode", "static"], ["==", "$type", "Point"]],
	    paint: {
	      "circle-radius": 5,
	      "circle-color": "#404040"
	    }
	  }];
	  function et(t) {
	    return function (e) {
	      var n = e.featureTarget;
	      return !!n && !!n.properties && n.properties.meta === t;
	    };
	  }
	  function nt(t) {
	    return !!t.originalEvent && !!t.originalEvent.shiftKey && 0 === t.originalEvent.button;
	  }
	  function ot(t) {
	    return !!t.featureTarget && !!t.featureTarget.properties && t.featureTarget.properties.active === v.ACTIVE && t.featureTarget.properties.meta === y.FEATURE;
	  }
	  function rt(t) {
	    return !!t.featureTarget && !!t.featureTarget.properties && t.featureTarget.properties.active === v.INACTIVE && t.featureTarget.properties.meta === y.FEATURE;
	  }
	  function it(t) {
	    return void 0 === t.featureTarget;
	  }
	  function at(t) {
	    return !!t.featureTarget && !!t.featureTarget.properties && t.featureTarget.properties.meta === y.FEATURE;
	  }
	  function st(t) {
	    var e = t.featureTarget;
	    return !!e && !!e.properties && e.properties.meta === y.VERTEX;
	  }
	  function ut(t) {
	    return !!t.originalEvent && !0 === t.originalEvent.shiftKey;
	  }
	  function ct(t) {
	    return 27 === t.keyCode;
	  }
	  function lt(t) {
	    return 13 === t.keyCode;
	  }
	  var dt = Object.freeze({
	      __proto__: null,
	      isOfMetaType: et,
	      isShiftMousedown: nt,
	      isActiveFeature: ot,
	      isInactiveFeature: rt,
	      noTarget: it,
	      isFeature: at,
	      isVertex: st,
	      isShiftDown: ut,
	      isEscapeKey: ct,
	      isEnterKey: lt,
	      isTrue: function () {
	        return !0;
	      }
	    }),
	    pt = ft;
	  function ft(t, e) {
	    this.x = t, this.y = e;
	  }
	  function ht(t, e) {
	    var n = e.getBoundingClientRect();
	    return new pt(t.clientX - n.left - (e.clientLeft || 0), t.clientY - n.top - (e.clientTop || 0));
	  }
	  function gt(t, e, n, o) {
	    return {
	      type: p.FEATURE,
	      properties: {
	        meta: y.VERTEX,
	        parent: t,
	        coord_path: n,
	        active: o ? v.ACTIVE : v.INACTIVE
	      },
	      geometry: {
	        type: p.POINT,
	        coordinates: e
	      }
	    };
	  }
	  function yt(t, e, n) {
	    var o = e.geometry.coordinates,
	      r = n.geometry.coordinates;
	    if (o[1] > 85 || o[1] < _ || r[1] > 85 || r[1] < _) return null;
	    var i = {
	      lng: (o[0] + r[0]) / 2,
	      lat: (o[1] + r[1]) / 2
	    };
	    return {
	      type: p.FEATURE,
	      properties: {
	        meta: y.MIDPOINT,
	        parent: t,
	        lng: i.lng,
	        lat: i.lat,
	        coord_path: n.properties.coord_path
	      },
	      geometry: {
	        type: p.POINT,
	        coordinates: [i.lng, i.lat]
	      }
	    };
	  }
	  function vt(t, e, n) {
	    void 0 === e && (e = {}), void 0 === n && (n = null);
	    var o,
	      r = t.geometry,
	      i = r.type,
	      a = r.coordinates,
	      s = t.properties && t.properties.id,
	      u = [];
	    function c(t, n) {
	      var o = "",
	        r = null;
	      t.forEach(function (t, i) {
	        var a = null != n ? n + "." + i : String(i),
	          c = gt(s, t, a, l(a));
	        if (e.midpoints && r) {
	          var d = yt(s, r, c);
	          d && u.push(d);
	        }
	        r = c;
	        var p = JSON.stringify(t);
	        o !== p && u.push(c), 0 === i && (o = p);
	      });
	    }
	    function l(t) {
	      return !!e.selectedPaths && -1 !== e.selectedPaths.indexOf(t);
	    }
	    return i === p.POINT ? u.push(gt(s, a, n, l(n))) : i === p.POLYGON ? a.forEach(function (t, e) {
	      c(t, null !== n ? n + "." + e : String(e));
	    }) : i === p.LINE_STRING ? c(a, n) : 0 === i.indexOf(p.MULTI_PREFIX) && (o = i.replace(p.MULTI_PREFIX, ""), a.forEach(function (n, r) {
	      var i = {
	        type: p.FEATURE,
	        properties: t.properties,
	        geometry: {
	          type: o,
	          coordinates: n
	        }
	      };
	      u = u.concat(vt(i, e, r));
	    })), u;
	  }
	  ft.prototype = {
	    clone: function () {
	      return new ft(this.x, this.y);
	    },
	    add: function (t) {
	      return this.clone()._add(t);
	    },
	    sub: function (t) {
	      return this.clone()._sub(t);
	    },
	    multByPoint: function (t) {
	      return this.clone()._multByPoint(t);
	    },
	    divByPoint: function (t) {
	      return this.clone()._divByPoint(t);
	    },
	    mult: function (t) {
	      return this.clone()._mult(t);
	    },
	    div: function (t) {
	      return this.clone()._div(t);
	    },
	    rotate: function (t) {
	      return this.clone()._rotate(t);
	    },
	    rotateAround: function (t, e) {
	      return this.clone()._rotateAround(t, e);
	    },
	    matMult: function (t) {
	      return this.clone()._matMult(t);
	    },
	    unit: function () {
	      return this.clone()._unit();
	    },
	    perp: function () {
	      return this.clone()._perp();
	    },
	    round: function () {
	      return this.clone()._round();
	    },
	    mag: function () {
	      return Math.sqrt(this.x * this.x + this.y * this.y);
	    },
	    equals: function (t) {
	      return this.x === t.x && this.y === t.y;
	    },
	    dist: function (t) {
	      return Math.sqrt(this.distSqr(t));
	    },
	    distSqr: function (t) {
	      var e = t.x - this.x,
	        n = t.y - this.y;
	      return e * e + n * n;
	    },
	    angle: function () {
	      return Math.atan2(this.y, this.x);
	    },
	    angleTo: function (t) {
	      return Math.atan2(this.y - t.y, this.x - t.x);
	    },
	    angleWith: function (t) {
	      return this.angleWithSep(t.x, t.y);
	    },
	    angleWithSep: function (t, e) {
	      return Math.atan2(this.x * e - this.y * t, this.x * t + this.y * e);
	    },
	    _matMult: function (t) {
	      var e = t[0] * this.x + t[1] * this.y,
	        n = t[2] * this.x + t[3] * this.y;
	      return this.x = e, this.y = n, this;
	    },
	    _add: function (t) {
	      return this.x += t.x, this.y += t.y, this;
	    },
	    _sub: function (t) {
	      return this.x -= t.x, this.y -= t.y, this;
	    },
	    _mult: function (t) {
	      return this.x *= t, this.y *= t, this;
	    },
	    _div: function (t) {
	      return this.x /= t, this.y /= t, this;
	    },
	    _multByPoint: function (t) {
	      return this.x *= t.x, this.y *= t.y, this;
	    },
	    _divByPoint: function (t) {
	      return this.x /= t.x, this.y /= t.y, this;
	    },
	    _unit: function () {
	      return this._div(this.mag()), this;
	    },
	    _perp: function () {
	      var t = this.y;
	      return this.y = this.x, this.x = -t, this;
	    },
	    _rotate: function (t) {
	      var e = Math.cos(t),
	        n = Math.sin(t),
	        o = e * this.x - n * this.y,
	        r = n * this.x + e * this.y;
	      return this.x = o, this.y = r, this;
	    },
	    _rotateAround: function (t, e) {
	      var n = Math.cos(t),
	        o = Math.sin(t),
	        r = e.x + n * (this.x - e.x) - o * (this.y - e.y),
	        i = e.y + o * (this.x - e.x) + n * (this.y - e.y);
	      return this.x = r, this.y = i, this;
	    },
	    _round: function () {
	      return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
	    }
	  }, ft.convert = function (t) {
	    return t instanceof ft ? t : Array.isArray(t) ? new ft(t[0], t[1]) : t;
	  };
	  var mt = {
	      enable: function (t) {
	        setTimeout(function () {
	          t.map && t.map.doubleClickZoom && t._ctx && t._ctx.store && t._ctx.store.getInitialConfigValue && t._ctx.store.getInitialConfigValue("doubleClickZoom") && t.map.doubleClickZoom.enable();
	        }, 0);
	      },
	      disable: function (t) {
	        setTimeout(function () {
	          t.map && t.map.doubleClickZoom && t.map.doubleClickZoom.disable();
	        }, 0);
	      }
	    },
	    _t = {},
	    bt = {
	      get exports() {
	        return _t;
	      },
	      set exports(t) {
	        _t = t;
	      }
	    },
	    Et = function (t) {
	      if (!t || !t.type) return null;
	      var e = Tt[t.type];
	      if (!e) return null;
	      if ("geometry" === e) return {
	        type: "FeatureCollection",
	        features: [{
	          type: "Feature",
	          properties: {},
	          geometry: t
	        }]
	      };
	      if ("feature" === e) return {
	        type: "FeatureCollection",
	        features: [t]
	      };
	      if ("featurecollection" === e) return t;
	    },
	    Tt = {
	      Point: "geometry",
	      MultiPoint: "geometry",
	      LineString: "geometry",
	      MultiLineString: "geometry",
	      Polygon: "geometry",
	      MultiPolygon: "geometry",
	      GeometryCollection: "geometry",
	      Feature: "feature",
	      FeatureCollection: "featurecollection"
	    };
	  var Ct = Object.freeze({
	      __proto__: null,
	      default: function t(e) {
	        switch (e && e.type || null) {
	          case "FeatureCollection":
	            return e.features = e.features.reduce(function (e, n) {
	              return e.concat(t(n));
	            }, []), e;
	          case "Feature":
	            return e.geometry ? t(e.geometry).map(function (t) {
	              var n = {
	                type: "Feature",
	                properties: JSON.parse(JSON.stringify(e.properties)),
	                geometry: t
	              };
	              return void 0 !== e.id && (n.id = e.id), n;
	            }) : [e];
	          case "MultiPoint":
	            return e.coordinates.map(function (t) {
	              return {
	                type: "Point",
	                coordinates: t
	              };
	            });
	          case "MultiPolygon":
	            return e.coordinates.map(function (t) {
	              return {
	                type: "Polygon",
	                coordinates: t
	              };
	            });
	          case "MultiLineString":
	            return e.coordinates.map(function (t) {
	              return {
	                type: "LineString",
	                coordinates: t
	              };
	            });
	          case "GeometryCollection":
	            return e.geometries.map(t).reduce(function (t, e) {
	              return t.concat(e);
	            }, []);
	          case "Point":
	          case "Polygon":
	          case "LineString":
	            return [e];
	        }
	      }
	    }),
	    Ot = Et,
	    St = e(Ct),
	    It = function (t) {
	      return function t(e) {
	        if (Array.isArray(e) && e.length && "number" == typeof e[0]) return [e];
	        return e.reduce(function (e, n) {
	          return Array.isArray(n) && Array.isArray(n[0]) ? e.concat(t(n)) : (e.push(n), e);
	        }, []);
	      }(t);
	    };
	  St instanceof Function || (St = St.default);
	  var xt = {},
	    Mt = {
	      get exports() {
	        return xt;
	      },
	      set exports(t) {
	        xt = t;
	      }
	    }.exports = function (t) {
	      return new Lt(t);
	    };
	  function Lt(t) {
	    this.value = t;
	  }
	  function Nt(t, e, n) {
	    var o = [],
	      r = [],
	      i = !0;
	    return function t(a) {
	      var s = n ? At(a) : a,
	        u = {},
	        c = !0,
	        l = {
	          node: s,
	          node_: a,
	          path: [].concat(o),
	          parent: r[r.length - 1],
	          parents: r,
	          key: o.slice(-1)[0],
	          isRoot: 0 === o.length,
	          level: o.length,
	          circular: null,
	          update: function (t, e) {
	            l.isRoot || (l.parent.node[l.key] = t), l.node = t, e && (c = !1);
	          },
	          delete: function (t) {
	            delete l.parent.node[l.key], t && (c = !1);
	          },
	          remove: function (t) {
	            wt(l.parent.node) ? l.parent.node.splice(l.key, 1) : delete l.parent.node[l.key], t && (c = !1);
	          },
	          keys: null,
	          before: function (t) {
	            u.before = t;
	          },
	          after: function (t) {
	            u.after = t;
	          },
	          pre: function (t) {
	            u.pre = t;
	          },
	          post: function (t) {
	            u.post = t;
	          },
	          stop: function () {
	            i = !1;
	          },
	          block: function () {
	            c = !1;
	          }
	        };
	      if (!i) return l;
	      function d() {
	        if ("object" == typeof l.node && null !== l.node) {
	          l.keys && l.node_ === l.node || (l.keys = Pt(l.node)), l.isLeaf = 0 == l.keys.length;
	          for (var t = 0; t < r.length; t++) if (r[t].node_ === a) {
	            l.circular = r[t];
	            break;
	          }
	        } else l.isLeaf = !0, l.keys = null;
	        l.notLeaf = !l.isLeaf, l.notRoot = !l.isRoot;
	      }
	      d();
	      var p = e.call(l, l.node);
	      return void 0 !== p && l.update && l.update(p), u.before && u.before.call(l, l.node), c ? ("object" != typeof l.node || null === l.node || l.circular || (r.push(l), d(), Rt(l.keys, function (e, r) {
	        o.push(e), u.pre && u.pre.call(l, l.node[e], e);
	        var i = t(l.node[e]);
	        n && Dt.call(l.node, e) && (l.node[e] = i.node), i.isLast = r == l.keys.length - 1, i.isFirst = 0 == r, u.post && u.post.call(l, i), o.pop();
	      }), r.pop()), u.after && u.after.call(l, l.node), l) : l;
	    }(t).node;
	  }
	  function At(t) {
	    if ("object" == typeof t && null !== t) {
	      var e;
	      if (wt(t)) e = [];else if ("[object Date]" === Ft(t)) e = new Date(t.getTime ? t.getTime() : t);else if (function (t) {
	        return "[object RegExp]" === Ft(t);
	      }(t)) e = new RegExp(t);else if (function (t) {
	        return "[object Error]" === Ft(t);
	      }(t)) e = {
	        message: t.message
	      };else if (function (t) {
	        return "[object Boolean]" === Ft(t);
	      }(t)) e = new Boolean(t);else if (function (t) {
	        return "[object Number]" === Ft(t);
	      }(t)) e = new Number(t);else if (function (t) {
	        return "[object String]" === Ft(t);
	      }(t)) e = new String(t);else if (Object.create && Object.getPrototypeOf) e = Object.create(Object.getPrototypeOf(t));else if (t.constructor === Object) e = {};else {
	        var n = t.constructor && t.constructor.prototype || t.__proto__ || {},
	          o = function () {};
	        o.prototype = n, e = new o();
	      }
	      return Rt(Pt(t), function (n) {
	        e[n] = t[n];
	      }), e;
	    }
	    return t;
	  }
	  Lt.prototype.get = function (t) {
	    for (var e = this.value, n = 0; n < t.length; n++) {
	      var o = t[n];
	      if (!e || !Dt.call(e, o)) {
	        e = void 0;
	        break;
	      }
	      e = e[o];
	    }
	    return e;
	  }, Lt.prototype.has = function (t) {
	    for (var e = this.value, n = 0; n < t.length; n++) {
	      var o = t[n];
	      if (!e || !Dt.call(e, o)) return !1;
	      e = e[o];
	    }
	    return !0;
	  }, Lt.prototype.set = function (t, e) {
	    for (var n = this.value, o = 0; o < t.length - 1; o++) {
	      var r = t[o];
	      Dt.call(n, r) || (n[r] = {}), n = n[r];
	    }
	    return n[t[o]] = e, e;
	  }, Lt.prototype.map = function (t) {
	    return Nt(this.value, t, !0);
	  }, Lt.prototype.forEach = function (t) {
	    return this.value = Nt(this.value, t, !1), this.value;
	  }, Lt.prototype.reduce = function (t, e) {
	    var n = 1 === arguments.length,
	      o = n ? this.value : e;
	    return this.forEach(function (e) {
	      this.isRoot && n || (o = t.call(this, o, e));
	    }), o;
	  }, Lt.prototype.paths = function () {
	    var t = [];
	    return this.forEach(function (e) {
	      t.push(this.path);
	    }), t;
	  }, Lt.prototype.nodes = function () {
	    var t = [];
	    return this.forEach(function (e) {
	      t.push(this.node);
	    }), t;
	  }, Lt.prototype.clone = function () {
	    var t = [],
	      e = [];
	    return function n(o) {
	      for (var r = 0; r < t.length; r++) if (t[r] === o) return e[r];
	      if ("object" == typeof o && null !== o) {
	        var i = At(o);
	        return t.push(o), e.push(i), Rt(Pt(o), function (t) {
	          i[t] = n(o[t]);
	        }), t.pop(), e.pop(), i;
	      }
	      return o;
	    }(this.value);
	  };
	  var Pt = Object.keys || function (t) {
	    var e = [];
	    for (var n in t) e.push(n);
	    return e;
	  };
	  function Ft(t) {
	    return Object.prototype.toString.call(t);
	  }
	  var wt = Array.isArray || function (t) {
	      return "[object Array]" === Object.prototype.toString.call(t);
	    },
	    Rt = function (t, e) {
	      if (t.forEach) return t.forEach(e);
	      for (var n = 0; n < t.length; n++) e(t[n], n, t);
	    };
	  Rt(Pt(Lt.prototype), function (t) {
	    Mt[t] = function (e) {
	      var n = [].slice.call(arguments, 1),
	        o = new Lt(e);
	      return o[t].apply(o, n);
	    };
	  });
	  var Dt = Object.hasOwnProperty || function (t, e) {
	      return e in t;
	    },
	    kt = Ut;
	  function Ut(t) {
	    if (!(this instanceof Ut)) return new Ut(t);
	    this._bbox = t || [1 / 0, 1 / 0, -1 / 0, -1 / 0], this._valid = !!t;
	  }
	  Ut.prototype.include = function (t) {
	    return this._valid = !0, this._bbox[0] = Math.min(this._bbox[0], t[0]), this._bbox[1] = Math.min(this._bbox[1], t[1]), this._bbox[2] = Math.max(this._bbox[2], t[0]), this._bbox[3] = Math.max(this._bbox[3], t[1]), this;
	  }, Ut.prototype.equals = function (t) {
	    var e;
	    return e = t instanceof Ut ? t.bbox() : t, this._bbox[0] == e[0] && this._bbox[1] == e[1] && this._bbox[2] == e[2] && this._bbox[3] == e[3];
	  }, Ut.prototype.center = function (t) {
	    return this._valid ? [(this._bbox[0] + this._bbox[2]) / 2, (this._bbox[1] + this._bbox[3]) / 2] : null;
	  }, Ut.prototype.union = function (t) {
	    var e;
	    return this._valid = !0, e = t instanceof Ut ? t.bbox() : t, this._bbox[0] = Math.min(this._bbox[0], e[0]), this._bbox[1] = Math.min(this._bbox[1], e[1]), this._bbox[2] = Math.max(this._bbox[2], e[2]), this._bbox[3] = Math.max(this._bbox[3], e[3]), this;
	  }, Ut.prototype.bbox = function () {
	    return this._valid ? this._bbox : null;
	  }, Ut.prototype.contains = function (t) {
	    if (!t) return this._fastContains();
	    if (!this._valid) return null;
	    var e = t[0],
	      n = t[1];
	    return this._bbox[0] <= e && this._bbox[1] <= n && this._bbox[2] >= e && this._bbox[3] >= n;
	  }, Ut.prototype.intersect = function (t) {
	    return this._valid ? (e = t instanceof Ut ? t.bbox() : t, !(this._bbox[0] > e[2] || this._bbox[2] < e[0] || this._bbox[3] < e[1] || this._bbox[1] > e[3])) : null;
	    var e;
	  }, Ut.prototype._fastContains = function () {
	    if (!this._valid) return new Function("return null;");
	    var t = "return " + this._bbox[0] + "<= ll[0] &&" + this._bbox[1] + "<= ll[1] &&" + this._bbox[2] + ">= ll[0] &&" + this._bbox[3] + ">= ll[1]";
	    return new Function("ll", t);
	  }, Ut.prototype.polygon = function () {
	    return this._valid ? {
	      type: "Polygon",
	      coordinates: [[[this._bbox[0], this._bbox[1]], [this._bbox[2], this._bbox[1]], [this._bbox[2], this._bbox[3]], [this._bbox[0], this._bbox[3]], [this._bbox[0], this._bbox[1]]]]
	    } : null;
	  };
	  var jt = function (t) {
	      if (!t) return [];
	      var e = St(Ot(t)),
	        n = [];
	      return e.features.forEach(function (t) {
	        t.geometry && (n = n.concat(It(t.geometry.coordinates)));
	      }), n;
	    },
	    Vt = xt,
	    Bt = kt,
	    Gt = {
	      features: ["FeatureCollection"],
	      coordinates: ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon"],
	      geometry: ["Feature"],
	      geometries: ["GeometryCollection"]
	    },
	    Jt = Object.keys(Gt);
	  function zt(t) {
	    for (var e = Bt(), n = jt(t), o = 0; o < n.length; o++) e.include(n[o]);
	    return e;
	  }
	  bt.exports = function (t) {
	    return zt(t).bbox();
	  }, _t.polygon = function (t) {
	    return zt(t).polygon();
	  }, _t.bboxify = function (t) {
	    return Vt(t).map(function (t) {
	      t && Jt.some(function (e) {
	        return !!t[e] && -1 !== Gt[e].indexOf(t.type);
	      }) && (t.bbox = zt(t).bbox(), this.update(t));
	    });
	  };
	  var Yt = -90;
	  function $t(t, e) {
	    var n = Yt,
	      o = 90,
	      r = Yt,
	      i = 90,
	      a = 270,
	      s = -270;
	    t.forEach(function (t) {
	      var e = _t(t),
	        u = e[1],
	        c = e[3],
	        l = e[0],
	        d = e[2];
	      u > n && (n = u), c < o && (o = c), c > r && (r = c), u < i && (i = u), l < a && (a = l), d > s && (s = d);
	    });
	    var u = e;
	    return n + u.lat > 85 && (u.lat = 85 - n), r + u.lat > 90 && (u.lat = 90 - r), o + u.lat < -85 && (u.lat = -85 - o), i + u.lat < Yt && (u.lat = Yt - i), a + u.lng <= -270 && (u.lng += 360 * Math.ceil(Math.abs(u.lng) / 360)), s + u.lng >= 270 && (u.lng -= 360 * Math.ceil(Math.abs(u.lng) / 360)), u;
	  }
	  function qt(t, e) {
	    var n = $t(t.map(function (t) {
	      return t.toGeoJSON();
	    }), e);
	    t.forEach(function (t) {
	      var e,
	        o = t.getCoordinates(),
	        r = function (t) {
	          var e = {
	            lng: t[0] + n.lng,
	            lat: t[1] + n.lat
	          };
	          return [e.lng, e.lat];
	        },
	        i = function (t) {
	          return t.map(function (t) {
	            return r(t);
	          });
	        };
	      t.type === p.POINT ? e = r(o) : t.type === p.LINE_STRING || t.type === p.MULTI_POINT ? e = o.map(r) : t.type === p.POLYGON || t.type === p.MULTI_LINE_STRING ? e = o.map(i) : t.type === p.MULTI_POLYGON && (e = o.map(function (t) {
	        return t.map(function (t) {
	          return i(t);
	        });
	      })), t.incomingCoords(e);
	    });
	  }
	  var Ht = {
	    onSetup: function (t) {
	      var e = this,
	        n = {
	          dragMoveLocation: null,
	          boxSelectStartLocation: null,
	          boxSelectElement: void 0,
	          boxSelecting: !1,
	          canBoxSelect: !1,
	          dragMoving: !1,
	          canDragMove: !1,
	          initiallySelectedFeatureIds: t.featureIds || []
	        };
	      return this.setSelected(n.initiallySelectedFeatureIds.filter(function (t) {
	        return void 0 !== e.getFeature(t);
	      })), this.fireActionable(), this.setActionableState({
	        combineFeatures: !0,
	        uncombineFeatures: !0,
	        trash: !0
	      }), n;
	    },
	    fireUpdate: function () {
	      this.map.fire(h.UPDATE, {
	        action: g.MOVE,
	        features: this.getSelected().map(function (t) {
	          return t.toGeoJSON();
	        })
	      });
	    },
	    fireActionable: function () {
	      var t = this,
	        e = this.getSelected(),
	        n = e.filter(function (e) {
	          return t.isInstanceOf("MultiFeature", e);
	        }),
	        o = !1;
	      if (e.length > 1) {
	        o = !0;
	        var r = e[0].type.replace("Multi", "");
	        e.forEach(function (t) {
	          t.type.replace("Multi", "") !== r && (o = !1);
	        });
	      }
	      var i = n.length > 0,
	        a = e.length > 0;
	      this.setActionableState({
	        combineFeatures: o,
	        uncombineFeatures: i,
	        trash: a
	      });
	    },
	    getUniqueIds: function (t) {
	      return t.length ? t.map(function (t) {
	        return t.properties.id;
	      }).filter(function (t) {
	        return void 0 !== t;
	      }).reduce(function (t, e) {
	        return t.add(e), t;
	      }, new S()).values() : [];
	    },
	    stopExtendedInteractions: function (t) {
	      t.boxSelectElement && (t.boxSelectElement.parentNode && t.boxSelectElement.parentNode.removeChild(t.boxSelectElement), t.boxSelectElement = null), this.map.dragPan.enable(), t.boxSelecting = !1, t.canBoxSelect = !1, t.dragMoving = !1, t.canDragMove = !1;
	    },
	    onStop: function () {
	      mt.enable(this);
	    },
	    onMouseMove: function (t) {
	      return this.stopExtendedInteractions(t), !0;
	    },
	    onMouseOut: function (t) {
	      return !t.dragMoving || this.fireUpdate();
	    }
	  };
	  Ht.onTap = Ht.onClick = function (t, e) {
	    return it(e) ? this.clickAnywhere(t, e) : et(y.VERTEX)(e) ? this.clickOnVertex(t, e) : at(e) ? this.clickOnFeature(t, e) : void 0;
	  }, Ht.clickAnywhere = function (t) {
	    var e = this,
	      n = this.getSelectedIds();
	    n.length && (this.clearSelectedFeatures(), n.forEach(function (t) {
	      return e.doRender(t);
	    })), mt.enable(this), this.stopExtendedInteractions(t);
	  }, Ht.clickOnVertex = function (t, e) {
	    this.changeMode(f.DIRECT_SELECT, {
	      featureId: e.featureTarget.properties.parent,
	      coordPath: e.featureTarget.properties.coord_path,
	      startPos: e.lngLat
	    }), this.updateUIClasses({
	      mouse: l.MOVE
	    });
	  }, Ht.startOnActiveFeature = function (t, e) {
	    this.stopExtendedInteractions(t), this.map.dragPan.disable(), this.doRender(e.featureTarget.properties.id), t.canDragMove = !0, t.dragMoveLocation = e.lngLat;
	  }, Ht.clickOnFeature = function (t, e) {
	    var n = this;
	    mt.disable(this), this.stopExtendedInteractions(t);
	    var o = ut(e),
	      r = this.getSelectedIds(),
	      i = e.featureTarget.properties.id,
	      a = this.isSelected(i);
	    if (!o && a && this.getFeature(i).type !== p.POINT) return this.changeMode(f.DIRECT_SELECT, {
	      featureId: i
	    });
	    a && o ? (this.deselect(i), this.updateUIClasses({
	      mouse: l.POINTER
	    }), 1 === r.length && mt.enable(this)) : !a && o ? (this.select(i), this.updateUIClasses({
	      mouse: l.MOVE
	    })) : a || o || (r.forEach(function (t) {
	      return n.doRender(t);
	    }), this.setSelected(i), this.updateUIClasses({
	      mouse: l.MOVE
	    })), this.doRender(i);
	  }, Ht.onMouseDown = function (t, e) {
	    return ot(e) ? this.startOnActiveFeature(t, e) : this.drawConfig.boxSelect && nt(e) ? this.startBoxSelect(t, e) : void 0;
	  }, Ht.startBoxSelect = function (t, e) {
	    this.stopExtendedInteractions(t), this.map.dragPan.disable(), t.boxSelectStartLocation = ht(e.originalEvent, this.map.getContainer()), t.canBoxSelect = !0;
	  }, Ht.onTouchStart = function (t, e) {
	    if (ot(e)) return this.startOnActiveFeature(t, e);
	  }, Ht.onDrag = function (t, e) {
	    return t.canDragMove ? this.dragMove(t, e) : this.drawConfig.boxSelect && t.canBoxSelect ? this.whileBoxSelect(t, e) : void 0;
	  }, Ht.whileBoxSelect = function (t, e) {
	    t.boxSelecting = !0, this.updateUIClasses({
	      mouse: l.ADD
	    }), t.boxSelectElement || (t.boxSelectElement = document.createElement("div"), t.boxSelectElement.classList.add(u.BOX_SELECT), this.map.getContainer().appendChild(t.boxSelectElement));
	    var n = ht(e.originalEvent, this.map.getContainer()),
	      o = Math.min(t.boxSelectStartLocation.x, n.x),
	      r = Math.max(t.boxSelectStartLocation.x, n.x),
	      i = Math.min(t.boxSelectStartLocation.y, n.y),
	      a = Math.max(t.boxSelectStartLocation.y, n.y),
	      s = "translate(" + o + "px, " + i + "px)";
	    t.boxSelectElement.style.transform = s, t.boxSelectElement.style.WebkitTransform = s, t.boxSelectElement.style.width = r - o + "px", t.boxSelectElement.style.height = a - i + "px";
	  }, Ht.dragMove = function (t, e) {
	    t.dragMoving = !0, e.originalEvent.stopPropagation();
	    var n = {
	      lng: e.lngLat.lng - t.dragMoveLocation.lng,
	      lat: e.lngLat.lat - t.dragMoveLocation.lat
	    };
	    qt(this.getSelected(), n), t.dragMoveLocation = e.lngLat;
	  }, Ht.onTouchEnd = Ht.onMouseUp = function (t, e) {
	    var n = this;
	    if (t.dragMoving) this.fireUpdate();else if (t.boxSelecting) {
	      var o = [t.boxSelectStartLocation, ht(e.originalEvent, this.map.getContainer())],
	        r = this.featuresAt(null, o, "click"),
	        i = this.getUniqueIds(r).filter(function (t) {
	          return !n.isSelected(t);
	        });
	      i.length && (this.select(i), i.forEach(function (t) {
	        return n.doRender(t);
	      }), this.updateUIClasses({
	        mouse: l.MOVE
	      }));
	    }
	    this.stopExtendedInteractions(t);
	  }, Ht.toDisplayFeatures = function (t, e, n) {
	    e.properties.active = this.isSelected(e.properties.id) ? v.ACTIVE : v.INACTIVE, n(e), this.fireActionable(), e.properties.active === v.ACTIVE && e.geometry.type !== p.POINT && vt(e).forEach(n);
	  }, Ht.onTrash = function () {
	    this.deleteFeature(this.getSelectedIds()), this.fireActionable();
	  }, Ht.onCombineFeatures = function () {
	    var t = this.getSelected();
	    if (!(0 === t.length || t.length < 2)) {
	      for (var e = [], n = [], o = t[0].type.replace("Multi", ""), r = 0; r < t.length; r++) {
	        var i = t[r];
	        if (i.type.replace("Multi", "") !== o) return;
	        i.type.includes("Multi") ? i.getCoordinates().forEach(function (t) {
	          e.push(t);
	        }) : e.push(i.getCoordinates()), n.push(i.toGeoJSON());
	      }
	      if (n.length > 1) {
	        var a = this.newFeature({
	          type: p.FEATURE,
	          properties: n[0].properties,
	          geometry: {
	            type: "Multi" + o,
	            coordinates: e
	          }
	        });
	        this.addFeature(a), this.deleteFeature(this.getSelectedIds(), {
	          silent: !0
	        }), this.setSelected([a.id]), this.map.fire(h.COMBINE_FEATURES, {
	          createdFeatures: [a.toGeoJSON()],
	          deletedFeatures: n
	        });
	      }
	      this.fireActionable();
	    }
	  }, Ht.onUncombineFeatures = function () {
	    var t = this,
	      e = this.getSelected();
	    if (0 !== e.length) {
	      for (var n = [], o = [], r = function (r) {
	          var i = e[r];
	          t.isInstanceOf("MultiFeature", i) && (i.getFeatures().forEach(function (e) {
	            t.addFeature(e), e.properties = i.properties, n.push(e.toGeoJSON()), t.select([e.id]);
	          }), t.deleteFeature(i.id, {
	            silent: !0
	          }), o.push(i.toGeoJSON()));
	        }, i = 0; i < e.length; i++) r(i);
	      n.length > 1 && this.map.fire(h.UNCOMBINE_FEATURES, {
	        createdFeatures: n,
	        deletedFeatures: o
	      }), this.fireActionable();
	    }
	  };
	  var Xt = et(y.VERTEX),
	    Wt = et(y.MIDPOINT),
	    Zt = {
	      fireUpdate: function () {
	        this.map.fire(h.UPDATE, {
	          action: g.CHANGE_COORDINATES,
	          features: this.getSelected().map(function (t) {
	            return t.toGeoJSON();
	          })
	        });
	      },
	      fireActionable: function (t) {
	        this.setActionableState({
	          combineFeatures: !1,
	          uncombineFeatures: !1,
	          trash: t.selectedCoordPaths.length > 0
	        });
	      },
	      startDragging: function (t, e) {
	        this.map.dragPan.disable(), t.canDragMove = !0, t.dragMoveLocation = e.lngLat;
	      },
	      stopDragging: function (t) {
	        this.map.dragPan.enable(), t.dragMoving = !1, t.canDragMove = !1, t.dragMoveLocation = null;
	      },
	      onVertex: function (t, e) {
	        this.startDragging(t, e);
	        var n = e.featureTarget.properties,
	          o = t.selectedCoordPaths.indexOf(n.coord_path);
	        ut(e) || -1 !== o ? ut(e) && -1 === o && t.selectedCoordPaths.push(n.coord_path) : t.selectedCoordPaths = [n.coord_path];
	        var r = this.pathsToCoordinates(t.featureId, t.selectedCoordPaths);
	        this.setSelectedCoordinates(r);
	      },
	      onMidpoint: function (t, e) {
	        this.startDragging(t, e);
	        var n = e.featureTarget.properties;
	        t.feature.addCoordinate(n.coord_path, n.lng, n.lat), this.fireUpdate(), t.selectedCoordPaths = [n.coord_path];
	      },
	      pathsToCoordinates: function (t, e) {
	        return e.map(function (e) {
	          return {
	            feature_id: t,
	            coord_path: e
	          };
	        });
	      },
	      onFeature: function (t, e) {
	        0 === t.selectedCoordPaths.length ? this.startDragging(t, e) : this.stopDragging(t);
	      },
	      dragFeature: function (t, e, n) {
	        qt(this.getSelected(), n), t.dragMoveLocation = e.lngLat;
	      },
	      dragVertex: function (t, e, n) {
	        for (var o = t.selectedCoordPaths.map(function (e) {
	            return t.feature.getCoordinate(e);
	          }), r = $t(o.map(function (t) {
	            return {
	              type: p.FEATURE,
	              properties: {},
	              geometry: {
	                type: p.POINT,
	                coordinates: t
	              }
	            };
	          }), n), i = 0; i < o.length; i++) {
	          var a = o[i];
	          t.feature.updateCoordinate(t.selectedCoordPaths[i], a[0] + r.lng, a[1] + r.lat);
	        }
	      },
	      clickNoTarget: function () {
	        this.changeMode(f.SIMPLE_SELECT);
	      },
	      clickInactive: function () {
	        this.changeMode(f.SIMPLE_SELECT);
	      },
	      clickActiveFeature: function (t) {
	        t.selectedCoordPaths = [], this.clearSelectedCoordinates(), t.feature.changed();
	      },
	      onSetup: function (t) {
	        var e = t.featureId,
	          n = this.getFeature(e);
	        if (!n) throw new Error("You must provide a featureId to enter direct_select mode");
	        if (n.type === p.POINT) throw new TypeError("direct_select mode doesn't handle point features");
	        var o = {
	          featureId: e,
	          feature: n,
	          dragMoveLocation: t.startPos || null,
	          dragMoving: !1,
	          canDragMove: !1,
	          selectedCoordPaths: t.coordPath ? [t.coordPath] : []
	        };
	        return this.setSelectedCoordinates(this.pathsToCoordinates(e, o.selectedCoordPaths)), this.setSelected(e), mt.disable(this), this.setActionableState({
	          trash: !0
	        }), o;
	      },
	      onStop: function () {
	        mt.enable(this), this.clearSelectedCoordinates();
	      },
	      toDisplayFeatures: function (t, e, n) {
	        t.featureId === e.properties.id ? (e.properties.active = v.ACTIVE, n(e), vt(e, {
	          map: this.map,
	          midpoints: !0,
	          selectedPaths: t.selectedCoordPaths
	        }).forEach(n)) : (e.properties.active = v.INACTIVE, n(e)), this.fireActionable(t);
	      },
	      onTrash: function (t) {
	        t.selectedCoordPaths.sort(function (t, e) {
	          return e.localeCompare(t, "en", {
	            numeric: !0
	          });
	        }).forEach(function (e) {
	          return t.feature.removeCoordinate(e);
	        }), this.fireUpdate(), t.selectedCoordPaths = [], this.clearSelectedCoordinates(), this.fireActionable(t), !1 === t.feature.isValid() && (this.deleteFeature([t.featureId]), this.changeMode(f.SIMPLE_SELECT, {}));
	      },
	      onMouseMove: function (t, e) {
	        var n = ot(e),
	          o = Xt(e),
	          r = 0 === t.selectedCoordPaths.length;
	        return n && r || o && !r ? this.updateUIClasses({
	          mouse: l.MOVE
	        }) : this.updateUIClasses({
	          mouse: l.NONE
	        }), this.stopDragging(t), !0;
	      },
	      onMouseOut: function (t) {
	        return t.dragMoving && this.fireUpdate(), !0;
	      }
	    };
	  Zt.onTouchStart = Zt.onMouseDown = function (t, e) {
	    return Xt(e) ? this.onVertex(t, e) : ot(e) ? this.onFeature(t, e) : Wt(e) ? this.onMidpoint(t, e) : void 0;
	  }, Zt.onDrag = function (t, e) {
	    if (!0 === t.canDragMove) {
	      t.dragMoving = !0, e.originalEvent.stopPropagation();
	      var n = {
	        lng: e.lngLat.lng - t.dragMoveLocation.lng,
	        lat: e.lngLat.lat - t.dragMoveLocation.lat
	      };
	      t.selectedCoordPaths.length > 0 ? this.dragVertex(t, e, n) : this.dragFeature(t, e, n), t.dragMoveLocation = e.lngLat;
	    }
	  }, Zt.onClick = function (t, e) {
	    return it(e) ? this.clickNoTarget(t, e) : ot(e) ? this.clickActiveFeature(t, e) : rt(e) ? this.clickInactive(t, e) : void this.stopDragging(t);
	  }, Zt.onTap = function (t, e) {
	    return it(e) ? this.clickNoTarget(t, e) : ot(e) ? this.clickActiveFeature(t, e) : rt(e) ? this.clickInactive(t, e) : void 0;
	  }, Zt.onTouchEnd = Zt.onMouseUp = function (t) {
	    t.dragMoving && this.fireUpdate(), this.stopDragging(t);
	  };
	  var Kt = {};
	  function Qt(t, e) {
	    return !!t.lngLat && t.lngLat.lng === e[0] && t.lngLat.lat === e[1];
	  }
	  Kt.onSetup = function () {
	    var t = this.newFeature({
	      type: p.FEATURE,
	      properties: {},
	      geometry: {
	        type: p.POINT,
	        coordinates: []
	      }
	    });
	    return this.addFeature(t), this.clearSelectedFeatures(), this.updateUIClasses({
	      mouse: l.ADD
	    }), this.activateUIButton(d.POINT), this.setActionableState({
	      trash: !0
	    }), {
	      point: t
	    };
	  }, Kt.stopDrawingAndRemove = function (t) {
	    this.deleteFeature([t.point.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT);
	  }, Kt.onTap = Kt.onClick = function (t, e) {
	    this.updateUIClasses({
	      mouse: l.MOVE
	    }), t.point.updateCoordinate("", e.lngLat.lng, e.lngLat.lat), this.map.fire(h.CREATE, {
	      features: [t.point.toGeoJSON()]
	    }), this.changeMode(f.SIMPLE_SELECT, {
	      featureIds: [t.point.id]
	    });
	  }, Kt.onStop = function (t) {
	    this.activateUIButton(), t.point.getCoordinate().length || this.deleteFeature([t.point.id], {
	      silent: !0
	    });
	  }, Kt.toDisplayFeatures = function (t, e, n) {
	    var o = e.properties.id === t.point.id;
	    if (e.properties.active = o ? v.ACTIVE : v.INACTIVE, !o) return n(e);
	  }, Kt.onTrash = Kt.stopDrawingAndRemove, Kt.onKeyUp = function (t, e) {
	    if (ct(e) || lt(e)) return this.stopDrawingAndRemove(t, e);
	  };
	  var te = {
	    onSetup: function () {
	      var t = this.newFeature({
	        type: p.FEATURE,
	        properties: {},
	        geometry: {
	          type: p.POLYGON,
	          coordinates: [[]]
	        }
	      });
	      return this.addFeature(t), this.clearSelectedFeatures(), mt.disable(this), this.updateUIClasses({
	        mouse: l.ADD
	      }), this.activateUIButton(d.POLYGON), this.setActionableState({
	        trash: !0
	      }), {
	        polygon: t,
	        currentVertexPosition: 0
	      };
	    },
	    clickAnywhere: function (t, e) {
	      if (t.currentVertexPosition > 0 && Qt(e, t.polygon.coordinates[0][t.currentVertexPosition - 1])) return this.changeMode(f.SIMPLE_SELECT, {
	        featureIds: [t.polygon.id]
	      });
	      this.updateUIClasses({
	        mouse: l.ADD
	      }), t.polygon.updateCoordinate("0." + t.currentVertexPosition, e.lngLat.lng, e.lngLat.lat), t.currentVertexPosition++, t.polygon.updateCoordinate("0." + t.currentVertexPosition, e.lngLat.lng, e.lngLat.lat);
	    },
	    clickOnVertex: function (t) {
	      return this.changeMode(f.SIMPLE_SELECT, {
	        featureIds: [t.polygon.id]
	      });
	    },
	    onMouseMove: function (t, e) {
	      t.polygon.updateCoordinate("0." + t.currentVertexPosition, e.lngLat.lng, e.lngLat.lat), st(e) && this.updateUIClasses({
	        mouse: l.POINTER
	      });
	    }
	  };
	  te.onTap = te.onClick = function (t, e) {
	    return st(e) ? this.clickOnVertex(t, e) : this.clickAnywhere(t, e);
	  }, te.onKeyUp = function (t, e) {
	    ct(e) ? (this.deleteFeature([t.polygon.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT)) : lt(e) && this.changeMode(f.SIMPLE_SELECT, {
	      featureIds: [t.polygon.id]
	    });
	  }, te.onStop = function (t) {
	    this.updateUIClasses({
	      mouse: l.NONE
	    }), mt.enable(this), this.activateUIButton(), void 0 !== this.getFeature(t.polygon.id) && (t.polygon.removeCoordinate("0." + t.currentVertexPosition), t.polygon.isValid() ? this.map.fire(h.CREATE, {
	      features: [t.polygon.toGeoJSON()]
	    }) : (this.deleteFeature([t.polygon.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT, {}, {
	      silent: !0
	    })));
	  }, te.toDisplayFeatures = function (t, e, n) {
	    var o = e.properties.id === t.polygon.id;
	    if (e.properties.active = o ? v.ACTIVE : v.INACTIVE, !o) return n(e);
	    if (0 !== e.geometry.coordinates.length) {
	      var r = e.geometry.coordinates[0].length;
	      if (!(r < 3)) {
	        if (e.properties.meta = y.FEATURE, n(gt(t.polygon.id, e.geometry.coordinates[0][0], "0.0", !1)), r > 3) {
	          var i = e.geometry.coordinates[0].length - 3;
	          n(gt(t.polygon.id, e.geometry.coordinates[0][i], "0." + i, !1));
	        }
	        if (r <= 4) {
	          var a = [[e.geometry.coordinates[0][0][0], e.geometry.coordinates[0][0][1]], [e.geometry.coordinates[0][1][0], e.geometry.coordinates[0][1][1]]];
	          if (n({
	            type: p.FEATURE,
	            properties: e.properties,
	            geometry: {
	              coordinates: a,
	              type: p.LINE_STRING
	            }
	          }), 3 === r) return;
	        }
	        return n(e);
	      }
	    }
	  }, te.onTrash = function (t) {
	    this.deleteFeature([t.polygon.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT);
	  };
	  var ee = {
	    onSetup: function (t) {
	      var e,
	        n,
	        o = (t = t || {}).featureId,
	        r = "forward";
	      if (o) {
	        if (!(e = this.getFeature(o))) throw new Error("Could not find a feature with the provided featureId");
	        var i = t.from;
	        if (i && "Feature" === i.type && i.geometry && "Point" === i.geometry.type && (i = i.geometry), i && "Point" === i.type && i.coordinates && 2 === i.coordinates.length && (i = i.coordinates), !i || !Array.isArray(i)) throw new Error("Please use the `from` property to indicate which point to continue the line from");
	        var a = e.coordinates.length - 1;
	        if (e.coordinates[a][0] === i[0] && e.coordinates[a][1] === i[1]) n = a + 1, e.addCoordinate.apply(e, [n].concat(e.coordinates[a]));else {
	          if (e.coordinates[0][0] !== i[0] || e.coordinates[0][1] !== i[1]) throw new Error("`from` should match the point at either the start or the end of the provided LineString");
	          r = "backwards", n = 0, e.addCoordinate.apply(e, [n].concat(e.coordinates[0]));
	        }
	      } else e = this.newFeature({
	        type: p.FEATURE,
	        properties: {},
	        geometry: {
	          type: p.LINE_STRING,
	          coordinates: []
	        }
	      }), n = 0, this.addFeature(e);
	      return this.clearSelectedFeatures(), mt.disable(this), this.updateUIClasses({
	        mouse: l.ADD
	      }), this.activateUIButton(d.LINE), this.setActionableState({
	        trash: !0
	      }), {
	        line: e,
	        currentVertexPosition: n,
	        direction: r
	      };
	    },
	    clickAnywhere: function (t, e) {
	      if (t.currentVertexPosition > 0 && Qt(e, t.line.coordinates[t.currentVertexPosition - 1]) || "backwards" === t.direction && Qt(e, t.line.coordinates[t.currentVertexPosition + 1])) return this.changeMode(f.SIMPLE_SELECT, {
	        featureIds: [t.line.id]
	      });
	      this.updateUIClasses({
	        mouse: l.ADD
	      }), t.line.updateCoordinate(t.currentVertexPosition, e.lngLat.lng, e.lngLat.lat), "forward" === t.direction ? (t.currentVertexPosition++, t.line.updateCoordinate(t.currentVertexPosition, e.lngLat.lng, e.lngLat.lat)) : t.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat);
	    },
	    clickOnVertex: function (t) {
	      return this.changeMode(f.SIMPLE_SELECT, {
	        featureIds: [t.line.id]
	      });
	    },
	    onMouseMove: function (t, e) {
	      t.line.updateCoordinate(t.currentVertexPosition, e.lngLat.lng, e.lngLat.lat), st(e) && this.updateUIClasses({
	        mouse: l.POINTER
	      });
	    }
	  };
	  ee.onTap = ee.onClick = function (t, e) {
	    if (st(e)) return this.clickOnVertex(t, e);
	    this.clickAnywhere(t, e);
	  }, ee.onKeyUp = function (t, e) {
	    lt(e) ? this.changeMode(f.SIMPLE_SELECT, {
	      featureIds: [t.line.id]
	    }) : ct(e) && (this.deleteFeature([t.line.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT));
	  }, ee.onStop = function (t) {
	    mt.enable(this), this.activateUIButton(), void 0 !== this.getFeature(t.line.id) && (t.line.removeCoordinate("" + t.currentVertexPosition), t.line.isValid() ? this.map.fire(h.CREATE, {
	      features: [t.line.toGeoJSON()]
	    }) : (this.deleteFeature([t.line.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT, {}, {
	      silent: !0
	    })));
	  }, ee.onTrash = function (t) {
	    this.deleteFeature([t.line.id], {
	      silent: !0
	    }), this.changeMode(f.SIMPLE_SELECT);
	  }, ee.toDisplayFeatures = function (t, e, n) {
	    var o = e.properties.id === t.line.id;
	    if (e.properties.active = o ? v.ACTIVE : v.INACTIVE, !o) return n(e);
	    e.geometry.coordinates.length < 2 || (e.properties.meta = y.FEATURE, n(gt(t.line.id, e.geometry.coordinates["forward" === t.direction ? e.geometry.coordinates.length - 2 : 1], "" + ("forward" === t.direction ? e.geometry.coordinates.length - 2 : 1), !1)), n(e));
	  };
	  var ne = {
	      simple_select: Ht,
	      direct_select: Zt,
	      draw_point: Kt,
	      draw_polygon: te,
	      draw_line_string: ee
	    },
	    oe = {
	      defaultMode: f.SIMPLE_SELECT,
	      keybindings: !0,
	      touchEnabled: !0,
	      clickBuffer: 2,
	      touchBuffer: 25,
	      boxSelect: !0,
	      displayControlsDefault: !0,
	      styles: tt,
	      modes: ne,
	      controls: {},
	      userProperties: !1
	    },
	    re = {
	      point: !0,
	      line_string: !0,
	      polygon: !0,
	      trash: !0,
	      combine_features: !0,
	      uncombine_features: !0
	    },
	    ie = {
	      point: !1,
	      line_string: !1,
	      polygon: !1,
	      trash: !1,
	      combine_features: !1,
	      uncombine_features: !1
	    };
	  function ae(t, e) {
	    return t.map(function (t) {
	      return t.source ? t : W(t, {
	        id: t.id + "." + e,
	        source: "hot" === e ? c.HOT : c.COLD
	      });
	    });
	  }
	  var se = {};
	  !function (t, e) {
	    var n = "__lodash_hash_undefined__",
	      o = 9007199254740991,
	      r = "[object Arguments]",
	      i = "[object Array]",
	      a = "[object Boolean]",
	      s = "[object Date]",
	      u = "[object Error]",
	      c = "[object Function]",
	      l = "[object Map]",
	      d = "[object Number]",
	      p = "[object Object]",
	      f = "[object Promise]",
	      h = "[object RegExp]",
	      g = "[object Set]",
	      y = "[object String]",
	      v = "[object Symbol]",
	      m = "[object WeakMap]",
	      _ = "[object ArrayBuffer]",
	      b = "[object DataView]",
	      E = /^\[object .+?Constructor\]$/,
	      T = /^(?:0|[1-9]\d*)$/,
	      C = {};
	    C["[object Float32Array]"] = C["[object Float64Array]"] = C["[object Int8Array]"] = C["[object Int16Array]"] = C["[object Int32Array]"] = C["[object Uint8Array]"] = C["[object Uint8ClampedArray]"] = C["[object Uint16Array]"] = C["[object Uint32Array]"] = !0, C[r] = C[i] = C[_] = C[a] = C[b] = C[s] = C[u] = C[c] = C[l] = C[d] = C[p] = C[h] = C[g] = C[y] = C[m] = !1;
	    var O = "object" == typeof commonjsGlobal && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal,
	      S = "object" == typeof self && self && self.Object === Object && self,
	      I = O || S || Function("return this")(),
	      x = e && !e.nodeType && e,
	      M = x && t && !t.nodeType && t,
	      L = M && M.exports === x,
	      N = L && O.process,
	      A = function () {
	        try {
	          return N && N.binding && N.binding("util");
	        } catch (t) {}
	      }(),
	      P = A && A.isTypedArray;
	    function F(t, e) {
	      for (var n = -1, o = null == t ? 0 : t.length; ++n < o;) if (e(t[n], n, t)) return !0;
	      return !1;
	    }
	    function w(t) {
	      var e = -1,
	        n = Array(t.size);
	      return t.forEach(function (t, o) {
	        n[++e] = [o, t];
	      }), n;
	    }
	    function R(t) {
	      var e = -1,
	        n = Array(t.size);
	      return t.forEach(function (t) {
	        n[++e] = t;
	      }), n;
	    }
	    var D,
	      k,
	      U,
	      j = Array.prototype,
	      V = Function.prototype,
	      B = Object.prototype,
	      G = I["__core-js_shared__"],
	      J = V.toString,
	      z = B.hasOwnProperty,
	      Y = (D = /[^.]+$/.exec(G && G.keys && G.keys.IE_PROTO || "")) ? "Symbol(src)_1." + D : "",
	      $ = B.toString,
	      q = RegExp("^" + J.call(z).replace(/[\\^$.*+?()[\]{}|]/g, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"),
	      H = L ? I.Buffer : void 0,
	      X = I.Symbol,
	      W = I.Uint8Array,
	      Z = B.propertyIsEnumerable,
	      K = j.splice,
	      Q = X ? X.toStringTag : void 0,
	      tt = Object.getOwnPropertySymbols,
	      et = H ? H.isBuffer : void 0,
	      nt = (k = Object.keys, U = Object, function (t) {
	        return k(U(t));
	      }),
	      ot = At(I, "DataView"),
	      rt = At(I, "Map"),
	      it = At(I, "Promise"),
	      at = At(I, "Set"),
	      st = At(I, "WeakMap"),
	      ut = At(Object, "create"),
	      ct = Rt(ot),
	      lt = Rt(rt),
	      dt = Rt(it),
	      pt = Rt(at),
	      ft = Rt(st),
	      ht = X ? X.prototype : void 0,
	      gt = ht ? ht.valueOf : void 0;
	    function yt(t) {
	      var e = -1,
	        n = null == t ? 0 : t.length;
	      for (this.clear(); ++e < n;) {
	        var o = t[e];
	        this.set(o[0], o[1]);
	      }
	    }
	    function vt(t) {
	      var e = -1,
	        n = null == t ? 0 : t.length;
	      for (this.clear(); ++e < n;) {
	        var o = t[e];
	        this.set(o[0], o[1]);
	      }
	    }
	    function mt(t) {
	      var e = -1,
	        n = null == t ? 0 : t.length;
	      for (this.clear(); ++e < n;) {
	        var o = t[e];
	        this.set(o[0], o[1]);
	      }
	    }
	    function _t(t) {
	      var e = -1,
	        n = null == t ? 0 : t.length;
	      for (this.__data__ = new mt(); ++e < n;) this.add(t[e]);
	    }
	    function bt(t) {
	      var e = this.__data__ = new vt(t);
	      this.size = e.size;
	    }
	    function Et(t, e) {
	      var n = Ut(t),
	        o = !n && kt(t),
	        r = !n && !o && jt(t),
	        i = !n && !o && !r && zt(t),
	        a = n || o || r || i,
	        s = a ? function (t, e) {
	          for (var n = -1, o = Array(t); ++n < t;) o[n] = e(n);
	          return o;
	        }(t.length, String) : [],
	        u = s.length;
	      for (var c in t) !e && !z.call(t, c) || a && ("length" == c || r && ("offset" == c || "parent" == c) || i && ("buffer" == c || "byteLength" == c || "byteOffset" == c) || wt(c, u)) || s.push(c);
	      return s;
	    }
	    function Tt(t, e) {
	      for (var n = t.length; n--;) if (Dt(t[n][0], e)) return n;
	      return -1;
	    }
	    function Ct(t) {
	      return null == t ? void 0 === t ? "[object Undefined]" : "[object Null]" : Q && Q in Object(t) ? function (t) {
	        var e = z.call(t, Q),
	          n = t[Q];
	        try {
	          t[Q] = void 0;
	          var o = !0;
	        } catch (t) {}
	        var r = $.call(t);
	        o && (e ? t[Q] = n : delete t[Q]);
	        return r;
	      }(t) : function (t) {
	        return $.call(t);
	      }(t);
	    }
	    function Ot(t) {
	      return Jt(t) && Ct(t) == r;
	    }
	    function St(t, e, n, o, c) {
	      return t === e || (null == t || null == e || !Jt(t) && !Jt(e) ? t != t && e != e : function (t, e, n, o, c, f) {
	        var m = Ut(t),
	          E = Ut(e),
	          T = m ? i : Ft(t),
	          C = E ? i : Ft(e),
	          O = (T = T == r ? p : T) == p,
	          S = (C = C == r ? p : C) == p,
	          I = T == C;
	        if (I && jt(t)) {
	          if (!jt(e)) return !1;
	          m = !0, O = !1;
	        }
	        if (I && !O) return f || (f = new bt()), m || zt(t) ? Mt(t, e, n, o, c, f) : function (t, e, n, o, r, i, c) {
	          switch (n) {
	            case b:
	              if (t.byteLength != e.byteLength || t.byteOffset != e.byteOffset) return !1;
	              t = t.buffer, e = e.buffer;
	            case _:
	              return !(t.byteLength != e.byteLength || !i(new W(t), new W(e)));
	            case a:
	            case s:
	            case d:
	              return Dt(+t, +e);
	            case u:
	              return t.name == e.name && t.message == e.message;
	            case h:
	            case y:
	              return t == e + "";
	            case l:
	              var p = w;
	            case g:
	              var f = 1 & o;
	              if (p || (p = R), t.size != e.size && !f) return !1;
	              var m = c.get(t);
	              if (m) return m == e;
	              o |= 2, c.set(t, e);
	              var E = Mt(p(t), p(e), o, r, i, c);
	              return c.delete(t), E;
	            case v:
	              if (gt) return gt.call(t) == gt.call(e);
	          }
	          return !1;
	        }(t, e, T, n, o, c, f);
	        if (!(1 & n)) {
	          var x = O && z.call(t, "__wrapped__"),
	            M = S && z.call(e, "__wrapped__");
	          if (x || M) {
	            var L = x ? t.value() : t,
	              N = M ? e.value() : e;
	            return f || (f = new bt()), c(L, N, n, o, f);
	          }
	        }
	        if (!I) return !1;
	        return f || (f = new bt()), function (t, e, n, o, r, i) {
	          var a = 1 & n,
	            s = Lt(t),
	            u = s.length,
	            c = Lt(e).length;
	          if (u != c && !a) return !1;
	          var l = u;
	          for (; l--;) {
	            var d = s[l];
	            if (!(a ? d in e : z.call(e, d))) return !1;
	          }
	          var p = i.get(t);
	          if (p && i.get(e)) return p == e;
	          var f = !0;
	          i.set(t, e), i.set(e, t);
	          var h = a;
	          for (; ++l < u;) {
	            var g = t[d = s[l]],
	              y = e[d];
	            if (o) var v = a ? o(y, g, d, e, t, i) : o(g, y, d, t, e, i);
	            if (!(void 0 === v ? g === y || r(g, y, n, o, i) : v)) {
	              f = !1;
	              break;
	            }
	            h || (h = "constructor" == d);
	          }
	          if (f && !h) {
	            var m = t.constructor,
	              _ = e.constructor;
	            m == _ || !("constructor" in t) || !("constructor" in e) || "function" == typeof m && m instanceof m && "function" == typeof _ && _ instanceof _ || (f = !1);
	          }
	          return i.delete(t), i.delete(e), f;
	        }(t, e, n, o, c, f);
	      }(t, e, n, o, St, c));
	    }
	    function It(t) {
	      return !(!Gt(t) || function (t) {
	        return !!Y && Y in t;
	      }(t)) && (Vt(t) ? q : E).test(Rt(t));
	    }
	    function xt(t) {
	      if (n = (e = t) && e.constructor, o = "function" == typeof n && n.prototype || B, e !== o) return nt(t);
	      var e,
	        n,
	        o,
	        r = [];
	      for (var i in Object(t)) z.call(t, i) && "constructor" != i && r.push(i);
	      return r;
	    }
	    function Mt(t, e, n, o, r, i) {
	      var a = 1 & n,
	        s = t.length,
	        u = e.length;
	      if (s != u && !(a && u > s)) return !1;
	      var c = i.get(t);
	      if (c && i.get(e)) return c == e;
	      var l = -1,
	        d = !0,
	        p = 2 & n ? new _t() : void 0;
	      for (i.set(t, e), i.set(e, t); ++l < s;) {
	        var f = t[l],
	          h = e[l];
	        if (o) var g = a ? o(h, f, l, e, t, i) : o(f, h, l, t, e, i);
	        if (void 0 !== g) {
	          if (g) continue;
	          d = !1;
	          break;
	        }
	        if (p) {
	          if (!F(e, function (t, e) {
	            if (a = e, !p.has(a) && (f === t || r(f, t, n, o, i))) return p.push(e);
	            var a;
	          })) {
	            d = !1;
	            break;
	          }
	        } else if (f !== h && !r(f, h, n, o, i)) {
	          d = !1;
	          break;
	        }
	      }
	      return i.delete(t), i.delete(e), d;
	    }
	    function Lt(t) {
	      return function (t, e, n) {
	        var o = e(t);
	        return Ut(t) ? o : function (t, e) {
	          for (var n = -1, o = e.length, r = t.length; ++n < o;) t[r + n] = e[n];
	          return t;
	        }(o, n(t));
	      }(t, Yt, Pt);
	    }
	    function Nt(t, e) {
	      var n,
	        o,
	        r = t.__data__;
	      return ("string" == (o = typeof (n = e)) || "number" == o || "symbol" == o || "boolean" == o ? "__proto__" !== n : null === n) ? r["string" == typeof e ? "string" : "hash"] : r.map;
	    }
	    function At(t, e) {
	      var n = function (t, e) {
	        return null == t ? void 0 : t[e];
	      }(t, e);
	      return It(n) ? n : void 0;
	    }
	    yt.prototype.clear = function () {
	      this.__data__ = ut ? ut(null) : {}, this.size = 0;
	    }, yt.prototype.delete = function (t) {
	      var e = this.has(t) && delete this.__data__[t];
	      return this.size -= e ? 1 : 0, e;
	    }, yt.prototype.get = function (t) {
	      var e = this.__data__;
	      if (ut) {
	        var o = e[t];
	        return o === n ? void 0 : o;
	      }
	      return z.call(e, t) ? e[t] : void 0;
	    }, yt.prototype.has = function (t) {
	      var e = this.__data__;
	      return ut ? void 0 !== e[t] : z.call(e, t);
	    }, yt.prototype.set = function (t, e) {
	      var o = this.__data__;
	      return this.size += this.has(t) ? 0 : 1, o[t] = ut && void 0 === e ? n : e, this;
	    }, vt.prototype.clear = function () {
	      this.__data__ = [], this.size = 0;
	    }, vt.prototype.delete = function (t) {
	      var e = this.__data__,
	        n = Tt(e, t);
	      return !(n < 0) && (n == e.length - 1 ? e.pop() : K.call(e, n, 1), --this.size, !0);
	    }, vt.prototype.get = function (t) {
	      var e = this.__data__,
	        n = Tt(e, t);
	      return n < 0 ? void 0 : e[n][1];
	    }, vt.prototype.has = function (t) {
	      return Tt(this.__data__, t) > -1;
	    }, vt.prototype.set = function (t, e) {
	      var n = this.__data__,
	        o = Tt(n, t);
	      return o < 0 ? (++this.size, n.push([t, e])) : n[o][1] = e, this;
	    }, mt.prototype.clear = function () {
	      this.size = 0, this.__data__ = {
	        hash: new yt(),
	        map: new (rt || vt)(),
	        string: new yt()
	      };
	    }, mt.prototype.delete = function (t) {
	      var e = Nt(this, t).delete(t);
	      return this.size -= e ? 1 : 0, e;
	    }, mt.prototype.get = function (t) {
	      return Nt(this, t).get(t);
	    }, mt.prototype.has = function (t) {
	      return Nt(this, t).has(t);
	    }, mt.prototype.set = function (t, e) {
	      var n = Nt(this, t),
	        o = n.size;
	      return n.set(t, e), this.size += n.size == o ? 0 : 1, this;
	    }, _t.prototype.add = _t.prototype.push = function (t) {
	      return this.__data__.set(t, n), this;
	    }, _t.prototype.has = function (t) {
	      return this.__data__.has(t);
	    }, bt.prototype.clear = function () {
	      this.__data__ = new vt(), this.size = 0;
	    }, bt.prototype.delete = function (t) {
	      var e = this.__data__,
	        n = e.delete(t);
	      return this.size = e.size, n;
	    }, bt.prototype.get = function (t) {
	      return this.__data__.get(t);
	    }, bt.prototype.has = function (t) {
	      return this.__data__.has(t);
	    }, bt.prototype.set = function (t, e) {
	      var n = this.__data__;
	      if (n instanceof vt) {
	        var o = n.__data__;
	        if (!rt || o.length < 199) return o.push([t, e]), this.size = ++n.size, this;
	        n = this.__data__ = new mt(o);
	      }
	      return n.set(t, e), this.size = n.size, this;
	    };
	    var Pt = tt ? function (t) {
	        return null == t ? [] : (t = Object(t), function (t, e) {
	          for (var n = -1, o = null == t ? 0 : t.length, r = 0, i = []; ++n < o;) {
	            var a = t[n];
	            e(a, n, t) && (i[r++] = a);
	          }
	          return i;
	        }(tt(t), function (e) {
	          return Z.call(t, e);
	        }));
	      } : function () {
	        return [];
	      },
	      Ft = Ct;
	    function wt(t, e) {
	      return !!(e = null == e ? o : e) && ("number" == typeof t || T.test(t)) && t > -1 && t % 1 == 0 && t < e;
	    }
	    function Rt(t) {
	      if (null != t) {
	        try {
	          return J.call(t);
	        } catch (t) {}
	        try {
	          return t + "";
	        } catch (t) {}
	      }
	      return "";
	    }
	    function Dt(t, e) {
	      return t === e || t != t && e != e;
	    }
	    (ot && Ft(new ot(new ArrayBuffer(1))) != b || rt && Ft(new rt()) != l || it && Ft(it.resolve()) != f || at && Ft(new at()) != g || st && Ft(new st()) != m) && (Ft = function (t) {
	      var e = Ct(t),
	        n = e == p ? t.constructor : void 0,
	        o = n ? Rt(n) : "";
	      if (o) switch (o) {
	        case ct:
	          return b;
	        case lt:
	          return l;
	        case dt:
	          return f;
	        case pt:
	          return g;
	        case ft:
	          return m;
	      }
	      return e;
	    });
	    var kt = Ot(function () {
	        return arguments;
	      }()) ? Ot : function (t) {
	        return Jt(t) && z.call(t, "callee") && !Z.call(t, "callee");
	      },
	      Ut = Array.isArray;
	    var jt = et || function () {
	      return !1;
	    };
	    function Vt(t) {
	      if (!Gt(t)) return !1;
	      var e = Ct(t);
	      return e == c || "[object GeneratorFunction]" == e || "[object AsyncFunction]" == e || "[object Proxy]" == e;
	    }
	    function Bt(t) {
	      return "number" == typeof t && t > -1 && t % 1 == 0 && t <= o;
	    }
	    function Gt(t) {
	      var e = typeof t;
	      return null != t && ("object" == e || "function" == e);
	    }
	    function Jt(t) {
	      return null != t && "object" == typeof t;
	    }
	    var zt = P ? function (t) {
	      return function (e) {
	        return t(e);
	      };
	    }(P) : function (t) {
	      return Jt(t) && Bt(t.length) && !!C[Ct(t)];
	    };
	    function Yt(t) {
	      return null != (e = t) && Bt(e.length) && !Vt(e) ? Et(t) : xt(t);
	      var e;
	    }
	    t.exports = function (t, e) {
	      return St(t, e);
	    };
	  }({
	    get exports() {
	      return se;
	    },
	    set exports(t) {
	      se = t;
	    }
	  }, se);
	  var ue = se;
	  function ce(t, e) {
	    return t.length === e.length && JSON.stringify(t.map(function (t) {
	      return t;
	    }).sort()) === JSON.stringify(e.map(function (t) {
	      return t;
	    }).sort());
	  }
	  var le = {
	    Polygon: U,
	    LineString: k,
	    Point: D,
	    MultiPolygon: B,
	    MultiLineString: B,
	    MultiPoint: B
	  };
	  var de = Object.freeze({
	      __proto__: null,
	      CommonSelectors: dt,
	      constrainFeatureMovement: $t,
	      createMidPoint: yt,
	      createSupplementaryPoints: vt,
	      createVertex: gt,
	      doubleClickZoom: mt,
	      euclideanDistance: N,
	      featuresAt: x,
	      getFeatureAtAndSetCursors: L,
	      isClick: A,
	      isEventAtCoordinates: Qt,
	      isTap: P,
	      mapEventToBoundingBox: O,
	      ModeHandler: t,
	      moveFeatures: qt,
	      sortFeatures: C,
	      stringSetsAreEqual: ce,
	      StringSet: S,
	      theme: tt,
	      toDenseArray: $
	    }),
	    pe = function (t, e) {
	      var n = {
	        options: t = function (t) {
	          void 0 === t && (t = {});
	          var e = W(t);
	          return t.controls || (e.controls = {}), !1 === t.displayControlsDefault ? e.controls = W(ie, t.controls) : e.controls = W(re, t.controls), (e = W(oe, e)).styles = ae(e.styles, "cold").concat(ae(e.styles, "hot")), e;
	        }(t)
	      };
	      e = function (t, e) {
	        return e.modes = f, e.getFeatureIdsAt = function (e) {
	          return x.click({
	            point: e
	          }, null, t).map(function (t) {
	            return t.properties.id;
	          });
	        }, e.getSelectedIds = function () {
	          return t.store.getSelectedIds();
	        }, e.getSelected = function () {
	          return {
	            type: p.FEATURE_COLLECTION,
	            features: t.store.getSelectedIds().map(function (e) {
	              return t.store.get(e);
	            }).map(function (t) {
	              return t.toGeoJSON();
	            })
	          };
	        }, e.getSelectedPoints = function () {
	          return {
	            type: p.FEATURE_COLLECTION,
	            features: t.store.getSelectedCoordinates().map(function (t) {
	              return {
	                type: p.FEATURE,
	                properties: {},
	                geometry: {
	                  type: p.POINT,
	                  coordinates: t.coordinates
	                }
	              };
	            })
	          };
	        }, e.set = function (n) {
	          if (void 0 === n.type || n.type !== p.FEATURE_COLLECTION || !Array.isArray(n.features)) throw new Error("Invalid FeatureCollection");
	          var o = t.store.createRenderBatch(),
	            r = t.store.getAllIds().slice(),
	            i = e.add(n),
	            a = new S(i);
	          return (r = r.filter(function (t) {
	            return !a.has(t);
	          })).length && e.delete(r), o(), i;
	        }, e.add = function (e) {
	          var n = JSON.parse(JSON.stringify(Et(e))).features.map(function (e) {
	            if (e.id = e.id || F(), null === e.geometry) throw new Error("Invalid geometry: null");
	            if (void 0 === t.store.get(e.id) || t.store.get(e.id).type !== e.geometry.type) {
	              var n = le[e.geometry.type];
	              if (void 0 === n) throw new Error("Invalid geometry type: " + e.geometry.type + ".");
	              var o = new n(t, e);
	              t.store.add(o);
	            } else {
	              var r = t.store.get(e.id);
	              r.properties = e.properties, ue(r.getCoordinates(), e.geometry.coordinates) || r.incomingCoords(e.geometry.coordinates);
	            }
	            return e.id;
	          });
	          return t.store.render(), n;
	        }, e.get = function (e) {
	          var n = t.store.get(e);
	          if (n) return n.toGeoJSON();
	        }, e.getAll = function () {
	          return {
	            type: p.FEATURE_COLLECTION,
	            features: t.store.getAll().map(function (t) {
	              return t.toGeoJSON();
	            })
	          };
	        }, e.delete = function (n) {
	          return t.store.delete(n, {
	            silent: !0
	          }), e.getMode() !== f.DIRECT_SELECT || t.store.getSelectedIds().length ? t.store.render() : t.events.changeMode(f.SIMPLE_SELECT, void 0, {
	            silent: !0
	          }), e;
	        }, e.deleteAll = function () {
	          return t.store.delete(t.store.getAllIds(), {
	            silent: !0
	          }), e.getMode() === f.DIRECT_SELECT ? t.events.changeMode(f.SIMPLE_SELECT, void 0, {
	            silent: !0
	          }) : t.store.render(), e;
	        }, e.changeMode = function (n, o) {
	          return void 0 === o && (o = {}), n === f.SIMPLE_SELECT && e.getMode() === f.SIMPLE_SELECT ? (ce(o.featureIds || [], t.store.getSelectedIds()) || (t.store.setSelected(o.featureIds, {
	            silent: !0
	          }), t.store.render()), e) : (n === f.DIRECT_SELECT && e.getMode() === f.DIRECT_SELECT && o.featureId === t.store.getSelectedIds()[0] || t.events.changeMode(n, o, {
	            silent: !0
	          }), e);
	        }, e.getMode = function () {
	          return t.events.getMode();
	        }, e.trash = function () {
	          return t.events.trash({
	            silent: !0
	          }), e;
	        }, e.combineFeatures = function () {
	          return t.events.combineFeatures({
	            silent: !0
	          }), e;
	        }, e.uncombineFeatures = function () {
	          return t.events.uncombineFeatures({
	            silent: !0
	          }), e;
	        }, e.setFeatureProperty = function (n, o, r) {
	          return t.store.setFeatureProperty(n, o, r), e;
	        }, e;
	      }(n, e), n.api = e;
	      var o = Q(n);
	      return e.onAdd = o.onAdd, e.onRemove = o.onRemove, e.types = d, e.options = t, e;
	    };
	  function fe(t) {
	    pe(t, this);
	  }
	  return fe.modes = ne, fe.constants = b, fe.lib = de, fe;
	}); 
} (mapboxGlDraw));

var mapboxGlDrawExports = mapboxGlDraw.exports;
var MapboxDraw = /*@__PURE__*/getDefaultExportFromCjs(mapboxGlDrawExports);

function Draw({
  type,
  required,
  data,
  setData
}) {
  const types = type === "all" ? ["point", "line_string", "polygon"] : [type],
    controls = {},
    ref = reactExports$1.useRef();
  types.forEach(type => controls[type] = true);
  if (!required) {
    controls.trash = true;
  }
  const draw = useControl(() => {
    const {
      classes
    } = MapboxDraw.constants;
    for (const [key, value] of Object.entries(classes)) {
      if (value.startsWith("mapboxgl-")) {
        classes[key] = value.replace("mapboxgl-", "maplibregl-");
      }
    }
    return new MapboxDraw({
      displayControlsDefault: false,
      controls
    });
  }, ({
    map
  }) => {
    map.on("draw.create", handleChange);
    map.on("draw.delete", handleChange);
    map.on("draw.update", handleChange);
    map.on("draw.combine", handleChange);
    map.on("draw.uncombine", handleChange);
  }, ({
    map
  }) => {
    map.off("draw.create", handleChange);
    map.off("draw.delete", handleChange);
    map.off("draw.update", handleChange);
    map.off("draw.combine", handleChange);
    map.off("draw.uncombine", handleChange);
  }, {
    position: "top-right"
  });
  reactExports$1.useEffect(() => {
    ref.current = {
      draw
    };
  }, [draw]);
  reactExports$1.useEffect(() => {
    if (draw && data) {
      draw.set(data);
    }
  }, [draw, data]);
  function handleChange() {
    const {
      draw
    } = ref.current;
    setData(draw.getAll());
  }
  return null;
}
Draw.propTypes = {
  type: PropTypes.string,
  required: PropTypes.boolean,
  data: PropTypes.object,
  setData: PropTypes.func
};

/**
 * @module helpers
 */
/**
 * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.
 *
 * @memberof helpers
 * @type {number}
 */
var earthRadius = 6371008.8;
/**
 * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.
 *
 * @memberof helpers
 * @type {Object}
 */
var factors = {
  centimeters: earthRadius * 100,
  centimetres: earthRadius * 100,
  degrees: earthRadius / 111325,
  feet: earthRadius * 3.28084,
  inches: earthRadius * 39.37,
  kilometers: earthRadius / 1000,
  kilometres: earthRadius / 1000,
  meters: earthRadius,
  metres: earthRadius,
  miles: earthRadius / 1609.344,
  millimeters: earthRadius * 1000,
  millimetres: earthRadius * 1000,
  nauticalmiles: earthRadius / 1852,
  radians: 1,
  yards: earthRadius * 1.0936
};
/**
 * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.
 *
 * @name feature
 * @param {Geometry} geometry input geometry
 * @param {Object} [properties={}] an Object of key-value pairs to add as properties
 * @param {Object} [options={}] Optional Parameters
 * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
 * @param {string|number} [options.id] Identifier associated with the Feature
 * @returns {Feature} a GeoJSON Feature
 * @example
 * var geometry = {
 *   "type": "Point",
 *   "coordinates": [110, 50]
 * };
 *
 * var feature = turf.feature(geometry);
 *
 * //=feature
 */
function feature(geom, properties, options) {
  if (options === void 0) {
    options = {};
  }
  var feat = {
    type: "Feature"
  };
  if (options.id === 0 || options.id) {
    feat.id = options.id;
  }
  if (options.bbox) {
    feat.bbox = options.bbox;
  }
  feat.properties = properties || {};
  feat.geometry = geom;
  return feat;
}
/**
 * Creates a {@link Point} {@link Feature} from a Position.
 *
 * @name point
 * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)
 * @param {Object} [properties={}] an Object of key-value pairs to add as properties
 * @param {Object} [options={}] Optional Parameters
 * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
 * @param {string|number} [options.id] Identifier associated with the Feature
 * @returns {Feature<Point>} a Point feature
 * @example
 * var point = turf.point([-75.343, 39.984]);
 *
 * //=point
 */
function point(coordinates, properties, options) {
  if (options === void 0) {
    options = {};
  }
  if (!coordinates) {
    throw new Error("coordinates is required");
  }
  if (!Array.isArray(coordinates)) {
    throw new Error("coordinates must be an Array");
  }
  if (coordinates.length < 2) {
    throw new Error("coordinates must be at least 2 numbers long");
  }
  if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {
    throw new Error("coordinates must contain numbers");
  }
  var geom = {
    type: "Point",
    coordinates: coordinates
  };
  return feature(geom, properties, options);
}
/**
 * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.
 *
 * @name polygon
 * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
 * @param {Object} [properties={}] an Object of key-value pairs to add as properties
 * @param {Object} [options={}] Optional Parameters
 * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
 * @param {string|number} [options.id] Identifier associated with the Feature
 * @returns {Feature<Polygon>} Polygon Feature
 * @example
 * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });
 *
 * //=polygon
 */
function polygon(coordinates, properties, options) {
  if (options === void 0) {
    options = {};
  }
  for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {
    var ring = coordinates_1[_i];
    if (ring.length < 4) {
      throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");
    }
    for (var j = 0; j < ring[ring.length - 1].length; j++) {
      // Check if first point of Polygon contains two numbers
      if (ring[ring.length - 1][j] !== ring[0][j]) {
        throw new Error("First and last Position are not equivalent.");
      }
    }
  }
  var geom = {
    type: "Polygon",
    coordinates: coordinates
  };
  return feature(geom, properties, options);
}
/**
 * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians
 * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
 *
 * @name lengthToRadians
 * @param {number} distance in real units
 * @param {string} [units="kilometers"] can be degrees, radians, miles, inches, yards, metres,
 * meters, kilometres, kilometers.
 * @returns {number} radians
 */
function lengthToRadians(distance, units) {
  if (units === void 0) {
    units = "kilometers";
  }
  var factor = factors[units];
  if (!factor) {
    throw new Error(units + " units is invalid");
  }
  return distance / factor;
}
/**
 * Converts an angle in radians to degrees
 *
 * @name radiansToDegrees
 * @param {number} radians angle in radians
 * @returns {number} degrees between 0 and 360 degrees
 */
function radiansToDegrees(radians) {
  var degrees = radians % (2 * Math.PI);
  return degrees * 180 / Math.PI;
}
/**
 * Converts an angle in degrees to radians
 *
 * @name degreesToRadians
 * @param {number} degrees angle between 0 and 360 degrees
 * @returns {number} angle in radians
 */
function degreesToRadians(degrees) {
  var radians = degrees % 360;
  return radians * Math.PI / 180;
}
/**
 * isNumber
 *
 * @param {*} num Number to validate
 * @returns {boolean} true/false
 * @example
 * turf.isNumber(123)
 * //=true
 * turf.isNumber('foo')
 * //=false
 */
function isNumber(num) {
  return !isNaN(num) && num !== null && !Array.isArray(num);
}

/**
 * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.
 *
 * @name getCoord
 * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers
 * @returns {Array<number>} coordinates
 * @example
 * var pt = turf.point([10, 10]);
 *
 * var coord = turf.getCoord(pt);
 * //= [10, 10]
 */
function getCoord(coord) {
  if (!coord) {
    throw new Error("coord is required");
  }
  if (!Array.isArray(coord)) {
    if (coord.type === "Feature" && coord.geometry !== null && coord.geometry.type === "Point") {
      return coord.geometry.coordinates;
    }
    if (coord.type === "Point") {
      return coord.coordinates;
    }
  }
  if (Array.isArray(coord) && coord.length >= 2 && !Array.isArray(coord[0]) && !Array.isArray(coord[1])) {
    return coord;
  }
  throw new Error("coord must be GeoJSON Point or an Array of numbers");
}

// http://en.wikipedia.org/wiki/Haversine_formula
// http://www.movable-type.co.uk/scripts/latlong.html
/**
 * Takes a {@link Point} and calculates the location of a destination point given a distance in
 * degrees, radians, miles, or kilometers; and bearing in degrees.
 * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.
 *
 * @name destination
 * @param {Coord} origin starting point
 * @param {number} distance distance from the origin point
 * @param {number} bearing ranging from -180 to 180
 * @param {Object} [options={}] Optional parameters
 * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
 * @param {Object} [options.properties={}] Translate properties to Point
 * @returns {Feature<Point>} destination point
 * @example
 * var point = turf.point([-75.343, 39.984]);
 * var distance = 50;
 * var bearing = 90;
 * var options = {units: 'miles'};
 *
 * var destination = turf.destination(point, distance, bearing, options);
 *
 * //addToMap
 * var addToMap = [point, destination]
 * destination.properties['marker-color'] = '#f00';
 * point.properties['marker-color'] = '#0f0';
 */
function destination(origin, distance, bearing, options) {
  if (options === void 0) {
    options = {};
  }
  // Handle input
  var coordinates1 = getCoord(origin);
  var longitude1 = degreesToRadians(coordinates1[0]);
  var latitude1 = degreesToRadians(coordinates1[1]);
  var bearingRad = degreesToRadians(bearing);
  var radians = lengthToRadians(distance, options.units);
  // Main
  var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) + Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad));
  var longitude2 = longitude1 + Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));
  var lng = radiansToDegrees(longitude2);
  var lat = radiansToDegrees(latitude2);
  return point([lng, lat], options.properties);
}

/**
 * Takes a {@link Point} and calculates the circle polygon given a radius in degrees, radians, miles, or kilometers; and steps for precision.
 *
 * @name circle
 * @param {Feature<Point>|number[]} center center point
 * @param {number} radius radius of the circle
 * @param {Object} [options={}] Optional parameters
 * @param {number} [options.steps=64] number of steps
 * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians
 * @param {Object} [options.properties={}] properties
 * @returns {Feature<Polygon>} circle polygon
 * @example
 * var center = [-75.343, 39.984];
 * var radius = 5;
 * var options = {steps: 10, units: 'kilometers', properties: {foo: 'bar'}};
 * var circle = turf.circle(center, radius, options);
 *
 * //addToMap
 * var addToMap = [turf.point(center), circle]
 */
function circle(center, radius, options) {
  if (options === void 0) {
    options = {};
  }
  // default params
  var steps = options.steps || 64;
  var properties = options.properties ? options.properties : !Array.isArray(center) && center.type === "Feature" && center.properties ? center.properties : {};
  // main
  var coordinates = [];
  for (var i = 0; i < steps; i++) {
    coordinates.push(destination(center, radius, i * -360 / steps, options).geometry.coordinates);
  }
  coordinates.push(coordinates[0]);
  return polygon([coordinates], properties);
}

function Accuracy({
  accuracy,
  data
}) {
  const geometry = data && data.features && data.features[0] && data.features[0].geometry;
  if (!accuracy || !geometry || geometry.type !== "Point") {
    return null;
  }
  const circleData = circle(geometry.coordinates, accuracy / 1000);
  return /*#__PURE__*/React.createElement(Geojson, {
    name: "accuracy",
    active: true,
    data: circleData
  });
}
Accuracy.propTypes = {
  accuracy: PropTypes.number,
  data: PropTypes.object
};

function Tile({
  name,
  active,
  url,
  tileSize,
  layout = {},
  paint = {}
}) {
  const source = reactExports$1.useMemo(() => {
    return {
      id: name,
      type: "raster",
      tiles: [url],
      tileSize: tileSize || 256
    };
  }, [name, url]);
  const layer = reactExports$1.useMemo(() => {
    return {
      id: name,
      type: "raster",
      layout: active === false ? {
        ...(layout || {}),
        visibility: "none"
      } : layout,
      paint
    };
  }, [name, active, layout, paint]);
  return /*#__PURE__*/React.createElement(Source, {
    ...source
  }, /*#__PURE__*/React.createElement(Layer, {
    ...layer
  }));
}
Tile.propTypes = {
  name: PropTypes.string,
  active: PropTypes.bool,
  url: PropTypes.string,
  tileSize: PropTypes.number,
  layout: PropTypes.object,
  paint: PropTypes.object
};

function AutoLayer({
  id,
  active,
  before,
  layout = {},
  paint = {},
  ...rest
}) {
  const layer = reactExports$1.useMemo(() => {
    return {
      id,
      layout: active === false ? {
        ...layout,
        visibility: "none"
      } : layout,
      paint
    };
  }, [id, active, layout, paint]);
  return /*#__PURE__*/React.createElement(Layer, {
    beforeId: before,
    ...layer,
    ...rest
  });
}
function VectorTile({
  name,
  active,
  before,
  url,
  style
}) {
  if (url) {
    return /*#__PURE__*/React.createElement(UrlVectorTile, {
      name: name,
      active: active,
      url: url,
      before: before
    });
  }
  const {
    sources,
    layers
  } = style;
  if (!sources || !layers) {
    return null;
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, Object.entries(sources).map(([id, source]) => /*#__PURE__*/React.createElement(Source, {
    key: id,
    id: id,
    ...source
  })), layers.map(layer => /*#__PURE__*/React.createElement(AutoLayer, {
    key: layer.id,
    active: active,
    before: before,
    ...layer
  })));
}
function UrlVectorTile({
  name,
  active,
  before,
  url
}) {
  const [style, setStyle] = reactExports$1.useState();
  reactExports$1.useEffect(() => {
    async function loadStyle() {
      const response = await fetch(url),
        data = await response.json();
      setStyle(data);
    }
    loadStyle();
  }, [url]);
  if (style) {
    return /*#__PURE__*/React.createElement(VectorTile, {
      name: name,
      active: active,
      before: before,
      style: style
    });
  } else {
    return null;
  }
}
AutoLayer.propTypes = {
  active: PropTypes.bool,
  before: PropTypes.string,
  id: PropTypes.string,
  type: PropTypes.string,
  layout: PropTypes.object,
  paint: PropTypes.object,
  metadata: PropTypes.object,
  source: PropTypes.string,
  minzoom: PropTypes.number,
  maxzoom: PropTypes.number,
  filter: PropTypes.object
};
VectorTile.propTypes = {
  name: PropTypes.string,
  active: PropTypes.bool,
  before: PropTypes.string,
  style: PropTypes.object,
  url: PropTypes.string
};
UrlVectorTile.propTypes = {
  name: PropTypes.string,
  active: PropTypes.bool,
  before: PropTypes.string,
  url: PropTypes.string
};

var mapgl = {
  name: "map-gl",
  dependencies: [map],
  setEngine(engine) {
    this.engine = engine;
    if (engine.prewarm && typeof Worker !== "undefined") {
      engine.prewarm();
    }
  },
  components: {
    Map: Map$1,
    MapProvider,
    useMapInstance,
    MapInteraction,
    MapAutoZoom,
    MapIdentify,
    MapLayers,
    GeoHelpIcon,
    HighlightPopup
  },
  basemaps: {
    VectorTile: VectorTile$1,
    Tile: Tile$1
  },
  overlays: {
    Geojson,
    Highlight,
    Draw,
    Accuracy,
    VectorTile: VectorTile,
    Tile: Tile
  },
  zoomToLocation
};

var mapglExports = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Accuracy: Accuracy,
  Draw: Draw,
  GeoHelpIcon: GeoHelpIcon,
  Geojson: Geojson,
  Highlight: Highlight,
  HighlightPopup: HighlightPopup,
  Map: Map$1,
  MapAutoZoom: MapAutoZoom,
  MapIdentify: MapIdentify,
  MapInteraction: MapInteraction,
  MapProvider: MapProvider,
  Tile: Tile$1,
  TileOverlay: Tile,
  VectorTile: VectorTile$1,
  VectorTileOverlay: VectorTile,
  default: mapgl,
  useMapInstance: useMapInstance
});

function getAlertUtilityClass(slot) {
  return generateUtilityClass('MuiAlert', slot);
}
const alertClasses = generateUtilityClasses('MuiAlert', ['root', 'action', 'icon', 'message', 'filled', 'filledSuccess', 'filledInfo', 'filledWarning', 'filledError', 'outlined', 'outlinedSuccess', 'outlinedInfo', 'outlinedWarning', 'outlinedError', 'standard', 'standardSuccess', 'standardInfo', 'standardWarning', 'standardError']);
var alertClasses$1 = alertClasses;

var SuccessOutlinedIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4C12.76,4 13.5,4.11 14.2, 4.31L15.77,2.74C14.61,2.26 13.34,2 12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0, 0 22,12M7.91,10.08L6.5,11.5L11,16L21,6L19.59,4.58L11,13.17L7.91,10.08Z"
}), 'SuccessOutlined');

var ReportProblemOutlinedIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M12 5.99L19.53 19H4.47L12 5.99M12 2L1 21h22L12 2zm1 14h-2v2h2v-2zm0-6h-2v4h2v-4z"
}), 'ReportProblemOutlined');

var ErrorOutlineIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
}), 'ErrorOutline');

var InfoOutlinedIcon = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
  d: "M11,9H13V7H11M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20, 12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10, 10 0 0,0 12,2M11,17H13V11H11V17Z"
}), 'InfoOutlined');

const _excluded$b = ["action", "children", "className", "closeText", "color", "components", "componentsProps", "icon", "iconMapping", "onClose", "role", "severity", "slotProps", "slots", "variant"];
const useUtilityClasses$9 = ownerState => {
  const {
    variant,
    color,
    severity,
    classes
  } = ownerState;
  const slots = {
    root: ['root', `${variant}${capitalize(color || severity)}`, `${variant}`],
    icon: ['icon'],
    message: ['message'],
    action: ['action']
  };
  return composeClasses(slots, getAlertUtilityClass, classes);
};
const AlertRoot = styled$1(Paper$1, {
  name: 'MuiAlert',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant], styles[`${ownerState.variant}${capitalize(ownerState.color || ownerState.severity)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  const getColor = theme.palette.mode === 'light' ? darken : lighten;
  const getBackgroundColor = theme.palette.mode === 'light' ? lighten : darken;
  const color = ownerState.color || ownerState.severity;
  return _extends({}, theme.typography.body2, {
    backgroundColor: 'transparent',
    display: 'flex',
    padding: '6px 16px'
  }, color && ownerState.variant === 'standard' && {
    color: theme.vars ? theme.vars.palette.Alert[`${color}Color`] : getColor(theme.palette[color].light, 0.6),
    backgroundColor: theme.vars ? theme.vars.palette.Alert[`${color}StandardBg`] : getBackgroundColor(theme.palette[color].light, 0.9),
    [`& .${alertClasses$1.icon}`]: theme.vars ? {
      color: theme.vars.palette.Alert[`${color}IconColor`]
    } : {
      color: theme.palette[color].main
    }
  }, color && ownerState.variant === 'outlined' && {
    color: theme.vars ? theme.vars.palette.Alert[`${color}Color`] : getColor(theme.palette[color].light, 0.6),
    border: `1px solid ${(theme.vars || theme).palette[color].light}`,
    [`& .${alertClasses$1.icon}`]: theme.vars ? {
      color: theme.vars.palette.Alert[`${color}IconColor`]
    } : {
      color: theme.palette[color].main
    }
  }, color && ownerState.variant === 'filled' && _extends({
    fontWeight: theme.typography.fontWeightMedium
  }, theme.vars ? {
    color: theme.vars.palette.Alert[`${color}FilledColor`],
    backgroundColor: theme.vars.palette.Alert[`${color}FilledBg`]
  } : {
    backgroundColor: theme.palette.mode === 'dark' ? theme.palette[color].dark : theme.palette[color].main,
    color: theme.palette.getContrastText(theme.palette[color].main)
  }));
});
const AlertIcon = styled$1('div', {
  name: 'MuiAlert',
  slot: 'Icon',
  overridesResolver: (props, styles) => styles.icon
})({
  marginRight: 12,
  padding: '7px 0',
  display: 'flex',
  fontSize: 22,
  opacity: 0.9
});
const AlertMessage = styled$1('div', {
  name: 'MuiAlert',
  slot: 'Message',
  overridesResolver: (props, styles) => styles.message
})({
  padding: '8px 0',
  minWidth: 0,
  overflow: 'auto'
});
const AlertAction = styled$1('div', {
  name: 'MuiAlert',
  slot: 'Action',
  overridesResolver: (props, styles) => styles.action
})({
  display: 'flex',
  alignItems: 'flex-start',
  padding: '4px 0 0 16px',
  marginLeft: 'auto',
  marginRight: -8
});
const defaultIconMapping = {
  success: /*#__PURE__*/jsxRuntimeExports.jsx(SuccessOutlinedIcon, {
    fontSize: "inherit"
  }),
  warning: /*#__PURE__*/jsxRuntimeExports.jsx(ReportProblemOutlinedIcon, {
    fontSize: "inherit"
  }),
  error: /*#__PURE__*/jsxRuntimeExports.jsx(ErrorOutlineIcon, {
    fontSize: "inherit"
  }),
  info: /*#__PURE__*/jsxRuntimeExports.jsx(InfoOutlinedIcon, {
    fontSize: "inherit"
  })
};
const Alert = /*#__PURE__*/reactExports$1.forwardRef(function Alert(inProps, ref) {
  var _ref, _slots$closeButton, _ref2, _slots$closeIcon, _slotProps$closeButto, _slotProps$closeIcon;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAlert'
  });
  const {
      action,
      children,
      className,
      closeText = 'Close',
      color,
      components = {},
      componentsProps = {},
      icon,
      iconMapping = defaultIconMapping,
      onClose,
      role = 'alert',
      severity = 'success',
      slotProps = {},
      slots = {},
      variant = 'standard'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$b);
  const ownerState = _extends({}, props, {
    color,
    severity,
    variant
  });
  const classes = useUtilityClasses$9(ownerState);
  const AlertCloseButton = (_ref = (_slots$closeButton = slots.closeButton) != null ? _slots$closeButton : components.CloseButton) != null ? _ref : IconButton$2;
  const AlertCloseIcon = (_ref2 = (_slots$closeIcon = slots.closeIcon) != null ? _slots$closeIcon : components.CloseIcon) != null ? _ref2 : CloseIcon;
  const closeButtonProps = (_slotProps$closeButto = slotProps.closeButton) != null ? _slotProps$closeButto : componentsProps.closeButton;
  const closeIconProps = (_slotProps$closeIcon = slotProps.closeIcon) != null ? _slotProps$closeIcon : componentsProps.closeIcon;
  return /*#__PURE__*/jsxRuntimeExports.jsxs(AlertRoot, _extends({
    role: role,
    elevation: 0,
    ownerState: ownerState,
    className: clsx(classes.root, className),
    ref: ref
  }, other, {
    children: [icon !== false ? /*#__PURE__*/jsxRuntimeExports.jsx(AlertIcon, {
      ownerState: ownerState,
      className: classes.icon,
      children: icon || iconMapping[severity] || defaultIconMapping[severity]
    }) : null, /*#__PURE__*/jsxRuntimeExports.jsx(AlertMessage, {
      ownerState: ownerState,
      className: classes.message,
      children: children
    }), action != null ? /*#__PURE__*/jsxRuntimeExports.jsx(AlertAction, {
      ownerState: ownerState,
      className: classes.action,
      children: action
    }) : null, action == null && onClose ? /*#__PURE__*/jsxRuntimeExports.jsx(AlertAction, {
      ownerState: ownerState,
      className: classes.action,
      children: /*#__PURE__*/jsxRuntimeExports.jsx(AlertCloseButton, _extends({
        size: "small",
        "aria-label": closeText,
        title: closeText,
        color: "inherit",
        onClick: onClose
      }, closeButtonProps, {
        children: /*#__PURE__*/jsxRuntimeExports.jsx(AlertCloseIcon, _extends({
          fontSize: "small"
        }, closeIconProps))
      }))
    }) : null]
  }));
});
Alert.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display. It renders after the message, at the end of the alert.
   */
  action: PropTypes.node,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Override the default label for the *close popup* icon button.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @default 'Close'
   */
  closeText: PropTypes.string,
  /**
   * The color of the component. Unless provided, the value is taken from the `severity` prop.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    CloseButton: PropTypes.elementType,
    CloseIcon: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    closeButton: PropTypes.object,
    closeIcon: PropTypes.object
  }),
  /**
   * Override the icon displayed before the children.
   * Unless provided, the icon is mapped to the value of the `severity` prop.
   * Set to `false` to remove the `icon`.
   */
  icon: PropTypes.node,
  /**
   * The component maps the `severity` prop to a range of different icons,
   * for instance success to `<SuccessOutlined>`.
   * If you wish to change this mapping, you can provide your own.
   * Alternatively, you can use the `icon` prop to override the icon displayed.
   */
  iconMapping: PropTypes.shape({
    error: PropTypes.node,
    info: PropTypes.node,
    success: PropTypes.node,
    warning: PropTypes.node
  }),
  /**
   * Callback fired when the component requests to be closed.
   * When provided and no `action` prop is set, a close icon button is displayed that triggers the callback when clicked.
   * @param {React.SyntheticEvent} event The event source of the callback.
   */
  onClose: PropTypes.func,
  /**
   * The ARIA role attribute of the element.
   * @default 'alert'
   */
  role: PropTypes.string,
  /**
   * The severity of the alert. This defines the color and icon used.
   * @default 'success'
   */
  severity: PropTypes.oneOf(['error', 'info', 'success', 'warning']),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slotProps: PropTypes.shape({
    closeButton: PropTypes.object,
    closeIcon: PropTypes.object
  }),
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `components` prop, which will be deprecated in the future.
   *
   * @default {}
   */
  slots: PropTypes.shape({
    closeButton: PropTypes.elementType,
    closeIcon: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'standard'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['filled', 'outlined', 'standard']), PropTypes.string])
} ;
var Alert$1 = Alert;

function getAlertTitleUtilityClass(slot) {
  return generateUtilityClass('MuiAlertTitle', slot);
}
generateUtilityClasses('MuiAlertTitle', ['root']);

const _excluded$a = ["className"];
const useUtilityClasses$8 = ownerState => {
  const {
    classes
  } = ownerState;
  const slots = {
    root: ['root']
  };
  return composeClasses(slots, getAlertTitleUtilityClass, classes);
};
const AlertTitleRoot = styled$1(Typography$1, {
  name: 'MuiAlertTitle',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => {
  return {
    fontWeight: theme.typography.fontWeightMedium,
    marginTop: -2
  };
});
const AlertTitle = /*#__PURE__*/reactExports$1.forwardRef(function AlertTitle(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiAlertTitle'
  });
  const {
      className
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$a);
  const ownerState = props;
  const classes = useUtilityClasses$8(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(AlertTitleRoot, _extends({
    gutterBottom: true,
    component: "div",
    ownerState: ownerState,
    ref: ref,
    className: clsx(classes.root, className)
  }, other));
});
AlertTitle.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var AlertTitle$1 = AlertTitle;

function getBadgeUtilityClass(slot) {
  return generateUtilityClass('MuiBadge', slot);
}
const badgeClasses = generateUtilityClasses('MuiBadge', ['root', 'badge', 'dot', 'standard', 'anchorOriginTopRight', 'anchorOriginBottomRight', 'anchorOriginTopLeft', 'anchorOriginBottomLeft', 'invisible', 'colorError', 'colorInfo', 'colorPrimary', 'colorSecondary', 'colorSuccess', 'colorWarning', 'overlapRectangular', 'overlapCircular',
// TODO: v6 remove the overlap value from these class keys
'anchorOriginTopLeftCircular', 'anchorOriginTopLeftRectangular', 'anchorOriginTopRightCircular', 'anchorOriginTopRightRectangular', 'anchorOriginBottomLeftCircular', 'anchorOriginBottomLeftRectangular', 'anchorOriginBottomRightCircular', 'anchorOriginBottomRightRectangular']);
var badgeClasses$1 = badgeClasses;

const _excluded$9 = ["anchorOrigin", "className", "classes", "component", "components", "componentsProps", "children", "overlap", "color", "invisible", "max", "badgeContent", "slots", "slotProps", "showZero", "variant"];
const RADIUS_STANDARD = 10;
const RADIUS_DOT = 4;
const useUtilityClasses$7 = ownerState => {
  const {
    color,
    anchorOrigin,
    invisible,
    overlap,
    variant,
    classes = {}
  } = ownerState;
  const slots = {
    root: ['root'],
    badge: ['badge', variant, invisible && 'invisible', `anchorOrigin${capitalize(anchorOrigin.vertical)}${capitalize(anchorOrigin.horizontal)}`, `anchorOrigin${capitalize(anchorOrigin.vertical)}${capitalize(anchorOrigin.horizontal)}${capitalize(overlap)}`, `overlap${capitalize(overlap)}`, color !== 'default' && `color${capitalize(color)}`]
  };
  return composeClasses(slots, getBadgeUtilityClass, classes);
};
const BadgeRoot = styled$1('span', {
  name: 'MuiBadge',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({
  position: 'relative',
  display: 'inline-flex',
  // For correct alignment with the text.
  verticalAlign: 'middle',
  flexShrink: 0
});
const BadgeBadge = styled$1('span', {
  name: 'MuiBadge',
  slot: 'Badge',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.badge, styles[ownerState.variant], styles[`anchorOrigin${capitalize(ownerState.anchorOrigin.vertical)}${capitalize(ownerState.anchorOrigin.horizontal)}${capitalize(ownerState.overlap)}`], ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`], ownerState.invisible && styles.invisible];
  }
})(({
  theme,
  ownerState
}) => _extends({
  display: 'flex',
  flexDirection: 'row',
  flexWrap: 'wrap',
  justifyContent: 'center',
  alignContent: 'center',
  alignItems: 'center',
  position: 'absolute',
  boxSizing: 'border-box',
  fontFamily: theme.typography.fontFamily,
  fontWeight: theme.typography.fontWeightMedium,
  fontSize: theme.typography.pxToRem(12),
  minWidth: RADIUS_STANDARD * 2,
  lineHeight: 1,
  padding: '0 6px',
  height: RADIUS_STANDARD * 2,
  borderRadius: RADIUS_STANDARD,
  zIndex: 1,
  // Render the badge on top of potential ripples.
  transition: theme.transitions.create('transform', {
    easing: theme.transitions.easing.easeInOut,
    duration: theme.transitions.duration.enteringScreen
  })
}, ownerState.color !== 'default' && {
  backgroundColor: (theme.vars || theme).palette[ownerState.color].main,
  color: (theme.vars || theme).palette[ownerState.color].contrastText
}, ownerState.variant === 'dot' && {
  borderRadius: RADIUS_DOT,
  height: RADIUS_DOT * 2,
  minWidth: RADIUS_DOT * 2,
  padding: 0
}, ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'rectangular' && {
  top: 0,
  right: 0,
  transform: 'scale(1) translate(50%, -50%)',
  transformOrigin: '100% 0%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(50%, -50%)'
  }
}, ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'rectangular' && {
  bottom: 0,
  right: 0,
  transform: 'scale(1) translate(50%, 50%)',
  transformOrigin: '100% 100%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(50%, 50%)'
  }
}, ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'rectangular' && {
  top: 0,
  left: 0,
  transform: 'scale(1) translate(-50%, -50%)',
  transformOrigin: '0% 0%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(-50%, -50%)'
  }
}, ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'rectangular' && {
  bottom: 0,
  left: 0,
  transform: 'scale(1) translate(-50%, 50%)',
  transformOrigin: '0% 100%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(-50%, 50%)'
  }
}, ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'circular' && {
  top: '14%',
  right: '14%',
  transform: 'scale(1) translate(50%, -50%)',
  transformOrigin: '100% 0%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(50%, -50%)'
  }
}, ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'circular' && {
  bottom: '14%',
  right: '14%',
  transform: 'scale(1) translate(50%, 50%)',
  transformOrigin: '100% 100%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(50%, 50%)'
  }
}, ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'circular' && {
  top: '14%',
  left: '14%',
  transform: 'scale(1) translate(-50%, -50%)',
  transformOrigin: '0% 0%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(-50%, -50%)'
  }
}, ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'circular' && {
  bottom: '14%',
  left: '14%',
  transform: 'scale(1) translate(-50%, 50%)',
  transformOrigin: '0% 100%',
  [`&.${badgeClasses$1.invisible}`]: {
    transform: 'scale(0) translate(-50%, 50%)'
  }
}, ownerState.invisible && {
  transition: theme.transitions.create('transform', {
    easing: theme.transitions.easing.easeInOut,
    duration: theme.transitions.duration.leavingScreen
  })
}));
const Badge = /*#__PURE__*/reactExports$1.forwardRef(function Badge(inProps, ref) {
  var _ref, _slots$root, _ref2, _slots$badge, _slotProps$root, _slotProps$badge;
  const props = useThemeProps({
    props: inProps,
    name: 'MuiBadge'
  });
  const {
      anchorOrigin: anchorOriginProp = {
        vertical: 'top',
        horizontal: 'right'
      },
      className,
      component,
      components = {},
      componentsProps = {},
      children,
      overlap: overlapProp = 'rectangular',
      color: colorProp = 'default',
      invisible: invisibleProp = false,
      max: maxProp = 99,
      badgeContent: badgeContentProp,
      slots,
      slotProps,
      showZero = false,
      variant: variantProp = 'standard'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$9);
  const {
    badgeContent,
    invisible: invisibleFromHook,
    max,
    displayValue: displayValueFromHook
  } = useBadge({
    max: maxProp,
    invisible: invisibleProp,
    badgeContent: badgeContentProp,
    showZero
  });
  const prevProps = usePreviousProps$1({
    anchorOrigin: anchorOriginProp,
    color: colorProp,
    overlap: overlapProp,
    variant: variantProp,
    badgeContent: badgeContentProp
  });
  const invisible = invisibleFromHook || badgeContent == null && variantProp !== 'dot';
  const {
    color = colorProp,
    overlap = overlapProp,
    anchorOrigin = anchorOriginProp,
    variant = variantProp
  } = invisible ? prevProps : props;
  const displayValue = variant !== 'dot' ? displayValueFromHook : undefined;
  const ownerState = _extends({}, props, {
    badgeContent,
    invisible,
    max,
    displayValue,
    showZero,
    anchorOrigin,
    color,
    overlap,
    variant
  });
  const classes = useUtilityClasses$7(ownerState);

  // support both `slots` and `components` for backward compatibility
  const RootSlot = (_ref = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : components.Root) != null ? _ref : BadgeRoot;
  const BadgeSlot = (_ref2 = (_slots$badge = slots == null ? void 0 : slots.badge) != null ? _slots$badge : components.Badge) != null ? _ref2 : BadgeBadge;
  const rootSlotProps = (_slotProps$root = slotProps == null ? void 0 : slotProps.root) != null ? _slotProps$root : componentsProps.root;
  const badgeSlotProps = (_slotProps$badge = slotProps == null ? void 0 : slotProps.badge) != null ? _slotProps$badge : componentsProps.badge;
  const rootProps = useSlotProps({
    elementType: RootSlot,
    externalSlotProps: rootSlotProps,
    externalForwardedProps: other,
    additionalProps: {
      ref,
      as: component
    },
    ownerState,
    className: clsx(rootSlotProps == null ? void 0 : rootSlotProps.className, classes.root, className)
  });
  const badgeProps = useSlotProps({
    elementType: BadgeSlot,
    externalSlotProps: badgeSlotProps,
    ownerState,
    className: clsx(classes.badge, badgeSlotProps == null ? void 0 : badgeSlotProps.className)
  });
  return /*#__PURE__*/jsxRuntimeExports.jsxs(RootSlot, _extends({}, rootProps, {
    children: [children, /*#__PURE__*/jsxRuntimeExports.jsx(BadgeSlot, _extends({}, badgeProps, {
      children: displayValue
    }))]
  }));
});
Badge.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The anchor of the badge.
   * @default {
   *   vertical: 'top',
   *   horizontal: 'right',
   * }
   */
  anchorOrigin: PropTypes.shape({
    horizontal: PropTypes.oneOf(['left', 'right']).isRequired,
    vertical: PropTypes.oneOf(['bottom', 'top']).isRequired
  }),
  /**
   * The content rendered within the badge.
   */
  badgeContent: PropTypes.node,
  /**
   * The badge will be added relative to this node.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'default'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The components used for each slot inside.
   *
   * This prop is an alias for the `slots` prop.
   * It's recommended to use the `slots` prop instead.
   *
   * @default {}
   */
  components: PropTypes.shape({
    Badge: PropTypes.elementType,
    Root: PropTypes.elementType
  }),
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * This prop is an alias for the `slotProps` prop.
   * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.
   *
   * @default {}
   */
  componentsProps: PropTypes.shape({
    badge: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * If `true`, the badge is invisible.
   * @default false
   */
  invisible: PropTypes.bool,
  /**
   * Max count to show.
   * @default 99
   */
  max: PropTypes.number,
  /**
   * Wrapped shape the badge should overlap.
   * @default 'rectangular'
   */
  overlap: PropTypes.oneOf(['circular', 'rectangular']),
  /**
   * Controls whether the badge is hidden when `badgeContent` is zero.
   * @default false
   */
  showZero: PropTypes.bool,
  /**
   * The props used for each slot inside the Badge.
   * @default {}
   */
  slotProps: PropTypes.shape({
    badge: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
  }),
  /**
   * The components used for each slot inside the Badge.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: PropTypes.shape({
    badge: PropTypes.elementType,
    root: PropTypes.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'standard'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['dot', 'standard']), PropTypes.string])
} ;
var Badge$1 = Badge;

/**
 * @ignore - internal component.
 */
const GridContext = /*#__PURE__*/reactExports$1.createContext();
{
  GridContext.displayName = 'GridContext';
}
var GridContext$1 = GridContext;

function getGridUtilityClass(slot) {
  return generateUtilityClass('MuiGrid', slot);
}
const SPACINGS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const DIRECTIONS = ['column-reverse', 'column', 'row-reverse', 'row'];
const WRAPS = ['nowrap', 'wrap-reverse', 'wrap'];
const GRID_SIZES = ['auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const gridClasses = generateUtilityClasses('MuiGrid', ['root', 'container', 'item', 'zeroMinWidth',
// spacings
...SPACINGS.map(spacing => `spacing-xs-${spacing}`),
// direction values
...DIRECTIONS.map(direction => `direction-xs-${direction}`),
// wrap values
...WRAPS.map(wrap => `wrap-xs-${wrap}`),
// grid sizes for all breakpoints
...GRID_SIZES.map(size => `grid-xs-${size}`), ...GRID_SIZES.map(size => `grid-sm-${size}`), ...GRID_SIZES.map(size => `grid-md-${size}`), ...GRID_SIZES.map(size => `grid-lg-${size}`), ...GRID_SIZES.map(size => `grid-xl-${size}`)]);

const _excluded$8 = ["className", "columns", "columnSpacing", "component", "container", "direction", "item", "rowSpacing", "spacing", "wrap", "zeroMinWidth"];
function getOffset(val) {
  const parse = parseFloat(val);
  return `${parse}${String(val).replace(String(parse), '') || 'px'}`;
}
function generateGrid({
  theme,
  ownerState
}) {
  let size;
  return theme.breakpoints.keys.reduce((globalStyles, breakpoint) => {
    // Use side effect over immutability for better performance.
    let styles = {};
    if (ownerState[breakpoint]) {
      size = ownerState[breakpoint];
    }
    if (!size) {
      return globalStyles;
    }
    if (size === true) {
      // For the auto layouting
      styles = {
        flexBasis: 0,
        flexGrow: 1,
        maxWidth: '100%'
      };
    } else if (size === 'auto') {
      styles = {
        flexBasis: 'auto',
        flexGrow: 0,
        flexShrink: 0,
        maxWidth: 'none',
        width: 'auto'
      };
    } else {
      const columnsBreakpointValues = resolveBreakpointValues({
        values: ownerState.columns,
        breakpoints: theme.breakpoints.values
      });
      const columnValue = typeof columnsBreakpointValues === 'object' ? columnsBreakpointValues[breakpoint] : columnsBreakpointValues;
      if (columnValue === undefined || columnValue === null) {
        return globalStyles;
      }
      // Keep 7 significant numbers.
      const width = `${Math.round(size / columnValue * 10e7) / 10e5}%`;
      let more = {};
      if (ownerState.container && ownerState.item && ownerState.columnSpacing !== 0) {
        const themeSpacing = theme.spacing(ownerState.columnSpacing);
        if (themeSpacing !== '0px') {
          const fullWidth = `calc(${width} + ${getOffset(themeSpacing)})`;
          more = {
            flexBasis: fullWidth,
            maxWidth: fullWidth
          };
        }
      }

      // Close to the bootstrap implementation:
      // https://github.com/twbs/bootstrap/blob/8fccaa2439e97ec72a4b7dc42ccc1f649790adb0/scss/mixins/_grid.scss#L41
      styles = _extends({
        flexBasis: width,
        flexGrow: 0,
        maxWidth: width
      }, more);
    }

    // No need for a media query for the first size.
    if (theme.breakpoints.values[breakpoint] === 0) {
      Object.assign(globalStyles, styles);
    } else {
      globalStyles[theme.breakpoints.up(breakpoint)] = styles;
    }
    return globalStyles;
  }, {});
}
function generateDirection({
  theme,
  ownerState
}) {
  const directionValues = resolveBreakpointValues({
    values: ownerState.direction,
    breakpoints: theme.breakpoints.values
  });
  return handleBreakpoints({
    theme
  }, directionValues, propValue => {
    const output = {
      flexDirection: propValue
    };
    if (propValue.indexOf('column') === 0) {
      output[`& > .${gridClasses.item}`] = {
        maxWidth: 'none'
      };
    }
    return output;
  });
}

/**
 * Extracts zero value breakpoint keys before a non-zero value breakpoint key.
 * @example { xs: 0, sm: 0, md: 2, lg: 0, xl: 0 } or [0, 0, 2, 0, 0]
 * @returns [xs, sm]
 */
function extractZeroValueBreakpointKeys({
  breakpoints,
  values
}) {
  let nonZeroKey = '';
  Object.keys(values).forEach(key => {
    if (nonZeroKey !== '') {
      return;
    }
    if (values[key] !== 0) {
      nonZeroKey = key;
    }
  });
  const sortedBreakpointKeysByValue = Object.keys(breakpoints).sort((a, b) => {
    return breakpoints[a] - breakpoints[b];
  });
  return sortedBreakpointKeysByValue.slice(0, sortedBreakpointKeysByValue.indexOf(nonZeroKey));
}
function generateRowGap({
  theme,
  ownerState
}) {
  const {
    container,
    rowSpacing
  } = ownerState;
  let styles = {};
  if (container && rowSpacing !== 0) {
    const rowSpacingValues = resolveBreakpointValues({
      values: rowSpacing,
      breakpoints: theme.breakpoints.values
    });
    let zeroValueBreakpointKeys;
    if (typeof rowSpacingValues === 'object') {
      zeroValueBreakpointKeys = extractZeroValueBreakpointKeys({
        breakpoints: theme.breakpoints.values,
        values: rowSpacingValues
      });
    }
    styles = handleBreakpoints({
      theme
    }, rowSpacingValues, (propValue, breakpoint) => {
      var _zeroValueBreakpointK;
      const themeSpacing = theme.spacing(propValue);
      if (themeSpacing !== '0px') {
        return {
          marginTop: `-${getOffset(themeSpacing)}`,
          [`& > .${gridClasses.item}`]: {
            paddingTop: getOffset(themeSpacing)
          }
        };
      }
      if ((_zeroValueBreakpointK = zeroValueBreakpointKeys) != null && _zeroValueBreakpointK.includes(breakpoint)) {
        return {};
      }
      return {
        marginTop: 0,
        [`& > .${gridClasses.item}`]: {
          paddingTop: 0
        }
      };
    });
  }
  return styles;
}
function generateColumnGap({
  theme,
  ownerState
}) {
  const {
    container,
    columnSpacing
  } = ownerState;
  let styles = {};
  if (container && columnSpacing !== 0) {
    const columnSpacingValues = resolveBreakpointValues({
      values: columnSpacing,
      breakpoints: theme.breakpoints.values
    });
    let zeroValueBreakpointKeys;
    if (typeof columnSpacingValues === 'object') {
      zeroValueBreakpointKeys = extractZeroValueBreakpointKeys({
        breakpoints: theme.breakpoints.values,
        values: columnSpacingValues
      });
    }
    styles = handleBreakpoints({
      theme
    }, columnSpacingValues, (propValue, breakpoint) => {
      var _zeroValueBreakpointK2;
      const themeSpacing = theme.spacing(propValue);
      if (themeSpacing !== '0px') {
        return {
          width: `calc(100% + ${getOffset(themeSpacing)})`,
          marginLeft: `-${getOffset(themeSpacing)}`,
          [`& > .${gridClasses.item}`]: {
            paddingLeft: getOffset(themeSpacing)
          }
        };
      }
      if ((_zeroValueBreakpointK2 = zeroValueBreakpointKeys) != null && _zeroValueBreakpointK2.includes(breakpoint)) {
        return {};
      }
      return {
        width: '100%',
        marginLeft: 0,
        [`& > .${gridClasses.item}`]: {
          paddingLeft: 0
        }
      };
    });
  }
  return styles;
}
function resolveSpacingStyles(spacing, breakpoints, styles = {}) {
  // undefined/null or `spacing` <= 0
  if (!spacing || spacing <= 0) {
    return [];
  }
  // in case of string/number `spacing`
  if (typeof spacing === 'string' && !Number.isNaN(Number(spacing)) || typeof spacing === 'number') {
    return [styles[`spacing-xs-${String(spacing)}`]];
  }
  // in case of object `spacing`
  const spacingStyles = [];
  breakpoints.forEach(breakpoint => {
    const value = spacing[breakpoint];
    if (Number(value) > 0) {
      spacingStyles.push(styles[`spacing-${breakpoint}-${String(value)}`]);
    }
  });
  return spacingStyles;
}

// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',
const GridRoot = styled$1('div', {
  name: 'MuiGrid',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    const {
      container,
      direction,
      item,
      spacing,
      wrap,
      zeroMinWidth,
      breakpoints
    } = ownerState;
    let spacingStyles = [];

    // in case of grid item
    if (container) {
      spacingStyles = resolveSpacingStyles(spacing, breakpoints, styles);
    }
    const breakpointsStyles = [];
    breakpoints.forEach(breakpoint => {
      const value = ownerState[breakpoint];
      if (value) {
        breakpointsStyles.push(styles[`grid-${breakpoint}-${String(value)}`]);
      }
    });
    return [styles.root, container && styles.container, item && styles.item, zeroMinWidth && styles.zeroMinWidth, ...spacingStyles, direction !== 'row' && styles[`direction-xs-${String(direction)}`], wrap !== 'wrap' && styles[`wrap-xs-${String(wrap)}`], ...breakpointsStyles];
  }
})(({
  ownerState
}) => _extends({
  boxSizing: 'border-box'
}, ownerState.container && {
  display: 'flex',
  flexWrap: 'wrap',
  width: '100%'
}, ownerState.item && {
  margin: 0 // For instance, it's useful when used with a `figure` element.
}, ownerState.zeroMinWidth && {
  minWidth: 0
}, ownerState.wrap !== 'wrap' && {
  flexWrap: ownerState.wrap
}), generateDirection, generateRowGap, generateColumnGap, generateGrid);
function resolveSpacingClasses(spacing, breakpoints) {
  // undefined/null or `spacing` <= 0
  if (!spacing || spacing <= 0) {
    return [];
  }
  // in case of string/number `spacing`
  if (typeof spacing === 'string' && !Number.isNaN(Number(spacing)) || typeof spacing === 'number') {
    return [`spacing-xs-${String(spacing)}`];
  }
  // in case of object `spacing`
  const classes = [];
  breakpoints.forEach(breakpoint => {
    const value = spacing[breakpoint];
    if (Number(value) > 0) {
      const className = `spacing-${breakpoint}-${String(value)}`;
      classes.push(className);
    }
  });
  return classes;
}
const useUtilityClasses$6 = ownerState => {
  const {
    classes,
    container,
    direction,
    item,
    spacing,
    wrap,
    zeroMinWidth,
    breakpoints
  } = ownerState;
  let spacingClasses = [];

  // in case of grid item
  if (container) {
    spacingClasses = resolveSpacingClasses(spacing, breakpoints);
  }
  const breakpointsClasses = [];
  breakpoints.forEach(breakpoint => {
    const value = ownerState[breakpoint];
    if (value) {
      breakpointsClasses.push(`grid-${breakpoint}-${String(value)}`);
    }
  });
  const slots = {
    root: ['root', container && 'container', item && 'item', zeroMinWidth && 'zeroMinWidth', ...spacingClasses, direction !== 'row' && `direction-xs-${String(direction)}`, wrap !== 'wrap' && `wrap-xs-${String(wrap)}`, ...breakpointsClasses]
  };
  return composeClasses(slots, getGridUtilityClass, classes);
};
const Grid = /*#__PURE__*/reactExports$1.forwardRef(function Grid(inProps, ref) {
  const themeProps = useThemeProps({
    props: inProps,
    name: 'MuiGrid'
  });
  const {
    breakpoints
  } = useTheme();
  const props = extendSxProp(themeProps);
  const {
      className,
      columns: columnsProp,
      columnSpacing: columnSpacingProp,
      component = 'div',
      container = false,
      direction = 'row',
      item = false,
      rowSpacing: rowSpacingProp,
      spacing = 0,
      wrap = 'wrap',
      zeroMinWidth = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$8);
  const rowSpacing = rowSpacingProp || spacing;
  const columnSpacing = columnSpacingProp || spacing;
  const columnsContext = reactExports$1.useContext(GridContext$1);

  // columns set with default breakpoint unit of 12
  const columns = container ? columnsProp || 12 : columnsContext;
  const breakpointsValues = {};
  const otherFiltered = _extends({}, other);
  breakpoints.keys.forEach(breakpoint => {
    if (other[breakpoint] != null) {
      breakpointsValues[breakpoint] = other[breakpoint];
      delete otherFiltered[breakpoint];
    }
  });
  const ownerState = _extends({}, props, {
    columns,
    container,
    direction,
    item,
    rowSpacing,
    columnSpacing,
    wrap,
    zeroMinWidth,
    spacing
  }, breakpointsValues, {
    breakpoints: breakpoints.keys
  });
  const classes = useUtilityClasses$6(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(GridContext$1.Provider, {
    value: columns,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(GridRoot, _extends({
      ownerState: ownerState,
      className: clsx(classes.root, className),
      as: component,
      ref: ref
    }, otherFiltered))
  });
});
Grid.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The number of columns.
   * @default 12
   */
  columns: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number, PropTypes.object]),
  /**
   * Defines the horizontal space between the type `item` components.
   * It overrides the value of the `spacing` prop.
   */
  columnSpacing: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])), PropTypes.number, PropTypes.object, PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * If `true`, the component will have the flex *container* behavior.
   * You should be wrapping *items* with a *container*.
   * @default false
   */
  container: PropTypes.bool,
  /**
   * Defines the `flex-direction` style property.
   * It is applied for all screen sizes.
   * @default 'row'
   */
  direction: PropTypes.oneOfType([PropTypes.oneOf(['column-reverse', 'column', 'row-reverse', 'row']), PropTypes.arrayOf(PropTypes.oneOf(['column-reverse', 'column', 'row-reverse', 'row'])), PropTypes.object]),
  /**
   * If `true`, the component will have the flex *item* behavior.
   * You should be wrapping *items* with a *container*.
   * @default false
   */
  item: PropTypes.bool,
  /**
   * If a number, it sets the number of columns the grid item uses.
   * It can't be greater than the total number of columns of the container (12 by default).
   * If 'auto', the grid item's width matches its content.
   * If false, the prop is ignored.
   * If true, the grid item's width grows to use the space available in the grid container.
   * The value is applied for the `lg` breakpoint and wider screens if not overridden.
   * @default false
   */
  lg: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.bool]),
  /**
   * If a number, it sets the number of columns the grid item uses.
   * It can't be greater than the total number of columns of the container (12 by default).
   * If 'auto', the grid item's width matches its content.
   * If false, the prop is ignored.
   * If true, the grid item's width grows to use the space available in the grid container.
   * The value is applied for the `md` breakpoint and wider screens if not overridden.
   * @default false
   */
  md: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.bool]),
  /**
   * Defines the vertical space between the type `item` components.
   * It overrides the value of the `spacing` prop.
   */
  rowSpacing: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])), PropTypes.number, PropTypes.object, PropTypes.string]),
  /**
   * If a number, it sets the number of columns the grid item uses.
   * It can't be greater than the total number of columns of the container (12 by default).
   * If 'auto', the grid item's width matches its content.
   * If false, the prop is ignored.
   * If true, the grid item's width grows to use the space available in the grid container.
   * The value is applied for the `sm` breakpoint and wider screens if not overridden.
   * @default false
   */
  sm: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.bool]),
  /**
   * Defines the space between the type `item` components.
   * It can only be used on a type `container` component.
   * @default 0
   */
  spacing: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])), PropTypes.number, PropTypes.object, PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Defines the `flex-wrap` style property.
   * It's applied for all screen sizes.
   * @default 'wrap'
   */
  wrap: PropTypes.oneOf(['nowrap', 'wrap-reverse', 'wrap']),
  /**
   * If a number, it sets the number of columns the grid item uses.
   * It can't be greater than the total number of columns of the container (12 by default).
   * If 'auto', the grid item's width matches its content.
   * If false, the prop is ignored.
   * If true, the grid item's width grows to use the space available in the grid container.
   * The value is applied for the `xl` breakpoint and wider screens if not overridden.
   * @default false
   */
  xl: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.bool]),
  /**
   * If a number, it sets the number of columns the grid item uses.
   * It can't be greater than the total number of columns of the container (12 by default).
   * If 'auto', the grid item's width matches its content.
   * If false, the prop is ignored.
   * If true, the grid item's width grows to use the space available in the grid container.
   * The value is applied for all the screen sizes with the lowest priority.
   * @default false
   */
  xs: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.bool]),
  /**
   * If `true`, it sets `min-width: 0` on the item.
   * Refer to the limitations section of the documentation to better understand the use case.
   * @default false
   */
  zeroMinWidth: PropTypes.bool
} ;
{
  const requireProp = requirePropFactory('Grid', Grid);
  // eslint-disable-next-line no-useless-concat
  Grid['propTypes' + ''] = _extends({}, Grid.propTypes, {
    direction: requireProp('container'),
    lg: requireProp('item'),
    md: requireProp('item'),
    sm: requireProp('item'),
    spacing: requireProp('container'),
    wrap: requireProp('container'),
    xs: requireProp('item'),
    zeroMinWidth: requireProp('item')
  });
}
var Grid$1 = Grid;

const _excluded$7 = ["initialWidth", "width"];
const breakpointKeys = ['xs', 'sm', 'md', 'lg', 'xl'];

// By default, returns true if screen width is the same or greater than the given breakpoint.
const isWidthUp = (breakpoint, width, inclusive = true) => {
  if (inclusive) {
    return breakpointKeys.indexOf(breakpoint) <= breakpointKeys.indexOf(width);
  }
  return breakpointKeys.indexOf(breakpoint) < breakpointKeys.indexOf(width);
};

// By default, returns true if screen width is less than the given breakpoint.
const isWidthDown = (breakpoint, width, inclusive = false) => {
  if (inclusive) {
    return breakpointKeys.indexOf(width) <= breakpointKeys.indexOf(breakpoint);
  }
  return breakpointKeys.indexOf(width) < breakpointKeys.indexOf(breakpoint);
};
const withWidth = (options = {}) => Component => {
  const {
    withTheme: withThemeOption = false,
    noSSR = false,
    initialWidth: initialWidthOption
  } = options;
  function WithWidth(props) {
    const contextTheme = useTheme();
    const theme = props.theme || contextTheme;
    const _getThemeProps = getThemeProps({
        theme,
        name: 'MuiWithWidth',
        props
      }),
      {
        initialWidth,
        width
      } = _getThemeProps,
      other = _objectWithoutPropertiesLoose$2(_getThemeProps, _excluded$7);
    const [mountedState, setMountedState] = reactExports$1.useState(false);
    useEnhancedEffect$1(() => {
      setMountedState(true);
    }, []);

    /**
     * innerWidth |xs      sm      md      lg      xl
     *            |-------|-------|-------|-------|------>
     * width      |  xs   |  sm   |  md   |  lg   |  xl
     */
    const keys = theme.breakpoints.keys.slice().reverse();
    const widthComputed = keys.reduce((output, key) => {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const matches = useMediaQuery(theme.breakpoints.up(key));
      return !output && matches ? key : output;
    }, null);
    const more = _extends({
      width: width || (mountedState || noSSR ? widthComputed : undefined) || initialWidth || initialWidthOption
    }, withThemeOption ? {
      theme
    } : {}, other);

    // When rendering the component on the server,
    // we have no idea about the client browser screen width.
    // In order to prevent blinks and help the reconciliation of the React tree
    // we are not rendering the child component.
    //
    // An alternative is to use the `initialWidth` property.
    if (more.width === undefined) {
      return null;
    }
    return /*#__PURE__*/jsxRuntimeExports.jsx(Component, _extends({}, more));
  }
  WithWidth.propTypes = {
    /**
     * As `window.innerWidth` is unavailable on the server,
     * we default to rendering an empty component during the first mount.
     * You might want to use a heuristic to approximate
     * the screen width of the client browser screen width.
     *
     * For instance, you could be using the user-agent or the client-hints.
     * https://caniuse.com/#search=client%20hint
     */
    initialWidth: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
    /**
     * @ignore
     */
    theme: PropTypes.object,
    /**
     * Bypass the width calculation logic.
     */
    width: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl'])
  } ;
  {
    WithWidth.displayName = `WithWidth(${getDisplayName(Component)})`;
  }
  return WithWidth;
};
var withWidth$1 = withWidth;

function HiddenJs(props) {
  const {
    children,
    only,
    width
  } = props;
  const theme = useTheme();
  let visible = true;

  // `only` check is faster to get out sooner if used.
  if (only) {
    if (Array.isArray(only)) {
      for (let i = 0; i < only.length; i += 1) {
        const breakpoint = only[i];
        if (width === breakpoint) {
          visible = false;
          break;
        }
      }
    } else if (only && width === only) {
      visible = false;
    }
  }

  // Allow `only` to be combined with other props. If already hidden, no need to check others.
  if (visible) {
    // determine visibility based on the smallest size up
    for (let i = 0; i < theme.breakpoints.keys.length; i += 1) {
      const breakpoint = theme.breakpoints.keys[i];
      const breakpointUp = props[`${breakpoint}Up`];
      const breakpointDown = props[`${breakpoint}Down`];
      if (breakpointUp && isWidthUp(breakpoint, width) || breakpointDown && isWidthDown(breakpoint, width)) {
        visible = false;
        break;
      }
    }
  }
  if (!visible) {
    return null;
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(reactExports$1.Fragment, {
    children: children
  });
}
HiddenJs.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * If `true`, screens this size and down are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  lgDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  lgUp: PropTypes.bool,
  /**
   * If `true`, screens this size and down are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  mdDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  mdUp: PropTypes.bool,
  /**
   * Hide the given breakpoint(s).
   */
  only: PropTypes.oneOfType([PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), PropTypes.arrayOf(PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']))]),
  /**
   * If `true`, screens this size and down are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  smDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  smUp: PropTypes.bool,
  /**
   * @ignore
   * width prop provided by withWidth decorator.
   */
  width: PropTypes.string.isRequired,
  /**
   * If `true`, screens this size and down are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  xlDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  xlUp: PropTypes.bool,
  /**
   * If `true`, screens this size and down are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  xsDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  // eslint-disable-next-line react/no-unused-prop-types
  xsUp: PropTypes.bool
} ;
{
  HiddenJs.propTypes = exactProp(HiddenJs.propTypes) ;
}
var HiddenJs$1 = withWidth$1()(HiddenJs);

function getHiddenCssUtilityClass(slot) {
  return generateUtilityClass('PrivateHiddenCss', slot);
}
generateUtilityClasses('PrivateHiddenCss', ['root', 'xlDown', 'xlUp', 'onlyXl', 'lgDown', 'lgUp', 'onlyLg', 'mdDown', 'mdUp', 'onlyMd', 'smDown', 'smUp', 'onlySm', 'xsDown', 'xsUp', 'onlyXs']);

const _excluded$6 = ["children", "className", "only"];
const useUtilityClasses$5 = ownerState => {
  const {
    classes,
    breakpoints
  } = ownerState;
  const slots = {
    root: ['root', ...breakpoints.map(({
      breakpoint,
      dir
    }) => {
      return dir === 'only' ? `${dir}${capitalize(breakpoint)}` : `${breakpoint}${capitalize(dir)}`;
    })]
  };
  return composeClasses(slots, getHiddenCssUtilityClass, classes);
};
const HiddenCssRoot = styled$1('div', {
  name: 'PrivateHiddenCss',
  slot: 'Root'
})(({
  theme,
  ownerState
}) => {
  const hidden = {
    display: 'none'
  };
  return _extends({}, ownerState.breakpoints.map(({
    breakpoint,
    dir
  }) => {
    if (dir === 'only') {
      return {
        [theme.breakpoints.only(breakpoint)]: hidden
      };
    }
    return dir === 'up' ? {
      [theme.breakpoints.up(breakpoint)]: hidden
    } : {
      [theme.breakpoints.down(breakpoint)]: hidden
    };
  }).reduce((r, o) => {
    Object.keys(o).forEach(k => {
      r[k] = o[k];
    });
    return r;
  }, {}));
});

/**
 * @ignore - internal component.
 */
function HiddenCss(props) {
  const {
      children,
      className,
      only
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$6);
  const theme = useTheme();
  {
    const unknownProps = Object.keys(other).filter(propName => {
      const isUndeclaredBreakpoint = !theme.breakpoints.keys.some(breakpoint => {
        return `${breakpoint}Up` === propName || `${breakpoint}Down` === propName;
      });
      return !['classes', 'theme', 'isRtl', 'sx'].includes(propName) && isUndeclaredBreakpoint;
    });
    if (unknownProps.length > 0) {
      console.error(`MUI: Unsupported props received by \`<Hidden implementation="css" />\`: ${unknownProps.join(', ')}. Did you forget to wrap this component in a ThemeProvider declaring these breakpoints?`);
    }
  }
  const breakpoints = [];
  for (let i = 0; i < theme.breakpoints.keys.length; i += 1) {
    const breakpoint = theme.breakpoints.keys[i];
    const breakpointUp = other[`${breakpoint}Up`];
    const breakpointDown = other[`${breakpoint}Down`];
    if (breakpointUp) {
      breakpoints.push({
        breakpoint,
        dir: 'up'
      });
    }
    if (breakpointDown) {
      breakpoints.push({
        breakpoint,
        dir: 'down'
      });
    }
  }
  if (only) {
    const onlyBreakpoints = Array.isArray(only) ? only : [only];
    onlyBreakpoints.forEach(breakpoint => {
      breakpoints.push({
        breakpoint,
        dir: 'only'
      });
    });
  }
  const ownerState = _extends({}, props, {
    breakpoints
  });
  const classes = useUtilityClasses$5(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(HiddenCssRoot, {
    className: clsx(classes.root, className),
    ownerState: ownerState,
    children: children
  });
}
HiddenCss.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Specify which implementation to use.  'js' is the default, 'css' works better for
   * server-side rendering.
   */
  implementation: PropTypes.oneOf(['js', 'css']),
  /**
   * If `true`, screens this size and down are hidden.
   */
  lgDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  lgUp: PropTypes.bool,
  /**
   * If `true`, screens this size and down are hidden.
   */
  mdDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  mdUp: PropTypes.bool,
  /**
   * Hide the given breakpoint(s).
   */
  only: PropTypes.oneOfType([PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), PropTypes.arrayOf(PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']))]),
  /**
   * If `true`, screens this size and down are hidden.
   */
  smDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  smUp: PropTypes.bool,
  /**
   * If `true`, screens this size and down are hidden.
   */
  xlDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  xlUp: PropTypes.bool,
  /**
   * If `true`, screens this size and down are hidden.
   */
  xsDown: PropTypes.bool,
  /**
   * If `true`, screens this size and up are hidden.
   */
  xsUp: PropTypes.bool
} ;

const _excluded$5 = ["implementation", "lgDown", "lgUp", "mdDown", "mdUp", "smDown", "smUp", "xlDown", "xlUp", "xsDown", "xsUp"];
function Hidden(props) {
  const {
      implementation = 'js',
      lgDown = false,
      lgUp = false,
      mdDown = false,
      mdUp = false,
      smDown = false,
      smUp = false,
      xlDown = false,
      xlUp = false,
      xsDown = false,
      xsUp = false
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$5);
  if (implementation === 'js') {
    return /*#__PURE__*/jsxRuntimeExports.jsx(HiddenJs$1, _extends({
      lgDown: lgDown,
      lgUp: lgUp,
      mdDown: mdDown,
      mdUp: mdUp,
      smDown: smDown,
      smUp: smUp,
      xlDown: xlDown,
      xlUp: xlUp,
      xsDown: xsDown,
      xsUp: xsUp
    }, other));
  }
  return /*#__PURE__*/jsxRuntimeExports.jsx(HiddenCss, _extends({
    lgDown: lgDown,
    lgUp: lgUp,
    mdDown: mdDown,
    mdUp: mdUp,
    smDown: smDown,
    smUp: smUp,
    xlDown: xlDown,
    xlUp: xlUp,
    xsDown: xsDown,
    xsUp: xsUp
  }, other));
}
Hidden.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Specify which implementation to use.  'js' is the default, 'css' works better for
   * server-side rendering.
   * @default 'js'
   */
  implementation: PropTypes.oneOf(['css', 'js']),
  /**
   * You can use this prop when choosing the `js` implementation with server-side rendering.
   *
   * As `window.innerWidth` is unavailable on the server,
   * we default to rendering an empty component during the first mount.
   * You might want to use a heuristic to approximate
   * the screen width of the client browser screen width.
   *
   * For instance, you could be using the user-agent or the client-hints.
   * https://caniuse.com/#search=client%20hint
   */
  initialWidth: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
  /**
   * If `true`, component is hidden on screens below (but not including) this size.
   * @default false
   */
  lgDown: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens this size and above.
   * @default false
   */
  lgUp: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens below (but not including) this size.
   * @default false
   */
  mdDown: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens this size and above.
   * @default false
   */
  mdUp: PropTypes.bool,
  /**
   * Hide the given breakpoint(s).
   */
  only: PropTypes.oneOfType([PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), PropTypes.arrayOf(PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']).isRequired)]),
  /**
   * If `true`, component is hidden on screens below (but not including) this size.
   * @default false
   */
  smDown: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens this size and above.
   * @default false
   */
  smUp: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens below (but not including) this size.
   * @default false
   */
  xlDown: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens this size and above.
   * @default false
   */
  xlUp: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens below (but not including) this size.
   * @default false
   */
  xsDown: PropTypes.bool,
  /**
   * If `true`, component is hidden on screens this size and above.
   * @default false
   */
  xsUp: PropTypes.bool
} ;

function getIconUtilityClass(slot) {
  return generateUtilityClass('MuiIcon', slot);
}
generateUtilityClasses('MuiIcon', ['root', 'colorPrimary', 'colorSecondary', 'colorAction', 'colorError', 'colorDisabled', 'fontSizeInherit', 'fontSizeSmall', 'fontSizeMedium', 'fontSizeLarge']);

const _excluded$4 = ["baseClassName", "className", "color", "component", "fontSize"];
const useUtilityClasses$4 = ownerState => {
  const {
    color,
    fontSize,
    classes
  } = ownerState;
  const slots = {
    root: ['root', color !== 'inherit' && `color${capitalize(color)}`, `fontSize${capitalize(fontSize)}`]
  };
  return composeClasses(slots, getIconUtilityClass, classes);
};
const IconRoot = styled$1('span', {
  name: 'MuiIcon',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize(ownerState.color)}`], styles[`fontSize${capitalize(ownerState.fontSize)}`]];
  }
})(({
  theme,
  ownerState
}) => ({
  userSelect: 'none',
  width: '1em',
  height: '1em',
  // Chrome fix for https://bugs.chromium.org/p/chromium/issues/detail?id=820541
  // To remove at some point.
  overflow: 'hidden',
  display: 'inline-block',
  // allow overflow hidden to take action
  textAlign: 'center',
  // support non-square icon
  flexShrink: 0,
  fontSize: {
    inherit: 'inherit',
    small: theme.typography.pxToRem(20),
    medium: theme.typography.pxToRem(24),
    large: theme.typography.pxToRem(36)
  }[ownerState.fontSize],
  // TODO v5 deprecate, v6 remove for sx
  color: {
    primary: (theme.vars || theme).palette.primary.main,
    secondary: (theme.vars || theme).palette.secondary.main,
    info: (theme.vars || theme).palette.info.main,
    success: (theme.vars || theme).palette.success.main,
    warning: (theme.vars || theme).palette.warning.main,
    action: (theme.vars || theme).palette.action.active,
    error: (theme.vars || theme).palette.error.main,
    disabled: (theme.vars || theme).palette.action.disabled,
    inherit: undefined
  }[ownerState.color]
}));
const Icon = /*#__PURE__*/reactExports$1.forwardRef(function Icon(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiIcon'
  });
  const {
      baseClassName = 'material-icons',
      className,
      color = 'inherit',
      component: Component = 'span',
      fontSize = 'medium'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$4);
  const ownerState = _extends({}, props, {
    baseClassName,
    color,
    component: Component,
    fontSize
  });
  const classes = useUtilityClasses$4(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(IconRoot, _extends({
    as: Component,
    className: clsx(baseClassName,
    // Prevent the translation of the text content.
    // The font relies on the exact text content to render the icon.
    'notranslate', classes.root, className),
    ownerState: ownerState,
    "aria-hidden": true,
    ref: ref
  }, other));
});
Icon.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The base class applied to the icon. Defaults to 'material-icons', but can be changed to any
   * other base class that suits the icon font you're using (e.g. material-icons-rounded, fas, etc).
   * @default 'material-icons'
   */
  baseClassName: PropTypes.string,
  /**
   * The name of the icon font ligature.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'inherit'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'action', 'disabled', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size.
   * @default 'medium'
   */
  fontSize: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'large', 'medium', 'small']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
Icon.muiName = 'Icon';
var Icon$1 = Icon;

function getImageListUtilityClass(slot) {
  return generateUtilityClass('MuiImageList', slot);
}
generateUtilityClasses('MuiImageList', ['root', 'masonry', 'quilted', 'standard', 'woven']);

/**
 * @ignore - internal component.
 * @type {React.Context<{} | {expanded: boolean, disabled: boolean, toggle: () => void}>}
 */
const ImageListContext = /*#__PURE__*/reactExports$1.createContext({});
{
  ImageListContext.displayName = 'ImageListContext';
}
var ImageListContext$1 = ImageListContext;

const _excluded$3 = ["children", "className", "cols", "component", "rowHeight", "gap", "style", "variant"];
const useUtilityClasses$3 = ownerState => {
  const {
    classes,
    variant
  } = ownerState;
  const slots = {
    root: ['root', variant]
  };
  return composeClasses(slots, getImageListUtilityClass, classes);
};
const ImageListRoot = styled$1('ul', {
  name: 'MuiImageList',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[ownerState.variant]];
  }
})(({
  ownerState
}) => {
  return _extends({
    display: 'grid',
    overflowY: 'auto',
    listStyle: 'none',
    padding: 0,
    // Add iOS momentum scrolling for iOS < 13.0
    WebkitOverflowScrolling: 'touch'
  }, ownerState.variant === 'masonry' && {
    display: 'block'
  });
});
const ImageList = /*#__PURE__*/reactExports$1.forwardRef(function ImageList(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiImageList'
  });
  const {
      children,
      className,
      cols = 2,
      component = 'ul',
      rowHeight = 'auto',
      gap = 4,
      style: styleProp,
      variant = 'standard'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$3);
  const contextValue = reactExports$1.useMemo(() => ({
    rowHeight,
    gap,
    variant
  }), [rowHeight, gap, variant]);
  reactExports$1.useEffect(() => {
    {
      // Detect Internet Explorer 8+
      if (document !== undefined && 'objectFit' in document.documentElement.style === false) {
        console.error(['MUI: ImageList v5+ no longer natively supports Internet Explorer.', 'Use v4 of this component instead, or polyfill CSS object-fit.'].join('\n'));
      }
    }
  }, []);
  const style = variant === 'masonry' ? _extends({
    columnCount: cols,
    columnGap: gap
  }, styleProp) : _extends({
    gridTemplateColumns: `repeat(${cols}, 1fr)`,
    gap
  }, styleProp);
  const ownerState = _extends({}, props, {
    component,
    gap,
    rowHeight,
    variant
  });
  const classes = useUtilityClasses$3(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ImageListRoot, _extends({
    as: component,
    className: clsx(classes.root, classes[variant], className),
    ref: ref,
    style: style,
    ownerState: ownerState
  }, other, {
    children: /*#__PURE__*/jsxRuntimeExports.jsx(ImageListContext$1.Provider, {
      value: contextValue,
      children: children
    })
  }));
});
ImageList.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally `ImageListItem`s.
   */
  children: PropTypes /* @typescript-to-proptypes-ignore */.node.isRequired,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Number of columns.
   * @default 2
   */
  cols: integerPropType,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The gap between items in px.
   * @default 4
   */
  gap: PropTypes.number,
  /**
   * The height of one row in px.
   * @default 'auto'
   */
  rowHeight: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number]),
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The variant to use.
   * @default 'standard'
   */
  variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['masonry', 'quilted', 'standard', 'woven']), PropTypes.string])
} ;
var ImageList$1 = ImageList;

function getImageListItemUtilityClass(slot) {
  return generateUtilityClass('MuiImageListItem', slot);
}
const imageListItemClasses = generateUtilityClasses('MuiImageListItem', ['root', 'img', 'standard', 'woven', 'masonry', 'quilted']);
var imageListItemClasses$1 = imageListItemClasses;

const _excluded$2 = ["children", "className", "cols", "component", "rows", "style"];
const useUtilityClasses$2 = ownerState => {
  const {
    classes,
    variant
  } = ownerState;
  const slots = {
    root: ['root', variant],
    img: ['img']
  };
  return composeClasses(slots, getImageListItemUtilityClass, classes);
};
const ImageListItemRoot = styled$1('li', {
  name: 'MuiImageListItem',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [{
      [`& .${imageListItemClasses$1.img}`]: styles.img
    }, styles.root, styles[ownerState.variant]];
  }
})(({
  ownerState
}) => _extends({
  display: 'block',
  position: 'relative'
}, ownerState.variant === 'standard' && {
  // For titlebar under list item
  display: 'flex',
  flexDirection: 'column'
}, ownerState.variant === 'woven' && {
  height: '100%',
  alignSelf: 'center',
  '&:nth-of-type(even)': {
    height: '70%'
  }
}, {
  [`& .${imageListItemClasses$1.img}`]: _extends({
    objectFit: 'cover',
    width: '100%',
    height: '100%',
    display: 'block'
  }, ownerState.variant === 'standard' && {
    height: 'auto',
    flexGrow: 1
  })
}));
const ImageListItem = /*#__PURE__*/reactExports$1.forwardRef(function ImageListItem(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiImageListItem'
  });

  // TODO: - Use jsdoc @default?: "cols rows default values are for docs only"
  const {
      children,
      className,
      cols = 1,
      component = 'li',
      rows = 1,
      style
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$2);
  const {
    rowHeight = 'auto',
    gap,
    variant
  } = reactExports$1.useContext(ImageListContext$1);
  let height = 'auto';
  if (variant === 'woven') {
    height = undefined;
  } else if (rowHeight !== 'auto') {
    height = rowHeight * rows + gap * (rows - 1);
  }
  const ownerState = _extends({}, props, {
    cols,
    component,
    gap,
    rowHeight,
    rows,
    variant
  });
  const classes = useUtilityClasses$2(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsx(ImageListItemRoot, _extends({
    as: component,
    className: clsx(classes.root, classes[variant], className),
    ref: ref,
    style: _extends({
      height,
      gridColumnEnd: variant !== 'masonry' ? `span ${cols}` : undefined,
      gridRowEnd: variant !== 'masonry' ? `span ${rows}` : undefined,
      marginBottom: variant === 'masonry' ? gap : undefined
    }, style),
    ownerState: ownerState
  }, other, {
    children: reactExports$1.Children.map(children, child => {
      if (! /*#__PURE__*/reactExports$1.isValidElement(child)) {
        return null;
      }
      {
        if (reactIsExports$1.isFragment(child)) {
          console.error(["MUI: The ImageListItem component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
        }
      }
      if (child.type === 'img' || isMuiElement(child, ['Image'])) {
        return /*#__PURE__*/reactExports$1.cloneElement(child, {
          className: clsx(classes.img, child.props.className)
        });
      }
      return child;
    })
  }));
});
ImageListItem.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The content of the component, normally an `<img>`.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Width of the item in number of grid columns.
   * @default 1
   */
  cols: integerPropType,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * Height of the item in number of grid rows.
   * @default 1
   */
  rows: integerPropType,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} ;
var ImageListItem$1 = ImageListItem;

function getImageListItemBarUtilityClass(slot) {
  return generateUtilityClass('MuiImageListItemBar', slot);
}
generateUtilityClasses('MuiImageListItemBar', ['root', 'positionBottom', 'positionTop', 'positionBelow', 'titleWrap', 'titleWrapBottom', 'titleWrapTop', 'titleWrapBelow', 'titleWrapActionPosLeft', 'titleWrapActionPosRight', 'title', 'subtitle', 'actionIcon', 'actionIconActionPosLeft', 'actionIconActionPosRight']);

const _excluded$1 = ["actionIcon", "actionPosition", "className", "subtitle", "title", "position"];
const useUtilityClasses$1 = ownerState => {
  const {
    classes,
    position,
    actionIcon,
    actionPosition
  } = ownerState;
  const slots = {
    root: ['root', `position${capitalize(position)}`],
    titleWrap: ['titleWrap', `titleWrap${capitalize(position)}`, actionIcon && `titleWrapActionPos${capitalize(actionPosition)}`],
    title: ['title'],
    subtitle: ['subtitle'],
    actionIcon: ['actionIcon', `actionIconActionPos${capitalize(actionPosition)}`]
  };
  return composeClasses(slots, getImageListItemBarUtilityClass, classes);
};
const ImageListItemBarRoot = styled$1('div', {
  name: 'MuiImageListItemBar',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`position${capitalize(ownerState.position)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  return _extends({
    position: 'absolute',
    left: 0,
    right: 0,
    background: 'rgba(0, 0, 0, 0.5)',
    display: 'flex',
    alignItems: 'center',
    fontFamily: theme.typography.fontFamily
  }, ownerState.position === 'bottom' && {
    bottom: 0
  }, ownerState.position === 'top' && {
    top: 0
  }, ownerState.position === 'below' && {
    position: 'relative',
    background: 'transparent',
    alignItems: 'normal'
  });
});
const ImageListItemBarTitleWrap = styled$1('div', {
  name: 'MuiImageListItemBar',
  slot: 'TitleWrap',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.titleWrap, styles[`titleWrap${capitalize(ownerState.position)}`], ownerState.actionIcon && styles[`titleWrapActionPos${capitalize(ownerState.actionPosition)}`]];
  }
})(({
  theme,
  ownerState
}) => {
  return _extends({
    flexGrow: 1,
    padding: '12px 16px',
    color: (theme.vars || theme).palette.common.white,
    overflow: 'hidden'
  }, ownerState.position === 'below' && {
    padding: '6px 0 12px',
    color: 'inherit'
  }, ownerState.actionIcon && ownerState.actionPosition === 'left' && {
    paddingLeft: 0
  }, ownerState.actionIcon && ownerState.actionPosition === 'right' && {
    paddingRight: 0
  });
});
const ImageListItemBarTitle = styled$1('div', {
  name: 'MuiImageListItemBar',
  slot: 'Title',
  overridesResolver: (props, styles) => styles.title
})(({
  theme
}) => {
  return {
    fontSize: theme.typography.pxToRem(16),
    lineHeight: '24px',
    textOverflow: 'ellipsis',
    overflow: 'hidden',
    whiteSpace: 'nowrap'
  };
});
const ImageListItemBarSubtitle = styled$1('div', {
  name: 'MuiImageListItemBar',
  slot: 'Subtitle',
  overridesResolver: (props, styles) => styles.subtitle
})(({
  theme
}) => {
  return {
    fontSize: theme.typography.pxToRem(12),
    lineHeight: 1,
    textOverflow: 'ellipsis',
    overflow: 'hidden',
    whiteSpace: 'nowrap'
  };
});
const ImageListItemBarActionIcon = styled$1('div', {
  name: 'MuiImageListItemBar',
  slot: 'ActionIcon',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.actionIcon, styles[`actionIconActionPos${capitalize(ownerState.actionPosition)}`]];
  }
})(({
  ownerState
}) => {
  return _extends({}, ownerState.actionPosition === 'left' && {
    order: -1
  });
});
const ImageListItemBar = /*#__PURE__*/reactExports$1.forwardRef(function ImageListItemBar(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiImageListItemBar'
  });
  const {
      actionIcon,
      actionPosition = 'right',
      className,
      subtitle,
      title,
      position = 'bottom'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded$1);
  const ownerState = _extends({}, props, {
    position,
    actionPosition
  });
  const classes = useUtilityClasses$1(ownerState);
  return /*#__PURE__*/jsxRuntimeExports.jsxs(ImageListItemBarRoot, _extends({
    ownerState: ownerState,
    className: clsx(classes.root, className),
    ref: ref
  }, other, {
    children: [/*#__PURE__*/jsxRuntimeExports.jsxs(ImageListItemBarTitleWrap, {
      ownerState: ownerState,
      className: classes.titleWrap,
      children: [/*#__PURE__*/jsxRuntimeExports.jsx(ImageListItemBarTitle, {
        className: classes.title,
        children: title
      }), subtitle ? /*#__PURE__*/jsxRuntimeExports.jsx(ImageListItemBarSubtitle, {
        className: classes.subtitle,
        children: subtitle
      }) : null]
    }), actionIcon ? /*#__PURE__*/jsxRuntimeExports.jsx(ImageListItemBarActionIcon, {
      ownerState: ownerState,
      className: classes.actionIcon,
      children: actionIcon
    }) : null]
  }));
});
ImageListItemBar.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * An IconButton element to be used as secondary action target
   * (primary action target is the item itself).
   */
  actionIcon: PropTypes.node,
  /**
   * Position of secondary action IconButton.
   * @default 'right'
   */
  actionPosition: PropTypes.oneOf(['left', 'right']),
  /**
   * @ignore
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Position of the title bar.
   * @default 'bottom'
   */
  position: PropTypes.oneOf(['below', 'bottom', 'top']),
  /**
   * String or element serving as subtitle (support text).
   */
  subtitle: PropTypes.node,
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * Title to be displayed.
   */
  title: PropTypes.node
} ;
var ImageListItemBar$1 = ImageListItemBar;

function getLinearProgressUtilityClass(slot) {
  return generateUtilityClass('MuiLinearProgress', slot);
}
generateUtilityClasses('MuiLinearProgress', ['root', 'colorPrimary', 'colorSecondary', 'determinate', 'indeterminate', 'buffer', 'query', 'dashed', 'dashedColorPrimary', 'dashedColorSecondary', 'bar', 'barColorPrimary', 'barColorSecondary', 'bar1Indeterminate', 'bar1Determinate', 'bar1Buffer', 'bar2Indeterminate', 'bar2Buffer']);

const _excluded = ["className", "color", "value", "valueBuffer", "variant"];
let _ = t => t,
  _t,
  _t2,
  _t3,
  _t4,
  _t5,
  _t6;
const TRANSITION_DURATION = 4; // seconds
const indeterminate1Keyframe = keyframes(_t || (_t = _`
  0% {
    left: -35%;
    right: 100%;
  }

  60% {
    left: 100%;
    right: -90%;
  }

  100% {
    left: 100%;
    right: -90%;
  }
`));
const indeterminate2Keyframe = keyframes(_t2 || (_t2 = _`
  0% {
    left: -200%;
    right: 100%;
  }

  60% {
    left: 107%;
    right: -8%;
  }

  100% {
    left: 107%;
    right: -8%;
  }
`));
const bufferKeyframe = keyframes(_t3 || (_t3 = _`
  0% {
    opacity: 1;
    background-position: 0 -23px;
  }

  60% {
    opacity: 0;
    background-position: 0 -23px;
  }

  100% {
    opacity: 1;
    background-position: -200px -23px;
  }
`));
const useUtilityClasses = ownerState => {
  const {
    classes,
    variant,
    color
  } = ownerState;
  const slots = {
    root: ['root', `color${capitalize(color)}`, variant],
    dashed: ['dashed', `dashedColor${capitalize(color)}`],
    bar1: ['bar', `barColor${capitalize(color)}`, (variant === 'indeterminate' || variant === 'query') && 'bar1Indeterminate', variant === 'determinate' && 'bar1Determinate', variant === 'buffer' && 'bar1Buffer'],
    bar2: ['bar', variant !== 'buffer' && `barColor${capitalize(color)}`, variant === 'buffer' && `color${capitalize(color)}`, (variant === 'indeterminate' || variant === 'query') && 'bar2Indeterminate', variant === 'buffer' && 'bar2Buffer']
  };
  return composeClasses(slots, getLinearProgressUtilityClass, classes);
};
const getColorShade = (theme, color) => {
  if (color === 'inherit') {
    return 'currentColor';
  }
  if (theme.vars) {
    return theme.vars.palette.LinearProgress[`${color}Bg`];
  }
  return theme.palette.mode === 'light' ? lighten(theme.palette[color].main, 0.62) : darken(theme.palette[color].main, 0.5);
};
const LinearProgressRoot = styled$1('span', {
  name: 'MuiLinearProgress',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, styles[`color${capitalize(ownerState.color)}`], styles[ownerState.variant]];
  }
})(({
  ownerState,
  theme
}) => _extends({
  position: 'relative',
  overflow: 'hidden',
  display: 'block',
  height: 4,
  zIndex: 0,
  // Fix Safari's bug during composition of different paint.
  '@media print': {
    colorAdjust: 'exact'
  },
  backgroundColor: getColorShade(theme, ownerState.color)
}, ownerState.color === 'inherit' && ownerState.variant !== 'buffer' && {
  backgroundColor: 'none',
  '&::before': {
    content: '""',
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'currentColor',
    opacity: 0.3
  }
}, ownerState.variant === 'buffer' && {
  backgroundColor: 'transparent'
}, ownerState.variant === 'query' && {
  transform: 'rotate(180deg)'
}));
const LinearProgressDashed = styled$1('span', {
  name: 'MuiLinearProgress',
  slot: 'Dashed',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.dashed, styles[`dashedColor${capitalize(ownerState.color)}`]];
  }
})(({
  ownerState,
  theme
}) => {
  const backgroundColor = getColorShade(theme, ownerState.color);
  return _extends({
    position: 'absolute',
    marginTop: 0,
    height: '100%',
    width: '100%'
  }, ownerState.color === 'inherit' && {
    opacity: 0.3
  }, {
    backgroundImage: `radial-gradient(${backgroundColor} 0%, ${backgroundColor} 16%, transparent 42%)`,
    backgroundSize: '10px 10px',
    backgroundPosition: '0 -23px'
  });
}, css(_t4 || (_t4 = _`
    animation: ${0} 3s infinite linear;
  `), bufferKeyframe));
const LinearProgressBar1 = styled$1('span', {
  name: 'MuiLinearProgress',
  slot: 'Bar1',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.bar, styles[`barColor${capitalize(ownerState.color)}`], (ownerState.variant === 'indeterminate' || ownerState.variant === 'query') && styles.bar1Indeterminate, ownerState.variant === 'determinate' && styles.bar1Determinate, ownerState.variant === 'buffer' && styles.bar1Buffer];
  }
})(({
  ownerState,
  theme
}) => _extends({
  width: '100%',
  position: 'absolute',
  left: 0,
  bottom: 0,
  top: 0,
  transition: 'transform 0.2s linear',
  transformOrigin: 'left',
  backgroundColor: ownerState.color === 'inherit' ? 'currentColor' : (theme.vars || theme).palette[ownerState.color].main
}, ownerState.variant === 'determinate' && {
  transition: `transform .${TRANSITION_DURATION}s linear`
}, ownerState.variant === 'buffer' && {
  zIndex: 1,
  transition: `transform .${TRANSITION_DURATION}s linear`
}), ({
  ownerState
}) => (ownerState.variant === 'indeterminate' || ownerState.variant === 'query') && css(_t5 || (_t5 = _`
      width: auto;
      animation: ${0} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
    `), indeterminate1Keyframe));
const LinearProgressBar2 = styled$1('span', {
  name: 'MuiLinearProgress',
  slot: 'Bar2',
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.bar, styles[`barColor${capitalize(ownerState.color)}`], (ownerState.variant === 'indeterminate' || ownerState.variant === 'query') && styles.bar2Indeterminate, ownerState.variant === 'buffer' && styles.bar2Buffer];
  }
})(({
  ownerState,
  theme
}) => _extends({
  width: '100%',
  position: 'absolute',
  left: 0,
  bottom: 0,
  top: 0,
  transition: 'transform 0.2s linear',
  transformOrigin: 'left'
}, ownerState.variant !== 'buffer' && {
  backgroundColor: ownerState.color === 'inherit' ? 'currentColor' : (theme.vars || theme).palette[ownerState.color].main
}, ownerState.color === 'inherit' && {
  opacity: 0.3
}, ownerState.variant === 'buffer' && {
  backgroundColor: getColorShade(theme, ownerState.color),
  transition: `transform .${TRANSITION_DURATION}s linear`
}), ({
  ownerState
}) => (ownerState.variant === 'indeterminate' || ownerState.variant === 'query') && css(_t6 || (_t6 = _`
      width: auto;
      animation: ${0} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
    `), indeterminate2Keyframe));

/**
 * ## ARIA
 *
 * If the progress bar is describing the loading progress of a particular region of a page,
 * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`
 * attribute to `true` on that region until it has finished loading.
 */
const LinearProgress = /*#__PURE__*/reactExports$1.forwardRef(function LinearProgress(inProps, ref) {
  const props = useThemeProps({
    props: inProps,
    name: 'MuiLinearProgress'
  });
  const {
      className,
      color = 'primary',
      value,
      valueBuffer,
      variant = 'indeterminate'
    } = props,
    other = _objectWithoutPropertiesLoose$2(props, _excluded);
  const ownerState = _extends({}, props, {
    color,
    variant
  });
  const classes = useUtilityClasses(ownerState);
  const theme = useTheme();
  const rootProps = {};
  const inlineStyles = {
    bar1: {},
    bar2: {}
  };
  if (variant === 'determinate' || variant === 'buffer') {
    if (value !== undefined) {
      rootProps['aria-valuenow'] = Math.round(value);
      rootProps['aria-valuemin'] = 0;
      rootProps['aria-valuemax'] = 100;
      let transform = value - 100;
      if (theme.direction === 'rtl') {
        transform = -transform;
      }
      inlineStyles.bar1.transform = `translateX(${transform}%)`;
    } else {
      console.error('MUI: You need to provide a value prop ' + 'when using the determinate or buffer variant of LinearProgress .');
    }
  }
  if (variant === 'buffer') {
    if (valueBuffer !== undefined) {
      let transform = (valueBuffer || 0) - 100;
      if (theme.direction === 'rtl') {
        transform = -transform;
      }
      inlineStyles.bar2.transform = `translateX(${transform}%)`;
    } else {
      console.error('MUI: You need to provide a valueBuffer prop ' + 'when using the buffer variant of LinearProgress.');
    }
  }
  return /*#__PURE__*/jsxRuntimeExports.jsxs(LinearProgressRoot, _extends({
    className: clsx(classes.root, className),
    ownerState: ownerState,
    role: "progressbar"
  }, rootProps, {
    ref: ref
  }, other, {
    children: [variant === 'buffer' ? /*#__PURE__*/jsxRuntimeExports.jsx(LinearProgressDashed, {
      className: classes.dashed,
      ownerState: ownerState
    }) : null, /*#__PURE__*/jsxRuntimeExports.jsx(LinearProgressBar1, {
      className: classes.bar1,
      ownerState: ownerState,
      style: inlineStyles.bar1
    }), variant === 'determinate' ? null : /*#__PURE__*/jsxRuntimeExports.jsx(LinearProgressBar2, {
      className: classes.bar2,
      ownerState: ownerState,
      style: inlineStyles.bar2
    })]
  }));
});
LinearProgress.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#adding-new-colors).
   * @default 'primary'
   */
  color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'primary', 'secondary']), PropTypes.string]),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
  /**
   * The value of the progress indicator for the determinate and buffer variants.
   * Value between 0 and 100.
   */
  value: PropTypes.number,
  /**
   * The value for the buffer variant.
   * Value between 0 and 100.
   */
  valueBuffer: PropTypes.number,
  /**
   * The variant to use.
   * Use indeterminate or query when there is no progress value.
   * @default 'indeterminate'
   */
  variant: PropTypes.oneOf(['buffer', 'determinate', 'indeterminate', 'query'])
} ;
var LinearProgress$1 = LinearProgress;

// For use with @wq/rollup-plugin
const modules = {
  react: React,
  "react/jsx-runtime": jsxRuntime,
  "react-dom": ReactDOM,
  "react-is": ReactIs$2,
  "prop-types": PropTypes,
  formik: formik,
  "@emotion/styled": newStyled,
  "@emotion/react": emReact,
  "@mui/utils": muiUtils,
  "@mui/material/utils": muiMaterialUtils,
  "react-map-gl": {
    default: Map$2,
    ...reactMapGlExports
  },
  "@mapbox/mapbox-gl-draw": MapboxDraw,
  "@mui/material": {
    Accordion: Accordion$2,
    AccordionDetails: AccordionDetails$1,
    AccordionSummary: AccordionSummary$1,
    Alert: Alert$1,
    AlertTitle: AlertTitle$1,
    AppBar: AppBar$1,
    Autocomplete: Autocomplete$1,
    Badge: Badge$1,
    BottomNavigation: BottomNavigation$1,
    BottomNavigationAction: BottomNavigationAction$2,
    Box: Box$1,
    Breadcrumbs: Breadcrumbs$2,
    Button: Button$2,
    ButtonBase: ButtonBase$1,
    Card: Card$1,
    CardContent: CardContent$1,
    Checkbox: Checkbox$1,
    Chip: Chip$2,
    CircularProgress: CircularProgress$1,
    Collapse: Collapse$1,
    CssBaseline,
    Dialog: Dialog$1,
    DialogActions: DialogActions$1,
    DialogContent: DialogContent$1,
    DialogTitle: DialogTitle$1,
    Divider: Divider$1,
    Drawer: Drawer$1,
    Fab: Fab$2,
    FormControl: FormControl$1,
    FormControlLabel: FormControlLabel$1,
    FormGroup: FormGroup$1,
    FormHelperText: FormHelperText$1,
    FormLabel: FormLabel$1,
    Grid: Grid$1,
    Hidden,
    Icon: Icon$1,
    IconButton: IconButton$2,
    ImageList: ImageList$1,
    ImageListItem: ImageListItem$1,
    ImageListItemBar: ImageListItemBar$1,
    InputLabel: InputLabel$1,
    LinearProgress: LinearProgress$1,
    Link: Link$2,
    List: List$2,
    ListItem: ListItem$2,
    ListItemIcon: ListItemIcon$1,
    ListItemSecondaryAction: ListItemSecondaryAction$1,
    ListItemText: ListItemText$1,
    ListSubheader: ListSubheader$1,
    Menu: Menu$2,
    MenuItem: MenuItem$1,
    Modal: Modal$1,
    Paper: Paper$1,
    Radio: Radio$2,
    Select: Select$3,
    SvgIcon: SvgIcon$1,
    Switch: Switch$1,
    Tab: Tab$1,
    Table: Table$1,
    TableBody: TableBody$1,
    TableCell: TableCell$1,
    TableContainer: TableContainer$1,
    TableHead: TableHead$1,
    TablePagination: TablePagination$1,
    TableRow: TableRow$1,
    Tabs: Tabs$1,
    TextField: TextField$2,
    ThemeProvider,
    ToggleButton: ToggleButton$1,
    ToggleButtonGroup: ToggleButtonGroup$2,
    Toolbar: Toolbar$1,
    Typography: Typography$1,
    createTheme: createTheme$1,
    useMediaQuery
  },
  "@wq/app": app,
  "@wq/react": {
    default: react,
    ...reactExports
  },
  "@wq/material": {
    default: material,
    ...materialExports
  },
  "@wq/map": {
    default: map,
    ...mapExports
  },
  "@wq/map-gl": {
    default: mapgl,
    ...mapglExports
  }
};
function notFound(moduleName, prop) {
  if (moduleName === "@mui/material") {
    return `${prop} is not included in wq.js's copy of ${moduleName}.` + ` Try importing ${moduleName}/${prop} directly,` + " or file an issue at https://github.com/wq/wq/issues";
  } else {
    return `${prop} not found in wq.js's copy of ${moduleName}!`;
  }
}
for (const [moduleName, value] of Object.entries(modules)) {
  modules[moduleName] = new Proxy(value, {
    get(target, prop) {
      if (!(prop in target)) {
        console.error(notFound(moduleName, prop));
        return () => null;
      }
      return Reflect.get(...arguments);
    }
  });
}

var version = "2.0.0";

mapgl.setEngine(window.maplibregl);
app.use([material, mapgl]);

var mapboxGl = {};

var printMsg = mapboxGl.printMsg = function () {
  console.log("This is a message from the demo package");
};

var index = /*#__PURE__*/_mergeNamespaces({
  __proto__: null,
  default: mapboxGl,
  printMsg: printMsg
}, [mapboxGl]);

export { app as default, modules, version };
//# sourceMappingURL=wq.dev.js.map
