{"ast":null,"code":"import _regeneratorRuntime from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js\";\nimport _asyncToGenerator from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js\";\nimport _defineProperty from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/defineProperty.js\";\nimport _createClass from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/createClass.js\";\nimport _classCallCheck from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/classCallCheck.js\";\nimport _inherits from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/inherits.js\";\nimport _createSuper from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/createSuper.js\";\nimport _wrapNativeSuper from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js\";\nimport _slicedToArray from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/slicedToArray.js\";\nimport _toArray from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/toArray.js\";\nimport _createForOfIteratorHelper from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js\";\nimport _toConsumableArray from \"C:/Users/user/Desktop/05mediaSocial/client/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js\";\n/**\n * @remix-run/router v1.2.1\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n  _extends = Object.assign ? Object.assign.bind() : function (target) {\n    for (var i = 1; i < arguments.length; i++) {\n      var source = arguments[i];\n      for (var key in source) {\n        if (Object.prototype.hasOwnProperty.call(source, key)) {\n          target[key] = source[key];\n        }\n      }\n    }\n    return target;\n  };\n  return _extends.apply(this, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n(function (Action) {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Action[\"Pop\"] = \"POP\";\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n\n  Action[\"Push\"] = \"PUSH\";\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n\n  Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\nvar PopStateEventType = \"popstate\";\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\n\nfunction createMemoryHistory(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  var _options = options,\n    _options$initialEntri = _options.initialEntries,\n    initialEntries = _options$initialEntri === void 0 ? [\"/\"] : _options$initialEntri,\n    initialIndex = _options.initialIndex,\n    _options$v5Compat = _options.v5Compat,\n    v5Compat = _options$v5Compat === void 0 ? false : _options$v5Compat;\n  var entries; // Declare so we can access from createMemoryLocation\n\n  entries = initialEntries.map(function (entry, index) {\n    return createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined);\n  });\n  var index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n  var action = Action.Pop;\n  var listener = null;\n  function clampIndex(n) {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation() {\n    return entries[index];\n  }\n  function createMemoryLocation(to, state, key) {\n    if (state === void 0) {\n      state = null;\n    }\n    var location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n    warning$1(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n    return location;\n  }\n  var history = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref: function createHref(to) {\n      return typeof to === \"string\" ? to : createPath(to);\n    },\n    encodeLocation: function encodeLocation(to) {\n      var path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\"\n      };\n    },\n    push: function push(to, state) {\n      action = Action.Push;\n      var nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({\n          action: action,\n          location: nextLocation\n        });\n      }\n    },\n    replace: function replace(to, state) {\n      action = Action.Replace;\n      var nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({\n          action: action,\n          location: nextLocation\n        });\n      }\n    },\n    go: function go(delta) {\n      action = Action.Pop;\n      index = clampIndex(index + delta);\n      if (listener) {\n        listener({\n          action: action,\n          location: getCurrentLocation()\n        });\n      }\n    },\n    listen: function listen(fn) {\n      listener = fn;\n      return function () {\n        listener = null;\n      };\n    }\n  };\n  return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\n\nfunction createBrowserHistory(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  function createBrowserLocation(window, globalHistory) {\n    var _window$location = window.location,\n      pathname = _window$location.pathname,\n      search = _window$location.search,\n      hash = _window$location.hash;\n    return createLocation(\"\", {\n      pathname: pathname,\n      search: search,\n      hash: hash\n    },\n    // state defaults to `null` because `window.history.state` does\n    globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n  }\n  function createBrowserHref(window, to) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n  return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\n\nfunction createHashHistory(options) {\n  if (options === void 0) {\n    options = {};\n  }\n  function createHashLocation(window, globalHistory) {\n    var _parsePath = parsePath(window.location.hash.substr(1)),\n      _parsePath$pathname = _parsePath.pathname,\n      pathname = _parsePath$pathname === void 0 ? \"/\" : _parsePath$pathname,\n      _parsePath$search = _parsePath.search,\n      search = _parsePath$search === void 0 ? \"\" : _parsePath$search,\n      _parsePath$hash = _parsePath.hash,\n      hash = _parsePath$hash === void 0 ? \"\" : _parsePath$hash;\n    return createLocation(\"\", {\n      pathname: pathname,\n      search: search,\n      hash: hash\n    },\n    // state defaults to `null` because `window.history.state` does\n    globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n  }\n  function createHashHref(window, to) {\n    var base = window.document.querySelector(\"base\");\n    var href = \"\";\n    if (base && base.getAttribute(\"href\")) {\n      var url = window.location.href;\n      var hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n  function validateHashLocation(location, to) {\n    warning$1(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n  }\n  return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\nfunction warning$1(cond, message) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n    try {\n      // Welcome to debugging history!\n      //\n      // This error is thrown as a convenience so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message); // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\n\nfunction getHistoryState(location) {\n  return {\n    usr: location.state,\n    key: location.key\n  };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\n\nfunction createLocation(current, to, state, key) {\n  if (state === void 0) {\n    state = null;\n  }\n  var location = _extends({\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\"\n  }, typeof to === \"string\" ? parsePath(to) : to, {\n    state: state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: to && to.key || key || createKey()\n  });\n  return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\n\nfunction createPath(_ref) {\n  var _ref$pathname = _ref.pathname,\n    pathname = _ref$pathname === void 0 ? \"/\" : _ref$pathname,\n    _ref$search = _ref.search,\n    search = _ref$search === void 0 ? \"\" : _ref$search,\n    _ref$hash = _ref.hash,\n    hash = _ref$hash === void 0 ? \"\" : _ref$hash;\n  if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\n\nfunction parsePath(path) {\n  var parsedPath = {};\n  if (path) {\n    var hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n    var searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n  return parsedPath;\n}\nfunction createClientSideURL(location) {\n  // window.location.origin is \"null\" (the literal string value) in Firefox\n  // under certain conditions, notably when serving from a local HTML file\n  // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n  var base = typeof window !== \"undefined\" && typeof window.location !== \"undefined\" && window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n  var href = typeof location === \"string\" ? location : createPath(location);\n  invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n  return new URL(href, base);\n}\nfunction getUrlBasedHistory(getLocation, _createHref, validateLocation, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  var _options2 = options,\n    _options2$window = _options2.window,\n    window = _options2$window === void 0 ? document.defaultView : _options2$window,\n    _options2$v5Compat = _options2.v5Compat,\n    v5Compat = _options2$v5Compat === void 0 ? false : _options2$v5Compat;\n  var globalHistory = window.history;\n  var action = Action.Pop;\n  var listener = null;\n  function handlePop() {\n    action = Action.Pop;\n    if (listener) {\n      listener({\n        action: action,\n        location: history.location\n      });\n    }\n  }\n  function push(to, state) {\n    action = Action.Push;\n    var location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n    var historyState = getHistoryState(location);\n    var url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/\n\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n    if (v5Compat && listener) {\n      listener({\n        action: action,\n        location: history.location\n      });\n    }\n  }\n  function replace(to, state) {\n    action = Action.Replace;\n    var location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n    var historyState = getHistoryState(location);\n    var url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n    if (v5Compat && listener) {\n      listener({\n        action: action,\n        location: history.location\n      });\n    }\n  }\n  var history = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen: function listen(fn) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n      return function () {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref: function createHref(to) {\n      return _createHref(window, to);\n    },\n    encodeLocation: function encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      var url = createClientSideURL(typeof to === \"string\" ? to : createPath(to));\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash\n      };\n    },\n    push: push,\n    replace: replace,\n    go: function go(n) {\n      return globalHistory.go(n);\n    }\n  };\n  return history;\n} //#endregion\n\nvar ResultType;\n(function (ResultType) {\n  ResultType[\"data\"] = \"data\";\n  ResultType[\"deferred\"] = \"deferred\";\n  ResultType[\"redirect\"] = \"redirect\";\n  ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nfunction isIndexRoute(route) {\n  return route.index === true;\n} // Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\n\nfunction convertRoutesToDataRoutes(routes, parentPath, allIds) {\n  if (parentPath === void 0) {\n    parentPath = [];\n  }\n  if (allIds === void 0) {\n    allIds = new Set();\n  }\n  return routes.map(function (route, index) {\n    var treePath = [].concat(_toConsumableArray(parentPath), [index]);\n    var id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n    invariant(!allIds.has(id), \"Found a route id collision on id \\\"\" + id + \"\\\".  Route \" + \"id's must be globally unique within Data Router usages\");\n    allIds.add(id);\n    if (isIndexRoute(route)) {\n      var indexRoute = _extends({}, route, {\n        id: id\n      });\n      return indexRoute;\n    } else {\n      var pathOrLayoutRoute = _extends({}, route, {\n        id: id,\n        children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined\n      });\n      return pathOrLayoutRoute;\n    }\n  });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\n\nfunction matchRoutes(routes, locationArg, basename) {\n  if (basename === void 0) {\n    basename = \"/\";\n  }\n  var location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n  var pathname = stripBasename(location.pathname || \"/\", basename);\n  if (pathname == null) {\n    return null;\n  }\n  var branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n  var matches = null;\n  for (var i = 0; matches == null && i < branches.length; ++i) {\n    matches = matchRouteBranch(branches[i],\n    // Incoming pathnames are generally encoded from either window.location\n    // or from router.navigate, but we want to match against the unencoded\n    // paths in the route definitions.  Memory router locations won't be\n    // encoded here but there also shouldn't be anything to decode so this\n    // should be a safe operation.  This avoids needing matchRoutes to be\n    // history-aware.\n    safelyDecodeURI(pathname));\n  }\n  return matches;\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n  if (branches === void 0) {\n    branches = [];\n  }\n  if (parentsMeta === void 0) {\n    parentsMeta = [];\n  }\n  if (parentPath === void 0) {\n    parentPath = \"\";\n  }\n  var flattenRoute = function flattenRoute(route, index, relativePath) {\n    var meta = {\n      relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route: route\n    };\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(meta.relativePath.startsWith(parentPath), \"Absolute route path \\\"\" + meta.relativePath + \"\\\" nested under path \" + (\"\\\"\" + parentPath + \"\\\" is not valid. An absolute child route path \") + \"must start with the combined path of all its parent routes.\");\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n    var path = joinPaths([parentPath, meta.relativePath]);\n    var routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n\n    if (route.children && route.children.length > 0) {\n      invariant(\n      // Our types know better, but runtime JS may not!\n      // @ts-expect-error\n      route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n      flattenRoutes(route.children, branches, routesMeta, path);\n    } // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n\n    if (route.path == null && !route.index) {\n      return;\n    }\n    branches.push({\n      path: path,\n      score: computeScore(path, route.index),\n      routesMeta: routesMeta\n    });\n  };\n  routes.forEach(function (route, index) {\n    var _route$path;\n\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !((_route$path = route.path) != null && _route$path.includes(\"?\"))) {\n      flattenRoute(route, index);\n    } else {\n      var _iterator = _createForOfIteratorHelper(explodeOptionalSegments(route.path)),\n        _step;\n      try {\n        for (_iterator.s(); !(_step = _iterator.n()).done;) {\n          var exploded = _step.value;\n          flattenRoute(route, index, exploded);\n        }\n      } catch (err) {\n        _iterator.e(err);\n      } finally {\n        _iterator.f();\n      }\n    }\n  });\n  return branches;\n}\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\n\nfunction explodeOptionalSegments(path) {\n  var segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n  var _segments = _toArray(segments),\n    first = _segments[0],\n    rest = _segments.slice(1); // Optional path segments are denoted by a trailing `?`\n\n  var isOptional = first.endsWith(\"?\"); // Compute the corresponding required segment: `foo?` -> `foo`\n\n  var required = first.replace(/\\?$/, \"\");\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n  var restExploded = explodeOptionalSegments(rest.join(\"/\"));\n  var result = []; // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explodes _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n\n  result.push.apply(result, _toConsumableArray(restExploded.map(function (subpath) {\n    return subpath === \"\" ? required : [required, subpath].join(\"/\");\n  }))); // Then if this is an optional value, add all child versions without\n\n  if (isOptional) {\n    result.push.apply(result, _toConsumableArray(restExploded));\n  } // for absolute paths, ensure `/` instead of empty segment\n\n  return result.map(function (exploded) {\n    return path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded;\n  });\n}\nfunction rankRouteBranches(branches) {\n  branches.sort(function (a, b) {\n    return a.score !== b.score ? b.score - a.score // Higher score first\n    : compareIndexes(a.routesMeta.map(function (meta) {\n      return meta.childrenIndex;\n    }), b.routesMeta.map(function (meta) {\n      return meta.childrenIndex;\n    }));\n  });\n}\nvar paramRe = /^:\\w+$/;\nvar dynamicSegmentValue = 3;\nvar indexRouteValue = 2;\nvar emptySegmentValue = 1;\nvar staticSegmentValue = 10;\nvar splatPenalty = -2;\nvar isSplat = function isSplat(s) {\n  return s === \"*\";\n};\nfunction computeScore(path, index) {\n  var segments = path.split(\"/\");\n  var initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n  return segments.filter(function (s) {\n    return !isSplat(s);\n  }).reduce(function (score, segment) {\n    return score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue);\n  }, initialScore);\n}\nfunction compareIndexes(a, b) {\n  var siblings = a.length === b.length && a.slice(0, -1).every(function (n, i) {\n    return n === b[i];\n  });\n  return siblings ?\n  // If two routes are siblings, we should try to match the earlier sibling\n  // first. This allows people to have fine-grained control over the matching\n  // behavior by simply putting routes with identical paths in the order they\n  // want them tried.\n  a[a.length - 1] - b[b.length - 1] :\n  // Otherwise, it doesn't really make sense to rank non-siblings by index,\n  // so they sort equally.\n  0;\n}\nfunction matchRouteBranch(branch, pathname) {\n  var routesMeta = branch.routesMeta;\n  var matchedParams = {};\n  var matchedPathname = \"/\";\n  var matches = [];\n  for (var i = 0; i < routesMeta.length; ++i) {\n    var meta = routesMeta[i];\n    var end = i === routesMeta.length - 1;\n    var remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n    var match = matchPath({\n      path: meta.relativePath,\n      caseSensitive: meta.caseSensitive,\n      end: end\n    }, remainingPathname);\n    if (!match) return null;\n    Object.assign(matchedParams, match.params);\n    var route = meta.route;\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n      route: route\n    });\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n  return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\n\nfunction generatePath(originalPath, params) {\n  if (params === void 0) {\n    params = {};\n  }\n  var path = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(false, \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n    path = path.replace(/\\*$/, \"/*\");\n  }\n  return path.replace(/^:(\\w+)/g, function (_, key) {\n    invariant(params[key] != null, \"Missing \\\":\" + key + \"\\\" param\");\n    return params[key];\n  }).replace(/\\/:(\\w+)/g, function (_, key) {\n    invariant(params[key] != null, \"Missing \\\":\" + key + \"\\\" param\");\n    return \"/\" + params[key];\n  }).replace(/(\\/?)\\*/, function (_, prefix, __, str) {\n    var star = \"*\";\n    if (params[star] == null) {\n      // If no splat was provided, trim the trailing slash _unless_ it's\n      // the entire path\n      return str === \"/*\" ? \"/\" : \"\";\n    } // Apply the splat\n\n    return \"\" + prefix + params[star];\n  });\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\n\nfunction matchPath(pattern, pathname) {\n  if (typeof pattern === \"string\") {\n    pattern = {\n      path: pattern,\n      caseSensitive: false,\n      end: true\n    };\n  }\n  var _compilePath = compilePath(pattern.path, pattern.caseSensitive, pattern.end),\n    _compilePath2 = _slicedToArray(_compilePath, 2),\n    matcher = _compilePath2[0],\n    paramNames = _compilePath2[1];\n  var match = pathname.match(matcher);\n  if (!match) return null;\n  var matchedPathname = match[0];\n  var pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  var captureGroups = match.slice(1);\n  var params = paramNames.reduce(function (memo, paramName, index) {\n    // We need to compute the pathnameBase here using the raw splat value\n    // instead of using params[\"*\"] later because it will be decoded then\n    if (paramName === \"*\") {\n      var splatValue = captureGroups[index] || \"\";\n      pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n    }\n    memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || \"\", paramName);\n    return memo;\n  }, {});\n  return {\n    params: params,\n    pathname: matchedPathname,\n    pathnameBase: pathnameBase,\n    pattern: pattern\n  };\n}\nfunction compilePath(path, caseSensitive, end) {\n  if (caseSensitive === void 0) {\n    caseSensitive = false;\n  }\n  if (end === void 0) {\n    end = true;\n  }\n  warning(path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"), \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n  var paramNames = [];\n  var regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n  .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n  .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n  .replace(/\\/:(\\w+)/g, function (_, paramName) {\n    paramNames.push(paramName);\n    return \"/([^\\\\/]+)\";\n  });\n  if (path.endsWith(\"*\")) {\n    paramNames.push(\"*\");\n    regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n    : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else ;\n  var matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n  return [matcher, paramNames];\n}\nfunction safelyDecodeURI(value) {\n  try {\n    return decodeURI(value);\n  } catch (error) {\n    warning(false, \"The URL path \\\"\" + value + \"\\\" could not be decoded because it is is a \" + \"malformed URL segment. This is probably due to a bad percent \" + (\"encoding (\" + error + \").\"));\n    return value;\n  }\n}\nfunction safelyDecodeURIComponent(value, paramName) {\n  try {\n    return decodeURIComponent(value);\n  } catch (error) {\n    warning(false, \"The value for the URL param \\\"\" + paramName + \"\\\" will not be decoded because\" + (\" the string \\\"\" + value + \"\\\" is a malformed URL segment. This is probably\") + (\" due to a bad percent encoding (\" + error + \").\"));\n    return value;\n  }\n}\n/**\n * @private\n */\n\nfunction stripBasename(pathname, basename) {\n  if (basename === \"/\") return pathname;\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\n  } // We want to leave trailing slash behavior in the user's control, so if they\n  // specify a basename with a trailing slash, we should support it\n\n  var startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n  var nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n  return pathname.slice(startIndex) || \"/\";\n}\n/**\n * @private\n */\n\nfunction warning(cond, message) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n    try {\n      // Welcome to debugging React Router!\n      //\n      // This error is thrown as a convenience so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message); // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\n\nfunction resolvePath(to, fromPathname) {\n  if (fromPathname === void 0) {\n    fromPathname = \"/\";\n  }\n  var _ref11 = typeof to === \"string\" ? parsePath(to) : to,\n    toPathname = _ref11.pathname,\n    _ref11$search = _ref11.search,\n    search = _ref11$search === void 0 ? \"\" : _ref11$search,\n    _ref11$hash = _ref11.hash,\n    hash = _ref11$hash === void 0 ? \"\" : _ref11$hash;\n  var pathname = toPathname ? toPathname.startsWith(\"/\") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;\n  return {\n    pathname: pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash)\n  };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n  var segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  var relativeSegments = relativePath.split(\"/\");\n  relativeSegments.forEach(function (segment) {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length > 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n  return \"Cannot include a '\" + char + \"' character in a manually specified \" + (\"`to.\" + field + \"` field [\" + JSON.stringify(path) + \"].  Please separate it out to the \") + (\"`to.\" + dest + \"` field. Alternatively you may provide the full path as \") + \"a string in <Link to=\\\"...\\\"> and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\n\nfunction getPathContributingMatches(matches) {\n  return matches.filter(function (match, index) {\n    return index === 0 || match.route.path && match.route.path.length > 0;\n  });\n}\n/**\n * @private\n */\n\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n  if (isPathRelative === void 0) {\n    isPathRelative = false;\n  }\n  var to;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = _extends({}, toArg);\n    invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n    invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n    invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n  }\n  var isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  var toPathname = isEmptyPath ? \"/\" : to.pathname;\n  var from; // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n\n  if (isPathRelative || toPathname == null) {\n    from = locationPathname;\n  } else {\n    var routePathnameIndex = routePathnames.length - 1;\n    if (toPathname.startsWith(\"..\")) {\n      var toSegments = toPathname.split(\"/\"); // Each leading .. segment means \"go up one route\" instead of \"go up one\n      // URL segment\".  This is a key difference from how <a href> works and a\n      // major reason we call this a \"to\" value instead of a \"href\".\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n      to.pathname = toSegments.join(\"/\");\n    } // If there are more \"..\" segments than parent routes, resolve relative to\n    // the root / URL.\n\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n  var path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original \"to\" had one\n\n  var hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\"); // Or if this was a link to the current path which has a trailing slash\n\n  var hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n    path.pathname += \"/\";\n  }\n  return path;\n}\n/**\n * @private\n */\n\nfunction getToPathname(to) {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\n/**\n * @private\n */\n\nvar joinPaths = function joinPaths(paths) {\n  return paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n};\n/**\n * @private\n */\n\nvar normalizePathname = function normalizePathname(pathname) {\n  return pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n};\n/**\n * @private\n */\n\nvar normalizeSearch = function normalizeSearch(search) {\n  return !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n};\n/**\n * @private\n */\n\nvar normalizeHash = function normalizeHash(hash) {\n  return !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n};\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\n\nvar json = function json(data, init) {\n  if (init === void 0) {\n    init = {};\n  }\n  var responseInit = typeof init === \"number\" ? {\n    status: init\n  } : init;\n  var headers = new Headers(responseInit.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n  }\n  return new Response(JSON.stringify(data), _extends({}, responseInit, {\n    headers: headers\n  }));\n};\nvar AbortedDeferredError = /*#__PURE__*/function (_Error) {\n  _inherits(AbortedDeferredError, _Error);\n  var _super = _createSuper(AbortedDeferredError);\n  function AbortedDeferredError() {\n    _classCallCheck(this, AbortedDeferredError);\n    return _super.apply(this, arguments);\n  }\n  return _createClass(AbortedDeferredError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\nvar DeferredData = /*#__PURE__*/function () {\n  function DeferredData(data) {\n    var _this = this;\n    _classCallCheck(this, DeferredData);\n    this.pendingKeys = new Set();\n    this.subscriber = undefined;\n    invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\"); // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n\n    var reject;\n    this.abortPromise = new Promise(function (_, r) {\n      return reject = r;\n    });\n    this.controller = new AbortController();\n    var onAbort = function onAbort() {\n      return reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    };\n    this.unlistenAbortSignal = function () {\n      return _this.controller.signal.removeEventListener(\"abort\", onAbort);\n    };\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n    this.data = Object.entries(data).reduce(function (acc, _ref) {\n      var _ref12 = _slicedToArray(_ref, 2),\n        key = _ref12[0],\n        value = _ref12[1];\n      return Object.assign(acc, _defineProperty({}, key, _this.trackPromise(key, value)));\n    }, {});\n  }\n  _createClass(DeferredData, [{\n    key: \"trackPromise\",\n    value: function trackPromise(key, value) {\n      var _this2 = this;\n      if (!(value instanceof Promise)) {\n        return value;\n      }\n      this.pendingKeys.add(key); // We store a little wrapper promise that will be extended with\n      // _data/_error props upon resolve/reject\n\n      var promise = Promise.race([value, this.abortPromise]).then(function (data) {\n        return _this2.onSettle(promise, key, null, data);\n      }, function (error) {\n        return _this2.onSettle(promise, key, error);\n      }); // Register rejection listeners to avoid uncaught promise rejections on\n      // errors or aborted deferred values\n\n      promise.catch(function () {});\n      Object.defineProperty(promise, \"_tracked\", {\n        get: function get() {\n          return true;\n        }\n      });\n      return promise;\n    }\n  }, {\n    key: \"onSettle\",\n    value: function onSettle(promise, key, error, data) {\n      if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n        this.unlistenAbortSignal();\n        Object.defineProperty(promise, \"_error\", {\n          get: function get() {\n            return error;\n          }\n        });\n        return Promise.reject(error);\n      }\n      this.pendingKeys.delete(key);\n      if (this.done) {\n        // Nothing left to abort!\n        this.unlistenAbortSignal();\n      }\n      var subscriber = this.subscriber;\n      if (error) {\n        Object.defineProperty(promise, \"_error\", {\n          get: function get() {\n            return error;\n          }\n        });\n        subscriber && subscriber(false);\n        return Promise.reject(error);\n      }\n      Object.defineProperty(promise, \"_data\", {\n        get: function get() {\n          return data;\n        }\n      });\n      subscriber && subscriber(false);\n      return data;\n    }\n  }, {\n    key: \"subscribe\",\n    value: function subscribe(fn) {\n      this.subscriber = fn;\n    }\n  }, {\n    key: \"cancel\",\n    value: function cancel() {\n      var _this3 = this;\n      this.controller.abort();\n      this.pendingKeys.forEach(function (v, k) {\n        return _this3.pendingKeys.delete(k);\n      });\n      var subscriber = this.subscriber;\n      subscriber && subscriber(true);\n    }\n  }, {\n    key: \"resolveData\",\n    value: function () {\n      var _resolveData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(signal) {\n        var _this4 = this;\n        var aborted, onAbort;\n        return _regeneratorRuntime().wrap(function _callee$(_context) {\n          while (1) switch (_context.prev = _context.next) {\n            case 0:\n              aborted = false;\n              if (this.done) {\n                _context.next = 7;\n                break;\n              }\n              onAbort = function onAbort() {\n                return _this4.cancel();\n              };\n              signal.addEventListener(\"abort\", onAbort);\n              _context.next = 6;\n              return new Promise(function (resolve) {\n                _this4.subscribe(function (aborted) {\n                  signal.removeEventListener(\"abort\", onAbort);\n                  if (aborted || _this4.done) {\n                    resolve(aborted);\n                  }\n                });\n              });\n            case 6:\n              aborted = _context.sent;\n            case 7:\n              return _context.abrupt(\"return\", aborted);\n            case 8:\n            case \"end\":\n              return _context.stop();\n          }\n        }, _callee, this);\n      }));\n      function resolveData(_x) {\n        return _resolveData.apply(this, arguments);\n      }\n      return resolveData;\n    }()\n  }, {\n    key: \"done\",\n    get: function get() {\n      return this.pendingKeys.size === 0;\n    }\n  }, {\n    key: \"unwrappedData\",\n    get: function get() {\n      invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n      return Object.entries(this.data).reduce(function (acc, _ref2) {\n        var _ref13 = _slicedToArray(_ref2, 2),\n          key = _ref13[0],\n          value = _ref13[1];\n        return Object.assign(acc, _defineProperty({}, key, unwrapTrackedPromise(value)));\n      }, {});\n    }\n  }]);\n  return DeferredData;\n}();\nfunction isTrackedPromise(value) {\n  return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\nfunction defer(data) {\n  return new DeferredData(data);\n}\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\n\nvar redirect = function redirect(url, init) {\n  if (init === void 0) {\n    init = 302;\n  }\n  var responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = {\n      status: responseInit\n    };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n  var headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n  return new Response(null, _extends({}, responseInit, {\n    headers: headers\n  }));\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nvar ErrorResponse = /*#__PURE__*/_createClass(function ErrorResponse(status, statusText, data, internal) {\n  _classCallCheck(this, ErrorResponse);\n  if (internal === void 0) {\n    internal = false;\n  }\n  this.status = status;\n  this.statusText = statusText || \"\";\n  this.internal = internal;\n  if (data instanceof Error) {\n    this.data = data.toString();\n    this.error = data;\n  } else {\n    this.data = data;\n  }\n});\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response throw from an action/loader\n */\nfunction isRouteErrorResponse(e) {\n  return e instanceof ErrorResponse;\n}\nvar validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nvar validMutationMethods = new Set(validMutationMethodsArr);\nvar validRequestMethodsArr = [\"get\"].concat(validMutationMethodsArr);\nvar validRequestMethods = new Set(validRequestMethodsArr);\nvar redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nvar redirectPreserveMethodStatusCodes = new Set([307, 308]);\nvar IDLE_NAVIGATION = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined\n};\nvar IDLE_FETCHER = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined\n};\nvar isBrowser = typeof window !== \"undefined\" && typeof window.document !== \"undefined\" && typeof window.document.createElement !== \"undefined\";\nvar isServer = !isBrowser; //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\n\nfunction createRouter(init) {\n  invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n  var dataRoutes = convertRoutesToDataRoutes(init.routes); // Cleanup function for history\n\n  var unlistenHistory = null; // Externally-provided functions to call on all state changes\n\n  var subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing\n\n  var savedScrollPositions = null; // Externally-provided function to get scroll restoration keys\n\n  var getScrollRestorationKey = null; // Externally-provided function to get current scroll position\n\n  var getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n\n  var initialScrollRestored = init.hydrationData != null;\n  var initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);\n  var initialErrors = null;\n  if (initialMatches == null) {\n    // If we do not match a user-provided-route, fall back to the root\n    // to allow the error boundary to take over\n    var error = getInternalRouterError(404, {\n      pathname: init.history.location.pathname\n    });\n    var _getShortCircuitMatch = getShortCircuitMatches(dataRoutes),\n      matches = _getShortCircuitMatch.matches,\n      route = _getShortCircuitMatch.route;\n    initialMatches = matches;\n    initialErrors = _defineProperty({}, route.id, error);\n  }\n  var initialized = !initialMatches.some(function (m) {\n    return m.route.loader;\n  }) || init.hydrationData != null;\n  var router;\n  var state = {\n    historyAction: init.history.action,\n    location: init.history.location,\n    matches: initialMatches,\n    initialized: initialized,\n    navigation: IDLE_NAVIGATION,\n    // Don't restore on initial updateState() if we were SSR'd\n    restoreScrollPosition: init.hydrationData != null ? false : null,\n    preventScrollReset: false,\n    revalidation: \"idle\",\n    loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n    actionData: init.hydrationData && init.hydrationData.actionData || null,\n    errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n    fetchers: new Map()\n  }; // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n\n  var pendingAction = Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n\n  var pendingPreventScrollReset = false; // AbortController for the active navigation\n\n  var pendingNavigationController; // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n\n  var isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidate()\n  //  - X-Remix-Revalidate (from redirect)\n\n  var isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n\n  var cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n\n  var cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers\n\n  var fetchControllers = new Map(); // Track loads based on the order in which they started\n\n  var incrementingLoadId = 0; // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n\n  var pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions\n\n  var fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions\n\n  var fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers\n\n  var fetchLoadMatches = new Map(); // Store DeferredData instances for active route matches.  When a\n  // route loader returns defer() we stick one in here.  Then, when a nested\n  // promise resolves we update loaderData.  If a new navigation starts we\n  // cancel active deferreds for eliminated routes.\n\n  var activeDeferreds = new Map(); // Initialize the router, all side effects should be kicked off from here.\n  // Implemented as a Fluent API for ease of:\n  //   let router = createRouter(init).initialize();\n\n  function initialize() {\n    // If history informs us of a POP navigation, start the navigation but do not update\n    // state.  We'll update our own state once the navigation completes\n    unlistenHistory = init.history.listen(function (_ref) {\n      var historyAction = _ref.action,\n        location = _ref.location;\n      return startNavigation(historyAction, location);\n    }); // Kick off initial data load if needed.  Use Pop to avoid modifying history\n\n    if (!state.initialized) {\n      startNavigation(Action.Pop, state.location);\n    }\n    return router;\n  } // Clean up a router and it's side effects\n\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach(function (_, key) {\n      return deleteFetcher(key);\n    });\n  } // Subscribe to state updates for the router\n\n  function subscribe(fn) {\n    subscribers.add(fn);\n    return function () {\n      return subscribers.delete(fn);\n    };\n  } // Update our state and notify the calling context of the change\n\n  function updateState(newState) {\n    state = _extends({}, state, newState);\n    subscribers.forEach(function (subscriber) {\n      return subscriber(state);\n    });\n  } // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n  // and setting state.[historyAction/location/matches] to the new route.\n  // - Location is a required param\n  // - Navigation will always be set to IDLE_NAVIGATION\n  // - Can pass any other state in newState\n\n  function completeNavigation(location, newState) {\n    var _location$state;\n\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    var isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === \"loading\" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;\n    var actionData;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    } // Always preserve any existing loaderData from re-used routes\n\n    var loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n    updateState(_extends({}, newState, {\n      actionData: actionData,\n      loaderData: loaderData,\n      historyAction: pendingAction,\n      location: location,\n      initialized: true,\n      navigation: IDLE_NAVIGATION,\n      revalidation: \"idle\",\n      // Don't restore on submission navigations\n      restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches),\n      preventScrollReset: pendingPreventScrollReset\n    }));\n    if (isUninterruptedRevalidation) ;else if (pendingAction === Action.Pop) ;else if (pendingAction === Action.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === Action.Replace) {\n      init.history.replace(location, location.state);\n    } // Reset stateful navigation vars\n\n    pendingAction = Action.Pop;\n    pendingPreventScrollReset = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n    cancelledFetcherLoads = [];\n  } // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n  function navigate(_x2, _x3) {\n    return _navigate.apply(this, arguments);\n  } // Revalidate all current loaders.  If a navigation is in progress or if this\n  // is interrupted by a navigation, allow this to \"succeed\" by calling all\n  // loaders during the next loader round\n  function _navigate() {\n    _navigate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(to, opts) {\n      var _normalizeNavigateOpt2, path, submission, error, location, userReplace, historyAction, preventScrollReset;\n      return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n        while (1) switch (_context2.prev = _context2.next) {\n          case 0:\n            if (!(typeof to === \"number\")) {\n              _context2.next = 3;\n              break;\n            }\n            init.history.go(to);\n            return _context2.abrupt(\"return\");\n          case 3:\n            _normalizeNavigateOpt2 = normalizeNavigateOptions(to, opts), path = _normalizeNavigateOpt2.path, submission = _normalizeNavigateOpt2.submission, error = _normalizeNavigateOpt2.error;\n            location = createLocation(state.location, path, opts && opts.state); // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n            // URL from window.location, so we need to encode it here so the behavior\n            // remains the same as POP and non-data-router usages.  new URL() does all\n            // the same encoding we'd get from a history.pushState/window.location read\n            // without having to touch history\n            location = _extends({}, location, init.history.encodeLocation(location));\n            userReplace = opts && opts.replace != null ? opts.replace : undefined;\n            historyAction = Action.Push;\n            if (userReplace === true) {\n              historyAction = Action.Replace;\n            } else if (userReplace === false) ;else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\n              // By default on submissions to the current location we REPLACE so that\n              // users don't have to double-click the back button to get to the prior\n              // location.  If the user redirects to a different location from the\n              // action/loader this will be ignored and the redirect will be a PUSH\n              historyAction = Action.Replace;\n            }\n            preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n            _context2.next = 12;\n            return startNavigation(historyAction, location, {\n              submission: submission,\n              // Send through the formData serialization error if we have one so we can\n              // render at the right error boundary after we match routes\n              pendingError: error,\n              preventScrollReset: preventScrollReset,\n              replace: opts && opts.replace\n            });\n          case 12:\n            return _context2.abrupt(\"return\", _context2.sent);\n          case 13:\n          case \"end\":\n            return _context2.stop();\n        }\n      }, _callee2);\n    }));\n    return _navigate.apply(this, arguments);\n  }\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({\n      revalidation: \"loading\"\n    }); // If we're currently submitting an action, we don't need to start a new\n    // navigation, we'll just let the follow up loader execution call all loaders\n\n    if (state.navigation.state === \"submitting\") {\n      return;\n    } // If we're currently in an idle state, start a new navigation for the current\n    // action/location and mark it as uninterrupted, which will skip the history\n    // update in completeNavigation\n\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true\n      });\n      return;\n    } // Otherwise, if we're currently in a loading state, just start a new\n    // navigation to the navigation.location but do not trigger an uninterrupted\n    // revalidation so that history correctly updates once the navigation completes\n\n    startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n      overrideNavigation: state.navigation\n    });\n  } // Start a navigation to the given action/location.  Can optionally provide a\n  // overrideNavigation which will override the normalLoad in the case of a redirect\n  // navigation\n  function startNavigation(_x4, _x5, _x6) {\n    return _startNavigation.apply(this, arguments);\n  } // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  function _startNavigation() {\n    _startNavigation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(historyAction, location, opts) {\n      var loadingNavigation, matches, _error, _getShortCircuitMatch2, notFoundMatches, _route, request, pendingActionData, pendingError, actionOutput, navigation, _yield$handleLoaders, shortCircuited, loaderData, errors;\n      return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n        while (1) switch (_context3.prev = _context3.next) {\n          case 0:\n            // Abort any in-progress navigations and start a new one. Unset any ongoing\n            // uninterrupted revalidations unless told otherwise, since we want this\n            // new navigation to update history normally\n            pendingNavigationController && pendingNavigationController.abort();\n            pendingNavigationController = null;\n            pendingAction = historyAction;\n            isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; // Save the current scroll position every time we start a new navigation,\n            // and track whether we should reset scroll on completion\n\n            saveScrollPosition(state.location, state.matches);\n            pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n            loadingNavigation = opts && opts.overrideNavigation;\n            matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing\n            if (matches) {\n              _context3.next = 14;\n              break;\n            }\n            _error = getInternalRouterError(404, {\n              pathname: location.pathname\n            });\n            _getShortCircuitMatch2 = getShortCircuitMatches(dataRoutes), notFoundMatches = _getShortCircuitMatch2.matches, _route = _getShortCircuitMatch2.route; // Cancel all pending deferred on 404s since we don't keep any routes\n            cancelActiveDeferreds();\n            completeNavigation(location, {\n              matches: notFoundMatches,\n              loaderData: {},\n              errors: _defineProperty({}, _route.id, _error)\n            });\n            return _context3.abrupt(\"return\");\n          case 14:\n            if (!isHashChangeOnly(state.location, location)) {\n              _context3.next = 17;\n              break;\n            }\n            completeNavigation(location, {\n              matches: matches\n            });\n            return _context3.abrupt(\"return\");\n          case 17:\n            // Create a controller/Request for this navigation\n\n            pendingNavigationController = new AbortController();\n            request = createClientSideRequest(location, pendingNavigationController.signal, opts && opts.submission);\n            if (!(opts && opts.pendingError)) {\n              _context3.next = 23;\n              break;\n            }\n            // If we have a pendingError, it means the user attempted a GET submission\n            // with binary FormData so assign here and skip to handleLoaders.  That\n            // way we handle calling loaders above the boundary etc.  It's not really\n            // different from an actionError in that sense.\n            pendingError = _defineProperty({}, findNearestBoundary(matches).route.id, opts.pendingError);\n            _context3.next = 34;\n            break;\n          case 23:\n            if (!(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {\n              _context3.next = 34;\n              break;\n            }\n            _context3.next = 26;\n            return handleAction(request, location, opts.submission, matches, {\n              replace: opts.replace\n            });\n          case 26:\n            actionOutput = _context3.sent;\n            if (!actionOutput.shortCircuited) {\n              _context3.next = 29;\n              break;\n            }\n            return _context3.abrupt(\"return\");\n          case 29:\n            pendingActionData = actionOutput.pendingActionData;\n            pendingError = actionOutput.pendingActionError;\n            navigation = _extends({\n              state: \"loading\",\n              location: location\n            }, opts.submission);\n            loadingNavigation = navigation; // Create a GET request for the loaders\n\n            request = new Request(request.url, {\n              signal: request.signal\n            });\n          case 34:\n            _context3.next = 36;\n            return handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);\n          case 36:\n            _yield$handleLoaders = _context3.sent;\n            shortCircuited = _yield$handleLoaders.shortCircuited;\n            loaderData = _yield$handleLoaders.loaderData;\n            errors = _yield$handleLoaders.errors;\n            if (!shortCircuited) {\n              _context3.next = 42;\n              break;\n            }\n            return _context3.abrupt(\"return\");\n          case 42:\n            // Clean up now that the action/loaders have completed.  Don't clean up if\n            // we short circuited because pendingNavigationController will have already\n            // been assigned to a new controller for the next navigation\n\n            pendingNavigationController = null;\n            completeNavigation(location, _extends({\n              matches: matches\n            }, pendingActionData ? {\n              actionData: pendingActionData\n            } : {}, {\n              loaderData: loaderData,\n              errors: errors\n            }));\n          case 44:\n          case \"end\":\n            return _context3.stop();\n        }\n      }, _callee3);\n    }));\n    return _startNavigation.apply(this, arguments);\n  }\n  function handleAction(_x7, _x8, _x9, _x10, _x11) {\n    return _handleAction.apply(this, arguments);\n  } // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  function _handleAction() {\n    _handleAction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(request, location, submission, matches, opts) {\n      var navigation, result, actionMatch, replace, boundaryMatch;\n      return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n        while (1) switch (_context4.prev = _context4.next) {\n          case 0:\n            interruptActiveLoads(); // Put us in a submitting state\n            navigation = _extends({\n              state: \"submitting\",\n              location: location\n            }, submission);\n            updateState({\n              navigation: navigation\n            }); // Call our action and get the result\n            actionMatch = getTargetMatch(matches, location);\n            if (actionMatch.route.action) {\n              _context4.next = 8;\n              break;\n            }\n            result = {\n              type: ResultType.error,\n              error: getInternalRouterError(405, {\n                method: request.method,\n                pathname: location.pathname,\n                routeId: actionMatch.route.id\n              })\n            };\n            _context4.next = 13;\n            break;\n          case 8:\n            _context4.next = 10;\n            return callLoaderOrAction(\"action\", request, actionMatch, matches, router.basename);\n          case 10:\n            result = _context4.sent;\n            if (!request.signal.aborted) {\n              _context4.next = 13;\n              break;\n            }\n            return _context4.abrupt(\"return\", {\n              shortCircuited: true\n            });\n          case 13:\n            if (!isRedirectResult(result)) {\n              _context4.next = 18;\n              break;\n            }\n            if (opts && opts.replace != null) {\n              replace = opts.replace;\n            } else {\n              // If the user didn't explicity indicate replace behavior, replace if\n              // we redirected to the exact same location we're currently at to avoid\n              // double back-buttons\n              replace = result.location === state.location.pathname + state.location.search;\n            }\n            _context4.next = 17;\n            return startRedirectNavigation(state, result, {\n              submission: submission,\n              replace: replace\n            });\n          case 17:\n            return _context4.abrupt(\"return\", {\n              shortCircuited: true\n            });\n          case 18:\n            if (!isErrorResult(result)) {\n              _context4.next = 22;\n              break;\n            }\n            // Store off the pending error - we use it to determine which loaders\n            // to call and will commit it when we complete the navigation\n            boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // By default, all submissions are REPLACE navigations, but if the\n            // action threw an error that'll be rendered in an errorElement, we fall\n            // back to PUSH so that the user can use the back button to get back to\n            // the pre-submission form location to try again\n            if ((opts && opts.replace) !== true) {\n              pendingAction = Action.Push;\n            }\n            return _context4.abrupt(\"return\", {\n              // Send back an empty object we can use to clear out any prior actionData\n              pendingActionData: {},\n              pendingActionError: _defineProperty({}, boundaryMatch.route.id, result.error)\n            });\n          case 22:\n            if (!isDeferredResult(result)) {\n              _context4.next = 24;\n              break;\n            }\n            throw new Error(\"defer() is not supported in actions\");\n          case 24:\n            return _context4.abrupt(\"return\", {\n              pendingActionData: _defineProperty({}, actionMatch.route.id, result.data)\n            });\n          case 25:\n          case \"end\":\n            return _context4.stop();\n        }\n      }, _callee4);\n    }));\n    return _handleAction.apply(this, arguments);\n  }\n  function handleLoaders(_x12, _x13, _x14, _x15, _x16, _x17, _x18, _x19) {\n    return _handleLoaders.apply(this, arguments);\n  }\n  function _handleLoaders() {\n    _handleLoaders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {\n      var loadingNavigation, navigation, activeSubmission, _getMatchesToLoad, _getMatchesToLoad2, matchesToLoad, revalidatingFetchers, actionData, _yield$callLoadersAnd, results, loaderResults, fetcherResults, redirect, _processLoaderData, loaderData, errors, didAbortFetchLoads;\n      return _regeneratorRuntime().wrap(function _callee5$(_context5) {\n        while (1) switch (_context5.prev = _context5.next) {\n          case 0:\n            // Figure out the right navigation we want to use for data loading\n            loadingNavigation = overrideNavigation;\n            if (!loadingNavigation) {\n              navigation = _extends({\n                state: \"loading\",\n                location: location,\n                formMethod: undefined,\n                formAction: undefined,\n                formEncType: undefined,\n                formData: undefined\n              }, submission);\n              loadingNavigation = navigation;\n            } // If this was a redirect from an action we don't have a \"submission\" but\n            // we have it on the loading navigation so use that if available\n            activeSubmission = submission ? submission : loadingNavigation.formMethod && loadingNavigation.formAction && loadingNavigation.formData && loadingNavigation.formEncType ? {\n              formMethod: loadingNavigation.formMethod,\n              formAction: loadingNavigation.formAction,\n              formData: loadingNavigation.formData,\n              formEncType: loadingNavigation.formEncType\n            } : undefined;\n            _getMatchesToLoad = getMatchesToLoad(state, matches, activeSubmission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches), _getMatchesToLoad2 = _slicedToArray(_getMatchesToLoad, 2), matchesToLoad = _getMatchesToLoad2[0], revalidatingFetchers = _getMatchesToLoad2[1]; // Cancel pending deferreds for no-longer-matched routes or routes we're\n            // about to reload.  Note that if this is an action reload we would have\n            // already cancelled all pending deferreds so this would be a no-op\n            cancelActiveDeferreds(function (routeId) {\n              return !(matches && matches.some(function (m) {\n                return m.route.id === routeId;\n              })) || matchesToLoad && matchesToLoad.some(function (m) {\n                return m.route.id === routeId;\n              });\n            }); // Short circuit if we have no loaders to run\n            if (!(matchesToLoad.length === 0 && revalidatingFetchers.length === 0)) {\n              _context5.next = 8;\n              break;\n            }\n            completeNavigation(location, _extends({\n              matches: matches,\n              loaderData: {},\n              // Commit pending error if we're short circuiting\n              errors: pendingError || null\n            }, pendingActionData ? {\n              actionData: pendingActionData\n            } : {}));\n            return _context5.abrupt(\"return\", {\n              shortCircuited: true\n            });\n          case 8:\n            // If this is an uninterrupted revalidation, we remain in our current idle\n            // state.  If not, we need to switch to our loading state and load data,\n            // preserving any new action data or existing action data (in the case of\n            // a revalidation interrupting an actionReload)\n\n            if (!isUninterruptedRevalidation) {\n              revalidatingFetchers.forEach(function (_ref2) {\n                var _ref14 = _slicedToArray(_ref2, 1),\n                  key = _ref14[0];\n                var fetcher = state.fetchers.get(key);\n                var revalidatingFetcher = {\n                  state: \"loading\",\n                  data: fetcher && fetcher.data,\n                  formMethod: undefined,\n                  formAction: undefined,\n                  formEncType: undefined,\n                  formData: undefined,\n                  \" _hasFetcherDoneAnything \": true\n                };\n                state.fetchers.set(key, revalidatingFetcher);\n              });\n              actionData = pendingActionData || state.actionData;\n              updateState(_extends({\n                navigation: loadingNavigation\n              }, actionData ? Object.keys(actionData).length === 0 ? {\n                actionData: null\n              } : {\n                actionData: actionData\n              } : {}, revalidatingFetchers.length > 0 ? {\n                fetchers: new Map(state.fetchers)\n              } : {}));\n            }\n            pendingNavigationLoadId = ++incrementingLoadId;\n            revalidatingFetchers.forEach(function (_ref3) {\n              var _ref15 = _slicedToArray(_ref3, 1),\n                key = _ref15[0];\n              return fetchControllers.set(key, pendingNavigationController);\n            });\n            _context5.next = 13;\n            return callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);\n          case 13:\n            _yield$callLoadersAnd = _context5.sent;\n            results = _yield$callLoadersAnd.results;\n            loaderResults = _yield$callLoadersAnd.loaderResults;\n            fetcherResults = _yield$callLoadersAnd.fetcherResults;\n            if (!request.signal.aborted) {\n              _context5.next = 19;\n              break;\n            }\n            return _context5.abrupt(\"return\", {\n              shortCircuited: true\n            });\n          case 19:\n            // Clean up _after_ loaders have completed.  Don't clean up if we short\n            // circuited because fetchControllers would have been aborted and\n            // reassigned to new controllers for the next navigation\n\n            revalidatingFetchers.forEach(function (_ref4) {\n              var _ref16 = _slicedToArray(_ref4, 1),\n                key = _ref16[0];\n              return fetchControllers.delete(key);\n            }); // If any loaders returned a redirect Response, start a new REPLACE navigation\n            redirect = findRedirect(results);\n            if (!redirect) {\n              _context5.next = 25;\n              break;\n            }\n            _context5.next = 24;\n            return startRedirectNavigation(state, redirect, {\n              replace: replace\n            });\n          case 24:\n            return _context5.abrupt(\"return\", {\n              shortCircuited: true\n            });\n          case 25:\n            // Process and commit output from loaders\n            _processLoaderData = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds), loaderData = _processLoaderData.loaderData, errors = _processLoaderData.errors; // Wire up subscribers to update loaderData as promises settle\n            activeDeferreds.forEach(function (deferredData, routeId) {\n              deferredData.subscribe(function (aborted) {\n                // Note: No need to updateState here since the TrackedPromise on\n                // loaderData is stable across resolve/reject\n                // Remove this instance if we were aborted or if promises have settled\n                if (aborted || deferredData.done) {\n                  activeDeferreds.delete(routeId);\n                }\n              });\n            });\n            markFetchRedirectsDone();\n            didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n            return _context5.abrupt(\"return\", _extends({\n              loaderData: loaderData,\n              errors: errors\n            }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {\n              fetchers: new Map(state.fetchers)\n            } : {}));\n          case 30:\n          case \"end\":\n            return _context5.stop();\n        }\n      }, _callee5);\n    }));\n    return _handleLoaders.apply(this, arguments);\n  }\n  function getFetcher(key) {\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  } // Trigger a fetcher load/submit for the given fetcher key\n\n  function fetch(key, routeId, href, opts) {\n    if (isServer) {\n      throw new Error(\"router.fetch() was called during the server render, but it shouldn't be. \" + \"You are likely calling a useFetcher() method in the body of your component. \" + \"Try moving it to a useEffect or a callback.\");\n    }\n    if (fetchControllers.has(key)) abortFetcher(key);\n    var matches = matchRoutes(dataRoutes, href, init.basename);\n    if (!matches) {\n      setFetcherError(key, routeId, getInternalRouterError(404, {\n        pathname: href\n      }));\n      return;\n    }\n    var _normalizeNavigateOpt = normalizeNavigateOptions(href, opts, true),\n      path = _normalizeNavigateOpt.path,\n      submission = _normalizeNavigateOpt.submission;\n    var match = getTargetMatch(matches, path);\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(key, routeId, path, match, matches, submission);\n      return;\n    } // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n\n    fetchLoadMatches.set(key, [path, match, matches]);\n    handleFetcherLoader(key, routeId, path, match, matches, submission);\n  } // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  function handleFetcherAction(_x20, _x21, _x22, _x23, _x24, _x25) {\n    return _handleFetcherAction.apply(this, arguments);\n  } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  function _handleFetcherAction() {\n    _handleFetcherAction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(key, routeId, path, match, requestMatches, submission) {\n      var _error2, existingFetcher, fetcher, abortController, fetchRequest, actionResult, loadingFetcher, nextLocation, revalidationRequest, matches, loadId, loadFetcher, _getMatchesToLoad3, _getMatchesToLoad4, matchesToLoad, revalidatingFetchers, _yield$callLoadersAnd2, results, loaderResults, fetcherResults, redirect, _processLoaderData2, loaderData, errors, doneFetcher, didAbortFetchLoads;\n      return _regeneratorRuntime().wrap(function _callee6$(_context6) {\n        while (1) switch (_context6.prev = _context6.next) {\n          case 0:\n            interruptActiveLoads();\n            fetchLoadMatches.delete(key);\n            if (match.route.action) {\n              _context6.next = 6;\n              break;\n            }\n            _error2 = getInternalRouterError(405, {\n              method: submission.formMethod,\n              pathname: path,\n              routeId: routeId\n            });\n            setFetcherError(key, routeId, _error2);\n            return _context6.abrupt(\"return\");\n          case 6:\n            // Put this fetcher into it's submitting state\n            existingFetcher = state.fetchers.get(key);\n            fetcher = _extends({\n              state: \"submitting\"\n            }, submission, {\n              data: existingFetcher && existingFetcher.data,\n              \" _hasFetcherDoneAnything \": true\n            });\n            state.fetchers.set(key, fetcher);\n            updateState({\n              fetchers: new Map(state.fetchers)\n            }); // Call the action for the fetcher\n            abortController = new AbortController();\n            fetchRequest = createClientSideRequest(path, abortController.signal, submission);\n            fetchControllers.set(key, abortController);\n            _context6.next = 15;\n            return callLoaderOrAction(\"action\", fetchRequest, match, requestMatches, router.basename);\n          case 15:\n            actionResult = _context6.sent;\n            if (!fetchRequest.signal.aborted) {\n              _context6.next = 19;\n              break;\n            }\n            // We can delete this so long as we weren't aborted by ou our own fetcher\n            // re-submit which would have put _new_ controller is in fetchControllers\n            if (fetchControllers.get(key) === abortController) {\n              fetchControllers.delete(key);\n            }\n            return _context6.abrupt(\"return\");\n          case 19:\n            if (!isRedirectResult(actionResult)) {\n              _context6.next = 26;\n              break;\n            }\n            fetchControllers.delete(key);\n            fetchRedirectIds.add(key);\n            loadingFetcher = _extends({\n              state: \"loading\"\n            }, submission, {\n              data: undefined,\n              \" _hasFetcherDoneAnything \": true\n            });\n            state.fetchers.set(key, loadingFetcher);\n            updateState({\n              fetchers: new Map(state.fetchers)\n            });\n            return _context6.abrupt(\"return\", startRedirectNavigation(state, actionResult, {\n              isFetchActionRedirect: true\n            }));\n          case 26:\n            if (!isErrorResult(actionResult)) {\n              _context6.next = 29;\n              break;\n            }\n            setFetcherError(key, routeId, actionResult.error);\n            return _context6.abrupt(\"return\");\n          case 29:\n            if (isDeferredResult(actionResult)) {\n              invariant(false, \"defer() is not supported in actions\");\n            } // Start the data load for current matches, or the next location if we're\n            // in the middle of a navigation\n            nextLocation = state.navigation.location || state.location;\n            revalidationRequest = createClientSideRequest(nextLocation, abortController.signal);\n            matches = state.navigation.state !== \"idle\" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches;\n            invariant(matches, \"Didn't find any matches after fetcher action\");\n            loadId = ++incrementingLoadId;\n            fetchReloadIds.set(key, loadId);\n            loadFetcher = _extends({\n              state: \"loading\",\n              data: actionResult.data\n            }, submission, {\n              \" _hasFetcherDoneAnything \": true\n            });\n            state.fetchers.set(key, loadFetcher);\n            _getMatchesToLoad3 = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, _defineProperty({}, match.route.id, actionResult.data), undefined,\n            // No need to send through errors since we short circuit above\n            fetchLoadMatches), _getMatchesToLoad4 = _slicedToArray(_getMatchesToLoad3, 2), matchesToLoad = _getMatchesToLoad4[0], revalidatingFetchers = _getMatchesToLoad4[1]; // Put all revalidating fetchers into the loading state, except for the\n            // current fetcher which we want to keep in it's current loading state which\n            // contains it's action submission info + action data\n            revalidatingFetchers.filter(function (_ref5) {\n              var _ref17 = _slicedToArray(_ref5, 1),\n                staleKey = _ref17[0];\n              return staleKey !== key;\n            }).forEach(function (_ref6) {\n              var _ref18 = _slicedToArray(_ref6, 1),\n                staleKey = _ref18[0];\n              var existingFetcher = state.fetchers.get(staleKey);\n              var revalidatingFetcher = {\n                state: \"loading\",\n                data: existingFetcher && existingFetcher.data,\n                formMethod: undefined,\n                formAction: undefined,\n                formEncType: undefined,\n                formData: undefined,\n                \" _hasFetcherDoneAnything \": true\n              };\n              state.fetchers.set(staleKey, revalidatingFetcher);\n              fetchControllers.set(staleKey, abortController);\n            });\n            updateState({\n              fetchers: new Map(state.fetchers)\n            });\n            _context6.next = 43;\n            return callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n          case 43:\n            _yield$callLoadersAnd2 = _context6.sent;\n            results = _yield$callLoadersAnd2.results;\n            loaderResults = _yield$callLoadersAnd2.loaderResults;\n            fetcherResults = _yield$callLoadersAnd2.fetcherResults;\n            if (!abortController.signal.aborted) {\n              _context6.next = 49;\n              break;\n            }\n            return _context6.abrupt(\"return\");\n          case 49:\n            fetchReloadIds.delete(key);\n            fetchControllers.delete(key);\n            revalidatingFetchers.forEach(function (_ref7) {\n              var _ref19 = _slicedToArray(_ref7, 1),\n                staleKey = _ref19[0];\n              return fetchControllers.delete(staleKey);\n            });\n            redirect = findRedirect(results);\n            if (!redirect) {\n              _context6.next = 55;\n              break;\n            }\n            return _context6.abrupt(\"return\", startRedirectNavigation(state, redirect));\n          case 55:\n            // Process and commit output from loaders\n            _processLoaderData2 = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds), loaderData = _processLoaderData2.loaderData, errors = _processLoaderData2.errors;\n            doneFetcher = {\n              state: \"idle\",\n              data: actionResult.data,\n              formMethod: undefined,\n              formAction: undefined,\n              formEncType: undefined,\n              formData: undefined,\n              \" _hasFetcherDoneAnything \": true\n            };\n            state.fetchers.set(key, doneFetcher);\n            didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is\n            // more recent than the navigation, we want the newer data so abort the\n            // navigation and complete it with the fetcher data\n            if (state.navigation.state === \"loading\" && loadId > pendingNavigationLoadId) {\n              invariant(pendingAction, \"Expected pending action\");\n              pendingNavigationController && pendingNavigationController.abort();\n              completeNavigation(state.navigation.location, {\n                matches: matches,\n                loaderData: loaderData,\n                errors: errors,\n                fetchers: new Map(state.fetchers)\n              });\n            } else {\n              // otherwise just update with the fetcher data, preserving any existing\n              // loaderData for loaders that did not need to reload.  We have to\n              // manually merge here since we aren't going through completeNavigation\n              updateState(_extends({\n                errors: errors,\n                loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors)\n              }, didAbortFetchLoads ? {\n                fetchers: new Map(state.fetchers)\n              } : {}));\n              isRevalidationRequired = false;\n            }\n          case 60:\n          case \"end\":\n            return _context6.stop();\n        }\n      }, _callee6);\n    }));\n    return _handleFetcherAction.apply(this, arguments);\n  }\n  function handleFetcherLoader(_x26, _x27, _x28, _x29, _x30, _x31) {\n    return _handleFetcherLoader.apply(this, arguments);\n  }\n  /**\n   * Utility function to handle redirects returned from an action or loader.\n   * Normally, a redirect \"replaces\" the navigation that triggered it.  So, for\n   * example:\n   *\n   *  - user is on /a\n   *  - user clicks a link to /b\n   *  - loader for /b redirects to /c\n   *\n   * In a non-JS app the browser would track the in-flight navigation to /b and\n   * then replace it with /c when it encountered the redirect response.  In\n   * the end it would only ever update the URL bar with /c.\n   *\n   * In client-side routing using pushState/replaceState, we aim to emulate\n   * this behavior and we also do not update history until the end of the\n   * navigation (including processed redirects).  This means that we never\n   * actually touch history until we've processed redirects, so we just use\n   * the history action from the original navigation (PUSH or REPLACE).\n   */\n  function _handleFetcherLoader() {\n    _handleFetcherLoader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(key, routeId, path, match, matches, submission) {\n      var existingFetcher, loadingFetcher, abortController, fetchRequest, result, boundaryMatch, doneFetcher;\n      return _regeneratorRuntime().wrap(function _callee7$(_context7) {\n        while (1) switch (_context7.prev = _context7.next) {\n          case 0:\n            existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state\n            loadingFetcher = _extends({\n              state: \"loading\",\n              formMethod: undefined,\n              formAction: undefined,\n              formEncType: undefined,\n              formData: undefined\n            }, submission, {\n              data: existingFetcher && existingFetcher.data,\n              \" _hasFetcherDoneAnything \": true\n            });\n            state.fetchers.set(key, loadingFetcher);\n            updateState({\n              fetchers: new Map(state.fetchers)\n            }); // Call the loader for this fetcher route match\n            abortController = new AbortController();\n            fetchRequest = createClientSideRequest(path, abortController.signal);\n            fetchControllers.set(key, abortController);\n            _context7.next = 9;\n            return callLoaderOrAction(\"loader\", fetchRequest, match, matches, router.basename);\n          case 9:\n            result = _context7.sent;\n            if (!isDeferredResult(result)) {\n              _context7.next = 17;\n              break;\n            }\n            _context7.next = 13;\n            return resolveDeferredData(result, fetchRequest.signal, true);\n          case 13:\n            _context7.t0 = _context7.sent;\n            if (_context7.t0) {\n              _context7.next = 16;\n              break;\n            }\n            _context7.t0 = result;\n          case 16:\n            result = _context7.t0;\n          case 17:\n            // We can delete this so long as we weren't aborted by ou our own fetcher\n            // re-load which would have put _new_ controller is in fetchControllers\n\n            if (fetchControllers.get(key) === abortController) {\n              fetchControllers.delete(key);\n            }\n            if (!fetchRequest.signal.aborted) {\n              _context7.next = 20;\n              break;\n            }\n            return _context7.abrupt(\"return\");\n          case 20:\n            if (!isRedirectResult(result)) {\n              _context7.next = 24;\n              break;\n            }\n            _context7.next = 23;\n            return startRedirectNavigation(state, result);\n          case 23:\n            return _context7.abrupt(\"return\");\n          case 24:\n            if (!isErrorResult(result)) {\n              _context7.next = 29;\n              break;\n            }\n            boundaryMatch = findNearestBoundary(state.matches, routeId);\n            state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n            // do we need to behave any differently with our non-redirect errors?\n            // What if it was a non-redirect Response?\n\n            updateState({\n              fetchers: new Map(state.fetchers),\n              errors: _defineProperty({}, boundaryMatch.route.id, result.error)\n            });\n            return _context7.abrupt(\"return\");\n          case 29:\n            invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\"); // Put the fetcher back into an idle state\n            doneFetcher = {\n              state: \"idle\",\n              data: result.data,\n              formMethod: undefined,\n              formAction: undefined,\n              formEncType: undefined,\n              formData: undefined,\n              \" _hasFetcherDoneAnything \": true\n            };\n            state.fetchers.set(key, doneFetcher);\n            updateState({\n              fetchers: new Map(state.fetchers)\n            });\n          case 33:\n          case \"end\":\n            return _context7.stop();\n        }\n      }, _callee7);\n    }));\n    return _handleFetcherLoader.apply(this, arguments);\n  }\n  function startRedirectNavigation(_x32, _x33, _x34) {\n    return _startRedirectNavigation.apply(this, arguments);\n  }\n  function _startRedirectNavigation() {\n    _startRedirectNavigation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(state, redirect, _temp) {\n      var _window, _ref20, submission, replace, isFetchActionRedirect, redirectLocation, newOrigin, redirectHistoryAction, _state$navigation, formMethod, formAction, formEncType, formData;\n      return _regeneratorRuntime().wrap(function _callee8$(_context8) {\n        while (1) switch (_context8.prev = _context8.next) {\n          case 0:\n            _ref20 = _temp === void 0 ? {} : _temp, submission = _ref20.submission, replace = _ref20.replace, isFetchActionRedirect = _ref20.isFetchActionRedirect;\n            if (redirect.revalidate) {\n              isRevalidationRequired = true;\n            }\n            redirectLocation = createLocation(state.location, redirect.location,\n            // TODO: This can be removed once we get rid of useTransition in Remix v2\n            _extends({\n              _isRedirect: true\n            }, isFetchActionRedirect ? {\n              _isFetchActionRedirect: true\n            } : {}));\n            invariant(redirectLocation, \"Expected a location on the redirect navigation\"); // Check if this an external redirect that goes to a new origin\n            if (!(typeof ((_window = window) == null ? void 0 : _window.location) !== \"undefined\")) {\n              _context8.next = 9;\n              break;\n            }\n            newOrigin = createClientSideURL(redirect.location).origin;\n            if (!(window.location.origin !== newOrigin)) {\n              _context8.next = 9;\n              break;\n            }\n            if (replace) {\n              window.location.replace(redirect.location);\n            } else {\n              window.location.assign(redirect.location);\n            }\n            return _context8.abrupt(\"return\");\n          case 9:\n            // There's no need to abort on redirects, since we don't detect the\n            // redirect until the action/loaders have settled\n\n            pendingNavigationController = null;\n            redirectHistoryAction = replace === true ? Action.Replace : Action.Push; // Use the incoming submission if provided, fallback on the active one in\n            // state.navigation\n            _state$navigation = state.navigation, formMethod = _state$navigation.formMethod, formAction = _state$navigation.formAction, formEncType = _state$navigation.formEncType, formData = _state$navigation.formData;\n            if (!submission && formMethod && formAction && formData && formEncType) {\n              submission = {\n                formMethod: formMethod,\n                formAction: formAction,\n                formEncType: formEncType,\n                formData: formData\n              };\n            } // If this was a 307/308 submission we want to preserve the HTTP method and\n            // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n            // redirected location\n            if (!(redirectPreserveMethodStatusCodes.has(redirect.status) && submission && isMutationMethod(submission.formMethod))) {\n              _context8.next = 18;\n              break;\n            }\n            _context8.next = 16;\n            return startNavigation(redirectHistoryAction, redirectLocation, {\n              submission: _extends({}, submission, {\n                formAction: redirect.location\n              })\n            });\n          case 16:\n            _context8.next = 20;\n            break;\n          case 18:\n            _context8.next = 20;\n            return startNavigation(redirectHistoryAction, redirectLocation, {\n              overrideNavigation: {\n                state: \"loading\",\n                location: redirectLocation,\n                formMethod: submission ? submission.formMethod : undefined,\n                formAction: submission ? submission.formAction : undefined,\n                formEncType: submission ? submission.formEncType : undefined,\n                formData: submission ? submission.formData : undefined\n              }\n            });\n          case 20:\n          case \"end\":\n            return _context8.stop();\n        }\n      }, _callee8);\n    }));\n    return _startRedirectNavigation.apply(this, arguments);\n  }\n  function callLoadersAndMaybeResolveData(_x35, _x36, _x37, _x38, _x39) {\n    return _callLoadersAndMaybeResolveData.apply(this, arguments);\n  }\n  function _callLoadersAndMaybeResolveData() {\n    _callLoadersAndMaybeResolveData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {\n      var results, loaderResults, fetcherResults;\n      return _regeneratorRuntime().wrap(function _callee9$(_context9) {\n        while (1) switch (_context9.prev = _context9.next) {\n          case 0:\n            _context9.next = 2;\n            return Promise.all([].concat(_toConsumableArray(matchesToLoad.map(function (match) {\n              return callLoaderOrAction(\"loader\", request, match, matches, router.basename);\n            })), _toConsumableArray(fetchersToLoad.map(function (_ref8) {\n              var _ref21 = _slicedToArray(_ref8, 4),\n                href = _ref21[1],\n                match = _ref21[2],\n                fetchMatches = _ref21[3];\n              return callLoaderOrAction(\"loader\", createClientSideRequest(href, request.signal), match, fetchMatches, router.basename);\n            }))));\n          case 2:\n            results = _context9.sent;\n            loaderResults = results.slice(0, matchesToLoad.length);\n            fetcherResults = results.slice(matchesToLoad.length);\n            _context9.next = 7;\n            return Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(function (_ref9) {\n              var _ref22 = _slicedToArray(_ref9, 3),\n                match = _ref22[2];\n              return match;\n            }), fetcherResults, request.signal, true)]);\n          case 7:\n            return _context9.abrupt(\"return\", {\n              results: results,\n              loaderResults: loaderResults,\n              fetcherResults: fetcherResults\n            });\n          case 8:\n          case \"end\":\n            return _context9.stop();\n        }\n      }, _callee9);\n    }));\n    return _callLoadersAndMaybeResolveData.apply(this, arguments);\n  }\n  function interruptActiveLoads() {\n    var _cancelledDeferredRou;\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n\n    (_cancelledDeferredRou = cancelledDeferredRoutes).push.apply(_cancelledDeferredRou, _toConsumableArray(cancelActiveDeferreds())); // Abort in-flight fetcher loads\n\n    fetchLoadMatches.forEach(function (_, key) {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.push(key);\n        abortFetcher(key);\n      }\n    });\n  }\n  function setFetcherError(key, routeId, error) {\n    var boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState({\n      errors: _defineProperty({}, boundaryMatch.route.id, error),\n      fetchers: new Map(state.fetchers)\n    });\n  }\n  function deleteFetcher(key) {\n    if (fetchControllers.has(key)) abortFetcher(key);\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n    state.fetchers.delete(key);\n  }\n  function abortFetcher(key) {\n    var controller = fetchControllers.get(key);\n    invariant(controller, \"Expected fetch controller: \" + key);\n    controller.abort();\n    fetchControllers.delete(key);\n  }\n  function markFetchersDone(keys) {\n    var _iterator2 = _createForOfIteratorHelper(keys),\n      _step2;\n    try {\n      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n        var key = _step2.value;\n        var fetcher = getFetcher(key);\n        var doneFetcher = {\n          state: \"idle\",\n          data: fetcher.data,\n          formMethod: undefined,\n          formAction: undefined,\n          formEncType: undefined,\n          formData: undefined,\n          \" _hasFetcherDoneAnything \": true\n        };\n        state.fetchers.set(key, doneFetcher);\n      }\n    } catch (err) {\n      _iterator2.e(err);\n    } finally {\n      _iterator2.f();\n    }\n  }\n  function markFetchRedirectsDone() {\n    var doneKeys = [];\n    var _iterator3 = _createForOfIteratorHelper(fetchRedirectIds),\n      _step3;\n    try {\n      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n        var key = _step3.value;\n        var fetcher = state.fetchers.get(key);\n        invariant(fetcher, \"Expected fetcher: \" + key);\n        if (fetcher.state === \"loading\") {\n          fetchRedirectIds.delete(key);\n          doneKeys.push(key);\n        }\n      }\n    } catch (err) {\n      _iterator3.e(err);\n    } finally {\n      _iterator3.f();\n    }\n    markFetchersDone(doneKeys);\n  }\n  function abortStaleFetchLoads(landedId) {\n    var yeetedKeys = [];\n    var _iterator4 = _createForOfIteratorHelper(fetchReloadIds),\n      _step4;\n    try {\n      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n        var _step4$value = _slicedToArray(_step4.value, 2),\n          key = _step4$value[0],\n          id = _step4$value[1];\n        if (id < landedId) {\n          var fetcher = state.fetchers.get(key);\n          invariant(fetcher, \"Expected fetcher: \" + key);\n          if (fetcher.state === \"loading\") {\n            abortFetcher(key);\n            fetchReloadIds.delete(key);\n            yeetedKeys.push(key);\n          }\n        }\n      }\n    } catch (err) {\n      _iterator4.e(err);\n    } finally {\n      _iterator4.f();\n    }\n    markFetchersDone(yeetedKeys);\n    return yeetedKeys.length > 0;\n  }\n  function cancelActiveDeferreds(predicate) {\n    var cancelledRouteIds = [];\n    activeDeferreds.forEach(function (dfd, routeId) {\n      if (!predicate || predicate(routeId)) {\n        // Cancel the deferred - but do not remove from activeDeferreds here -\n        // we rely on the subscribers to do that so our tests can assert proper\n        // cleanup via _internalActiveDeferreds\n        dfd.cancel();\n        cancelledRouteIds.push(routeId);\n        activeDeferreds.delete(routeId);\n      }\n    });\n    return cancelledRouteIds;\n  } // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n\n  function enableScrollRestoration(positions, getPosition, getKey) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || function (location) {\n      return location.key;\n    }; // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      var y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({\n          restoreScrollPosition: y\n        });\n      }\n    }\n    return function () {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n  function saveScrollPosition(location, matches) {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      var userMatches = matches.map(function (m) {\n        return createUseMatchesMatch(m, state.loaderData);\n      });\n      var key = getScrollRestorationKey(location, userMatches) || location.key;\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n  function getSavedScrollPosition(location, matches) {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      var userMatches = matches.map(function (m) {\n        return createUseMatchesMatch(m, state.loaderData);\n      });\n      var key = getScrollRestorationKey(location, userMatches) || location.key;\n      var y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n  router = {\n    get basename() {\n      return init.basename;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    initialize: initialize,\n    subscribe: subscribe,\n    enableScrollRestoration: enableScrollRestoration,\n    navigate: navigate,\n    fetch: fetch,\n    revalidate: revalidate,\n    // Passthrough to history-aware createHref used by useHref so we get proper\n    // hash-aware URLs in DOM paths\n    createHref: function createHref(to) {\n      return init.history.createHref(to);\n    },\n    encodeLocation: function encodeLocation(to) {\n      return init.history.encodeLocation(to);\n    },\n    getFetcher: getFetcher,\n    deleteFetcher: deleteFetcher,\n    dispose: dispose,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds\n  };\n  return router;\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nfunction createStaticHandler(routes, opts) {\n  invariant(routes.length > 0, \"You must provide a non-empty routes array to createStaticHandler\");\n  var dataRoutes = convertRoutesToDataRoutes(routes);\n  var basename = (opts ? opts.basename : null) || \"/\";\n  /**\n   * The query() method is intended for document requests, in which we want to\n   * call an optional action and potentially multiple loaders for all nested\n   * routes.  It returns a StaticHandlerContext object, which is very similar\n   * to the router state (location, loaderData, actionData, errors, etc.) and\n   * also adds SSR-specific information such as the statusCode and headers\n   * from action/loaders Responses.\n   *\n   * It _should_ never throw and should report all errors through the\n   * returned context.errors object, properly associating errors to their error\n   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be\n   * used to emulate React error boundaries during SSr by performing a second\n   * pass only down to the boundaryId.\n   *\n   * The one exception where we do not return a StaticHandlerContext is when a\n   * redirect response is returned or thrown from any action/loader.  We\n   * propagate that out and return the raw Response so the HTTP server can\n   * return it directly.\n   */\n  function query(_x40, _x41) {\n    return _query.apply(this, arguments);\n  }\n  /**\n   * The queryRoute() method is intended for targeted route requests, either\n   * for fetch ?_data requests or resource route requests.  In this case, we\n   * are only ever calling a single action or loader, and we are returning the\n   * returned value directly.  In most cases, this will be a Response returned\n   * from the action/loader, but it may be a primitive or other value as well -\n   * and in such cases the calling context should handle that accordingly.\n   *\n   * We do respect the throw/return differentiation, so if an action/loader\n   * throws, then this method will throw the value.  This is important so we\n   * can do proper boundary identification in Remix where a thrown Response\n   * must go to the Catch Boundary but a returned Response is happy-path.\n   *\n   * One thing to note is that any Router-initiated Errors that make sense\n   * to associate with a status code will be thrown as an ErrorResponse\n   * instance which include the raw Error, such that the calling context can\n   * serialize the error as they see fit while including the proper response\n   * code.  Examples here are 404 and 405 errors that occur prior to reaching\n   * any user-defined loaders.\n   */\n  function _query() {\n    _query = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(request, _temp2) {\n      var _ref23, requestContext, url, method, location, matches, error, _getShortCircuitMatch3, methodNotAllowedMatches, route, _error3, _getShortCircuitMatch4, notFoundMatches, _route2, result;\n      return _regeneratorRuntime().wrap(function _callee10$(_context10) {\n        while (1) switch (_context10.prev = _context10.next) {\n          case 0:\n            _ref23 = _temp2 === void 0 ? {} : _temp2, requestContext = _ref23.requestContext;\n            url = new URL(request.url);\n            method = request.method.toLowerCase();\n            location = createLocation(\"\", createPath(url), null, \"default\");\n            matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't\n            if (!(!isValidMethod(method) && method !== \"head\")) {\n              _context10.next = 11;\n              break;\n            }\n            error = getInternalRouterError(405, {\n              method: method\n            });\n            _getShortCircuitMatch3 = getShortCircuitMatches(dataRoutes), methodNotAllowedMatches = _getShortCircuitMatch3.matches, route = _getShortCircuitMatch3.route;\n            return _context10.abrupt(\"return\", {\n              basename: basename,\n              location: location,\n              matches: methodNotAllowedMatches,\n              loaderData: {},\n              actionData: null,\n              errors: _defineProperty({}, route.id, error),\n              statusCode: error.status,\n              loaderHeaders: {},\n              actionHeaders: {}\n            });\n          case 11:\n            if (matches) {\n              _context10.next = 15;\n              break;\n            }\n            _error3 = getInternalRouterError(404, {\n              pathname: location.pathname\n            });\n            _getShortCircuitMatch4 = getShortCircuitMatches(dataRoutes), notFoundMatches = _getShortCircuitMatch4.matches, _route2 = _getShortCircuitMatch4.route;\n            return _context10.abrupt(\"return\", {\n              basename: basename,\n              location: location,\n              matches: notFoundMatches,\n              loaderData: {},\n              actionData: null,\n              errors: _defineProperty({}, _route2.id, _error3),\n              statusCode: _error3.status,\n              loaderHeaders: {},\n              actionHeaders: {}\n            });\n          case 15:\n            _context10.next = 17;\n            return queryImpl(request, location, matches, requestContext);\n          case 17:\n            result = _context10.sent;\n            if (!isResponse(result)) {\n              _context10.next = 20;\n              break;\n            }\n            return _context10.abrupt(\"return\", result);\n          case 20:\n            return _context10.abrupt(\"return\", _extends({\n              location: location,\n              basename: basename\n            }, result));\n          case 21:\n          case \"end\":\n            return _context10.stop();\n        }\n      }, _callee10);\n    }));\n    return _query.apply(this, arguments);\n  }\n  function queryRoute(_x42, _x43) {\n    return _queryRoute.apply(this, arguments);\n  }\n  function _queryRoute() {\n    _queryRoute = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(request, _temp3) {\n      var _ref24, routeId, requestContext, url, method, location, matches, match, result, error, routeData;\n      return _regeneratorRuntime().wrap(function _callee11$(_context11) {\n        while (1) switch (_context11.prev = _context11.next) {\n          case 0:\n            _ref24 = _temp3 === void 0 ? {} : _temp3, routeId = _ref24.routeId, requestContext = _ref24.requestContext;\n            url = new URL(request.url);\n            method = request.method.toLowerCase();\n            location = createLocation(\"\", createPath(url), null, \"default\");\n            matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't\n            if (!(!isValidMethod(method) && method !== \"head\")) {\n              _context11.next = 9;\n              break;\n            }\n            throw getInternalRouterError(405, {\n              method: method\n            });\n          case 9:\n            if (matches) {\n              _context11.next = 11;\n              break;\n            }\n            throw getInternalRouterError(404, {\n              pathname: location.pathname\n            });\n          case 11:\n            match = routeId ? matches.find(function (m) {\n              return m.route.id === routeId;\n            }) : getTargetMatch(matches, location);\n            if (!(routeId && !match)) {\n              _context11.next = 16;\n              break;\n            }\n            throw getInternalRouterError(403, {\n              pathname: location.pathname,\n              routeId: routeId\n            });\n          case 16:\n            if (match) {\n              _context11.next = 18;\n              break;\n            }\n            throw getInternalRouterError(404, {\n              pathname: location.pathname\n            });\n          case 18:\n            _context11.next = 20;\n            return queryImpl(request, location, matches, requestContext, match);\n          case 20:\n            result = _context11.sent;\n            if (!isResponse(result)) {\n              _context11.next = 23;\n              break;\n            }\n            return _context11.abrupt(\"return\", result);\n          case 23:\n            error = result.errors ? Object.values(result.errors)[0] : undefined;\n            if (!(error !== undefined)) {\n              _context11.next = 26;\n              break;\n            }\n            throw error;\n          case 26:\n            // Pick off the right state value to return\n            routeData = [result.actionData, result.loaderData].find(function (v) {\n              return v;\n            });\n            return _context11.abrupt(\"return\", Object.values(routeData || {})[0]);\n          case 28:\n          case \"end\":\n            return _context11.stop();\n        }\n      }, _callee11);\n    }));\n    return _queryRoute.apply(this, arguments);\n  }\n  function queryImpl(_x44, _x45, _x46, _x47, _x48) {\n    return _queryImpl.apply(this, arguments);\n  }\n  function _queryImpl() {\n    _queryImpl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(request, location, matches, requestContext, routeMatch) {\n      var _result, result;\n      return _regeneratorRuntime().wrap(function _callee12$(_context12) {\n        while (1) switch (_context12.prev = _context12.next) {\n          case 0:\n            invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n            _context12.prev = 1;\n            if (!isMutationMethod(request.method.toLowerCase())) {\n              _context12.next = 7;\n              break;\n            }\n            _context12.next = 5;\n            return submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null);\n          case 5:\n            _result = _context12.sent;\n            return _context12.abrupt(\"return\", _result);\n          case 7:\n            _context12.next = 9;\n            return loadRouteData(request, matches, requestContext, routeMatch);\n          case 9:\n            result = _context12.sent;\n            return _context12.abrupt(\"return\", isResponse(result) ? result : _extends({}, result, {\n              actionData: null,\n              actionHeaders: {}\n            }));\n          case 13:\n            _context12.prev = 13;\n            _context12.t0 = _context12[\"catch\"](1);\n            if (!isQueryRouteResponse(_context12.t0)) {\n              _context12.next = 19;\n              break;\n            }\n            if (!(_context12.t0.type === ResultType.error && !isRedirectResponse(_context12.t0.response))) {\n              _context12.next = 18;\n              break;\n            }\n            throw _context12.t0.response;\n          case 18:\n            return _context12.abrupt(\"return\", _context12.t0.response);\n          case 19:\n            if (!isRedirectResponse(_context12.t0)) {\n              _context12.next = 21;\n              break;\n            }\n            return _context12.abrupt(\"return\", _context12.t0);\n          case 21:\n            throw _context12.t0;\n          case 22:\n          case \"end\":\n            return _context12.stop();\n        }\n      }, _callee12, null, [[1, 13]]);\n    }));\n    return _queryImpl.apply(this, arguments);\n  }\n  function submit(_x49, _x50, _x51, _x52, _x53) {\n    return _submit.apply(this, arguments);\n  }\n  function _submit() {\n    _submit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(request, matches, actionMatch, requestContext, isRouteRequest) {\n      var result, error, method, boundaryMatch, _context13, loaderRequest, context;\n      return _regeneratorRuntime().wrap(function _callee13$(_context14) {\n        while (1) switch (_context14.prev = _context14.next) {\n          case 0:\n            if (actionMatch.route.action) {\n              _context14.next = 7;\n              break;\n            }\n            error = getInternalRouterError(405, {\n              method: request.method,\n              pathname: new URL(request.url).pathname,\n              routeId: actionMatch.route.id\n            });\n            if (!isRouteRequest) {\n              _context14.next = 4;\n              break;\n            }\n            throw error;\n          case 4:\n            result = {\n              type: ResultType.error,\n              error: error\n            };\n            _context14.next = 13;\n            break;\n          case 7:\n            _context14.next = 9;\n            return callLoaderOrAction(\"action\", request, actionMatch, matches, basename, true, isRouteRequest, requestContext);\n          case 9:\n            result = _context14.sent;\n            if (!request.signal.aborted) {\n              _context14.next = 13;\n              break;\n            }\n            method = isRouteRequest ? \"queryRoute\" : \"query\";\n            throw new Error(method + \"() call aborted\");\n          case 13:\n            if (!isRedirectResult(result)) {\n              _context14.next = 15;\n              break;\n            }\n            throw new Response(null, {\n              status: result.status,\n              headers: {\n                Location: result.location\n              }\n            });\n          case 15:\n            if (!isDeferredResult(result)) {\n              _context14.next = 17;\n              break;\n            }\n            throw new Error(\"defer() is not supported in actions\");\n          case 17:\n            if (!isRouteRequest) {\n              _context14.next = 21;\n              break;\n            }\n            if (!isErrorResult(result)) {\n              _context14.next = 20;\n              break;\n            }\n            throw result.error;\n          case 20:\n            return _context14.abrupt(\"return\", {\n              matches: [actionMatch],\n              loaderData: {},\n              actionData: _defineProperty({}, actionMatch.route.id, result.data),\n              errors: null,\n              // Note: statusCode + headers are unused here since queryRoute will\n              // return the raw Response or value\n              statusCode: 200,\n              loaderHeaders: {},\n              actionHeaders: {}\n            });\n          case 21:\n            if (!isErrorResult(result)) {\n              _context14.next = 27;\n              break;\n            }\n            // Store off the pending error - we use it to determine which loaders\n            // to call and will commit it when we complete the navigation\n            boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n            _context14.next = 25;\n            return loadRouteData(request, matches, requestContext, undefined, _defineProperty({}, boundaryMatch.route.id, result.error));\n          case 25:\n            _context13 = _context14.sent;\n            return _context14.abrupt(\"return\", _extends({}, _context13, {\n              statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,\n              actionData: null,\n              actionHeaders: _extends({}, result.headers ? _defineProperty({}, actionMatch.route.id, result.headers) : {})\n            }));\n          case 27:\n            // Create a GET request for the loaders\n            loaderRequest = new Request(request.url, {\n              headers: request.headers,\n              redirect: request.redirect,\n              signal: request.signal\n            });\n            _context14.next = 30;\n            return loadRouteData(loaderRequest, matches, requestContext);\n          case 30:\n            context = _context14.sent;\n            return _context14.abrupt(\"return\", _extends({}, context, result.statusCode ? {\n              statusCode: result.statusCode\n            } : {}, {\n              actionData: _defineProperty({}, actionMatch.route.id, result.data),\n              actionHeaders: _extends({}, result.headers ? _defineProperty({}, actionMatch.route.id, result.headers) : {})\n            }));\n          case 32:\n          case \"end\":\n            return _context14.stop();\n        }\n      }, _callee13);\n    }));\n    return _submit.apply(this, arguments);\n  }\n  function loadRouteData(_x54, _x55, _x56, _x57, _x58) {\n    return _loadRouteData.apply(this, arguments);\n  }\n  function _loadRouteData() {\n    _loadRouteData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(request, matches, requestContext, routeMatch, pendingActionError) {\n      var isRouteRequest, requestMatches, matchesToLoad, results, method, executedLoaders, context;\n      return _regeneratorRuntime().wrap(function _callee14$(_context15) {\n        while (1) switch (_context15.prev = _context15.next) {\n          case 0:\n            isRouteRequest = routeMatch != null; // Short circuit if we have no loaders to run (queryRoute())\n            if (!(isRouteRequest && !(routeMatch != null && routeMatch.route.loader))) {\n              _context15.next = 3;\n              break;\n            }\n            throw getInternalRouterError(400, {\n              method: request.method,\n              pathname: new URL(request.url).pathname,\n              routeId: routeMatch == null ? void 0 : routeMatch.route.id\n            });\n          case 3:\n            requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);\n            matchesToLoad = requestMatches.filter(function (m) {\n              return m.route.loader;\n            }); // Short circuit if we have no loaders to run (query())\n            if (!(matchesToLoad.length === 0)) {\n              _context15.next = 7;\n              break;\n            }\n            return _context15.abrupt(\"return\", {\n              matches: matches,\n              // Add a null for all matched routes for proper revalidation on the client\n              loaderData: matches.reduce(function (acc, m) {\n                return Object.assign(acc, _defineProperty({}, m.route.id, null));\n              }, {}),\n              errors: pendingActionError || null,\n              statusCode: 200,\n              loaderHeaders: {}\n            });\n          case 7:\n            _context15.next = 9;\n            return Promise.all(_toConsumableArray(matchesToLoad.map(function (match) {\n              return callLoaderOrAction(\"loader\", request, match, matches, basename, true, isRouteRequest, requestContext);\n            })));\n          case 9:\n            results = _context15.sent;\n            if (!request.signal.aborted) {\n              _context15.next = 13;\n              break;\n            }\n            method = isRouteRequest ? \"queryRoute\" : \"query\";\n            throw new Error(method + \"() call aborted\");\n          case 13:\n            executedLoaders = new Set();\n            results.forEach(function (result, i) {\n              executedLoaders.add(matchesToLoad[i].route.id); // Can't do anything with these without the Remix side of things, so just\n              // cancel them for now\n\n              if (isDeferredResult(result)) {\n                result.deferredData.cancel();\n              }\n            }); // Process and commit output from loaders\n            context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError); // Add a null for any non-loader matches for proper revalidation on the client\n            matches.forEach(function (match) {\n              if (!executedLoaders.has(match.route.id)) {\n                context.loaderData[match.route.id] = null;\n              }\n            });\n            return _context15.abrupt(\"return\", _extends({}, context, {\n              matches: matches\n            }));\n          case 18:\n          case \"end\":\n            return _context15.stop();\n        }\n      }, _callee14);\n    }));\n    return _loadRouteData.apply(this, arguments);\n  }\n  return {\n    dataRoutes: dataRoutes,\n    query: query,\n    queryRoute: queryRoute\n  };\n} //#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\n\nfunction getStaticContextFromError(routes, context, error) {\n  var newContext = _extends({}, context, {\n    statusCode: 500,\n    errors: _defineProperty({}, context._deepestRenderedBoundaryId || routes[0].id, error)\n  });\n  return newContext;\n}\nfunction isSubmissionNavigation(opts) {\n  return opts != null && \"formData\" in opts;\n} // Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\n\nfunction normalizeNavigateOptions(to, opts, isFetcher) {\n  if (isFetcher === void 0) {\n    isFetcher = false;\n  }\n  var path = typeof to === \"string\" ? to : createPath(to); // Return location verbatim on non-submission navigations\n\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return {\n      path: path\n    };\n  }\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path: path,\n      error: getInternalRouterError(405, {\n        method: opts.formMethod\n      })\n    };\n  } // Create a Submission on non-GET navigations\n\n  var submission;\n  if (opts.formData) {\n    submission = {\n      formMethod: opts.formMethod || \"get\",\n      formAction: stripHashFromPath(path),\n      formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n      formData: opts.formData\n    };\n    if (isMutationMethod(submission.formMethod)) {\n      return {\n        path: path,\n        submission: submission\n      };\n    }\n  } // Flatten submission onto URLSearchParams for GET submissions\n\n  var parsedPath = parsePath(path);\n  try {\n    var searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to\n    // navigation GET submissions which run all loaders), we need to preserve\n    // any incoming ?index params\n\n    if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n      searchParams.append(\"index\", \"\");\n    }\n    parsedPath.search = \"?\" + searchParams;\n  } catch (e) {\n    return {\n      path: path,\n      error: getInternalRouterError(400)\n    };\n  }\n  return {\n    path: createPath(parsedPath),\n    submission: submission\n  };\n} // Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\n\nfunction getLoaderMatchesUntilBoundary(matches, boundaryId) {\n  var boundaryMatches = matches;\n  if (boundaryId) {\n    var index = matches.findIndex(function (m) {\n      return m.route.id === boundaryId;\n    });\n    if (index >= 0) {\n      boundaryMatches = matches.slice(0, index);\n    }\n  }\n  return boundaryMatches;\n}\nfunction getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {\n  var actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined; // Pick navigation matches that are net-new or qualify for revalidation\n\n  var boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n  var boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n  var navigationMatches = boundaryMatches.filter(function (match, index) {\n    return match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) ||\n    // If this route had a pending deferred cancelled it must be revalidated\n    cancelledDeferredRoutes.some(function (id) {\n      return id === match.route.id;\n    }) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult));\n  }); // Pick fetcher.loads that need to be revalidated\n\n  var revalidatingFetchers = [];\n  fetchLoadMatches && fetchLoadMatches.forEach(function (_ref10, key) {\n    var _ref27 = _slicedToArray(_ref10, 3),\n      href = _ref27[0],\n      match = _ref27[1],\n      fetchMatches = _ref27[2];\n\n    // This fetcher was cancelled from a prior action submission - force reload\n    if (cancelledFetcherLoads.includes(key)) {\n      revalidatingFetchers.push([key, href, match, fetchMatches]);\n    } else if (isRevalidationRequired) {\n      var shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult);\n      if (shouldRevalidate) {\n        revalidatingFetchers.push([key, href, match, fetchMatches]);\n      }\n    }\n  });\n  return [navigationMatches, revalidatingFetchers];\n}\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n  var isNew =\n  // [a] -> [a, b]\n  !currentMatch ||\n  // [a, b] -> [a, c]\n  match.route.id !== currentMatch.route.id; // Handle the case that we don't have data for a re-used route, potentially\n  // from a prior error or from a cancelled pending deferred\n\n  var isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data\n\n  return isNew || isMissingData;\n}\nfunction isNewRouteInstance(currentMatch, match) {\n  var currentPath = currentMatch.route.path;\n  return (\n    // param change for this match, /users/123 -> /users/456\n    currentMatch.pathname !== match.pathname ||\n    // splat param changed, which is not present in match.path\n    // e.g. /files/images/avatar.jpg -> files/finances.xls\n    currentPath && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n  );\n}\nfunction shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) {\n  var currentUrl = createClientSideURL(currentLocation);\n  var currentParams = currentMatch.params;\n  var nextUrl = createClientSideURL(location);\n  var nextParams = match.params; // This is the default implementation as to when we revalidate.  If the route\n  // provides it's own implementation, then we give them full control but\n  // provide this value so they can leverage it if needed after they check\n  // their own specific use cases\n  // Note that fetchers always provide the same current/next locations so the\n  // URL-based checks here don't apply to fetcher shouldRevalidate calls\n\n  var defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) ||\n  // Clicked the same link, resubmitted a GET form\n  currentUrl.toString() === nextUrl.toString() ||\n  // Search params affect all loaders\n  currentUrl.search !== nextUrl.search ||\n  // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n  isRevalidationRequired;\n  if (match.route.shouldRevalidate) {\n    var routeChoice = match.route.shouldRevalidate(_extends({\n      currentUrl: currentUrl,\n      currentParams: currentParams,\n      nextUrl: nextUrl,\n      nextParams: nextParams\n    }, submission, {\n      actionResult: actionResult,\n      defaultShouldRevalidate: defaultShouldRevalidate\n    }));\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n  return defaultShouldRevalidate;\n}\nfunction callLoaderOrAction(_x59, _x60, _x61, _x62, _x63, _x64, _x65, _x66) {\n  return _callLoaderOrAction.apply(this, arguments);\n} // Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches.  During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction _callLoaderOrAction() {\n  _callLoaderOrAction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(type, request, match, matches, basename, isStaticRequest, isRouteRequest, requestContext) {\n    var resultType, result, reject, abortPromise, onReject, handler, status, location, isAbsolute, activeMatches, routePathnames, resolvedLocation, path, data, contentType;\n    return _regeneratorRuntime().wrap(function _callee15$(_context16) {\n      while (1) switch (_context16.prev = _context16.next) {\n        case 0:\n          if (basename === void 0) {\n            basename = \"/\";\n          }\n          if (isStaticRequest === void 0) {\n            isStaticRequest = false;\n          }\n          if (isRouteRequest === void 0) {\n            isRouteRequest = false;\n          }\n          abortPromise = new Promise(function (_, r) {\n            return reject = r;\n          });\n          onReject = function onReject() {\n            return reject();\n          };\n          request.signal.addEventListener(\"abort\", onReject);\n          _context16.prev = 6;\n          handler = match.route[type];\n          invariant(handler, \"Could not find the \" + type + \" to run on the \\\"\" + match.route.id + \"\\\" route\");\n          _context16.next = 11;\n          return Promise.race([handler({\n            request: request,\n            params: match.params,\n            context: requestContext\n          }), abortPromise]);\n        case 11:\n          result = _context16.sent;\n          invariant(result !== undefined, \"You defined \" + (type === \"action\" ? \"an action\" : \"a loader\") + \" for route \" + (\"\\\"\" + match.route.id + \"\\\" but didn't return anything from your `\" + type + \"` \") + \"function. Please return a value or `null`.\");\n          _context16.next = 19;\n          break;\n        case 15:\n          _context16.prev = 15;\n          _context16.t0 = _context16[\"catch\"](6);\n          resultType = ResultType.error;\n          result = _context16.t0;\n        case 19:\n          _context16.prev = 19;\n          request.signal.removeEventListener(\"abort\", onReject);\n          return _context16.finish(19);\n        case 22:\n          if (!isResponse(result)) {\n            _context16.next = 48;\n            break;\n          }\n          status = result.status; // Process redirects\n          if (!redirectStatusCodes.has(status)) {\n            _context16.next = 33;\n            break;\n          }\n          location = result.headers.get(\"Location\");\n          invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\");\n          isAbsolute = /^[a-z+]+:\\/\\//i.test(location) || location.startsWith(\"//\"); // Support relative routing in internal redirects\n          if (!isAbsolute) {\n            activeMatches = matches.slice(0, matches.indexOf(match) + 1);\n            routePathnames = getPathContributingMatches(activeMatches).map(function (match) {\n              return match.pathnameBase;\n            });\n            resolvedLocation = resolveTo(location, routePathnames, new URL(request.url).pathname);\n            invariant(createPath(resolvedLocation), \"Unable to resolve redirect location: \" + location); // Prepend the basename to the redirect location if we have one\n\n            if (basename) {\n              path = resolvedLocation.pathname;\n              resolvedLocation.pathname = path === \"/\" ? basename : joinPaths([basename, path]);\n            }\n            location = createPath(resolvedLocation);\n          } // Don't process redirects in the router during static requests requests.\n          // Instead, throw the Response and let the server handle it with an HTTP\n          // redirect.  We also update the Location header in place in this flow so\n          // basename and relative routing is taken into account\n          if (!isStaticRequest) {\n            _context16.next = 32;\n            break;\n          }\n          result.headers.set(\"Location\", location);\n          throw result;\n        case 32:\n          return _context16.abrupt(\"return\", {\n            type: ResultType.redirect,\n            status: status,\n            location: location,\n            revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null\n          });\n        case 33:\n          if (!isRouteRequest) {\n            _context16.next = 35;\n            break;\n          }\n          throw {\n            type: resultType || ResultType.data,\n            response: result\n          };\n        case 35:\n          contentType = result.headers.get(\"Content-Type\"); // Check between word boundaries instead of startsWith() due to the last\n          // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n          if (!(contentType && /\\bapplication\\/json\\b/.test(contentType))) {\n            _context16.next = 42;\n            break;\n          }\n          _context16.next = 39;\n          return result.json();\n        case 39:\n          data = _context16.sent;\n          _context16.next = 45;\n          break;\n        case 42:\n          _context16.next = 44;\n          return result.text();\n        case 44:\n          data = _context16.sent;\n        case 45:\n          if (!(resultType === ResultType.error)) {\n            _context16.next = 47;\n            break;\n          }\n          return _context16.abrupt(\"return\", {\n            type: resultType,\n            error: new ErrorResponse(status, result.statusText, data),\n            headers: result.headers\n          });\n        case 47:\n          return _context16.abrupt(\"return\", {\n            type: ResultType.data,\n            data: data,\n            statusCode: result.status,\n            headers: result.headers\n          });\n        case 48:\n          if (!(resultType === ResultType.error)) {\n            _context16.next = 50;\n            break;\n          }\n          return _context16.abrupt(\"return\", {\n            type: resultType,\n            error: result\n          });\n        case 50:\n          if (!(result instanceof DeferredData)) {\n            _context16.next = 52;\n            break;\n          }\n          return _context16.abrupt(\"return\", {\n            type: ResultType.deferred,\n            deferredData: result\n          });\n        case 52:\n          return _context16.abrupt(\"return\", {\n            type: ResultType.data,\n            data: result\n          });\n        case 53:\n        case \"end\":\n          return _context16.stop();\n      }\n    }, _callee15, null, [[6, 15, 19, 22]]);\n  }));\n  return _callLoaderOrAction.apply(this, arguments);\n}\nfunction createClientSideRequest(location, signal, submission) {\n  var url = createClientSideURL(stripHashFromPath(location)).toString();\n  var init = {\n    signal: signal\n  };\n  if (submission && isMutationMethod(submission.formMethod)) {\n    var formMethod = submission.formMethod,\n      formEncType = submission.formEncType,\n      formData = submission.formData;\n    init.method = formMethod.toUpperCase();\n    init.body = formEncType === \"application/x-www-form-urlencoded\" ? convertFormDataToSearchParams(formData) : formData;\n  } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n\n  return new Request(url, init);\n}\nfunction convertFormDataToSearchParams(formData) {\n  var searchParams = new URLSearchParams();\n  var _iterator5 = _createForOfIteratorHelper(formData.entries()),\n    _step5;\n  try {\n    for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n      var _step5$value = _slicedToArray(_step5.value, 2),\n        key = _step5$value[0],\n        value = _step5$value[1];\n      invariant(typeof value === \"string\", 'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' + 'please use \"multipart/form-data\" instead.');\n      searchParams.append(key, value);\n    }\n  } catch (err) {\n    _iterator5.e(err);\n  } finally {\n    _iterator5.f();\n  }\n  return searchParams;\n}\nfunction processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {\n  // Fill in loaderData/errors from our loaders\n  var loaderData = {};\n  var errors = null;\n  var statusCode;\n  var foundError = false;\n  var loaderHeaders = {}; // Process loader results into state.loaderData/state.errors\n\n  results.forEach(function (result, index) {\n    var id = matchesToLoad[index].route.id;\n    invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\n    if (isErrorResult(result)) {\n      // Look upwards from the matched route for the closest ancestor\n      // error boundary, defaulting to the root match\n      var boundaryMatch = findNearestBoundary(matches, id);\n      var error = result.error; // If we have a pending action error, we report it at the highest-route\n      // that throws a loader error, and then clear it out to indicate that\n      // it was consumed\n\n      if (pendingError) {\n        error = Object.values(pendingError)[0];\n        pendingError = undefined;\n      }\n      errors = errors || {}; // Prefer higher error values if lower errors bubble to the same boundary\n\n      if (errors[boundaryMatch.route.id] == null) {\n        errors[boundaryMatch.route.id] = error;\n      } // Clear our any prior loaderData for the throwing route\n\n      loaderData[id] = undefined; // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n\n      if (!foundError) {\n        foundError = true;\n        statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    } else if (isDeferredResult(result)) {\n      activeDeferreds && activeDeferreds.set(id, result.deferredData);\n      loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix\n    } else {\n      loaderData[id] = result.data; // Error status codes always override success status codes, but if all\n      // loaders are successful we take the deepest status code.\n\n      if (result.statusCode != null && result.statusCode !== 200 && !foundError) {\n        statusCode = result.statusCode;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    }\n  }); // If we didn't consume the pending action error (i.e., all loaders\n  // resolved), then consume it here.  Also clear out any loaderData for the\n  // throwing route\n\n  if (pendingError) {\n    errors = pendingError;\n    loaderData[Object.keys(pendingError)[0]] = undefined;\n  }\n  return {\n    loaderData: loaderData,\n    errors: errors,\n    statusCode: statusCode || 200,\n    loaderHeaders: loaderHeaders\n  };\n}\nfunction processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {\n  var _processRouteLoaderDa = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds),\n    loaderData = _processRouteLoaderDa.loaderData,\n    errors = _processRouteLoaderDa.errors; // Process results from our revalidating fetchers\n\n  for (var index = 0; index < revalidatingFetchers.length; index++) {\n    var _revalidatingFetchers = _slicedToArray(revalidatingFetchers[index], 3),\n      key = _revalidatingFetchers[0],\n      match = _revalidatingFetchers[2];\n    invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, \"Did not find corresponding fetcher result\");\n    var result = fetcherResults[index]; // Process fetcher non-redirect errors\n\n    if (isErrorResult(result)) {\n      var boundaryMatch = findNearestBoundary(state.matches, match.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = _extends({}, errors, _defineProperty({}, boundaryMatch.route.id, result.error));\n      }\n      state.fetchers.delete(key);\n    } else if (isRedirectResult(result)) {\n      // Should never get here, redirects should get processed above, but we\n      // keep this to type narrow to a success result in the else\n      throw new Error(\"Unhandled fetcher revalidation redirect\");\n    } else if (isDeferredResult(result)) {\n      // Should never get here, deferred data should be awaited for fetchers\n      // in resolveDeferredResults\n      throw new Error(\"Unhandled fetcher deferred data\");\n    } else {\n      var doneFetcher = {\n        state: \"idle\",\n        data: result.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true\n      };\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n  return {\n    loaderData: loaderData,\n    errors: errors\n  };\n}\nfunction mergeLoaderData(loaderData, newLoaderData, matches, errors) {\n  var mergedLoaderData = _extends({}, newLoaderData);\n  var _iterator6 = _createForOfIteratorHelper(matches),\n    _step6;\n  try {\n    for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {\n      var match = _step6.value;\n      var id = match.route.id;\n      if (newLoaderData.hasOwnProperty(id)) {\n        if (newLoaderData[id] !== undefined) {\n          mergedLoaderData[id] = newLoaderData[id];\n        }\n      } else if (loaderData[id] !== undefined) {\n        mergedLoaderData[id] = loaderData[id];\n      }\n      if (errors && errors.hasOwnProperty(id)) {\n        // Don't keep any loader data below the boundary\n        break;\n      }\n    }\n  } catch (err) {\n    _iterator6.e(err);\n  } finally {\n    _iterator6.f();\n  }\n  return mergedLoaderData;\n} // Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\n\nfunction findNearestBoundary(matches, routeId) {\n  var eligibleMatches = routeId ? matches.slice(0, matches.findIndex(function (m) {\n    return m.route.id === routeId;\n  }) + 1) : _toConsumableArray(matches);\n  return eligibleMatches.reverse().find(function (m) {\n    return m.route.hasErrorBoundary === true;\n  }) || matches[0];\n}\nfunction getShortCircuitMatches(routes) {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  var route = routes.find(function (r) {\n    return r.index || !r.path || r.path === \"/\";\n  }) || {\n    id: \"__shim-error-route__\"\n  };\n  return {\n    matches: [{\n      params: {},\n      pathname: \"\",\n      pathnameBase: \"\",\n      route: route\n    }],\n    route: route\n  };\n}\nfunction getInternalRouterError(status, _temp4) {\n  var _ref28 = _temp4 === void 0 ? {} : _temp4,\n    pathname = _ref28.pathname,\n    routeId = _ref28.routeId,\n    method = _ref28.method;\n  var statusText = \"Unknown Server Error\";\n  var errorMessage = \"Unknown @remix-run/router error\";\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage = \"You made a \" + method + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide a `loader` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n    } else {\n      errorMessage = \"Cannot submit binary form data using GET\";\n    }\n  } else if (status === 403) {\n    statusText = \"Forbidden\";\n    errorMessage = \"Route \\\"\" + routeId + \"\\\" does not match URL \\\"\" + pathname + \"\\\"\";\n  } else if (status === 404) {\n    statusText = \"Not Found\";\n    errorMessage = \"No route matches URL \\\"\" + pathname + \"\\\"\";\n  } else if (status === 405) {\n    statusText = \"Method Not Allowed\";\n    if (method && pathname && routeId) {\n      errorMessage = \"You made a \" + method.toUpperCase() + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide an `action` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n    } else if (method) {\n      errorMessage = \"Invalid request method \\\"\" + method.toUpperCase() + \"\\\"\";\n    }\n  }\n  return new ErrorResponse(status || 500, statusText, new Error(errorMessage), true);\n} // Find any returned redirect errors, starting from the lowest match\n\nfunction findRedirect(results) {\n  for (var i = results.length - 1; i >= 0; i--) {\n    var result = results[i];\n    if (isRedirectResult(result)) {\n      return result;\n    }\n  }\n}\nfunction stripHashFromPath(path) {\n  var parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath(_extends({}, parsedPath, {\n    hash: \"\"\n  }));\n}\nfunction isHashChangeOnly(a, b) {\n  return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;\n}\nfunction isDeferredResult(result) {\n  return result.type === ResultType.deferred;\n}\nfunction isErrorResult(result) {\n  return result.type === ResultType.error;\n}\nfunction isRedirectResult(result) {\n  return (result && result.type) === ResultType.redirect;\n}\nfunction isResponse(value) {\n  return value != null && typeof value.status === \"number\" && typeof value.statusText === \"string\" && typeof value.headers === \"object\" && typeof value.body !== \"undefined\";\n}\nfunction isRedirectResponse(result) {\n  if (!isResponse(result)) {\n    return false;\n  }\n  var status = result.status;\n  var location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\nfunction isQueryRouteResponse(obj) {\n  return obj && isResponse(obj.response) && (obj.type === ResultType.data || ResultType.error);\n}\nfunction isValidMethod(method) {\n  return validRequestMethods.has(method);\n}\nfunction isMutationMethod(method) {\n  return validMutationMethods.has(method);\n}\nfunction resolveDeferredResults(_x67, _x68, _x69, _x70, _x71, _x72) {\n  return _resolveDeferredResults.apply(this, arguments);\n}\nfunction _resolveDeferredResults() {\n  _resolveDeferredResults = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {\n    var _loop, index;\n    return _regeneratorRuntime().wrap(function _callee16$(_context18) {\n      while (1) switch (_context18.prev = _context18.next) {\n        case 0:\n          _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(index) {\n            var result, match, currentMatch, isRevalidatingLoader;\n            return _regeneratorRuntime().wrap(function _loop$(_context17) {\n              while (1) switch (_context17.prev = _context17.next) {\n                case 0:\n                  result = results[index];\n                  match = matchesToLoad[index];\n                  currentMatch = currentMatches.find(function (m) {\n                    return m.route.id === match.route.id;\n                  });\n                  isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n                  if (!(isDeferredResult(result) && (isFetcher || isRevalidatingLoader))) {\n                    _context17.next = 7;\n                    break;\n                  }\n                  _context17.next = 7;\n                  return resolveDeferredData(result, signal, isFetcher).then(function (result) {\n                    if (result) {\n                      results[index] = result || results[index];\n                    }\n                  });\n                case 7:\n                case \"end\":\n                  return _context17.stop();\n              }\n            }, _loop);\n          });\n          index = 0;\n        case 2:\n          if (!(index < results.length)) {\n            _context18.next = 7;\n            break;\n          }\n          return _context18.delegateYield(_loop(index), \"t0\", 4);\n        case 4:\n          index++;\n          _context18.next = 2;\n          break;\n        case 7:\n        case \"end\":\n          return _context18.stop();\n      }\n    }, _callee16);\n  }));\n  return _resolveDeferredResults.apply(this, arguments);\n}\nfunction resolveDeferredData(_x73, _x74, _x75) {\n  return _resolveDeferredData.apply(this, arguments);\n}\nfunction _resolveDeferredData() {\n  _resolveDeferredData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(result, signal, unwrap) {\n    var aborted;\n    return _regeneratorRuntime().wrap(function _callee17$(_context19) {\n      while (1) switch (_context19.prev = _context19.next) {\n        case 0:\n          if (unwrap === void 0) {\n            unwrap = false;\n          }\n          _context19.next = 3;\n          return result.deferredData.resolveData(signal);\n        case 3:\n          aborted = _context19.sent;\n          if (!aborted) {\n            _context19.next = 6;\n            break;\n          }\n          return _context19.abrupt(\"return\");\n        case 6:\n          if (!unwrap) {\n            _context19.next = 14;\n            break;\n          }\n          _context19.prev = 7;\n          return _context19.abrupt(\"return\", {\n            type: ResultType.data,\n            data: result.deferredData.unwrappedData\n          });\n        case 11:\n          _context19.prev = 11;\n          _context19.t0 = _context19[\"catch\"](7);\n          return _context19.abrupt(\"return\", {\n            type: ResultType.error,\n            error: _context19.t0\n          });\n        case 14:\n          return _context19.abrupt(\"return\", {\n            type: ResultType.data,\n            data: result.deferredData.data\n          });\n        case 15:\n        case \"end\":\n          return _context19.stop();\n      }\n    }, _callee17, null, [[7, 11]]);\n  }));\n  return _resolveDeferredData.apply(this, arguments);\n}\nfunction hasNakedIndexQuery(search) {\n  return new URLSearchParams(search).getAll(\"index\").some(function (v) {\n    return v === \"\";\n  });\n} // Note: This should match the format exported by useMatches, so if you change\n// this please also change that :)  Eventually we'll DRY this up\n\nfunction createUseMatchesMatch(match, loaderData) {\n  var route = match.route,\n    pathname = match.pathname,\n    params = match.params;\n  return {\n    id: route.id,\n    pathname: pathname,\n    params: params,\n    data: loaderData[route.id],\n    handle: route.handle\n  };\n}\nfunction getTargetMatch(matches, location) {\n  var search = typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || \"\")) {\n    // Return the leaf index route when index is present\n    return matches[matches.length - 1];\n  } // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n\n  var pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n} //#endregion\n\nexport { AbortedDeferredError, Action, ErrorResponse, IDLE_FETCHER, IDLE_NAVIGATION, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, getPathContributingMatches as UNSAFE_getPathContributingMatches, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, resolvePath, resolveTo, stripBasename, warning };","map":{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;;AAEG;IACSA;AAAZ,WAAYA,MAAZ,EAAkB;EAChB;;;;;;AAMG;EACHA;EAEA;;;;AAIG;;EACHA;EAEA;;;AAGG;;EACHA;AACD,CAtBD,EAAYA,MAAM,KAANA,MAAM,GAsBjB,EAtBiB,CAAlB;AA2KA,IAAMC,iBAAiB,GAAG,UAA1B;AA+BA;;;AAGG;;AACa,6BACdC,OADc,EACoB;EAAA,IAAlCA,OAAkC;IAAlCA,OAAkC,GAAF,EAAE;EAAA;EAElC,eAAiEA,OAAjE;IAAA,iCAAMC,cAAc;IAAdA,cAAc,sCAAG,CAAC,GAAD,CAAnB;IAA0BC,YAA1B,YAA0BA,YAA1B;IAAA,6BAAwCC,QAAQ;IAARA,QAAQ,kCAAG;EACvD,IAAIC,OAAJ,CAHkC;;EAIlCA,OAAO,GAAGH,cAAc,C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8B6E,KAAlC,CAAM7E,KAAF;IAAS1E,QAAT,GAA8BuJ,KAAlC,CAAavJ,QAAT;IAAmB0J,SAAWH,KAAlC,CAAuBG;EACvB,OAAO;IACLzE,EAAE,EAAEP,KAAK,CAACO,EADL;IAELjF,QAFK,EAELA,QAFK;IAGL0J,MAHK,EAGLA,MAHK;IAILsD,IAAI,EAAE2F,UAAU,CAACjO,KAAK,CAACO,EAAP,CAJX;IAKLqb,MAAM,EAAE5b,KAAK,CAAC4b;GALhB;AAOD;AAED,SAAS/J,cAAT,CACExQ,OADF,EAEEjG,QAFF,EAE6B;EAE3B,IAAIa,MAAM,GACR,OAAOb,QAAP,KAAoB,QAApB,GAA+BY,SAAS,CAACZ,QAAD,CAAT,CAAoBa,MAAnD,GAA4Db,QAAQ,CAACa,MADvE;EAEA,IACEoF,OAAO,CAACA,OAAO,CAAC5G,MAAR,GAAiB,CAAlB,CAAP,CAA4BuF,KAA5B,CAAkC5F,KAAlC,IACAse,kBAAkB,CAACzc,MAAM,IAAI,EAAX,CAFpB,EAGE;IACA;IACA,OAAOoF,OAAO,CAACA,OAAO,CAAC5G,MAAR,GAAiB,CAAlB,CAAd;EACD,CAV0B;EAY3B;;EACA,IAAIohB,WAAW,GAAGvU,0BAA0B,CAACjG,OAAD,CAA5C;EACA,OAAOwa,WAAW,CAACA,WAAW,CAACphB,MAAZ,GAAqB,CAAtB,CAAlB;AACD","names":["Action","PopStateEventType","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","history","createHref","createPath","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","replace","Replace","go","delta","listen","fn","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashLocation","substr","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","current","_ref","parsedPath","searchIndex","createClientSideURL","origin","invariant","URL","getLocation","validateLocation","defaultView","handlePop","historyState","pushState","error","assign","replaceState","addEventListener","removeEventListener","ResultType","isIndexRoute","route","convertRoutesToDataRoutes","routes","parentPath","allIds","Set","treePath","id","join","children","has","add","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","safelyDecodeURI","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","startsWith","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","explodeOptionalSegments","exploded","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","match","matchPath","Object","params","pathnameBase","normalizePathname","generatePath","originalPath","_","prefix","__","str","star","pattern","compilePath","matcher","paramNames","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","regexpSource","RegExp","decodeURI","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","data","init","responseInit","status","headers","Headers","set","Response","AbortedDeferredError","DeferredData","constructor","subscriber","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","trackPromise","pendingKeys","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","done","subscribe","cancel","abort","v","k","resolve","size","unwrapTrackedPromise","isTrackedPromise","_tracked","_error","_data","defer","redirect","ErrorResponse","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","IDLE_FETCHER","isBrowser","createElement","isServer","createRouter","dataRoutes","unlistenHistory","subscribers","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","m","loader","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","loaderData","actionData","errors","fetchers","Map","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeDeferreds","initialize","startNavigation","dispose","clear","deleteFetcher","updateState","newState","completeNavigation","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","getSavedScrollPosition","navigate","opts","normalizeNavigateOptions","submission","userReplace","pendingError","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","findNearestBoundary","handleAction","actionOutput","shortCircuited","pendingActionData","pendingActionError","Request","handleLoaders","actionMatch","getTargetMatch","type","method","routeId","callLoaderOrAction","isRedirectResult","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","activeSubmission","getMatchesToLoad","matchesToLoad","revalidatingFetchers","fetcher","revalidatingFetcher","callLoadersAndMaybeResolveData","results","loaderResults","fetcherResults","findRedirect","processLoaderData","deferredData","markFetchRedirectsDone","didAbortFetchLoads","abortStaleFetchLoads","_extends","getFetcher","fetch","abortFetcher","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","abortController","fetchRequest","actionResult","loadingFetcher","isFetchActionRedirect","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp","redirectLocation","_isFetchActionRedirect","_window","newOrigin","redirectHistoryAction","currentMatches","fetchersToLoad","all","fetchMatches","resolveDeferredResults","markFetchersDone","doneKeys","landedId","yeetedKeys","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","userMatches","createUseMatchesMatch","_internalFetchControllers","_internalActiveDeferreds","query","_temp2","requestContext","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp3","find","values","routeData","routeMatch","submit","loadRouteData","isQueryRouteResponse","isRedirectResponse","response","isRouteRequest","Location","context","loaderRequest","getLoaderMatchesUntilBoundary","executedLoaders","processRouteLoaderData","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isSubmissionNavigation","isFetcher","stripHashFromPath","searchParams","convertFormDataToSearchParams","hasNakedIndexQuery","append","boundaryId","boundaryMatches","findIndex","navigationMatches","isNewLoader","shouldRevalidateLoader","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","isNewRouteInstance","currentPath","currentLocation","currentUrl","currentParams","nextUrl","nextParams","defaultShouldRevalidate","routeChoice","isStaticRequest","onReject","handler","resultType","isAbsolute","activeMatches","resolvedLocation","contentType","text","deferred","toUpperCase","body","URLSearchParams","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","hasErrorBoundary","_temp4","errorMessage","obj","isRevalidatingLoader","unwrap","resolveData","unwrappedData","getAll","handle","pathMatches"],"sources":["C:\\Users\\user\\Desktop\\05mediaSocial\\client\\node_modules\\@remix-run\\router\\history.ts","C:\\Users\\user\\Desktop\\05mediaSocial\\client\\node_modules\\@remix-run\\router\\utils.ts","C:\\Users\\user\\Desktop\\05mediaSocial\\client\\node_modules\\@remix-run\\router\\router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Pop = \"POP\",\n\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n  Push = \"PUSH\",\n\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n  /**\n   * A URL pathname, beginning with a /.\n   */\n  pathname: string;\n\n  /**\n   * A URL search string, beginning with a ?.\n   */\n  search: string;\n\n  /**\n   * A URL fragment identifier, beginning with a #.\n   */\n  hash: string;\n}\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: any;\n\n  /**\n   * A unique string associated with this location. May be used to safely store\n   * and retrieve data in some other storage API, like `localStorage`.\n   *\n   * Note: This value is always \"default\" on the initial location.\n   */\n  key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n  /**\n   * The action that triggered the change.\n   */\n  action: Action;\n\n  /**\n   * The new location.\n   */\n  location: Location;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n  (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. May be either a URL or the pieces of a\n * URL path.\n */\nexport type To = string | Partial<Path>;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n  /**\n   * The last action that modified the current location. This will always be\n   * Action.Pop when a history instance is first created. This value is mutable.\n   */\n  readonly action: Action;\n\n  /**\n   * The current location. This value is mutable.\n   */\n  readonly location: Location;\n\n  /**\n   * Returns a valid href for the given `to` value that may be used as\n   * the value of an <a href> attribute.\n   *\n   * @param to - The destination URL\n   */\n  createHref(to: To): string;\n\n  /**\n   * Encode a location the same way window.history would do (no-op for memory\n   * history) so we ensure our PUSH/REPLACE navigations for data routers\n   * behave the same as POP\n   *\n   * @param to Unencoded path\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * Pushes a new location onto the history stack, increasing its length by one.\n   * If there were any entries in the stack after the current one, they are\n   * lost.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  push(to: To, state?: any): void;\n\n  /**\n   * Replaces the current location in the history stack with a new one.  The\n   * location that was replaced will no longer be available.\n   *\n   * @param to - The new URL\n   * @param state - Data to associate with the new location\n   */\n  replace(to: To, state?: any): void;\n\n  /**\n   * Navigates `n` entries backward/forward in the history stack relative to the\n   * current index. For example, a \"back\" navigation would use go(-1).\n   *\n   * @param delta - The delta in the stack index\n   */\n  go(delta: number): void;\n\n  /**\n   * Sets up a listener that will be called whenever the current location\n   * changes.\n   *\n   * @param listener - A function that will be called when the location changes\n   * @returns unlisten - A function that may be used to stop listening\n   */\n  listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n  usr: any;\n  key?: string;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial<Location>;\n\nexport type MemoryHistoryOptions = {\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n  /**\n   * The current index in the history stack.\n   */\n  readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n  options: MemoryHistoryOptions = {}\n): MemoryHistory {\n  let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n  let entries: Location[]; // Declare so we can access from createMemoryLocation\n  entries = initialEntries.map((entry, index) =>\n    createMemoryLocation(\n      entry,\n      typeof entry === \"string\" ? null : entry.state,\n      index === 0 ? \"default\" : undefined\n    )\n  );\n  let index = clampIndex(\n    initialIndex == null ? entries.length - 1 : initialIndex\n  );\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function clampIndex(n: number): number {\n    return Math.min(Math.max(n, 0), entries.length - 1);\n  }\n  function getCurrentLocation(): Location {\n    return entries[index];\n  }\n  function createMemoryLocation(\n    to: To,\n    state: any = null,\n    key?: string\n  ): Location {\n    let location = createLocation(\n      entries ? getCurrentLocation().pathname : \"/\",\n      to,\n      state,\n      key\n    );\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in memory history: ${JSON.stringify(\n        to\n      )}`\n    );\n    return location;\n  }\n\n  let history: MemoryHistory = {\n    get index() {\n      return index;\n    },\n    get action() {\n      return action;\n    },\n    get location() {\n      return getCurrentLocation();\n    },\n    createHref(to) {\n      return typeof to === \"string\" ? to : createPath(to);\n    },\n    encodeLocation(to: To) {\n      let path = typeof to === \"string\" ? parsePath(to) : to;\n      return {\n        pathname: path.pathname || \"\",\n        search: path.search || \"\",\n        hash: path.hash || \"\",\n      };\n    },\n    push(to, state) {\n      action = Action.Push;\n      let nextLocation = createMemoryLocation(to, state);\n      index += 1;\n      entries.splice(index, entries.length, nextLocation);\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation });\n      }\n    },\n    replace(to, state) {\n      action = Action.Replace;\n      let nextLocation = createMemoryLocation(to, state);\n      entries[index] = nextLocation;\n      if (v5Compat && listener) {\n        listener({ action, location: nextLocation });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      index = clampIndex(index + delta);\n      if (listener) {\n        listener({ action, location: getCurrentLocation() });\n      }\n    },\n    listen(fn: Listener) {\n      listener = fn;\n      return () => {\n        listener = null;\n      };\n    },\n  };\n\n  return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n  options: BrowserHistoryOptions = {}\n): BrowserHistory {\n  function createBrowserLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let { pathname, search, hash } = window.location;\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createBrowserHref(window: Window, to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\n  }\n\n  return getUrlBasedHistory(\n    createBrowserLocation,\n    createBrowserHref,\n    null,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n  options: HashHistoryOptions = {}\n): HashHistory {\n  function createHashLocation(\n    window: Window,\n    globalHistory: Window[\"history\"]\n  ) {\n    let {\n      pathname = \"/\",\n      search = \"\",\n      hash = \"\",\n    } = parsePath(window.location.hash.substr(1));\n    return createLocation(\n      \"\",\n      { pathname, search, hash },\n      // state defaults to `null` because `window.history.state` does\n      (globalHistory.state && globalHistory.state.usr) || null,\n      (globalHistory.state && globalHistory.state.key) || \"default\"\n    );\n  }\n\n  function createHashHref(window: Window, to: To) {\n    let base = window.document.querySelector(\"base\");\n    let href = \"\";\n\n    if (base && base.getAttribute(\"href\")) {\n      let url = window.location.href;\n      let hashIndex = url.indexOf(\"#\");\n      href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n    }\n\n    return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n  }\n\n  function validateHashLocation(location: Location, to: To) {\n    warning(\n      location.pathname.charAt(0) === \"/\",\n      `relative pathnames are not supported in hash history.push(${JSON.stringify(\n        to\n      )})`\n    );\n  }\n\n  return getUrlBasedHistory(\n    createHashLocation,\n    createHashHref,\n    validateHashLocation,\n    options\n  );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant<T>(\n  value: T | null | undefined,\n  message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n  if (value === false || value === null || typeof value === \"undefined\") {\n    throw new Error(message);\n  }\n}\n\nfunction warning(cond: any, message: string) {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n\n    try {\n      // Welcome to debugging history!\n      //\n      // This error is thrown as a convenience so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message);\n      // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n\nfunction createKey() {\n  return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n  };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n  current: string | Location,\n  to: To,\n  state: any = null,\n  key?: string\n): Readonly<Location> {\n  let location: Readonly<Location> = {\n    pathname: typeof current === \"string\" ? current : current.pathname,\n    search: \"\",\n    hash: \"\",\n    ...(typeof to === \"string\" ? parsePath(to) : to),\n    state,\n    // TODO: This could be cleaned up.  push/replace should probably just take\n    // full Locations now and avoid the need to run through this flow at all\n    // But that's a pretty big refactor to the current test suite so going to\n    // keep as is for the time being and just let any incoming keys take precedence\n    key: (to && (to as Location).key) || key || createKey(),\n  };\n  return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n  pathname = \"/\",\n  search = \"\",\n  hash = \"\",\n}: Partial<Path>) {\n  if (search && search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash && hash !== \"#\")\n    pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n  return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial<Path> {\n  let parsedPath: Partial<Path> = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex >= 0) {\n      parsedPath.search = path.substr(searchIndex);\n      path = path.substr(0, searchIndex);\n    }\n\n    if (path) {\n      parsedPath.pathname = path;\n    }\n  }\n\n  return parsedPath;\n}\n\nexport function createClientSideURL(location: Location | string): URL {\n  // window.location.origin is \"null\" (the literal string value) in Firefox\n  // under certain conditions, notably when serving from a local HTML file\n  // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n  let base =\n    typeof window !== \"undefined\" &&\n    typeof window.location !== \"undefined\" &&\n    window.location.origin !== \"null\"\n      ? window.location.origin\n      : window.location.href;\n  let href = typeof location === \"string\" ? location : createPath(location);\n  invariant(\n    base,\n    `No window.location.(origin|href) available to create URL for href: ${href}`\n  );\n  return new URL(href, base);\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n  window?: Window;\n  v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n  getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n  createHref: (window: Window, to: To) => string,\n  validateLocation: ((location: Location, to: To) => void) | null,\n  options: UrlHistoryOptions = {}\n): UrlHistory {\n  let { window = document.defaultView!, v5Compat = false } = options;\n  let globalHistory = window.history;\n  let action = Action.Pop;\n  let listener: Listener | null = null;\n\n  function handlePop() {\n    action = Action.Pop;\n    if (listener) {\n      listener({ action, location: history.location });\n    }\n  }\n\n  function push(to: To, state?: any) {\n    action = Action.Push;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    let historyState = getHistoryState(location);\n    let url = history.createHref(location);\n\n    // try...catch because iOS limits us to 100 pushState calls :/\n    try {\n      globalHistory.pushState(historyState, \"\", url);\n    } catch (error) {\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location });\n    }\n  }\n\n  function replace(to: To, state?: any) {\n    action = Action.Replace;\n    let location = createLocation(history.location, to, state);\n    if (validateLocation) validateLocation(location, to);\n\n    let historyState = getHistoryState(location);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location });\n    }\n  }\n\n  let history: History = {\n    get action() {\n      return action;\n    },\n    get location() {\n      return getLocation(window, globalHistory);\n    },\n    listen(fn: Listener) {\n      if (listener) {\n        throw new Error(\"A history only accepts one active listener\");\n      }\n      window.addEventListener(PopStateEventType, handlePop);\n      listener = fn;\n\n      return () => {\n        window.removeEventListener(PopStateEventType, handlePop);\n        listener = null;\n      };\n    },\n    createHref(to) {\n      return createHref(window, to);\n    },\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createClientSideURL(\n        typeof to === \"string\" ? to : createPath(to)\n      );\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n  [routeId: string]: any;\n}\n\nexport enum ResultType {\n  data = \"data\",\n  deferred = \"deferred\",\n  redirect = \"redirect\",\n  error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n  type: ResultType.data;\n  data: any;\n  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n  type: ResultType.deferred;\n  deferredData: DeferredData;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  status: number;\n  location: string;\n  revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: any;\n  headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n  | SuccessResult\n  | DeferredResult\n  | RedirectResult\n  | ErrorResult;\n\nexport type MutationFormMethod = \"post\" | \"put\" | \"patch\" | \"delete\";\nexport type FormMethod = \"get\" | MutationFormMethod;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\";\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport interface Submission {\n  formMethod: FormMethod;\n  formAction: string;\n  formEncType: FormEncType;\n  formData: FormData;\n}\n\n/**\n * @private\n * Arguments passed to route loader/action functions.  Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n  request: Request;\n  params: Params;\n  context?: any;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n  (args: LoaderFunctionArgs): Promise<Response> | Response | Promise<any> | any;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n  (args: ActionFunctionArgs): Promise<Response> | Response | Promise<any> | any;\n}\n\n/**\n * Route shouldRevalidate function signature.  This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments.  It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n  (args: {\n    currentUrl: URL;\n    currentParams: AgnosticDataRouteMatch[\"params\"];\n    nextUrl: URL;\n    nextParams: AgnosticDataRouteMatch[\"params\"];\n    formMethod?: Submission[\"formMethod\"];\n    formAction?: Submission[\"formAction\"];\n    formEncType?: Submission[\"formEncType\"];\n    formData?: Submission[\"formData\"];\n    actionResult?: DataResult;\n    defaultShouldRevalidate: boolean;\n  }): boolean;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n  caseSensitive?: boolean;\n  path?: string;\n  id?: string;\n  loader?: LoaderFunction;\n  action?: ActionFunction;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: undefined;\n  index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n  children?: AgnosticRouteObject[];\n  index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n  | AgnosticIndexRouteObject\n  | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n  children?: AgnosticDataRouteObject[];\n  id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n  | AgnosticDataIndexRouteObject\n  | AgnosticDataNonIndexRouteObject;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam<Path extends string> =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam<L> | _PathParam<R>\n    : // find params after `:`\n    Path extends `:${infer Param}`\n    ? Param\n    : // otherwise, there aren't any params present\n      never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\ntype PathParam<Path extends string> =\n  // check if path is just a wildcard\n  Path extends \"*\"\n    ? \"*\"\n    : // look for wildcard at the end of the path\n    Path extends `${infer Rest}/*`\n    ? \"*\" | _PathParam<Rest>\n    : // look for params in the absence of wildcards\n      _PathParam<Path>;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey<Segment extends string> =\n  // if could not find path params, fallback to `string`\n  [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params<Key extends string = string> = {\n  readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The route object that was used to match.\n   */\n  route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}\n\nfunction isIndexRoute(\n  route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n  return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n  routes: AgnosticRouteObject[],\n  parentPath: number[] = [],\n  allIds: Set<string> = new Set<string>()\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, index];\n    let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n    invariant(\n      route.index !== true || !route.children,\n      `Cannot specify children on an index route`\n    );\n    invariant(\n      !allIds.has(id),\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n    allIds.add(id);\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = { ...route, id };\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        id,\n        children: route.children\n          ? convertRoutesToDataRoutes(route.children, treePath, allIds)\n          : undefined,\n      };\n      return pathOrLayoutRoute;\n    }\n  });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename = \"/\"\n): AgnosticRouteMatch<string, RouteObjectType>[] | null {\n  let location =\n    typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n  let pathname = stripBasename(location.pathname || \"/\", basename);\n\n  if (pathname == null) {\n    return null;\n  }\n\n  let branches = flattenRoutes(routes);\n  rankRouteBranches(branches);\n\n  let matches = null;\n  for (let i = 0; matches == null && i < branches.length; ++i) {\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      // Incoming pathnames are generally encoded from either window.location\n      // or from router.navigate, but we want to match against the unencoded\n      // paths in the route definitions.  Memory router locations won't be\n      // encoded here but there also shouldn't be anything to decode so this\n      // should be a safe operation.  This avoids needing matchRoutes to be\n      // history-aware.\n      safelyDecodeURI(pathname)\n    );\n  }\n\n  return matches;\n}\n\ninterface RouteMeta<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta<RouteObjectType>[];\n}\n\nfunction flattenRoutes<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  branches: RouteBranch<RouteObjectType>[] = [],\n  parentsMeta: RouteMeta<RouteObjectType>[] = [],\n  parentPath = \"\"\n): RouteBranch<RouteObjectType>[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) => {\n    let meta: RouteMeta<RouteObjectType> = {\n      relativePath:\n        relativePath === undefined ? route.path || \"\" : relativePath,\n      caseSensitive: route.caseSensitive === true,\n      childrenIndex: index,\n      route,\n    };\n\n    if (meta.relativePath.startsWith(\"/\")) {\n      invariant(\n        meta.relativePath.startsWith(parentPath),\n        `Absolute route path \"${meta.relativePath}\" nested under path ` +\n          `\"${parentPath}\" is not valid. An absolute child route path ` +\n          `must start with the combined path of all its parent routes.`\n      );\n\n      meta.relativePath = meta.relativePath.slice(parentPath.length);\n    }\n\n    let path = joinPaths([parentPath, meta.relativePath]);\n    let routesMeta = parentsMeta.concat(meta);\n\n    // Add the children before adding this route to the array so we traverse the\n    // route tree depth-first and child routes appear before their parents in\n    // the \"flattened\" version.\n    if (route.children && route.children.length > 0) {\n      invariant(\n        // Our types know better, but runtime JS may not!\n        // @ts-expect-error\n        route.index !== true,\n        `Index routes must not have child routes. Please remove ` +\n          `all child routes from route path \"${path}\".`\n      );\n\n      flattenRoutes(route.children, branches, routesMeta, path);\n    }\n\n    // Routes without a path shouldn't ever match by themselves unless they are\n    // index routes, so don't add them to the list of possible branches.\n    if (route.path == null && !route.index) {\n      return;\n    }\n\n    branches.push({\n      path,\n      score: computeScore(path, route.index),\n      routesMeta,\n    });\n  };\n  routes.forEach((route, index) => {\n    // coarse-grain check for optional params\n    if (route.path === \"\" || !route.path?.includes(\"?\")) {\n      flattenRoute(route, index);\n    } else {\n      for (let exploded of explodeOptionalSegments(route.path)) {\n        flattenRoute(route, index, exploded);\n      }\n    }\n  });\n\n  return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n  let segments = path.split(\"/\");\n  if (segments.length === 0) return [];\n\n  let [first, ...rest] = segments;\n\n  // Optional path segments are denoted by a trailing `?`\n  let isOptional = first.endsWith(\"?\");\n  // Compute the corresponding required segment: `foo?` -> `foo`\n  let required = first.replace(/\\?$/, \"\");\n\n  if (rest.length === 0) {\n    // Intepret empty string as omitting an optional segment\n    // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n    return isOptional ? [required, \"\"] : [required];\n  }\n\n  let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n  let result: string[] = [];\n\n  // All child paths with the prefix.  Do this for all children before the\n  // optional version for all children so we get consistent ordering where the\n  // parent optional aspect is preferred as required.  Otherwise, we can get\n  // child sections interspersed where deeper optional segments are higher than\n  // parent optional segments, where for example, /:two would explodes _earlier_\n  // then /:one.  By always including the parent as required _for all children_\n  // first, we avoid this issue\n  result.push(\n    ...restExploded.map((subpath) =>\n      subpath === \"\" ? required : [required, subpath].join(\"/\")\n    )\n  );\n\n  // Then if this is an optional value, add all child versions without\n  if (isOptional) {\n    result.push(...restExploded);\n  }\n\n  // for absolute paths, ensure `/` instead of empty segment\n  return result.map((exploded) =>\n    path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =>\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) => meta.childrenIndex),\n          b.routesMeta.map((meta) => meta.childrenIndex)\n        )\n  );\n}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n  let segments = path.split(\"/\");\n  let initialScore = segments.length;\n  if (segments.some(isSplat)) {\n    initialScore += splatPenalty;\n  }\n\n  if (index) {\n    initialScore += indexRouteValue;\n  }\n\n  return segments\n    .filter((s) => !isSplat(s))\n    .reduce(\n      (score, segment) =>\n        score +\n        (paramRe.test(segment)\n          ? dynamicSegmentValue\n          : segment === \"\"\n          ? emptySegmentValue\n          : staticSegmentValue),\n      initialScore\n    );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n  let siblings =\n    a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n  return siblings\n    ? // If two routes are siblings, we should try to match the earlier sibling\n      // first. This allows people to have fine-grained control over the matching\n      // behavior by simply putting routes with identical paths in the order they\n      // want them tried.\n      a[a.length - 1] - b[b.length - 1]\n    : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n      // so they sort equally.\n      0;\n}\n\nfunction matchRouteBranch<\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  branch: RouteBranch<RouteObjectType>,\n  pathname: string\n): AgnosticRouteMatch<ParamKey, RouteObjectType>[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch<ParamKey, RouteObjectType>[] = [];\n  for (let i = 0; i < routesMeta.length; ++i) {\n    let meta = routesMeta[i];\n    let end = i === routesMeta.length - 1;\n    let remainingPathname =\n      matchedPathname === \"/\"\n        ? pathname\n        : pathname.slice(matchedPathname.length) || \"/\";\n    let match = matchPath(\n      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n      remainingPathname\n    );\n\n    if (!match) return null;\n\n    Object.assign(matchedParams, match.params);\n\n    let route = meta.route;\n\n    matches.push({\n      // TODO: Can this as be avoided?\n      params: matchedParams as Params<ParamKey>,\n      pathname: joinPaths([matchedPathname, match.pathname]),\n      pathnameBase: normalizePathname(\n        joinPaths([matchedPathname, match.pathnameBase])\n      ),\n      route,\n    });\n\n    if (match.pathnameBase !== \"/\") {\n      matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n    }\n  }\n\n  return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string;\n  } = {} as any\n): string {\n  let path = originalPath;\n  if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n    warning(\n      false,\n      `Route path \"${path}\" will be treated as if it were ` +\n        `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n        `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n        `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n    );\n    path = path.replace(/\\*$/, \"/*\") as Path;\n  }\n\n  return path\n    .replace(/^:(\\w+)/g, (_, key: PathParam<Path>) => {\n      invariant(params[key] != null, `Missing \":${key}\" param`);\n      return params[key]!;\n    })\n    .replace(/\\/:(\\w+)/g, (_, key: PathParam<Path>) => {\n      invariant(params[key] != null, `Missing \":${key}\" param`);\n      return `/${params[key]!}`;\n    })\n    .replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n      const star = \"*\" as PathParam<Path>;\n\n      if (params[star] == null) {\n        // If no splat was provided, trim the trailing slash _unless_ it's\n        // the entire path\n        return str === \"/*\" ? \"/\" : \"\";\n      }\n\n      // Apply the splat\n      return `${prefix}${params[star]}`;\n    });\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern<Path extends string = string> {\n  /**\n   * A string to match against a URL pathname. May contain `:id`-style segments\n   * to indicate placeholders for dynamic parameters. May also end with `/*` to\n   * indicate matching the rest of the URL pathname.\n   */\n  path: Path;\n  /**\n   * Should be `true` if the static portions of the `path` should be matched in\n   * the same case.\n   */\n  caseSensitive?: boolean;\n  /**\n   * Should be `true` if this pattern should match the entire URL pathname.\n   */\n  end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch<ParamKey extends string = string> {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params<ParamKey>;\n  /**\n   * The portion of the URL pathname that was matched.\n   */\n  pathname: string;\n  /**\n   * The portion of the URL pathname that was matched before child routes.\n   */\n  pathnameBase: string;\n  /**\n   * The pattern that was used to match.\n   */\n  pattern: PathPattern;\n}\n\ntype Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(\n  pattern: PathPattern<Path> | Path,\n  pathname: string\n): PathMatch<ParamKey> | null {\n  if (typeof pattern === \"string\") {\n    pattern = { path: pattern, caseSensitive: false, end: true };\n  }\n\n  let [matcher, paramNames] = compilePath(\n    pattern.path,\n    pattern.caseSensitive,\n    pattern.end\n  );\n\n  let match = pathname.match(matcher);\n  if (!match) return null;\n\n  let matchedPathname = match[0];\n  let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n  let captureGroups = match.slice(1);\n  let params: Params = paramNames.reduce<Mutable<Params>>(\n    (memo, paramName, index) => {\n      // We need to compute the pathnameBase here using the raw splat value\n      // instead of using params[\"*\"] later because it will be decoded then\n      if (paramName === \"*\") {\n        let splatValue = captureGroups[index] || \"\";\n        pathnameBase = matchedPathname\n          .slice(0, matchedPathname.length - splatValue.length)\n          .replace(/(.)\\/+$/, \"$1\");\n      }\n\n      memo[paramName] = safelyDecodeURIComponent(\n        captureGroups[index] || \"\",\n        paramName\n      );\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, string[]] {\n  warning(\n    path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n    `Route path \"${path}\" will be treated as if it were ` +\n      `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n      `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n      `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n  );\n\n  let paramNames: string[] = [];\n  let regexpSource =\n    \"^\" +\n    path\n      .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n      .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n      .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n      .replace(/\\/:(\\w+)/g, (_: string, paramName: string) => {\n        paramNames.push(paramName);\n        return \"/([^\\\\/]+)\";\n      });\n\n  if (path.endsWith(\"*\")) {\n    paramNames.push(\"*\");\n    regexpSource +=\n      path === \"*\" || path === \"/*\"\n        ? \"(.*)$\" // Already matched the initial /, just match the rest\n        : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n  } else if (end) {\n    // When matching to the end, ignore trailing slashes\n    regexpSource += \"\\\\/*$\";\n  } else if (path !== \"\" && path !== \"/\") {\n    // If our path is non-empty and contains anything beyond an initial slash,\n    // then we have _some_ form of path in our regex so we should expect to\n    // match only if we find the end of this path segment.  Look for an optional\n    // non-captured trailing slash (to match a portion of the URL) or the end\n    // of the path (if we've matched to the end).  We used to do this with a\n    // word boundary but that gives false positives on routes like\n    // /user-preferences since `-` counts as a word boundary.\n    regexpSource += \"(?:(?=\\\\/|$))\";\n  } else {\n    // Nothing to match for \"\" or \"/\"\n  }\n\n  let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n  return [matcher, paramNames];\n}\n\nfunction safelyDecodeURI(value: string) {\n  try {\n    return decodeURI(value);\n  } catch (error) {\n    warning(\n      false,\n      `The URL path \"${value}\" could not be decoded because it is is a ` +\n        `malformed URL segment. This is probably due to a bad percent ` +\n        `encoding (${error}).`\n    );\n\n    return value;\n  }\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n  try {\n    return decodeURIComponent(value);\n  } catch (error) {\n    warning(\n      false,\n      `The value for the URL param \"${paramName}\" will not be decoded because` +\n        ` the string \"${value}\" is a malformed URL segment. This is probably` +\n        ` due to a bad percent encoding (${error}).`\n    );\n\n    return value;\n  }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n  pathname: string,\n  basename: string\n): string | null {\n  if (basename === \"/\") return pathname;\n\n  if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n    return null;\n  }\n\n  // We want to leave trailing slash behavior in the user's control, so if they\n  // specify a basename with a trailing slash, we should support it\n  let startIndex = basename.endsWith(\"/\")\n    ? basename.length - 1\n    : basename.length;\n  let nextChar = pathname.charAt(startIndex);\n  if (nextChar && nextChar !== \"/\") {\n    // pathname does not start with basename/\n    return null;\n  }\n\n  return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * @private\n */\nexport function warning(cond: any, message: string): void {\n  if (!cond) {\n    // eslint-disable-next-line no-console\n    if (typeof console !== \"undefined\") console.warn(message);\n\n    try {\n      // Welcome to debugging React Router!\n      //\n      // This error is thrown as a convenience so you can more easily\n      // find the source for a warning that appears in the console by\n      // enabling \"pause on exceptions\" in your JavaScript debugger.\n      throw new Error(message);\n      // eslint-disable-next-line no-empty\n    } catch (e) {}\n  }\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n  let {\n    pathname: toPathname,\n    search = \"\",\n    hash = \"\",\n  } = typeof to === \"string\" ? parsePath(to) : to;\n\n  let pathname = toPathname\n    ? toPathname.startsWith(\"/\")\n      ? toPathname\n      : resolvePathname(toPathname, fromPathname)\n    : fromPathname;\n\n  return {\n    pathname,\n    search: normalizeSearch(search),\n    hash: normalizeHash(hash),\n  };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n  let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n  let relativeSegments = relativePath.split(\"/\");\n\n  relativeSegments.forEach((segment) => {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length > 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n\n  return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n  char: string,\n  field: string,\n  dest: string,\n  path: Partial<Path>\n) {\n  return (\n    `Cannot include a '${char}' character in a manually specified ` +\n    `\\`to.${field}\\` field [${JSON.stringify(\n      path\n    )}].  Please separate it out to the ` +\n    `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n    `a string in <Link to=\"...\"> and the router will parse it for you.`\n  );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same.  Both of the following examples should link back to the root:\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\" element={<Link to=\"..\"}>\n *   </Route>\n *\n *   <Route path=\"/\">\n *     <Route path=\"accounts\">\n *       <Route element={<AccountsLayout />}>       // <-- Does not contribute\n *         <Route index element={<Link to=\"..\"} />  // <-- Does not contribute\n *       </Route\n *     </Route>\n *   </Route>\n */\nexport function getPathContributingMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n  return matches.filter(\n    (match, index) =>\n      index === 0 || (match.route.path && match.route.path.length > 0)\n  );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n  toArg: To,\n  routePathnames: string[],\n  locationPathname: string,\n  isPathRelative = false\n): Path {\n  let to: Partial<Path>;\n  if (typeof toArg === \"string\") {\n    to = parsePath(toArg);\n  } else {\n    to = { ...toArg };\n\n    invariant(\n      !to.pathname || !to.pathname.includes(\"?\"),\n      getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n    );\n    invariant(\n      !to.pathname || !to.pathname.includes(\"#\"),\n      getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n    );\n    invariant(\n      !to.search || !to.search.includes(\"#\"),\n      getInvalidPathError(\"#\", \"search\", \"hash\", to)\n    );\n  }\n\n  let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n  let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n  let from: string;\n\n  // Routing is relative to the current pathname if explicitly requested.\n  //\n  // If a pathname is explicitly provided in `to`, it should be relative to the\n  // route context. This is explained in `Note on `<Link to>` values` in our\n  // migration guide from v5 as a means of disambiguation between `to` values\n  // that begin with `/` and those that do not. However, this is problematic for\n  // `to` values that do not provide a pathname. `to` can simply be a search or\n  // hash string, in which case we should assume that the navigation is relative\n  // to the current location's pathname and *not* the route pathname.\n  if (isPathRelative || toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    if (toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      // Each leading .. segment means \"go up one route\" instead of \"go up one\n      // URL segment\".  This is a key difference from how <a href> works and a\n      // major reason we call this a \"to\" value instead of a \"href\".\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\n    // If there are more \"..\" segments than parent routes, resolve relative to\n    // the root / URL.\n    from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n  }\n\n  let path = resolvePath(to, from);\n\n  // Ensure the pathname has a trailing slash if the original \"to\" had one\n  let hasExplicitTrailingSlash =\n    toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") &&\n    (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n  ) {\n    path.pathname += \"/\";\n  }\n\n  return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n  // Empty strings should be treated the same as / paths\n  return to === \"\" || (to as Path).pathname === \"\"\n    ? \"/\"\n    : typeof to === \"string\"\n    ? parsePath(to).pathname\n    : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n  paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n  pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n  !search || search === \"?\"\n    ? \"\"\n    : search.startsWith(\"?\")\n    ? search\n    : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n  !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = <Data>(\n  data: Data,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  let headers = new Headers(responseInit.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n  }\n\n  return new Response(JSON.stringify(data), {\n    ...responseInit,\n    headers,\n  });\n};\n\nexport interface TrackedPromise extends Promise<any> {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeys: Set<string | number> = new Set<string | number>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscriber?: (aborted: boolean) => void = undefined;\n  data: Record<string, unknown>;\n\n  constructor(data: Record<string, unknown>) {\n    invariant(\n      data && typeof data === \"object\" && !Array.isArray(data),\n      \"defer() only accepts plain objects\"\n    );\n\n    // Set up an AbortController + Promise we can race against to exit early\n    // cancellation\n    let reject: (e: AbortedDeferredError) => void;\n    this.abortPromise = new Promise((_, r) => (reject = r));\n    this.controller = new AbortController();\n    let onAbort = () =>\n      reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () =>\n      this.controller.signal.removeEventListener(\"abort\", onAbort);\n    this.controller.signal.addEventListener(\"abort\", onAbort);\n\n    this.data = Object.entries(data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: this.trackPromise(key, value),\n        }),\n      {}\n    );\n  }\n\n  private trackPromise(\n    key: string | number,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.pendingKeys.add(key);\n\n    // We store a little wrapper promise that will be extended with\n    // _data/_error props upon resolve/reject\n    let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n      (data) => this.onSettle(promise, key, null, data as unknown),\n      (error) => this.onSettle(promise, key, error as unknown)\n    );\n\n    // Register rejection listeners to avoid uncaught promise rejections on\n    // errors or aborted deferred values\n    promise.catch(() => {});\n\n    Object.defineProperty(promise, \"_tracked\", { get: () => true });\n    return promise;\n  }\n\n  private onSettle(\n    promise: TrackedPromise,\n    key: string | number,\n    error: unknown,\n    data?: unknown\n  ): unknown {\n    if (\n      this.controller.signal.aborted &&\n      error instanceof AbortedDeferredError\n    ) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      return Promise.reject(error);\n    }\n\n    this.pendingKeys.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    const subscriber = this.subscriber;\n    if (error) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      subscriber && subscriber(false);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    subscriber && subscriber(false);\n    return data;\n  }\n\n  subscribe(fn: (aborted: boolean) => void) {\n    this.subscriber = fn;\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n    let subscriber = this.subscriber;\n    subscriber && subscriber(true);\n  }\n\n  async resolveData(signal: AbortSignal) {\n    let aborted = false;\n    if (!this.done) {\n      let onAbort = () => this.cancel();\n      signal.addEventListener(\"abort\", onAbort);\n      aborted = await new Promise((resolve) => {\n        this.subscribe((aborted) => {\n          signal.removeEventListener(\"abort\", onAbort);\n          if (aborted || this.done) {\n            resolve(aborted);\n          }\n        });\n      });\n    }\n    return aborted;\n  }\n\n  get done() {\n    return this.pendingKeys.size === 0;\n  }\n\n  get unwrappedData() {\n    invariant(\n      this.data !== null && this.done,\n      \"Can only unwrap data on initialized and settled deferreds\"\n    );\n\n    return Object.entries(this.data).reduce(\n      (acc, [key, value]) =>\n        Object.assign(acc, {\n          [key]: unwrapTrackedPromise(value),\n        }),\n      {}\n    );\n  }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n  return (\n    value instanceof Promise && (value as TrackedPromise)._tracked === true\n  );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n  if (!isTrackedPromise(value)) {\n    return value;\n  }\n\n  if (value._error) {\n    throw value._error;\n  }\n  return value._data;\n}\n\nexport function defer(data: Record<string, unknown>) {\n  return new DeferredData(data);\n}\n\nexport type RedirectFunction = (\n  url: string,\n  init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n  let responseInit = init;\n  if (typeof responseInit === \"number\") {\n    responseInit = { status: responseInit };\n  } else if (typeof responseInit.status === \"undefined\") {\n    responseInit.status = 302;\n  }\n\n  let headers = new Headers(responseInit.headers);\n  headers.set(\"Location\", url);\n\n  return new Response(null, {\n    ...responseInit,\n    headers,\n  });\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  error?: Error;\n  internal: boolean;\n\n  constructor(\n    status: number,\n    statusText: string | undefined,\n    data: any,\n    internal = false\n  ) {\n    this.status = status;\n    this.statusText = statusText || \"\";\n    this.internal = internal;\n    if (data instanceof Error) {\n      this.data = data.toString();\n      this.error = data;\n    } else {\n      this.data = data;\n    }\n  }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response throw from an action/loader\n */\nexport function isRouteErrorResponse(e: any): e is ErrorResponse {\n  return e instanceof ErrorResponse;\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  createClientSideURL,\n  invariant,\n  parsePath,\n} from \"./history\";\nimport type {\n  DataResult,\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DeferredResult,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  RedirectResult,\n  RouteData,\n  AgnosticRouteObject,\n  Submission,\n  SuccessResult,\n  AgnosticRouteMatch,\n  MutationFormMethod,\n} from \"./utils\";\nimport {\n  DeferredData,\n  ErrorResponse,\n  ResultType,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  resolveTo,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the basename for the router\n   */\n  get basename(): RouterInit[\"basename\"];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the current state of the router\n   */\n  get state(): RouterState;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Return the routes for this router instance\n   */\n  get routes(): AgnosticDataRouteObject[];\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Initialize the router, including adding history listeners and kicking off\n   * initial data fetches.  Returns a function to cleanup listeners and abort\n   * any in-progress loads\n   */\n  initialize(): Router;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Subscribe to router.state updates\n   *\n   * @param fn function to call with the new state\n   */\n  subscribe(fn: RouterSubscriber): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Enable scroll restoration behavior in the router\n   *\n   * @param savedScrollPositions Object that will manage positions, in case\n   *                             it's being restored from sessionStorage\n   * @param getScrollPosition    Function to get the active Y scroll position\n   * @param getKey               Function to get the key to use for restoration\n   */\n  enableScrollRestoration(\n    savedScrollPositions: Record<string, number>,\n    getScrollPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ): () => void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Navigate forward/backward in the history stack\n   * @param to Delta to move in the history stack\n   */\n  navigate(to: number): void;\n\n  /**\n   * Navigate to the given path\n   * @param to Path to navigate to\n   * @param opts Navigation options (method, submission, etc.)\n   */\n  navigate(to: To, opts?: RouterNavigateOptions): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a fetcher load/submission\n   *\n   * @param key     Fetcher key\n   * @param routeId Route that owns the fetcher\n   * @param href    href to fetch\n   * @param opts    Fetcher options, (method, submission, etc.)\n   */\n  fetch(\n    key: string,\n    routeId: string,\n    href: string,\n    opts?: RouterNavigateOptions\n  ): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Trigger a revalidation of all current route loaders and fetcher loads\n   */\n  revalidate(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to create an href for the given location\n   * @param location\n   */\n  createHref(location: Location | URL): string;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Utility function to URL encode a destination path according to the internal\n   * history implementation\n   * @param to\n   */\n  encodeLocation(to: To): Path;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Get/create a fetcher for the given key\n   * @param key\n   */\n  getFetcher<TData = any>(key?: string): Fetcher<TData>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete the fetcher for a given key\n   * @param key\n   */\n  deleteFetcher(key?: string): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Cleanup listeners and abort any in-progress loads\n   */\n  dispose(): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal fetch AbortControllers accessed by unit tests\n   */\n  _internalFetchControllers: Map<string, AbortController>;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map<string, DeferredData>;\n}\n\n/**\n * State maintained internally by the router.  During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n  /**\n   * The action of the most recent navigation\n   */\n  historyAction: HistoryAction;\n\n  /**\n   * The current location reflected by the router\n   */\n  location: Location;\n\n  /**\n   * The current set of route matches\n   */\n  matches: AgnosticDataRouteMatch[];\n\n  /**\n   * Tracks whether we've completed our initial data load\n   */\n  initialized: boolean;\n\n  /**\n   * Current scroll position we should start at for a new view\n   *  - number -> scroll position to restore to\n   *  - false -> do not restore scroll at all (used during submissions)\n   *  - null -> don't have a saved position, scroll to hash or top of page\n   */\n  restoreScrollPosition: number | false | null;\n\n  /**\n   * Indicate whether this navigation should skip resetting the scroll position\n   * if we are unable to restore the scroll position\n   */\n  preventScrollReset: boolean;\n\n  /**\n   * Tracks the state of the current navigation\n   */\n  navigation: Navigation;\n\n  /**\n   * Tracks any in-progress revalidations\n   */\n  revalidation: RevalidationState;\n\n  /**\n   * Data from the loaders for the current matches\n   */\n  loaderData: RouteData;\n\n  /**\n   * Data from the action for the current matches\n   */\n  actionData: RouteData | null;\n\n  /**\n   * Errors caught from loaders for the current matches\n   */\n  errors: RouteData | null;\n\n  /**\n   * Map of current fetchers\n   */\n  fetchers: Map<string, Fetcher>;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n  Pick<RouterState, \"loaderData\" | \"actionData\" | \"errors\">\n>;\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  basename?: string;\n  routes: AgnosticRouteObject[];\n  history: History;\n  hydrationData?: HydrationState;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n  basename: Router[\"basename\"];\n  location: RouterState[\"location\"];\n  matches: RouterState[\"matches\"];\n  loaderData: RouterState[\"loaderData\"];\n  actionData: RouterState[\"actionData\"];\n  errors: RouterState[\"errors\"];\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n  actionHeaders: Record<string, Headers>;\n  _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n  dataRoutes: AgnosticDataRouteObject[];\n  query(\n    request: Request,\n    opts?: { requestContext?: unknown }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: { routeId?: string; requestContext?: unknown }\n  ): Promise<any>;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: unknown;\n  handle: unknown;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n  (location: Location, matches: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\n/**\n * Options for a navigate() call for a Link navigation\n */\ntype LinkNavigateOptions = {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n};\n\n/**\n * Options for a navigate() call for a Form navigation\n */\ntype SubmissionNavigateOptions = {\n  replace?: boolean;\n  state?: any;\n  formMethod?: FormMethod;\n  formEncType?: FormEncType;\n  formData: FormData;\n};\n\n/**\n * Options to pass to navigate() for either a Link or Form navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions =\n  | Omit<LinkNavigateOptions, \"replace\">\n  | Omit<SubmissionNavigateOptions, \"replace\">;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n  Idle: {\n    state: \"idle\";\n    location: undefined;\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    formData: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: FormMethod | undefined;\n    formAction: string | undefined;\n    formEncType: FormEncType | undefined;\n    formData: FormData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: FormMethod;\n    formAction: string;\n    formEncType: FormEncType;\n    formData: FormData;\n  };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates<TData = any> = {\n  Idle: {\n    state: \"idle\";\n    formMethod: undefined;\n    formAction: undefined;\n    formEncType: undefined;\n    formData: undefined;\n    data: TData | undefined;\n    \" _hasFetcherDoneAnything \"?: boolean;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: FormMethod | undefined;\n    formAction: string | undefined;\n    formEncType: FormEncType | undefined;\n    formData: FormData | undefined;\n    data: TData | undefined;\n    \" _hasFetcherDoneAnything \"?: boolean;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: FormMethod;\n    formAction: string;\n    formEncType: FormEncType;\n    formData: FormData;\n    data: TData | undefined;\n    \" _hasFetcherDoneAnything \"?: boolean;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface ShortCircuitable {\n  /**\n   * startNavigation does not need to complete the navigation because we\n   * redirected or got interrupted\n   */\n  shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Error thrown from the current action, keyed by the route containing the\n   * error boundary to render the error.  To be committed to the state after\n   * loaders have completed\n   */\n  pendingActionError?: RouteData;\n  /**\n   * Data returned from the current action, keyed by the route owning the action.\n   * To be committed to the state after loaders have completed\n   */\n  pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * loaderData returned from the current set of loaders\n   */\n  loaderData?: RouterState[\"loaderData\"];\n  /**\n   * errors thrown from the current set of loaders\n   */\n  errors?: RouterState[\"errors\"];\n}\n\n/**\n * Tuple of [key, href, DataRouteMatch, DataRouteMatch[]] for a revalidating\n * fetcher.load()\n */\ntype RevalidatingFetcher = [\n  string,\n  string,\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteMatch[]\n];\n\n/**\n * Tuple of [href, DataRouteMatch, DataRouteMatch[]] for an active\n * fetcher.load()\n */\ntype FetchLoadMatch = [\n  string,\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteMatch[]\n];\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n  type: ResultType.data | ResultType.error;\n  response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n  \"post\",\n  \"put\",\n  \"patch\",\n  \"delete\",\n];\nconst validMutationMethods = new Set<MutationFormMethod>(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set<FormMethod>(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n  state: \"idle\",\n  location: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n  state: \"idle\",\n  data: undefined,\n  formMethod: undefined,\n  formAction: undefined,\n  formEncType: undefined,\n  formData: undefined,\n};\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\nconst isServer = !isBrowser;\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let dataRoutes = convertRoutesToDataRoutes(init.routes);\n  // Cleanup function for history\n  let unlistenHistory: (() => void) | null = null;\n  // Externally-provided functions to call on all state changes\n  let subscribers = new Set<RouterSubscriber>();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record<string, number> | null = null;\n  // Externally-provided function to get scroll restoration keys\n  let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n  // Externally-provided function to get current scroll position\n  let getScrollPosition: GetScrollPositionFunction | null = null;\n  // One-time flag to control the initial hydration scroll restoration.  Because\n  // we don't get the saved positions from <ScrollRestoration /> until _after_\n  // the initial render, we need to manually trigger a separate updateState to\n  // send along the restoreScrollPosition\n  // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n  // SSR did the initial scroll restoration.\n  let initialScrollRestored = init.hydrationData != null;\n\n  let initialMatches = matchRoutes(\n    dataRoutes,\n    init.history.location,\n    init.basename\n  );\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null) {\n    // If we do not match a user-provided-route, fall back to the root\n    // to allow the error boundary to take over\n    let error = getInternalRouterError(404, {\n      pathname: init.history.location.pathname,\n    });\n    let { matches, route } = getShortCircuitMatches(dataRoutes);\n    initialMatches = matches;\n    initialErrors = { [route.id]: error };\n  }\n\n  let initialized =\n    !initialMatches.some((m) => m.route.loader) || init.hydrationData != null;\n\n  let router: Router;\n  let state: RouterState = {\n    historyAction: init.history.action,\n    location: init.history.location,\n    matches: initialMatches,\n    initialized,\n    navigation: IDLE_NAVIGATION,\n    // Don't restore on initial updateState() if we were SSR'd\n    restoreScrollPosition: init.hydrationData != null ? false : null,\n    preventScrollReset: false,\n    revalidation: \"idle\",\n    loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n    actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n    errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n    fetchers: new Map(),\n  };\n\n  // -- Stateful internal variables to manage navigations --\n  // Current navigation in progress (to be committed in completeNavigation)\n  let pendingAction: HistoryAction = HistoryAction.Pop;\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidate()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n  // Use this internal array to capture routes that require revalidation due\n  // to a cancelled deferred on action submission\n  let cancelledDeferredRoutes: string[] = [];\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: string[] = [];\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n  // Track the outstanding pending navigation data load to be compared against\n  // the globally incrementing load when a fetcher load lands after a completed\n  // navigation\n  let pendingNavigationLoadId = -1;\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n  // Fetchers that triggered redirect navigations from their actions\n  let fetchRedirectIds = new Set<string>();\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n  // Store DeferredData instances for active route matches.  When a\n  // route loader returns defer() we stick one in here.  Then, when a nested\n  // promise resolves we update loaderData.  If a new navigation starts we\n  // cancel active deferreds for eliminated routes.\n  let activeDeferreds = new Map<string, DeferredData>();\n\n  // Initialize the router, all side effects should be kicked off from here.\n  // Implemented as a Fluent API for ease of:\n  //   let router = createRouter(init).initialize();\n  function initialize() {\n    // If history informs us of a POP navigation, start the navigation but do not update\n    // state.  We'll update our own state once the navigation completes\n    unlistenHistory = init.history.listen(\n      ({ action: historyAction, location }) =>\n        startNavigation(historyAction, location)\n    );\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location);\n    }\n\n    return router;\n  }\n\n  // Clean up a router and it's side effects\n  function dispose() {\n    if (unlistenHistory) {\n      unlistenHistory();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n  }\n\n  // Subscribe to state updates for the router\n  function subscribe(fn: RouterSubscriber) {\n    subscribers.add(fn);\n    return () => subscribers.delete(fn);\n  }\n\n  // Update our state and notify the calling context of the change\n  function updateState(newState: Partial<RouterState>): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n    subscribers.forEach((subscriber) => subscriber(state));\n  }\n\n  // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n  // and setting state.[historyAction/location/matches] to the new route.\n  // - Location is a required param\n  // - Navigation will always be set to IDLE_NAVIGATION\n  // - Can pass any other state in newState\n  function completeNavigation(\n    location: Location,\n    newState: Partial<Omit<RouterState, \"action\" | \"location\" | \"navigation\">>\n  ): void {\n    // Deduce if we're in a loading/actionReload state:\n    // - We have committed actionData in the store\n    // - The current navigation was a mutation submission\n    // - We're past the submitting state and into the loading state\n    // - The location being loaded is not the result of a redirect\n    let isActionReload =\n      state.actionData != null &&\n      state.navigation.formMethod != null &&\n      isMutationMethod(state.navigation.formMethod) &&\n      state.navigation.state === \"loading\" &&\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length > 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -> clear prior actionData due to an action error\n        actionData = null;\n      }\n    } else if (isActionReload) {\n      // Keep the current data if we're wrapping up the action reload\n      actionData = state.actionData;\n    } else {\n      // Clear actionData on any other completed navigations\n      actionData = null;\n    }\n\n    // Always preserve any existing loaderData from re-used routes\n    let loaderData = newState.loaderData\n      ? mergeLoaderData(\n          state.loaderData,\n          newState.loaderData,\n          newState.matches || [],\n          newState.errors\n        )\n      : state.loaderData;\n\n    updateState({\n      ...newState, // matches, errors, fetchers go through as-is\n      actionData,\n      loaderData,\n      historyAction: pendingAction,\n      location,\n      initialized: true,\n      navigation: IDLE_NAVIGATION,\n      revalidation: \"idle\",\n      // Don't restore on submission navigations\n      restoreScrollPosition: state.navigation.formData\n        ? false\n        : getSavedScrollPosition(location, newState.matches || state.matches),\n      preventScrollReset: pendingPreventScrollReset,\n    });\n\n    if (isUninterruptedRevalidation) {\n      // If this was an uninterrupted revalidation then do not touch history\n    } else if (pendingAction === HistoryAction.Pop) {\n      // Do nothing for POP - URL has already been updated\n    } else if (pendingAction === HistoryAction.Push) {\n      init.history.push(location, location.state);\n    } else if (pendingAction === HistoryAction.Replace) {\n      init.history.replace(location, location.state);\n    }\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\n    cancelledFetcherLoads = [];\n  }\n\n  // Trigger a navigation event, which can either be a numerical POP or a PUSH\n  // replace with an optional submission\n  async function navigate(\n    to: number | To,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(to, opts);\n\n    let location = createLocation(state.location, path, opts && opts.state);\n\n    // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n    // URL from window.location, so we need to encode it here so the behavior\n    // remains the same as POP and non-data-router usages.  new URL() does all\n    // the same encoding we'd get from a history.pushState/window.location read\n    // without having to touch history\n    location = {\n      ...location,\n      ...init.history.encodeLocation(location),\n    };\n\n    let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n    let historyAction = HistoryAction.Push;\n\n    if (userReplace === true) {\n      historyAction = HistoryAction.Replace;\n    } else if (userReplace === false) {\n      // no-op\n    } else if (\n      submission != null &&\n      isMutationMethod(submission.formMethod) &&\n      submission.formAction === state.location.pathname + state.location.search\n    ) {\n      // By default on submissions to the current location we REPLACE so that\n      // users don't have to double-click the back button to get to the prior\n      // location.  If the user redirects to a different location from the\n      // action/loader this will be ignored and the redirect will be a PUSH\n      historyAction = HistoryAction.Replace;\n    }\n\n    let preventScrollReset =\n      opts && \"preventScrollReset\" in opts\n        ? opts.preventScrollReset === true\n        : undefined;\n\n    return await startNavigation(historyAction, location, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n    });\n  }\n\n  // Revalidate all current loaders.  If a navigation is in progress or if this\n  // is interrupted by a navigation, allow this to \"succeed\" by calling all\n  // loaders during the next loader round\n  function revalidate() {\n    interruptActiveLoads();\n    updateState({ revalidation: \"loading\" });\n\n    // If we're currently submitting an action, we don't need to start a new\n    // navigation, we'll just let the follow up loader execution call all loaders\n    if (state.navigation.state === \"submitting\") {\n      return;\n    }\n\n    // If we're currently in an idle state, start a new navigation for the current\n    // action/location and mark it as uninterrupted, which will skip the history\n    // update in completeNavigation\n    if (state.navigation.state === \"idle\") {\n      startNavigation(state.historyAction, state.location, {\n        startUninterruptedRevalidation: true,\n      });\n      return;\n    }\n\n    // Otherwise, if we're currently in a loading state, just start a new\n    // navigation to the navigation.location but do not trigger an uninterrupted\n    // revalidation so that history correctly updates once the navigation completes\n    startNavigation(\n      pendingAction || state.historyAction,\n      state.navigation.location,\n      { overrideNavigation: state.navigation }\n    );\n  }\n\n  // Start a navigation to the given action/location.  Can optionally provide a\n  // overrideNavigation which will override the normalLoad in the case of a redirect\n  // navigation\n  async function startNavigation(\n    historyAction: HistoryAction,\n    location: Location,\n    opts?: {\n      submission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponse;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n    }\n  ): Promise<void> {\n    // Abort any in-progress navigations and start a new one. Unset any ongoing\n    // uninterrupted revalidations unless told otherwise, since we want this\n    // new navigation to update history normally\n    pendingNavigationController && pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts && opts.startUninterruptedRevalidation) === true;\n\n    // Save the current scroll position every time we start a new navigation,\n    // and track whether we should reset scroll on completion\n    saveScrollPosition(state.location, state.matches);\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches = matchRoutes(dataRoutes, location, init.basename);\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      // Cancel all pending deferred on 404s since we don't keep any routes\n      cancelActiveDeferreds();\n      completeNavigation(location, {\n        matches: notFoundMatches,\n        loaderData: {},\n        errors: {\n          [route.id]: error,\n        },\n      });\n      return;\n    }\n\n    // Short circuit if it's only a hash change\n    if (isHashChangeOnly(state.location, location)) {\n      completeNavigation(location, { matches });\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionData: RouteData | undefined;\n    let pendingError: RouteData | undefined;\n\n    if (opts && opts.pendingError) {\n      // If we have a pendingError, it means the user attempted a GET submission\n      // with binary FormData so assign here and skip to handleLoaders.  That\n      // way we handle calling loaders above the boundary etc.  It's not really\n      // different from an actionError in that sense.\n      pendingError = {\n        [findNearestBoundary(matches).route.id]: opts.pendingError,\n      };\n    } else if (\n      opts &&\n      opts.submission &&\n      isMutationMethod(opts.submission.formMethod)\n    ) {\n      // Call action if we received an action submission\n      let actionOutput = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        { replace: opts.replace }\n      );\n\n      if (actionOutput.shortCircuited) {\n        return;\n      }\n\n      pendingActionData = actionOutput.pendingActionData;\n      pendingError = actionOutput.pendingActionError;\n\n      let navigation: NavigationStates[\"Loading\"] = {\n        state: \"loading\",\n        location,\n        ...opts.submission,\n      };\n      loadingNavigation = navigation;\n\n      // Create a GET request for the loaders\n      request = new Request(request.url, { signal: request.signal });\n    }\n\n    // Call loaders\n    let { shortCircuited, loaderData, errors } = await handleLoaders(\n      request,\n      location,\n      matches,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.replace,\n      pendingActionData,\n      pendingError\n    );\n\n    if (shortCircuited) {\n      return;\n    }\n\n    // Clean up now that the action/loaders have completed.  Don't clean up if\n    // we short circuited because pendingNavigationController will have already\n    // been assigned to a new controller for the next navigation\n    pendingNavigationController = null;\n\n    completeNavigation(location, {\n      matches,\n      ...(pendingActionData ? { actionData: pendingActionData } : {}),\n      loaderData,\n      errors,\n    });\n  }\n\n  // Call the action matched by the leaf route for this navigation and handle\n  // redirects/errors\n  async function handleAction(\n    request: Request,\n    location: Location,\n    submission: Submission,\n    matches: AgnosticDataRouteMatch[],\n    opts?: { replace?: boolean }\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation: NavigationStates[\"Submitting\"] = {\n      state: \"submitting\",\n      location,\n      ...submission,\n    };\n    updateState({ navigation });\n\n    // Call our action and get the result\n    let result: DataResult;\n    let actionMatch = getTargetMatch(matches, location);\n\n    if (!actionMatch.route.action) {\n      result = {\n        type: ResultType.error,\n        error: getInternalRouterError(405, {\n          method: request.method,\n          pathname: location.pathname,\n          routeId: actionMatch.route.id,\n        }),\n      };\n    } else {\n      result = await callLoaderOrAction(\n        \"action\",\n        request,\n        actionMatch,\n        matches,\n        router.basename\n      );\n\n      if (request.signal.aborted) {\n        return { shortCircuited: true };\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      let replace: boolean;\n      if (opts && opts.replace != null) {\n        replace = opts.replace;\n      } else {\n        // If the user didn't explicity indicate replace behavior, replace if\n        // we redirected to the exact same location we're currently at to avoid\n        // double back-buttons\n        replace =\n          result.location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(state, result, { submission, replace });\n      return { shortCircuited: true };\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n      // By default, all submissions are REPLACE navigations, but if the\n      // action threw an error that'll be rendered in an errorElement, we fall\n      // back to PUSH so that the user can use the back button to get back to\n      // the pre-submission form location to try again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        // Send back an empty object we can use to clear out any prior actionData\n        pendingActionData: {},\n        pendingActionError: { [boundaryMatch.route.id]: result.error },\n      };\n    }\n\n    if (isDeferredResult(result)) {\n      throw new Error(\"defer() is not supported in actions\");\n    }\n\n    return {\n      pendingActionData: { [actionMatch.route.id]: result.data },\n    };\n  }\n\n  // Call all applicable loaders for the given matches, handling redirects,\n  // errors, etc.\n  async function handleLoaders(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    replace?: boolean,\n    pendingActionData?: RouteData,\n    pendingError?: RouteData\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation = overrideNavigation;\n    if (!loadingNavigation) {\n      let navigation: NavigationStates[\"Loading\"] = {\n        state: \"loading\",\n        location,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        ...submission,\n      };\n      loadingNavigation = navigation;\n    }\n\n    // If this was a redirect from an action we don't have a \"submission\" but\n    // we have it on the loading navigation so use that if available\n    let activeSubmission = submission\n      ? submission\n      : loadingNavigation.formMethod &&\n        loadingNavigation.formAction &&\n        loadingNavigation.formData &&\n        loadingNavigation.formEncType\n      ? {\n          formMethod: loadingNavigation.formMethod,\n          formAction: loadingNavigation.formAction,\n          formData: loadingNavigation.formData,\n          formEncType: loadingNavigation.formEncType,\n        }\n      : undefined;\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      state,\n      matches,\n      activeSubmission,\n      location,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      pendingActionData,\n      pendingError,\n      fetchLoadMatches\n    );\n\n    // Cancel pending deferreds for no-longer-matched routes or routes we're\n    // about to reload.  Note that if this is an action reload we would have\n    // already cancelled all pending deferreds so this would be a no-op\n    cancelActiveDeferreds(\n      (routeId) =>\n        !(matches && matches.some((m) => m.route.id === routeId)) ||\n        (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n    );\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      completeNavigation(location, {\n        matches,\n        loaderData: {},\n        // Commit pending error if we're short circuiting\n        errors: pendingError || null,\n        ...(pendingActionData ? { actionData: pendingActionData } : {}),\n      });\n      return { shortCircuited: true };\n    }\n\n    // If this is an uninterrupted revalidation, we remain in our current idle\n    // state.  If not, we need to switch to our loading state and load data,\n    // preserving any new action data or existing action data (in the case of\n    // a revalidation interrupting an actionReload)\n    if (!isUninterruptedRevalidation) {\n      revalidatingFetchers.forEach(([key]) => {\n        let fetcher = state.fetchers.get(key);\n        let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n          state: \"loading\",\n          data: fetcher && fetcher.data,\n          formMethod: undefined,\n          formAction: undefined,\n          formEncType: undefined,\n          formData: undefined,\n          \" _hasFetcherDoneAnything \": true,\n        };\n        state.fetchers.set(key, revalidatingFetcher);\n      });\n      let actionData = pendingActionData || state.actionData;\n      updateState({\n        navigation: loadingNavigation,\n        ...(actionData\n          ? Object.keys(actionData).length === 0\n            ? { actionData: null }\n            : { actionData }\n          : {}),\n        ...(revalidatingFetchers.length > 0\n          ? { fetchers: new Map(state.fetchers) }\n          : {}),\n      });\n    }\n\n    pendingNavigationLoadId = ++incrementingLoadId;\n    revalidatingFetchers.forEach(([key]) =>\n      fetchControllers.set(key, pendingNavigationController!)\n    );\n\n    let { results, loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state.matches,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        request\n      );\n\n    if (request.signal.aborted) {\n      return { shortCircuited: true };\n    }\n\n    // Clean up _after_ loaders have completed.  Don't clean up if we short\n    // circuited because fetchControllers would have been aborted and\n    // reassigned to new controllers for the next navigation\n    revalidatingFetchers.forEach(([key]) => fetchControllers.delete(key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(results);\n    if (redirect) {\n      await startRedirectNavigation(state, redirect, { replace });\n      return { shortCircuited: true };\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      matchesToLoad,\n      loaderResults,\n      pendingError,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Wire up subscribers to update loaderData as promises settle\n    activeDeferreds.forEach((deferredData, routeId) => {\n      deferredData.subscribe((aborted) => {\n        // Note: No need to updateState here since the TrackedPromise on\n        // loaderData is stable across resolve/reject\n        // Remove this instance if we were aborted or if promises have settled\n        if (aborted || deferredData.done) {\n          activeDeferreds.delete(routeId);\n        }\n      });\n    });\n\n    markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n\n    return {\n      loaderData,\n      errors,\n      ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n        ? { fetchers: new Map(state.fetchers) }\n        : {}),\n    };\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  // Trigger a fetcher load/submit for the given fetcher key\n  function fetch(\n    key: string,\n    routeId: string,\n    href: string,\n    opts?: RouterFetchOptions\n  ) {\n    if (isServer) {\n      throw new Error(\n        \"router.fetch() was called during the server render, but it shouldn't be. \" +\n          \"You are likely calling a useFetcher() method in the body of your component. \" +\n          \"Try moving it to a useEffect or a callback.\"\n      );\n    }\n\n    if (fetchControllers.has(key)) abortFetcher(key);\n\n    let matches = matchRoutes(dataRoutes, href, init.basename);\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: href })\n      );\n      return;\n    }\n\n    let { path, submission } = normalizeNavigateOptions(href, opts, true);\n    let match = getTargetMatch(matches, path);\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(key, routeId, path, match, matches, submission);\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, [path, match, matches]);\n    handleFetcherLoader(key, routeId, path, match, matches, submission);\n  }\n\n  // Call the action for the matched fetcher.submit(), and then handle redirects,\n  // errors, and revalidation\n  async function handleFetcherAction(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    requestMatches: AgnosticDataRouteMatch[],\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    if (!match.route.action) {\n      let error = getInternalRouterError(405, {\n        method: submission.formMethod,\n        pathname: path,\n        routeId: routeId,\n      });\n      setFetcherError(key, routeId, error);\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    let fetcher: FetcherStates[\"Submitting\"] = {\n      state: \"submitting\",\n      ...submission,\n      data: existingFetcher && existingFetcher.data,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, fetcher);\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    // Call the action for the fetcher\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      path,\n      abortController.signal,\n      submission\n    );\n    fetchControllers.set(key, abortController);\n\n    let actionResult = await callLoaderOrAction(\n      \"action\",\n      fetchRequest,\n      match,\n      requestMatches,\n      router.basename\n    );\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by ou our own fetcher\n      // re-submit which would have put _new_ controller is in fetchControllers\n      if (fetchControllers.get(key) === abortController) {\n        fetchControllers.delete(key);\n      }\n      return;\n    }\n\n    if (isRedirectResult(actionResult)) {\n      fetchControllers.delete(key);\n      fetchRedirectIds.add(key);\n      let loadingFetcher: FetcherStates[\"Loading\"] = {\n        state: \"loading\",\n        ...submission,\n        data: undefined,\n        \" _hasFetcherDoneAnything \": true,\n      };\n      state.fetchers.set(key, loadingFetcher);\n      updateState({ fetchers: new Map(state.fetchers) });\n\n      return startRedirectNavigation(state, actionResult, {\n        isFetchActionRedirect: true,\n      });\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(actionResult)) {\n      setFetcherError(key, routeId, actionResult.error);\n      return;\n    }\n\n    if (isDeferredResult(actionResult)) {\n      invariant(false, \"defer() is not supported in actions\");\n    }\n\n    // Start the data load for current matches, or the next location if we're\n    // in the middle of a navigation\n    let nextLocation = state.navigation.location || state.location;\n    let revalidationRequest = createClientSideRequest(\n      nextLocation,\n      abortController.signal\n    );\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(dataRoutes, state.navigation.location, init.basename)\n        : state.matches;\n\n    invariant(matches, \"Didn't find any matches after fetcher action\");\n\n    let loadId = ++incrementingLoadId;\n    fetchReloadIds.set(key, loadId);\n\n    let loadFetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      data: actionResult.data,\n      ...submission,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      state,\n      matches,\n      submission,\n      nextLocation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      { [match.route.id]: actionResult.data },\n      undefined, // No need to send through errors since we short circuit above\n      fetchLoadMatches\n    );\n\n    // Put all revalidating fetchers into the loading state, except for the\n    // current fetcher which we want to keep in it's current loading state which\n    // contains it's action submission info + action data\n    revalidatingFetchers\n      .filter(([staleKey]) => staleKey !== key)\n      .forEach(([staleKey]) => {\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n          state: \"loading\",\n          data: existingFetcher && existingFetcher.data,\n          formMethod: undefined,\n          formAction: undefined,\n          formEncType: undefined,\n          formData: undefined,\n          \" _hasFetcherDoneAnything \": true,\n        };\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        fetchControllers.set(staleKey, abortController);\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let { results, loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state.matches,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        revalidationRequest\n      );\n\n    if (abortController.signal.aborted) {\n      return;\n    }\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach(([staleKey]) =>\n      fetchControllers.delete(staleKey)\n    );\n\n    let redirect = findRedirect(results);\n    if (redirect) {\n      return startRedirectNavigation(state, redirect);\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      state.matches,\n      matchesToLoad,\n      loaderResults,\n      undefined,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    let doneFetcher: FetcherStates[\"Idle\"] = {\n      state: \"idle\",\n      data: actionResult.data,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, doneFetcher);\n\n    let didAbortFetchLoads = abortStaleFetchLoads(loadId);\n\n    // If we are currently in a navigation loading state and this fetcher is\n    // more recent than the navigation, we want the newer data so abort the\n    // navigation and complete it with the fetcher data\n    if (\n      state.navigation.state === \"loading\" &&\n      loadId > pendingNavigationLoadId\n    ) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController && pendingNavigationController.abort();\n\n      completeNavigation(state.navigation.location, {\n        matches,\n        loaderData,\n        errors,\n        fetchers: new Map(state.fetchers),\n      });\n    } else {\n      // otherwise just update with the fetcher data, preserving any existing\n      // loaderData for loaders that did not need to reload.  We have to\n      // manually merge here since we aren't going through completeNavigation\n      updateState({\n        errors,\n        loaderData: mergeLoaderData(\n          state.loaderData,\n          loaderData,\n          matches,\n          errors\n        ),\n        ...(didAbortFetchLoads ? { fetchers: new Map(state.fetchers) } : {}),\n      });\n      isRevalidationRequired = false;\n    }\n  }\n\n  // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n  async function handleFetcherLoader(\n    key: string,\n    routeId: string,\n    path: string,\n    match: AgnosticDataRouteMatch,\n    matches: AgnosticDataRouteMatch[],\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    // Put this fetcher into it's loading state\n    let loadingFetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      ...submission,\n      data: existingFetcher && existingFetcher.data,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, loadingFetcher);\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    // Call the loader for this fetcher route match\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(path, abortController.signal);\n    fetchControllers.set(key, abortController);\n    let result: DataResult = await callLoaderOrAction(\n      \"loader\",\n      fetchRequest,\n      match,\n      matches,\n      router.basename\n    );\n\n    // Deferred isn't supported or fetcher loads, await everything and treat it\n    // as a normal load.  resolveDeferredData will return undefined if this\n    // fetcher gets aborted, so we just leave result untouched and short circuit\n    // below if that happens\n    if (isDeferredResult(result)) {\n      result =\n        (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n        result;\n    }\n\n    // We can delete this so long as we weren't aborted by ou our own fetcher\n    // re-load which would have put _new_ controller is in fetchControllers\n    if (fetchControllers.get(key) === abortController) {\n      fetchControllers.delete(key);\n    }\n\n    if (fetchRequest.signal.aborted) {\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      await startRedirectNavigation(state, result);\n      return;\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, routeId);\n      state.fetchers.delete(key);\n      // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n      // do we need to behave any differently with our non-redirect errors?\n      // What if it was a non-redirect Response?\n      updateState({\n        fetchers: new Map(state.fetchers),\n        errors: {\n          [boundaryMatch.route.id]: result.error,\n        },\n      });\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    let doneFetcher: FetcherStates[\"Idle\"] = {\n      state: \"idle\",\n      data: result.data,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      \" _hasFetcherDoneAnything \": true,\n    };\n    state.fetchers.set(key, doneFetcher);\n    updateState({ fetchers: new Map(state.fetchers) });\n  }\n\n  /**\n   * Utility function to handle redirects returned from an action or loader.\n   * Normally, a redirect \"replaces\" the navigation that triggered it.  So, for\n   * example:\n   *\n   *  - user is on /a\n   *  - user clicks a link to /b\n   *  - loader for /b redirects to /c\n   *\n   * In a non-JS app the browser would track the in-flight navigation to /b and\n   * then replace it with /c when it encountered the redirect response.  In\n   * the end it would only ever update the URL bar with /c.\n   *\n   * In client-side routing using pushState/replaceState, we aim to emulate\n   * this behavior and we also do not update history until the end of the\n   * navigation (including processed redirects).  This means that we never\n   * actually touch history until we've processed redirects, so we just use\n   * the history action from the original navigation (PUSH or REPLACE).\n   */\n  async function startRedirectNavigation(\n    state: RouterState,\n    redirect: RedirectResult,\n    {\n      submission,\n      replace,\n      isFetchActionRedirect,\n    }: {\n      submission?: Submission;\n      replace?: boolean;\n      isFetchActionRedirect?: boolean;\n    } = {}\n  ) {\n    if (redirect.revalidate) {\n      isRevalidationRequired = true;\n    }\n\n    let redirectLocation = createLocation(\n      state.location,\n      redirect.location,\n      // TODO: This can be removed once we get rid of useTransition in Remix v2\n      {\n        _isRedirect: true,\n        ...(isFetchActionRedirect ? { _isFetchActionRedirect: true } : {}),\n      }\n    );\n    invariant(\n      redirectLocation,\n      \"Expected a location on the redirect navigation\"\n    );\n\n    // Check if this an external redirect that goes to a new origin\n    if (typeof window?.location !== \"undefined\") {\n      let newOrigin = createClientSideURL(redirect.location).origin;\n      if (window.location.origin !== newOrigin) {\n        if (replace) {\n          window.location.replace(redirect.location);\n        } else {\n          window.location.assign(redirect.location);\n        }\n        return;\n      }\n    }\n\n    // There's no need to abort on redirects, since we don't detect the\n    // redirect until the action/loaders have settled\n    pendingNavigationController = null;\n\n    let redirectHistoryAction =\n      replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType, formData } = state.navigation;\n    if (!submission && formMethod && formAction && formData && formEncType) {\n      submission = {\n        formMethod,\n        formAction,\n        formEncType,\n        formData,\n      };\n    }\n\n    // If this was a 307/308 submission we want to preserve the HTTP method and\n    // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n    // redirected location\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.status) &&\n      submission &&\n      isMutationMethod(submission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...submission,\n          formAction: redirect.location,\n        },\n      });\n    } else {\n      // Otherwise, we kick off a new loading navigation, preserving the\n      // submission info for the duration of this navigation\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation: {\n          state: \"loading\",\n          location: redirectLocation,\n          formMethod: submission ? submission.formMethod : undefined,\n          formAction: submission ? submission.formAction : undefined,\n          formEncType: submission ? submission.formEncType : undefined,\n          formData: submission ? submission.formData : undefined,\n        },\n      });\n    }\n  }\n\n  async function callLoadersAndMaybeResolveData(\n    currentMatches: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    matchesToLoad: AgnosticDataRouteMatch[],\n    fetchersToLoad: RevalidatingFetcher[],\n    request: Request\n  ) {\n    // Call all navigation loaders and revalidating fetcher loaders in parallel,\n    // then slice off the results into separate arrays so we can handle them\n    // accordingly\n    let results = await Promise.all([\n      ...matchesToLoad.map((match) =>\n        callLoaderOrAction(\"loader\", request, match, matches, router.basename)\n      ),\n      ...fetchersToLoad.map(([, href, match, fetchMatches]) =>\n        callLoaderOrAction(\n          \"loader\",\n          createClientSideRequest(href, request.signal),\n          match,\n          fetchMatches,\n          router.basename\n        )\n      ),\n    ]);\n    let loaderResults = results.slice(0, matchesToLoad.length);\n    let fetcherResults = results.slice(matchesToLoad.length);\n\n    await Promise.all([\n      resolveDeferredResults(\n        currentMatches,\n        matchesToLoad,\n        loaderResults,\n        request.signal,\n        false,\n        state.loaderData\n      ),\n      resolveDeferredResults(\n        currentMatches,\n        fetchersToLoad.map(([, , match]) => match),\n        fetcherResults,\n        request.signal,\n        true\n      ),\n    ]);\n\n    return { results, loaderResults, fetcherResults };\n  }\n\n  function interruptActiveLoads() {\n    // Every interruption triggers a revalidation\n    isRevalidationRequired = true;\n\n    // Cancel pending route-level deferreds and mark cancelled routes for\n    // revalidation\n    cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n    // Abort in-flight fetcher loads\n    fetchLoadMatches.forEach((_, key) => {\n      if (fetchControllers.has(key)) {\n        cancelledFetcherLoads.push(key);\n        abortFetcher(key);\n      }\n    });\n  }\n\n  function setFetcherError(key: string, routeId: string, error: any) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState({\n      errors: {\n        [boundaryMatch.route.id]: error,\n      },\n      fetchers: new Map(state.fetchers),\n    });\n  }\n\n  function deleteFetcher(key: string): void {\n    if (fetchControllers.has(key)) abortFetcher(key);\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function abortFetcher(key: string) {\n    let controller = fetchControllers.get(key);\n    invariant(controller, `Expected fetch controller: ${key}`);\n    controller.abort();\n    fetchControllers.delete(key);\n  }\n\n  function markFetchersDone(keys: string[]) {\n    for (let key of keys) {\n      let fetcher = getFetcher(key);\n      let doneFetcher: FetcherStates[\"Idle\"] = {\n        state: \"idle\",\n        data: fetcher.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true,\n      };\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): void {\n    let doneKeys = [];\n    for (let key of fetchRedirectIds) {\n      let fetcher = state.fetchers.get(key);\n      invariant(fetcher, `Expected fetcher: ${key}`);\n      if (fetcher.state === \"loading\") {\n        fetchRedirectIds.delete(key);\n        doneKeys.push(key);\n      }\n    }\n    markFetchersDone(doneKeys);\n  }\n\n  function abortStaleFetchLoads(landedId: number): boolean {\n    let yeetedKeys = [];\n    for (let [key, id] of fetchReloadIds) {\n      if (id < landedId) {\n        let fetcher = state.fetchers.get(key);\n        invariant(fetcher, `Expected fetcher: ${key}`);\n        if (fetcher.state === \"loading\") {\n          abortFetcher(key);\n          fetchReloadIds.delete(key);\n          yeetedKeys.push(key);\n        }\n      }\n    }\n    markFetchersDone(yeetedKeys);\n    return yeetedKeys.length > 0;\n  }\n\n  function cancelActiveDeferreds(\n    predicate?: (routeId: string) => boolean\n  ): string[] {\n    let cancelledRouteIds: string[] = [];\n    activeDeferreds.forEach((dfd, routeId) => {\n      if (!predicate || predicate(routeId)) {\n        // Cancel the deferred - but do not remove from activeDeferreds here -\n        // we rely on the subscribers to do that so our tests can assert proper\n        // cleanup via _internalActiveDeferreds\n        dfd.cancel();\n        cancelledRouteIds.push(routeId);\n        activeDeferreds.delete(routeId);\n      }\n    });\n    return cancelledRouteIds;\n  }\n\n  // Opt in to capturing and reporting scroll positions during navigations,\n  // used by the <ScrollRestoration> component\n  function enableScrollRestoration(\n    positions: Record<string, number>,\n    getPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ) {\n    savedScrollPositions = positions;\n    getScrollPosition = getPosition;\n    getScrollRestorationKey = getKey || ((location) => location.key);\n\n    // Perform initial hydration scroll restoration, since we miss the boat on\n    // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n      initialScrollRestored = true;\n      let y = getSavedScrollPosition(state.location, state.matches);\n      if (y != null) {\n        updateState({ restoreScrollPosition: y });\n      }\n    }\n\n    return () => {\n      savedScrollPositions = null;\n      getScrollPosition = null;\n      getScrollRestorationKey = null;\n    };\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      let userMatches = matches.map((m) =>\n        createUseMatchesMatch(m, state.loaderData)\n      );\n      let key = getScrollRestorationKey(location, userMatches) || location.key;\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n      let userMatches = matches.map((m) =>\n        createUseMatchesMatch(m, state.loaderData)\n      );\n      let key = getScrollRestorationKey(location, userMatches) || location.key;\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  router = {\n    get basename() {\n      return init.basename;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    initialize,\n    subscribe,\n    enableScrollRestoration,\n    navigate,\n    fetch,\n    revalidate,\n    // Passthrough to history-aware createHref used by useHref so we get proper\n    // hash-aware URLs in DOM paths\n    createHref: (to: To) => init.history.createHref(to),\n    encodeLocation: (to: To) => init.history.encodeLocation(to),\n    getFetcher,\n    deleteFetcher,\n    dispose,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: {\n    basename?: string;\n  }\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let dataRoutes = convertRoutesToDataRoutes(routes);\n  let basename = (opts ? opts.basename : null) || \"/\";\n\n  /**\n   * The query() method is intended for document requests, in which we want to\n   * call an optional action and potentially multiple loaders for all nested\n   * routes.  It returns a StaticHandlerContext object, which is very similar\n   * to the router state (location, loaderData, actionData, errors, etc.) and\n   * also adds SSR-specific information such as the statusCode and headers\n   * from action/loaders Responses.\n   *\n   * It _should_ never throw and should report all errors through the\n   * returned context.errors object, properly associating errors to their error\n   * boundary.  Additionally, it tracks _deepestRenderedBoundaryId which can be\n   * used to emulate React error boundaries during SSr by performing a second\n   * pass only down to the boundaryId.\n   *\n   * The one exception where we do not return a StaticHandlerContext is when a\n   * redirect response is returned or thrown from any action/loader.  We\n   * propagate that out and return the raw Response so the HTTP server can\n   * return it directly.\n   */\n  async function query(\n    request: Request,\n    { requestContext }: { requestContext?: unknown } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method.toLowerCase();\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"head\") {\n      let error = getInternalRouterError(405, { method });\n      let { matches: methodNotAllowedMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: methodNotAllowedMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n      };\n    } else if (!matches) {\n      let error = getInternalRouterError(404, { pathname: location.pathname });\n      let { matches: notFoundMatches, route } =\n        getShortCircuitMatches(dataRoutes);\n      return {\n        basename,\n        location,\n        matches: notFoundMatches,\n        loaderData: {},\n        actionData: null,\n        errors: {\n          [route.id]: error,\n        },\n        statusCode: error.status,\n        loaderHeaders: {},\n        actionHeaders: {},\n      };\n    }\n\n    let result = await queryImpl(request, location, matches, requestContext);\n    if (isResponse(result)) {\n      return result;\n    }\n\n    // When returning StaticHandlerContext, we patch back in the location here\n    // since we need it for React Context.  But this helps keep our submit and\n    // loadRouteData operating on a Request instead of a Location\n    return { location, basename, ...result };\n  }\n\n  /**\n   * The queryRoute() method is intended for targeted route requests, either\n   * for fetch ?_data requests or resource route requests.  In this case, we\n   * are only ever calling a single action or loader, and we are returning the\n   * returned value directly.  In most cases, this will be a Response returned\n   * from the action/loader, but it may be a primitive or other value as well -\n   * and in such cases the calling context should handle that accordingly.\n   *\n   * We do respect the throw/return differentiation, so if an action/loader\n   * throws, then this method will throw the value.  This is important so we\n   * can do proper boundary identification in Remix where a thrown Response\n   * must go to the Catch Boundary but a returned Response is happy-path.\n   *\n   * One thing to note is that any Router-initiated Errors that make sense\n   * to associate with a status code will be thrown as an ErrorResponse\n   * instance which include the raw Error, such that the calling context can\n   * serialize the error as they see fit while including the proper response\n   * code.  Examples here are 404 and 405 errors that occur prior to reaching\n   * any user-defined loaders.\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n    }: { requestContext?: unknown; routeId?: string } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method.toLowerCase();\n    let location = createLocation(\"\", createPath(url), null, \"default\");\n    let matches = matchRoutes(dataRoutes, location, basename);\n\n    // SSR supports HEAD requests while SPA doesn't\n    if (!isValidMethod(method) && method !== \"head\") {\n      throw getInternalRouterError(405, { method });\n    } else if (!matches) {\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let match = routeId\n      ? matches.find((m) => m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId && !match) {\n      throw getInternalRouterError(403, {\n        pathname: location.pathname,\n        routeId,\n      });\n    } else if (!match) {\n      // This should never hit I don't think?\n      throw getInternalRouterError(404, { pathname: location.pathname });\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      match\n    );\n    if (isResponse(result)) {\n      return result;\n    }\n\n    let error = result.errors ? Object.values(result.errors)[0] : undefined;\n    if (error !== undefined) {\n      // If we got back result.errors, that means the loader/action threw\n      // _something_ that wasn't a Response, but it's not guaranteed/required\n      // to be an `instanceof Error` either, so we have to use throw here to\n      // preserve the \"error\" state outside of queryImpl.\n      throw error;\n    }\n\n    // Pick off the right state value to return\n    let routeData = [result.actionData, result.loaderData].find((v) => v);\n    return Object.values(routeData || {})[0];\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    routeMatch?: AgnosticDataRouteMatch\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    invariant(\n      request.signal,\n      \"query()/queryRoute() requests must contain an AbortController signal\"\n    );\n\n    try {\n      if (isMutationMethod(request.method.toLowerCase())) {\n        let result = await submit(\n          request,\n          matches,\n          routeMatch || getTargetMatch(matches, location),\n          requestContext,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        routeMatch\n      );\n      return isResponse(result)\n        ? result\n        : {\n            ...result,\n            actionData: null,\n            actionHeaders: {},\n          };\n    } catch (e) {\n      // If the user threw/returned a Response in callLoaderOrAction, we throw\n      // it to bail out and then return or throw here based on whether the user\n      // returned or threw\n      if (isQueryRouteResponse(e)) {\n        if (e.type === ResultType.error && !isRedirectResponse(e.response)) {\n          throw e.response;\n        }\n        return e.response;\n      }\n      // Redirects are always returned since they don't propagate to catch\n      // boundaries\n      if (isRedirectResponse(e)) {\n        return e;\n      }\n      throw e;\n    }\n  }\n\n  async function submit(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    actionMatch: AgnosticDataRouteMatch,\n    requestContext: unknown,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action) {\n      let error = getInternalRouterError(405, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: actionMatch.route.id,\n      });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\n    } else {\n      result = await callLoaderOrAction(\n        \"action\",\n        request,\n        actionMatch,\n        matches,\n        basename,\n        true,\n        isRouteRequest,\n        requestContext\n      );\n\n      if (request.signal.aborted) {\n        let method = isRouteRequest ? \"queryRoute\" : \"query\";\n        throw new Error(`${method}() call aborted`);\n      }\n    }\n\n    if (isRedirectResult(result)) {\n      // Uhhhh - this should never happen, we should always throw these from\n      // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n      // can get back on the \"throw all redirect responses\" train here should\n      // this ever happen :/\n      throw new Response(null, {\n        status: result.status,\n        headers: {\n          Location: result.location,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      throw new Error(\"defer() is not supported in actions\");\n    }\n\n    if (isRouteRequest) {\n      // Note: This should only be non-Response values if we get here, since\n      // isRouteRequest should throw any Response received in callLoaderOrAction\n      if (isErrorResult(result)) {\n        throw result.error;\n      }\n\n      return {\n        matches: [actionMatch],\n        loaderData: {},\n        actionData: { [actionMatch.route.id]: result.data },\n        errors: null,\n        // Note: statusCode + headers are unused here since queryRoute will\n        // return the raw Response or value\n        statusCode: 200,\n        loaderHeaders: {},\n        actionHeaders: {},\n      };\n    }\n\n    if (isErrorResult(result)) {\n      // Store off the pending error - we use it to determine which loaders\n      // to call and will commit it when we complete the navigation\n      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n      let context = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        undefined,\n        {\n          [boundaryMatch.route.id]: result.error,\n        }\n      );\n\n      // action status codes take precedence over loader status codes\n      return {\n        ...context,\n        statusCode: isRouteErrorResponse(result.error)\n          ? result.error.status\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    // Create a GET request for the loaders\n    let loaderRequest = new Request(request.url, {\n      headers: request.headers,\n      redirect: request.redirect,\n      signal: request.signal,\n    });\n    let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n    return {\n      ...context,\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      actionHeaders: {\n        ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n      },\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    routeMatch?: AgnosticDataRouteMatch,\n    pendingActionError?: RouteData\n  ): Promise<\n    | Omit<\n        StaticHandlerContext,\n        \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n      >\n    | Response\n  > {\n    let isRouteRequest = routeMatch != null;\n\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (isRouteRequest && !routeMatch?.route.loader) {\n      throw getInternalRouterError(400, {\n        method: request.method,\n        pathname: new URL(request.url).pathname,\n        routeId: routeMatch?.route.id,\n      });\n    }\n\n    let requestMatches = routeMatch\n      ? [routeMatch]\n      : getLoaderMatchesUntilBoundary(\n          matches,\n          Object.keys(pendingActionError || {})[0]\n        );\n    let matchesToLoad = requestMatches.filter((m) => m.route.loader);\n\n    // Short circuit if we have no loaders to run (query())\n    if (matchesToLoad.length === 0) {\n      return {\n        matches,\n        // Add a null for all matched routes for proper revalidation on the client\n        loaderData: matches.reduce(\n          (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n          {}\n        ),\n        errors: pendingActionError || null,\n        statusCode: 200,\n        loaderHeaders: {},\n      };\n    }\n\n    let results = await Promise.all([\n      ...matchesToLoad.map((match) =>\n        callLoaderOrAction(\n          \"loader\",\n          request,\n          match,\n          matches,\n          basename,\n          true,\n          isRouteRequest,\n          requestContext\n        )\n      ),\n    ]);\n\n    if (request.signal.aborted) {\n      let method = isRouteRequest ? \"queryRoute\" : \"query\";\n      throw new Error(`${method}() call aborted`);\n    }\n\n    let executedLoaders = new Set<string>();\n    results.forEach((result, i) => {\n      executedLoaders.add(matchesToLoad[i].route.id);\n      // Can't do anything with these without the Remix side of things, so just\n      // cancel them for now\n      if (isDeferredResult(result)) {\n        result.deferredData.cancel();\n      }\n    });\n\n    // Process and commit output from loaders\n    let context = processRouteLoaderData(\n      matches,\n      matchesToLoad,\n      results,\n      pendingActionError\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    matches.forEach((match) => {\n      if (!executedLoaders.has(match.route.id)) {\n        context.loaderData[match.route.id] = null;\n      }\n    });\n\n    return {\n      ...context,\n      matches,\n    };\n  }\n\n  return {\n    dataRoutes,\n    query,\n    queryRoute,\n  };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n  routes: AgnosticDataRouteObject[],\n  context: StaticHandlerContext,\n  error: any\n) {\n  let newContext: StaticHandlerContext = {\n    ...context,\n    statusCode: 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction isSubmissionNavigation(\n  opts: RouterNavigateOptions\n): opts is SubmissionNavigateOptions {\n  return opts != null && \"formData\" in opts;\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n  to: To,\n  opts?: RouterNavigateOptions,\n  isFetcher = false\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponse;\n} {\n  let path = typeof to === \"string\" ? to : createPath(to);\n\n  // Return location verbatim on non-submission navigations\n  if (!opts || !isSubmissionNavigation(opts)) {\n    return { path };\n  }\n\n  if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, { method: opts.formMethod }),\n    };\n  }\n\n  // Create a Submission on non-GET navigations\n  let submission: Submission | undefined;\n  if (opts.formData) {\n    submission = {\n      formMethod: opts.formMethod || \"get\",\n      formAction: stripHashFromPath(path),\n      formEncType:\n        (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n      formData: opts.formData,\n    };\n\n    if (isMutationMethod(submission.formMethod)) {\n      return { path, submission };\n    }\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  try {\n    let searchParams = convertFormDataToSearchParams(opts.formData);\n    // Since fetcher GET submissions only run a single loader (as opposed to\n    // navigation GET submissions which run all loaders), we need to preserve\n    // any incoming ?index params\n    if (\n      isFetcher &&\n      parsedPath.search &&\n      hasNakedIndexQuery(parsedPath.search)\n    ) {\n      searchParams.append(\"index\", \"\");\n    }\n    parsedPath.search = `?${searchParams}`;\n  } catch (e) {\n    return {\n      path,\n      error: getInternalRouterError(400),\n    };\n  }\n\n  return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n  matches: AgnosticDataRouteMatch[],\n  boundaryId?: string\n) {\n  let boundaryMatches = matches;\n  if (boundaryId) {\n    let index = matches.findIndex((m) => m.route.id === boundaryId);\n    if (index >= 0) {\n      boundaryMatches = matches.slice(0, index);\n    }\n  }\n  return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: string[],\n  pendingActionData?: RouteData,\n  pendingError?: RouteData,\n  fetchLoadMatches?: Map<string, FetchLoadMatch>\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingError\n    ? Object.values(pendingError)[0]\n    : pendingActionData\n    ? Object.values(pendingActionData)[0]\n    : undefined;\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n  let navigationMatches = boundaryMatches.filter(\n    (match, index) =>\n      match.route.loader != null &&\n      (isNewLoader(state.loaderData, state.matches[index], match) ||\n        // If this route had a pending deferred cancelled it must be revalidated\n        cancelledDeferredRoutes.some((id) => id === match.route.id) ||\n        shouldRevalidateLoader(\n          state.location,\n          state.matches[index],\n          submission,\n          location,\n          match,\n          isRevalidationRequired,\n          actionResult\n        ))\n  );\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches &&\n    fetchLoadMatches.forEach(([href, match, fetchMatches], key) => {\n      // This fetcher was cancelled from a prior action submission - force reload\n      if (cancelledFetcherLoads.includes(key)) {\n        revalidatingFetchers.push([key, href, match, fetchMatches]);\n      } else if (isRevalidationRequired) {\n        let shouldRevalidate = shouldRevalidateLoader(\n          href,\n          match,\n          submission,\n          href,\n          match,\n          isRevalidationRequired,\n          actionResult\n        );\n        if (shouldRevalidate) {\n          revalidatingFetchers.push([key, href, match, fetchMatches]);\n        }\n      }\n    });\n\n  return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n  currentLoaderData: RouteData,\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let isNew =\n    // [a] -> [a, b]\n    !currentMatch ||\n    // [a, b] -> [a, c]\n    match.route.id !== currentMatch.route.id;\n\n  // Handle the case that we don't have data for a re-used route, potentially\n  // from a prior error or from a cancelled pending deferred\n  let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n  // Always load if this is a net-new route or we don't yet have data\n  return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let currentPath = currentMatch.route.path;\n  return (\n    // param change for this match, /users/123 -> /users/456\n    currentMatch.pathname !== match.pathname ||\n    // splat param changed, which is not present in match.path\n    // e.g. /files/images/avatar.jpg -> files/finances.xls\n    (currentPath &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  currentLocation: string | Location,\n  currentMatch: AgnosticDataRouteMatch,\n  submission: Submission | undefined,\n  location: string | Location,\n  match: AgnosticDataRouteMatch,\n  isRevalidationRequired: boolean,\n  actionResult: DataResult | undefined\n) {\n  let currentUrl = createClientSideURL(currentLocation);\n  let currentParams = currentMatch.params;\n  let nextUrl = createClientSideURL(location);\n  let nextParams = match.params;\n\n  // This is the default implementation as to when we revalidate.  If the route\n  // provides it's own implementation, then we give them full control but\n  // provide this value so they can leverage it if needed after they check\n  // their own specific use cases\n  // Note that fetchers always provide the same current/next locations so the\n  // URL-based checks here don't apply to fetcher shouldRevalidate calls\n  let defaultShouldRevalidate =\n    isNewRouteInstance(currentMatch, match) ||\n    // Clicked the same link, resubmitted a GET form\n    currentUrl.toString() === nextUrl.toString() ||\n    // Search params affect all loaders\n    currentUrl.search !== nextUrl.search ||\n    // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n    isRevalidationRequired;\n\n  if (match.route.shouldRevalidate) {\n    let routeChoice = match.route.shouldRevalidate({\n      currentUrl,\n      currentParams,\n      nextUrl,\n      nextParams,\n      ...submission,\n      actionResult,\n      defaultShouldRevalidate,\n    });\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return defaultShouldRevalidate;\n}\n\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  matches: AgnosticDataRouteMatch[],\n  basename = \"/\",\n  isStaticRequest: boolean = false,\n  isRouteRequest: boolean = false,\n  requestContext?: unknown\n): Promise<DataResult> {\n  let resultType;\n  let result;\n\n  // Setup a promise we can race against so that abort signals short circuit\n  let reject: () => void;\n  let abortPromise = new Promise((_, r) => (reject = r));\n  let onReject = () => reject();\n  request.signal.addEventListener(\"abort\", onReject);\n\n  try {\n    let handler = match.route[type];\n    invariant<Function>(\n      handler,\n      `Could not find the ${type} to run on the \"${match.route.id}\" route`\n    );\n\n    result = await Promise.race([\n      handler({ request, params: match.params, context: requestContext }),\n      abortPromise,\n    ]);\n\n    invariant(\n      result !== undefined,\n      `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n        `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n        `function. Please return a value or \\`null\\`.`\n    );\n  } catch (e) {\n    resultType = ResultType.error;\n    result = e;\n  } finally {\n    request.signal.removeEventListener(\"abort\", onReject);\n  }\n\n  if (isResponse(result)) {\n    let status = result.status;\n\n    // Process redirects\n    if (redirectStatusCodes.has(status)) {\n      let location = result.headers.get(\"Location\");\n      invariant(\n        location,\n        \"Redirects returned/thrown from loaders/actions must have a Location header\"\n      );\n\n      let isAbsolute =\n        /^[a-z+]+:\\/\\//i.test(location) || location.startsWith(\"//\");\n\n      // Support relative routing in internal redirects\n      if (!isAbsolute) {\n        let activeMatches = matches.slice(0, matches.indexOf(match) + 1);\n        let routePathnames = getPathContributingMatches(activeMatches).map(\n          (match) => match.pathnameBase\n        );\n        let resolvedLocation = resolveTo(\n          location,\n          routePathnames,\n          new URL(request.url).pathname\n        );\n        invariant(\n          createPath(resolvedLocation),\n          `Unable to resolve redirect location: ${location}`\n        );\n\n        // Prepend the basename to the redirect location if we have one\n        if (basename) {\n          let path = resolvedLocation.pathname;\n          resolvedLocation.pathname =\n            path === \"/\" ? basename : joinPaths([basename, path]);\n        }\n\n        location = createPath(resolvedLocation);\n      }\n\n      // Don't process redirects in the router during static requests requests.\n      // Instead, throw the Response and let the server handle it with an HTTP\n      // redirect.  We also update the Location header in place in this flow so\n      // basename and relative routing is taken into account\n      if (isStaticRequest) {\n        result.headers.set(\"Location\", location);\n        throw result;\n      }\n\n      return {\n        type: ResultType.redirect,\n        status,\n        location,\n        revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n      };\n    }\n\n    // For SSR single-route requests, we want to hand Responses back directly\n    // without unwrapping.  We do this with the QueryRouteResponse wrapper\n    // interface so we can know whether it was returned or thrown\n    if (isRouteRequest) {\n      // eslint-disable-next-line no-throw-literal\n      throw {\n        type: resultType || ResultType.data,\n        response: result,\n      };\n    }\n\n    let data: any;\n    let contentType = result.headers.get(\"Content-Type\");\n    // Check between word boundaries instead of startsWith() due to the last\n    // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n    if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n      data = await result.json();\n    } else {\n      data = await result.text();\n    }\n\n    if (resultType === ResultType.error) {\n      return {\n        type: resultType,\n        error: new ErrorResponse(status, result.statusText, data),\n        headers: result.headers,\n      };\n    }\n\n    return {\n      type: ResultType.data,\n      data,\n      statusCode: result.status,\n      headers: result.headers,\n    };\n  }\n\n  if (resultType === ResultType.error) {\n    return { type: resultType, error: result };\n  }\n\n  if (result instanceof DeferredData) {\n    return { type: ResultType.deferred, deferredData: result };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches.  During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = createClientSideURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType, formData } = submission;\n    init.method = formMethod.toUpperCase();\n    init.body =\n      formEncType === \"application/x-www-form-urlencoded\"\n        ? convertFormDataToSearchParams(formData)\n        : formData;\n  }\n\n  // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n  return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n  let searchParams = new URLSearchParams();\n\n  for (let [key, value] of formData.entries()) {\n    invariant(\n      typeof value === \"string\",\n      'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' +\n        'please use \"multipart/form-data\" instead.'\n    );\n    searchParams.append(key, value);\n  }\n\n  return searchParams;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  matchesToLoad: AgnosticDataRouteMatch[],\n  results: DataResult[],\n  pendingError: RouteData | undefined,\n  activeDeferreds?: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record<string, Headers>;\n} {\n  // Fill in loaderData/errors from our loaders\n  let loaderData: RouterState[\"loaderData\"] = {};\n  let errors: RouterState[\"errors\"] | null = null;\n  let statusCode: number | undefined;\n  let foundError = false;\n  let loaderHeaders: Record<string, Headers> = {};\n\n  // Process loader results into state.loaderData/state.errors\n  results.forEach((result, index) => {\n    let id = matchesToLoad[index].route.id;\n    invariant(\n      !isRedirectResult(result),\n      \"Cannot handle redirect results in processLoaderData\"\n    );\n    if (isErrorResult(result)) {\n      // Look upwards from the matched route for the closest ancestor\n      // error boundary, defaulting to the root match\n      let boundaryMatch = findNearestBoundary(matches, id);\n      let error = result.error;\n      // If we have a pending action error, we report it at the highest-route\n      // that throws a loader error, and then clear it out to indicate that\n      // it was consumed\n      if (pendingError) {\n        error = Object.values(pendingError)[0];\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      // Prefer higher error values if lower errors bubble to the same boundary\n      if (errors[boundaryMatch.route.id] == null) {\n        errors[boundaryMatch.route.id] = error;\n      }\n\n      // Clear our any prior loaderData for the throwing route\n      loaderData[id] = undefined;\n\n      // Once we find our first (highest) error, we set the status code and\n      // prevent deeper status codes from overriding\n      if (!foundError) {\n        foundError = true;\n        statusCode = isRouteErrorResponse(result.error)\n          ? result.error.status\n          : 500;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    } else if (isDeferredResult(result)) {\n      activeDeferreds && activeDeferreds.set(id, result.deferredData);\n      loaderData[id] = result.deferredData.data;\n      // TODO: Add statusCode/headers once we wire up streaming in Remix\n    } else {\n      loaderData[id] = result.data;\n      // Error status codes always override success status codes, but if all\n      // loaders are successful we take the deepest status code.\n      if (\n        result.statusCode != null &&\n        result.statusCode !== 200 &&\n        !foundError\n      ) {\n        statusCode = result.statusCode;\n      }\n      if (result.headers) {\n        loaderHeaders[id] = result.headers;\n      }\n    }\n  });\n\n  // If we didn't consume the pending action error (i.e., all loaders\n  // resolved), then consume it here.  Also clear out any loaderData for the\n  // throwing route\n  if (pendingError) {\n    errors = pendingError;\n    loaderData[Object.keys(pendingError)[0]] = undefined;\n  }\n\n  return {\n    loaderData,\n    errors,\n    statusCode: statusCode || 200,\n    loaderHeaders,\n  };\n}\n\nfunction processLoaderData(\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  matchesToLoad: AgnosticDataRouteMatch[],\n  results: DataResult[],\n  pendingError: RouteData | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: DataResult[],\n  activeDeferreds: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors?: RouterState[\"errors\"];\n} {\n  let { loaderData, errors } = processRouteLoaderData(\n    matches,\n    matchesToLoad,\n    results,\n    pendingError,\n    activeDeferreds\n  );\n\n  // Process results from our revalidating fetchers\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let [key, , match] = revalidatingFetchers[index];\n    invariant(\n      fetcherResults !== undefined && fetcherResults[index] !== undefined,\n      \"Did not find corresponding fetcher result\"\n    );\n    let result = fetcherResults[index];\n\n    // Process fetcher non-redirect errors\n    if (isErrorResult(result)) {\n      let boundaryMatch = findNearestBoundary(state.matches, match.route.id);\n      if (!(errors && errors[boundaryMatch.route.id])) {\n        errors = {\n          ...errors,\n          [boundaryMatch.route.id]: result.error,\n        };\n      }\n      state.fetchers.delete(key);\n    } else if (isRedirectResult(result)) {\n      // Should never get here, redirects should get processed above, but we\n      // keep this to type narrow to a success result in the else\n      throw new Error(\"Unhandled fetcher revalidation redirect\");\n    } else if (isDeferredResult(result)) {\n      // Should never get here, deferred data should be awaited for fetchers\n      // in resolveDeferredResults\n      throw new Error(\"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher: FetcherStates[\"Idle\"] = {\n        state: \"idle\",\n        data: result.data,\n        formMethod: undefined,\n        formAction: undefined,\n        formEncType: undefined,\n        formData: undefined,\n        \" _hasFetcherDoneAnything \": true,\n      };\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n  loaderData: RouteData,\n  newLoaderData: RouteData,\n  matches: AgnosticDataRouteMatch[],\n  errors: RouteData | null | undefined\n): RouteData {\n  let mergedLoaderData = { ...newLoaderData };\n  for (let match of matches) {\n    let id = match.route.id;\n    if (newLoaderData.hasOwnProperty(id)) {\n      if (newLoaderData[id] !== undefined) {\n        mergedLoaderData[id] = newLoaderData[id];\n      } else {\n        // No-op - this is so we ignore existing data if we have a key in the\n        // incoming object with an undefined value, which is how we unset a prior\n        // loaderData if we encounter a loader error\n      }\n    } else if (loaderData[id] !== undefined) {\n      mergedLoaderData[id] = loaderData[id];\n    }\n\n    if (errors && errors.hasOwnProperty(id)) {\n      // Don't keep any loader data below the boundary\n      break;\n    }\n  }\n  return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n  matches: AgnosticDataRouteMatch[],\n  routeId?: string\n): AgnosticDataRouteMatch {\n  let eligibleMatches = routeId\n    ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n    : [...matches];\n  return (\n    eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n    matches[0]\n  );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n  matches: AgnosticDataRouteMatch[];\n  route: AgnosticDataRouteObject;\n} {\n  // Prefer a root layout route if present, otherwise shim in a route object\n  let route = routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n    id: `__shim-error-route__`,\n  };\n\n  return {\n    matches: [\n      {\n        params: {},\n        pathname: \"\",\n        pathnameBase: \"\",\n        route,\n      },\n    ],\n    route,\n  };\n}\n\nfunction getInternalRouterError(\n  status: number,\n  {\n    pathname,\n    routeId,\n    method,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n  } = {}\n) {\n  let statusText = \"Unknown Server Error\";\n  let errorMessage = \"Unknown @remix-run/router error\";\n\n  if (status === 400) {\n    statusText = \"Bad Request\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method} request to \"${pathname}\" but ` +\n        `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else {\n      errorMessage = \"Cannot submit binary form data using GET\";\n    }\n  } else if (status === 403) {\n    statusText = \"Forbidden\";\n    errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n  } else if (status === 404) {\n    statusText = \"Not Found\";\n    errorMessage = `No route matches URL \"${pathname}\"`;\n  } else if (status === 405) {\n    statusText = \"Method Not Allowed\";\n    if (method && pathname && routeId) {\n      errorMessage =\n        `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n        `did not provide an \\`action\\` for route \"${routeId}\", ` +\n        `so there is no way to handle the request.`;\n    } else if (method) {\n      errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n    }\n  }\n\n  return new ErrorResponse(\n    status || 500,\n    statusText,\n    new Error(errorMessage),\n    true\n  );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results: DataResult[]): RedirectResult | undefined {\n  for (let i = results.length - 1; i >= 0; i--) {\n    let result = results[i];\n    if (isRedirectResult(result)) {\n      return result;\n    }\n  }\n}\n\nfunction stripHashFromPath(path: To) {\n  let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n  return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n  return (\n    a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash\n  );\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n  return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n  return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n  return (result && result.type) === ResultType.redirect;\n}\n\nfunction isResponse(value: any): value is Response {\n  return (\n    value != null &&\n    typeof value.status === \"number\" &&\n    typeof value.statusText === \"string\" &&\n    typeof value.headers === \"object\" &&\n    typeof value.body !== \"undefined\"\n  );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n  if (!isResponse(result)) {\n    return false;\n  }\n\n  let status = result.status;\n  let location = result.headers.get(\"Location\");\n  return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n  return (\n    obj &&\n    isResponse(obj.response) &&\n    (obj.type === ResultType.data || ResultType.error)\n  );\n}\n\nfunction isValidMethod(method: string): method is FormMethod {\n  return validRequestMethods.has(method as FormMethod);\n}\n\nfunction isMutationMethod(method?: string): method is MutationFormMethod {\n  return validMutationMethods.has(method as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n  currentMatches: AgnosticDataRouteMatch[],\n  matchesToLoad: AgnosticDataRouteMatch[],\n  results: DataResult[],\n  signal: AbortSignal,\n  isFetcher: boolean,\n  currentLoaderData?: RouteData\n) {\n  for (let index = 0; index < results.length; index++) {\n    let result = results[index];\n    let match = matchesToLoad[index];\n    let currentMatch = currentMatches.find(\n      (m) => m.route.id === match.route.id\n    );\n    let isRevalidatingLoader =\n      currentMatch != null &&\n      !isNewRouteInstance(currentMatch, match) &&\n      (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n    if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n      // Note: we do not have to touch activeDeferreds here since we race them\n      // against the signal in resolveDeferredData and they'll get aborted\n      // there if needed\n      await resolveDeferredData(result, signal, isFetcher).then((result) => {\n        if (result) {\n          results[index] = result || results[index];\n        }\n      });\n    }\n  }\n}\n\nasync function resolveDeferredData(\n  result: DeferredResult,\n  signal: AbortSignal,\n  unwrap = false\n): Promise<SuccessResult | ErrorResult | undefined> {\n  let aborted = await result.deferredData.resolveData(signal);\n  if (aborted) {\n    return;\n  }\n\n  if (unwrap) {\n    try {\n      return {\n        type: ResultType.data,\n        data: result.deferredData.unwrappedData,\n      };\n    } catch (e) {\n      // Handle any TrackedPromise._error values encountered while unwrapping\n      return {\n        type: ResultType.error,\n        error: e,\n      };\n    }\n  }\n\n  return {\n    type: ResultType.data,\n    data: result.deferredData.data,\n  };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n  return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :)  Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UseMatchesMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id] as unknown,\n    handle: route.handle as unknown,\n  };\n}\n\nfunction getTargetMatch(\n  matches: AgnosticDataRouteMatch[],\n  location: Location | string\n) {\n  let search =\n    typeof location === \"string\" ? parsePath(location).search : location.search;\n  if (\n    matches[matches.length - 1].route.index &&\n    hasNakedIndexQuery(search || \"\")\n  ) {\n    // Return the leaf index route when index is present\n    return matches[matches.length - 1];\n  }\n  // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n  // pathless layout routes)\n  let pathMatches = getPathContributingMatches(matches);\n  return pathMatches[pathMatches.length - 1];\n}\n//#endregion\n"]},"metadata":{},"sourceType":"module","externalDependencies":[]}