Index: imaps-frontend/node_modules/.vite/deps/react-router-dom.js.map
===================================================================
--- imaps-frontend/node_modules/.vite/deps/react-router-dom.js.map	(revision d56544918790c0c3bc50f2f0a98c99f3d2988ccf)
+++ imaps-frontend/node_modules/.vite/deps/react-router-dom.js.map	(revision 0c6b92add4cfaedcb91bcd37b45849f142f7d152)
@@ -1,7 +1,7 @@
 {
   "version": 3,
-  "sources": ["../../@remix-run/router/history.ts", "../../@remix-run/router/utils.ts", "../../@remix-run/router/router.ts", "../../react-router/lib/context.ts", "../../react-router/lib/hooks.tsx", "../../react-router/lib/components.tsx", "../../react-router/index.ts", "../../react-router-dom/dom.ts", "../../react-router-dom/index.tsx"],
-  "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// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\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<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\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   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\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`. This may be either a URL or the pieces\n * of a 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   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\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  idx: number;\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  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\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,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\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, delta: 1 });\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, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\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\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\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\nexport function 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, index: number): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index,\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 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  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\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    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\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      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\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    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): 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      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\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\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    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n", "import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } 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: unknown;\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  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  // We keep the raw Response for redirects so we can return it verbatim\n  response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: unknown;\n  statusCode?: number;\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\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface HandlerResult {\n  type: \"data\" | \"error\";\n  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState.  This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: FormData;\n      json: undefined;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: JsonValue;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: undefined;\n      text: string;\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<Context> {\n  request: Request;\n  params: Params;\n  context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n//   Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\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  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  actionStatus?: number;\n  actionResult?: any;\n  defaultShouldRevalidate: boolean;\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: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n  (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => Promise<HandlerResult>\n  ) => Promise<HandlerResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<HandlerResult[]>;\n}\n\nexport interface AgnosticPatchRoutesOnMissFunction<\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> {\n  (opts: {\n    path: string;\n    matches: M[];\n    patch: (routeId: string | null, children: AgnosticRouteObject[]) => void;\n  }): void | Promise<void>;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n  (route: AgnosticRouteObject): {\n    hasErrorBoundary: boolean;\n  } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\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 | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\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\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\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 extends `${infer Optional}?`\n      ? Optional\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 */\nexport type 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 you 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  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: string[] = [],\n  manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, String(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      !manifest[id],\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n      };\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n        children: undefined,\n      };\n      manifest[id] = pathOrLayoutRoute;\n\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n          route.children,\n          mapRouteProperties,\n          treePath,\n          manifest\n        );\n      }\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  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename: string,\n  allowPartial: boolean\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    // 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    let decoded = decodePath(pathname);\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\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      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 explode _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  allowPartial = false\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    let route = meta.route;\n\n    if (\n      !match &&\n      end &&\n      allowPartial &&\n      !routesMeta[routesMeta.length - 1].route.index\n    ) {\n      match = matchPath(\n        {\n          path: meta.relativePath,\n          caseSensitive: meta.caseSensitive,\n          end: false,\n        },\n        remainingPathname\n      );\n    }\n\n    if (!match) {\n      return null;\n    }\n\n    Object.assign(matchedParams, match.params);\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 | null;\n  } = {} as any\n): string {\n  let path: string = 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  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\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, compiledParams] = 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 = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, 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      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\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 params: CompiledPathParam[] = [];\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(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\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, params];\n}\n\nexport function decodePath(value: string) {\n  try {\n    return value\n      .split(\"/\")\n      .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n      .join(\"/\");\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\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 * 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// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n  let pathMatches = getPathContributingMatches(matches);\n\n  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n  // match so we include splat values for \".\" links.  See:\n  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n  if (v7_relativeSplatPath) {\n    return pathMatches.map((match, idx) =>\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) => match.pathnameBase);\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 (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\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 class DataWithResponseInit<D> {\n  type: string = \"DataWithResponseInit\";\n  data: D;\n  init: ResponseInit | null;\n\n  constructor(data: D, init?: ResponseInit) {\n    this.data = data;\n    this.init = init || null;\n  }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n  return new DataWithResponseInit(\n    data,\n    typeof init === \"number\" ? { status: init } : init\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 pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\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    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n\n    this.init = responseInit;\n  }\n\n  private trackPromise(\n    key: string,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.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, undefined, 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,\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.pendingKeysSet.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    // If the promise was resolved/rejected with undefined, we'll throw an error as you\n    // should always resolve with a value or null\n    if (error === undefined && data === undefined) {\n      let undefinedError = new Error(\n        `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n          `you must resolve/reject with a value or \\`null\\`.`\n      );\n      Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(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.pendingKeysSet.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  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\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 type DeferFunction = (\n  data: Record<string, unknown>,\n  init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  return new DeferredData(data, responseInit);\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 * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Replace\", \"true\");\n  return response;\n};\n\nexport type ErrorResponse = {\n  status: number;\n  statusText: string;\n  data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  private error?: Error;\n  private 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 thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n  return (\n    error != null &&\n    typeof error.status === \"number\" &&\n    typeof error.statusText === \"string\" &&\n    typeof error.internal === \"boolean\" &&\n    \"data\" in error\n  );\n}\n", "import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  invariant,\n  parsePath,\n  warning,\n} from \"./history\";\nimport type {\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DataStrategyMatch,\n  AgnosticRouteObject,\n  DataResult,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DeferredData,\n  DeferredResult,\n  DetectErrorBoundaryFunction,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  HTMLFormMethod,\n  HandlerResult,\n  ImmutableRouteKey,\n  MapRoutePropertiesFunction,\n  MutationFormMethod,\n  RedirectResult,\n  RouteData,\n  RouteManifest,\n  ShouldRevalidateFunctionArgs,\n  Submission,\n  SuccessResult,\n  UIMatch,\n  V7_FormMethod,\n  V7_MutationFormMethod,\n  AgnosticPatchRoutesOnMissFunction,\n  DataWithResponseInit,\n} from \"./utils\";\nimport {\n  ErrorResponseImpl,\n  ResultType,\n  convertRouteMatchToUiMatch,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  getResolveToMatches,\n  immutableRouteKeys,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  matchRoutesImpl,\n  resolveTo,\n  stripBasename,\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 future config for the router\n   */\n  get future(): FutureConfig;\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   * Return the window associated with the router\n   */\n  get window(): RouterInit[\"window\"];\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): Promise<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 | null, opts?: RouterNavigateOptions): Promise<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 | null,\n    opts?: RouterFetchOptions\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   * Get a navigation blocker\n   * @param key The identifier for the blocker\n   * @param fn The blocker function implementation\n   */\n  getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete a navigation blocker\n   * @param key The identifier for the blocker\n   */\n  deleteBlocker(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE DO NOT USE\n   *\n   * Patch additional children routes into an existing parent route\n   * @param routeId The parent route id or a callback function accepting `patch`\n   *                to perform batch patching\n   * @param children The additional children routes\n   */\n  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * HMR needs to pass in-flight route updates to React Router\n   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n   */\n  _internalSetRoutes(routes: AgnosticRouteObject[]): 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   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  v7_fetcherPersist: boolean;\n  v7_normalizeFormMethod: boolean;\n  v7_partialHydration: boolean;\n  v7_prependBasename: boolean;\n  v7_relativeSplatPath: boolean;\n  v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  routes: AgnosticRouteObject[];\n  history: History;\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<FutureConfig>;\n  hydrationData?: HydrationState;\n  window?: Window;\n  unstable_patchRoutesOnMiss?: AgnosticPatchRoutesOnMissFunction;\n  unstable_dataStrategy?: DataStrategyFunction;\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  activeDeferreds: Record<string, DeferredData> | null;\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?: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      unstable_dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      unstable_dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      unstable_viewTransitionOpts?: ViewTransitionOpts;\n      unstable_flushSync: boolean;\n    }\n  ): void;\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: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n  replace?: boolean;\n  state?: any;\n  fromRouteId?: string;\n  unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n  formMethod?: HTMLFormMethod;\n  formEncType?: FormEncType;\n} & (\n  | { formData: FormData; body?: undefined }\n  | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\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    json: undefined;\n    text: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    text: Submission[\"text\"];\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    text: undefined;\n    formData: undefined;\n    json: undefined;\n    data: TData | undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    data: TData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    text: Submission[\"text\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    data: TData | undefined;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: HistoryAction;\n}) => boolean;\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\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * Tuple for the returned or thrown value from the current action.  The routeId\n   * is the action route for success and the bubbled boundary route for errors.\n   */\n  pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n  routeId: string;\n  path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n  key: string;\n  match: AgnosticDataRouteMatch | null;\n  matches: AgnosticDataRouteMatch[] | null;\n  controller: AbortController | null;\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  json: undefined,\n  text: 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  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\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  const routerWindow = init.window\n    ? init.window\n    : typeof window !== \"undefined\"\n    ? window\n    : undefined;\n  const isBrowser =\n    typeof routerWindow !== \"undefined\" &&\n    typeof routerWindow.document !== \"undefined\" &&\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (init.mapRouteProperties) {\n    mapRouteProperties = init.mapRouteProperties;\n  } else if (init.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = init.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n\n  // Routes keyed by ID\n  let manifest: RouteManifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(\n    init.routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;\n  let patchRoutesOnMissImpl = init.unstable_patchRoutesOnMiss;\n\n  // Config driven behavior flags\n  let future: FutureConfig = {\n    v7_fetcherPersist: false,\n    v7_normalizeFormMethod: false,\n    v7_partialHydration: false,\n    v7_prependBasename: false,\n    v7_relativeSplatPath: false,\n    v7_skipActionErrorRevalidation: false,\n    ...init.future,\n  };\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(dataRoutes, init.history.location, basename);\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null && !patchRoutesOnMissImpl) {\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  // In SPA apps, if the user provided a patchRoutesOnMiss implementation and\n  // our initial match is a splat route, clear them out so we run through lazy\n  // discovery on hydration in case there's a more accurate lazy route match.\n  // In SSR apps (with `hydrationData`), we expect that the server will send\n  // up the proper matched routes so we don't want to run lazy discovery on\n  // initial hydration and want to hydrate into the splat route.\n  if (initialMatches && !init.hydrationData) {\n    let fogOfWar = checkFogOfWar(\n      initialMatches,\n      dataRoutes,\n      init.history.location.pathname\n    );\n    if (fogOfWar.active) {\n      initialMatches = null;\n    }\n  }\n\n  let initialized: boolean;\n  if (!initialMatches) {\n    initialized = false;\n    initialMatches = [];\n\n    // If partial hydration and fog of war is enabled, we will be running\n    // `patchRoutesOnMiss` during hydration so include any partial matches as\n    // the initial matches so we can properly render `HydrateFallback`'s\n    if (future.v7_partialHydration) {\n      let fogOfWar = checkFogOfWar(\n        null,\n        dataRoutes,\n        init.history.location.pathname\n      );\n      if (fogOfWar.active && fogOfWar.matches) {\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) => m.route.lazy)) {\n    // All initialMatches need to be loaded before we're ready.  If we have lazy\n    // functions around still then we'll need to run them in initialize()\n    initialized = false;\n  } else if (!initialMatches.some((m) => m.route.loader)) {\n    // If we've got no loaders to run, then we're good to go\n    initialized = true;\n  } else if (future.v7_partialHydration) {\n    // If partial hydration is enabled, we're initialized so long as we were\n    // provided with hydrationData for every route with a loader, and no loaders\n    // were marked for explicit hydration\n    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n    let errors = init.hydrationData ? init.hydrationData.errors : null;\n    let isRouteInitialized = (m: AgnosticDataRouteMatch) => {\n      // No loader, nothing to initialize\n      if (!m.route.loader) {\n        return true;\n      }\n      // Explicitly opting-in to running on hydration\n      if (\n        typeof m.route.loader === \"function\" &&\n        m.route.loader.hydrate === true\n      ) {\n        return false;\n      }\n      // Otherwise, initialized if hydrated with data or an error\n      return (\n        (loaderData && loaderData[m.route.id] !== undefined) ||\n        (errors && errors[m.route.id] !== undefined)\n      );\n    };\n\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(\n        (m) => errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);\n    } else {\n      initialized = initialMatches.every(isRouteInitialized);\n    }\n  } else {\n    // Without partial hydration - we're initialized if we were provided any\n    // hydrationData - which is expected to be complete\n    initialized = init.hydrationData != null;\n  }\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    blockers: 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\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions: Map<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\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\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: Set<string> = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\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\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers that have requested a delete when using v7_fetcherPersist,\n  // they'll be officially removed after they return to idle\n  let deletedFetchers = new Set<string>();\n\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  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // Map of pending patchRoutesOnMiss() promises (keyed by path/matches) so\n  // that we only kick them off once for a given combo\n  let pendingPatchRoutes = new Map<\n    string,\n    ReturnType<AgnosticPatchRoutesOnMissFunction>\n  >();\n\n  // Flag to ignore the next history update, so we can revert the URL change on\n  // a POP navigation that was blocked by the user without touching router state\n  let ignoreNextHistoryUpdate = false;\n\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, delta }) => {\n        // Ignore this event if it was just us resetting the URL from a\n        // blocked POP navigation\n        if (ignoreNextHistoryUpdate) {\n          ignoreNextHistoryUpdate = false;\n          return;\n        }\n\n        warning(\n          blockerFunctions.size === 0 || delta != null,\n          \"You are trying to use a blocker on a POP navigation to a location \" +\n            \"that was not created by @remix-run/router. This will fail silently in \" +\n            \"production. This can happen if you are navigating outside the router \" +\n            \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n            \"router navigation APIs.  This can also happen if you are using \" +\n            \"createHashRouter and the user manually changes the URL.\"\n        );\n\n        let blockerKey = shouldBlockNavigation({\n          currentLocation: state.location,\n          nextLocation: location,\n          historyAction,\n        });\n\n        if (blockerKey && delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          ignoreNextHistoryUpdate = true;\n          init.history.go(delta * -1);\n\n          // Put the blocker into a blocked state\n          updateBlocker(blockerKey, {\n            state: \"blocked\",\n            location,\n            proceed() {\n              updateBlocker(blockerKey!, {\n                state: \"proceeding\",\n                proceed: undefined,\n                reset: undefined,\n                location,\n              });\n              // Re-do the same POP navigation we just blocked\n              init.history.go(delta);\n            },\n            reset() {\n              let blockers = new Map(state.blockers);\n              blockers.set(blockerKey!, IDLE_BLOCKER);\n              updateState({ blockers });\n            },\n          });\n          return;\n        }\n\n        return startNavigation(historyAction, location);\n      }\n    );\n\n    if (isBrowser) {\n      // FIXME: This feels gross.  How can we cleanup the lines between\n      // scrollRestoration/appliedTransitions persistance?\n      restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n      let _saveAppliedTransitions = () =>\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =>\n        routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n    }\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    // Note we don't do any handling of lazy here.  For SPA's it'll get handled\n    // in the normal navigation flow.  For SSR it's expected that lazy modules are\n    // resolved prior to router creation since we can't go into a fallbackElement\n    // UI for SSR'd apps\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location, {\n        initialHydration: true,\n      });\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    if (removePageHideEventListener) {\n      removePageHideEventListener();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n    state.blockers.forEach((_, key) => deleteBlocker(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(\n    newState: Partial<RouterState>,\n    opts: {\n      flushSync?: boolean;\n      viewTransitionOpts?: ViewTransitionOpts;\n    } = {}\n  ): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers: string[] = [];\n    let deletedFetchersKeys: string[] = [];\n\n    if (future.v7_fetcherPersist) {\n      state.fetchers.forEach((fetcher, key) => {\n        if (fetcher.state === \"idle\") {\n          if (deletedFetchers.has(key)) {\n            // Unmounted from the UI and can be totally removed\n            deletedFetchersKeys.push(key);\n          } else {\n            // Returned to idle but still mounted in the UI, so semi-remains for\n            // revalidations and such\n            completedFetchers.push(key);\n          }\n        }\n      });\n    }\n\n    // Iterate over a local copy so that if flushSync is used and we end up\n    // removing and adding a new subscriber due to the useCallback dependencies,\n    // we don't get ourselves into a loop calling the new subscriber immediately\n    [...subscribers].forEach((subscriber) =>\n      subscriber(state, {\n        deletedFetchers: deletedFetchersKeys,\n        unstable_viewTransitionOpts: opts.viewTransitionOpts,\n        unstable_flushSync: opts.flushSync === true,\n      })\n    );\n\n    // Remove idle fetchers from state since we only care about in-flight fetchers.\n    if (future.v7_fetcherPersist) {\n      completedFetchers.forEach((key) => state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n    }\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    { flushSync }: { flushSync?: boolean } = {}\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    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\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    let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === HistoryAction.Pop) {\n      // Forward takes precedence so they behave like the original navigation\n      let priorPaths = appliedViewTransitions.get(state.location.pathname);\n      if (priorPaths && priorPaths.has(location.pathname)) {\n        viewTransitionOpts = {\n          currentLocation: state.location,\n          nextLocation: location,\n        };\n      } else if (appliedViewTransitions.has(location.pathname)) {\n        // If we don't have a previous forward nav, assume we're popping back to\n        // the new location and enable if that location previously enabled\n        viewTransitionOpts = {\n          currentLocation: location,\n          nextLocation: state.location,\n        };\n      }\n    } else if (pendingViewTransitionEnabled) {\n      // Store the applied transition on PUSH/REPLACE\n      let toPaths = appliedViewTransitions.get(state.location.pathname);\n      if (toPaths) {\n        toPaths.add(location.pathname);\n      } else {\n        toPaths = new Set<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\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        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\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 | null,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      to,\n      future.v7_relativeSplatPath,\n      opts?.fromRouteId,\n      opts?.relative\n    );\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      false,\n      normalizedPath,\n      opts\n    );\n\n    let currentLocation = state.location;\n    let nextLocation = 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    nextLocation = {\n      ...nextLocation,\n      ...init.history.encodeLocation(nextLocation),\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    let flushSync = (opts && opts.unstable_flushSync) === true;\n\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction,\n    });\n\n    if (blockerKey) {\n      // Put the blocker into a blocked state\n      updateBlocker(blockerKey, {\n        state: \"blocked\",\n        location: nextLocation,\n        proceed() {\n          updateBlocker(blockerKey!, {\n            state: \"proceeding\",\n            proceed: undefined,\n            reset: undefined,\n            location: nextLocation,\n          });\n          // Send the same navigation through\n          navigate(to, opts);\n        },\n        reset() {\n          let blockers = new Map(state.blockers);\n          blockers.set(blockerKey!, IDLE_BLOCKER);\n          updateState({ blockers });\n        },\n      });\n      return;\n    }\n\n    return await startNavigation(historyAction, nextLocation, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n      enableViewTransition: opts && opts.unstable_viewTransition,\n      flushSync,\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      initialHydration?: boolean;\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponseImpl;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n      enableViewTransition?: boolean;\n      flushSync?: 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    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches = matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let { error, notFoundMatches, route } = handleNavigational404(\n        location.pathname\n      );\n      completeNavigation(\n        location,\n        {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        },\n        { flushSync }\n      );\n      return;\n    }\n\n    // Short circuit if it's only a hash change and not a revalidation or\n    // mutation submission.\n    //\n    // Ignore on initial page loads because since the initial load will always\n    // be \"same hash\".  For example, on /page#hash and submit a <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | 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      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: 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 actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        fogOfWar.active,\n        { replace: opts.replace, flushSync }\n      );\n\n      if (actionResult.shortCircuited) {\n        return;\n      }\n\n      // If we received a 404 from handleAction, it's because we couldn't lazily\n      // discover the destination route so we don't want to call loaders\n      if (actionResult.pendingActionResult) {\n        let [routeId, result] = actionResult.pendingActionResult;\n        if (\n          isErrorResult(result) &&\n          isRouteErrorResponse(result.error) &&\n          result.error.status === 404\n        ) {\n          pendingNavigationController = null;\n\n          completeNavigation(location, {\n            matches: actionResult.matches,\n            loaderData: {},\n            errors: {\n              [routeId]: result.error,\n            },\n          });\n          return;\n        }\n      }\n\n      matches = actionResult.matches || matches;\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // No need to do fog of war matching again on loader execution\n      fogOfWar.active = false;\n\n      // Create a GET request for the loaders\n      request = createClientSideRequest(\n        init.history,\n        request.url,\n        request.signal\n      );\n    }\n\n    // Call loaders\n    let {\n      shortCircuited,\n      matches: updatedMatches,\n      loaderData,\n      errors,\n    } = await handleLoaders(\n      request,\n      location,\n      matches,\n      fogOfWar.active,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.fetcherSubmission,\n      opts && opts.replace,\n      opts && opts.initialHydration === true,\n      flushSync,\n      pendingActionResult\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: updatedMatches || matches,\n      ...getActionDataForCommit(pendingActionResult),\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    isFogOfWar: boolean,\n    opts: { replace?: boolean; flushSync?: boolean } = {}\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let { boundaryId, error } = handleDiscoverRouteError(\n          location.pathname,\n          discoverResult\n        );\n        return {\n          matches: discoverResult.partialMatches,\n          pendingActionResult: [\n            boundaryId,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else if (!discoverResult.matches) {\n        let { notFoundMatches, error, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          pendingActionResult: [\n            route.id,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\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 && !actionMatch.route.lazy) {\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      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches\n      );\n      result = results[0];\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        let location = normalizeRedirectLocation(\n          result.response.headers.get(\"Location\")!,\n          new URL(request.url),\n          basename\n        );\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, {\n        submission,\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\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 to the current location are REPLACE\n      // navigations, but if the action threw an error that'll be rendered in\n      // an errorElement, we fall back to PUSH so that the user can use the\n      // back button to get back to the pre-submission form location to try\n      // again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        matches,\n        pendingActionResult: [boundaryMatch.route.id, result],\n      };\n    }\n\n    return {\n      matches,\n      pendingActionResult: [actionMatch.route.id, result],\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    isFogOfWar: boolean,\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    fetcherSubmission?: Submission,\n    replace?: boolean,\n    initialHydration?: boolean,\n    flushSync?: boolean,\n    pendingActionResult?: PendingActionResult\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\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 =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\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 we have partialHydration enabled, then don't update the state for the\n    // initial data load since it's not a \"navigation\"\n    let shouldUpdateNavigationState =\n      !isUninterruptedRevalidation &&\n      (!future.v7_partialHydration || !initialHydration);\n\n    // When fog of war is enabled, we enter our `loading` state earlier so we\n    // can discover new routes during the `loading` state.  We skip this if\n    // we've already run actions since we would have done our matching already.\n    // If the children() function threw then, we want to proceed with the\n    // partial matches it discovered.\n    if (isFogOfWar) {\n      if (shouldUpdateNavigationState) {\n        let actionData = getUpdatedActionData(pendingActionResult);\n        updateState(\n          {\n            navigation: loadingNavigation,\n            ...(actionData !== undefined ? { actionData } : {}),\n          },\n          {\n            flushSync,\n          }\n        );\n      }\n\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let { boundaryId, error } = handleDiscoverRouteError(\n          location.pathname,\n          discoverResult\n        );\n        return {\n          matches: discoverResult.partialMatches,\n          loaderData: {},\n          errors: {\n            [boundaryId]: error,\n          },\n        };\n      } else if (!discoverResult.matches) {\n        let { error, notFoundMatches, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      activeSubmission,\n      location,\n      future.v7_partialHydration && initialHydration === true,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      pendingActionResult\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    pendingNavigationLoadId = ++incrementingLoadId;\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(\n        location,\n        {\n          matches,\n          loaderData: {},\n          // Commit pending error if we're short circuiting\n          errors:\n            pendingActionResult && isErrorResult(pendingActionResult[1])\n              ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n              : null,\n          ...getActionDataForCommit(pendingActionResult),\n          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n        },\n        { flushSync }\n      );\n      return { shortCircuited: true };\n    }\n\n    if (shouldUpdateNavigationState) {\n      let updates: Partial<RouterState> = {};\n      if (!isFogOfWar) {\n        // Only update navigation/actionNData if we didn't already do it above\n        updates.navigation = loadingNavigation;\n        let actionData = getUpdatedActionData(pendingActionResult);\n        if (actionData !== undefined) {\n          updates.actionData = actionData;\n        }\n      }\n      if (revalidatingFetchers.length > 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) => {\n      if (fetchControllers.has(rf.key)) {\n        abortFetcher(rf.key);\n      }\n      if (rf.controller) {\n        // Fetchers use an independent AbortController so that aborting a fetcher\n        // (via deleteFetcher) does not abort the triggering navigation that\n        // triggered the revalidation\n        fetchControllers.set(rf.key, rf.controller);\n      }\n    });\n\n    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    let { 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    if (pendingNavigationController) {\n      pendingNavigationController.signal.removeEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect([...loaderResults, ...fetcherResults]);\n    if (redirect) {\n      if (redirect.idx >= matchesToLoad.length) {\n        // If this redirect came from a fetcher make sure we mark it in\n        // fetchRedirectIds so it doesn't get revalidated on the next set of\n        // loader executions\n        let fetcherKey =\n          revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n        fetchRedirectIds.add(fetcherKey);\n      }\n      await startRedirectNavigation(request, redirect.result, {\n        replace,\n      });\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      pendingActionResult,\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    // During partial hydration, preserve SSR errors for routes that don't re-run\n    if (future.v7_partialHydration && initialHydration && state.errors) {\n      Object.entries(state.errors)\n        .filter(([id]) => !matchesToLoad.some((m) => m.route.id === id))\n        .forEach(([routeId, error]) => {\n          errors = Object.assign(errors || {}, { [routeId]: error });\n        });\n    }\n\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers =\n      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n    return {\n      matches,\n      loaderData,\n      errors,\n      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n    };\n  }\n\n  function getUpdatedActionData(\n    pendingActionResult: PendingActionResult | undefined\n  ): Record<string, RouteData> | null | undefined {\n    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n      // This is cast to `any` currently because `RouteData`uses any and it\n      // would be a breaking change to use any.\n      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n      return {\n        [pendingActionResult[0]]: pendingActionResult[1].data as any,\n      };\n    } else if (state.actionData) {\n      if (Object.keys(state.actionData).length === 0) {\n        return null;\n      } else {\n        return state.actionData;\n      }\n    }\n  }\n\n  function getUpdatedRevalidatingFetchers(\n    revalidatingFetchers: RevalidatingFetcher[]\n  ) {\n    revalidatingFetchers.forEach((rf) => {\n      let fetcher = state.fetchers.get(rf.key);\n      let revalidatingFetcher = getLoadingFetcher(\n        undefined,\n        fetcher ? fetcher.data : undefined\n      );\n      state.fetchers.set(rf.key, revalidatingFetcher);\n    });\n    return new Map(state.fetchers);\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 | null,\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    let flushSync = (opts && opts.unstable_flushSync) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      href,\n      future.v7_relativeSplatPath,\n      routeId,\n      opts?.relative\n    );\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: normalizedPath }),\n        { flushSync }\n      );\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      true,\n      normalizedPath,\n      opts\n    );\n\n    if (error) {\n      setFetcherError(key, routeId, error, { flushSync });\n      return;\n    }\n\n    let match = getTargetMatch(matches, path);\n\n    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(\n        key,\n        routeId,\n        path,\n        match,\n        matches,\n        fogOfWar.active,\n        flushSync,\n        submission\n      );\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, { routeId, path });\n    handleFetcherLoader(\n      key,\n      routeId,\n      path,\n      match,\n      matches,\n      fogOfWar.active,\n      flushSync,\n      submission\n    );\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    isFogOfWar: boolean,\n    flushSync: boolean,\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n      if (!m.route.action && !m.route.lazy) {\n        let error = getInternalRouterError(405, {\n          method: submission.formMethod,\n          pathname: path,\n          routeId: routeId,\n        });\n        setFetcherError(key, routeId, error, { flushSync });\n        return true;\n      }\n      return false;\n    }\n\n    if (!isFogOfWar && detectAndHandle405Error(match)) {\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n      flushSync,\n    });\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal,\n      submission\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        requestMatches,\n        path,\n        fetchRequest.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        let { error } = handleDiscoverRouteError(path, discoverResult);\n        setFetcherError(key, routeId, error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        requestMatches = discoverResult.matches;\n        match = getTargetMatch(requestMatches, path);\n\n        if (detectAndHandle405Error(match)) {\n          return;\n        }\n      }\n    }\n\n    // Call the action for the fetcher\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\n      \"action\",\n      fetchRequest,\n      [match],\n      requestMatches\n    );\n    let actionResult = actionResults[0];\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by 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    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n    // or redirects processed for unmounted fetchers so we just revert them to\n    // idle\n    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      }\n      // Let SuccessResult's fall through for revalidation\n    } else {\n      if (isRedirectResult(actionResult)) {\n        fetchControllers.delete(key);\n        if (pendingNavigationLoadId > originatingLoadId) {\n          // A new navigation was kicked off after our action started, so that\n          // should take precedence over this redirect navigation.  We already\n          // set isRevalidationRequired so all loaders for the new route should\n          // fire unless opted out via shouldRevalidate\n          updateFetcherState(key, getDoneFetcher(undefined));\n          return;\n        } else {\n          fetchRedirectIds.add(key);\n          updateFetcherState(key, getLoadingFetcher(submission));\n          return startRedirectNavigation(fetchRequest, actionResult, {\n            fetcherSubmission: submission,\n          });\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\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\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      init.history,\n      nextLocation,\n      abortController.signal\n    );\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(routesToUse, state.navigation.location, 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 = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      submission,\n      nextLocation,\n      false,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      [match.route.id, actionResult]\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((rf) => rf.key !== key)\n      .forEach((rf) => {\n        let staleKey = rf.key;\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher = getLoadingFetcher(\n          undefined,\n          existingFetcher ? existingFetcher.data : undefined\n        );\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        if (fetchControllers.has(staleKey)) {\n          abortFetcher(staleKey);\n        }\n        if (rf.controller) {\n          fetchControllers.set(staleKey, rf.controller);\n        }\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n    abortController.signal.addEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    let { 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    abortController.signal.removeEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n    let redirect = findRedirect([...loaderResults, ...fetcherResults]);\n    if (redirect) {\n      if (redirect.idx >= matchesToLoad.length) {\n        // If this redirect came from a fetcher make sure we mark it in\n        // fetchRedirectIds so it doesn't get revalidated on the next set of\n        // loader executions\n        let fetcherKey =\n          revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n        fetchRedirectIds.add(fetcherKey);\n      }\n      return startRedirectNavigation(revalidationRequest, redirect.result);\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    // Since we let revalidations complete even if the submitting fetcher was\n    // deleted, only put it back to idle if it hasn't been deleted\n    if (state.fetchers.has(key)) {\n      let doneFetcher = getDoneFetcher(actionResult.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n\n    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        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    isFogOfWar: boolean,\n    flushSync: boolean,\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(\n      key,\n      getLoadingFetcher(\n        submission,\n        existingFetcher ? existingFetcher.data : undefined\n      ),\n      { flushSync }\n    );\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        path,\n        fetchRequest.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        let { error } = handleDiscoverRouteError(path, discoverResult);\n        setFetcherError(key, routeId, error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        matches = discoverResult.matches;\n        match = getTargetMatch(matches, path);\n      }\n    }\n\n    // Call the loader for this fetcher route match\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\n      \"loader\",\n      fetchRequest,\n      [match],\n      matches\n    );\n    let result = results[0];\n\n    // Deferred isn't supported for 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 our 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    // We don't want errors bubbling up or redirects followed for unmounted\n    // fetchers, so short circuit here if it was removed from the UI\n    if (deletedFetchers.has(key)) {\n      updateFetcherState(key, getDoneFetcher(undefined));\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      if (pendingNavigationLoadId > originatingLoadId) {\n        // A new navigation was kicked off after our loader started, so that\n        // should take precedence over this redirect navigation\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      } else {\n        fetchRedirectIds.add(key);\n        await startRedirectNavigation(fetchRequest, result);\n        return;\n      }\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\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    request: Request,\n    redirect: RedirectResult,\n    {\n      submission,\n      fetcherSubmission,\n      replace,\n    }: {\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      replace?: boolean;\n    } = {}\n  ) {\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(\n      location,\n      new URL(request.url),\n      basename\n    );\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true,\n    });\n\n    if (isBrowser) {\n      let isDocumentReload = false;\n\n      if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n        // Hard reload if the response contained X-Remix-Reload-Document\n        isDocumentReload = true;\n      } else if (ABSOLUTE_URL_REGEX.test(location)) {\n        const url = init.history.createURL(location);\n        isDocumentReload =\n          // Hard reload if it's an absolute URL to a new origin\n          url.origin !== routerWindow.location.origin ||\n          // Hard reload if it's an absolute URL that does not match our basename\n          stripBasename(url.pathname, basename) == null;\n      }\n\n      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(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 || redirect.response.headers.has(\"X-Remix-Replace\")\n        ? HistoryAction.Replace\n        : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType } = state.navigation;\n    if (\n      !submission &&\n      !fetcherSubmission &&\n      formMethod &&\n      formAction &&\n      formEncType\n    ) {\n      submission = getSubmissionFromNavigation(state.navigation);\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    let activeSubmission = submission || fetcherSubmission;\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n      activeSubmission &&\n      isMutationMethod(activeSubmission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...activeSubmission,\n          formAction: location,\n        },\n        // Preserve this flag across redirects\n        preventScrollReset: pendingPreventScrollReset,\n      });\n    } else {\n      // If we have a navigation submission, we will preserve it through the\n      // redirect navigation\n      let overrideNavigation = getLoadingNavigation(\n        redirectLocation,\n        submission\n      );\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation,\n        // Send fetcher submissions through for shouldRevalidate\n        fetcherSubmission,\n        // Preserve this flag across redirects\n        preventScrollReset: pendingPreventScrollReset,\n      });\n    }\n  }\n\n  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[]\n  ): Promise<DataResult[]> {\n    try {\n      let results = await callDataStrategyImpl(\n        dataStrategyImpl,\n        type,\n        request,\n        matchesToLoad,\n        matches,\n        manifest,\n        mapRouteProperties\n      );\n\n      return await Promise.all(\n        results.map((result, i) => {\n          if (isRedirectHandlerResult(result)) {\n            let response = result.result as Response;\n            return {\n              type: ResultType.redirect,\n              response: normalizeRelativeRoutingRedirectResponse(\n                response,\n                request,\n                matchesToLoad[i].route.id,\n                matches,\n                basename,\n                future.v7_relativeSplatPath\n              ),\n            };\n          }\n\n          return convertHandlerResultToDataResult(result);\n        })\n      );\n    } catch (e) {\n      // If the outer dataStrategy method throws, just return the error for all\n      // matches - and it'll naturally bubble to the root\n      return matchesToLoad.map(() => ({\n        type: ResultType.error,\n        error: e,\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    let [loaderResults, ...fetcherResults] = await Promise.all([\n      matchesToLoad.length\n        ? callDataStrategy(\"loader\", request, matchesToLoad, matches)\n        : [],\n      ...fetchersToLoad.map((f) => {\n        if (f.matches && f.match && f.controller) {\n          let fetcherRequest = createClientSideRequest(\n            init.history,\n            f.path,\n            f.controller.signal\n          );\n          return callDataStrategy(\n            \"loader\",\n            fetcherRequest,\n            [f.match],\n            f.matches\n          ).then((r) => r[0]);\n        } else {\n          return Promise.resolve<DataResult>({\n            type: ResultType.error,\n            error: getInternalRouterError(404, {\n              pathname: f.path,\n            }),\n          });\n        }\n      }),\n    ]);\n\n    await Promise.all([\n      resolveDeferredResults(\n        currentMatches,\n        matchesToLoad,\n        loaderResults,\n        loaderResults.map(() => request.signal),\n        false,\n        state.loaderData\n      ),\n      resolveDeferredResults(\n        currentMatches,\n        fetchersToLoad.map((f) => f.match),\n        fetcherResults,\n        fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n        true\n      ),\n    ]);\n\n    return {\n      loaderResults,\n      fetcherResults,\n    };\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.add(key);\n        abortFetcher(key);\n      }\n    });\n  }\n\n  function updateFetcherState(\n    key: string,\n    fetcher: Fetcher,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    state.fetchers.set(key, fetcher);\n    updateState(\n      { fetchers: new Map(state.fetchers) },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function setFetcherError(\n    key: string,\n    routeId: string,\n    error: any,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState(\n      {\n        errors: {\n          [boundaryMatch.route.id]: error,\n        },\n        fetchers: new Map(state.fetchers),\n      },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    if (future.v7_fetcherPersist) {\n      activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n      // If this fetcher was previously marked for deletion, unmark it since we\n      // have a new instance\n      if (deletedFetchers.has(key)) {\n        deletedFetchers.delete(key);\n      }\n    }\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  function deleteFetcher(key: string): void {\n    let fetcher = state.fetchers.get(key);\n    // Don't abort the controller if this is a deletion of a fetcher.submit()\n    // in it's loading phase since - we don't want to abort the corresponding\n    // revalidation and want them to complete and land\n    if (\n      fetchControllers.has(key) &&\n      !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n    ) {\n      abortFetcher(key);\n    }\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n    deletedFetchers.delete(key);\n    cancelledFetcherLoads.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function deleteFetcherAndUpdateState(key: string): void {\n    if (future.v7_fetcherPersist) {\n      let count = (activeFetchers.get(key) || 0) - 1;\n      if (count <= 0) {\n        activeFetchers.delete(key);\n        deletedFetchers.add(key);\n      } else {\n        activeFetchers.set(key, count);\n      }\n    } else {\n      deleteFetcher(key);\n    }\n    updateState({ fetchers: new Map(state.fetchers) });\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 = getDoneFetcher(fetcher.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): boolean {\n    let doneKeys = [];\n    let updatedFetchers = false;\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        updatedFetchers = true;\n      }\n    }\n    markFetchersDone(doneKeys);\n    return updatedFetchers;\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 getBlocker(key: string, fn: BlockerFunction) {\n    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n\n    return blocker;\n  }\n\n  function deleteBlocker(key: string) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key: string, newBlocker: Blocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    invariant(\n      (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n    );\n\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({ blockers });\n  }\n\n  function shouldBlockNavigation({\n    currentLocation,\n    nextLocation,\n    historyAction,\n  }: {\n    currentLocation: Location;\n    nextLocation: Location;\n    historyAction: HistoryAction;\n  }): string | undefined {\n    if (blockerFunctions.size === 0) {\n      return;\n    }\n\n    // We ony support a single active blocker at the moment since we don't have\n    // any compelling use cases for multi-blocker yet\n    if (blockerFunctions.size > 1) {\n      warning(false, \"A router only supports one blocker at a time\");\n    }\n\n    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\n\n    if (blocker && blocker.state === \"proceeding\") {\n      // If the blocker is currently proceeding, we don't need to re-check\n      // it and can let this navigation continue\n      return;\n    }\n\n    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n      return blockerKey;\n    }\n  }\n\n  function handleNavigational404(pathname: string) {\n    let error = getInternalRouterError(404, { pathname });\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let { matches, route } = getShortCircuitMatches(routesToUse);\n\n    // Cancel all pending deferred on 404s since we don't keep any routes\n    cancelActiveDeferreds();\n\n    return { notFoundMatches: matches, route, error };\n  }\n\n  function handleDiscoverRouteError(\n    pathname: string,\n    discoverResult: DiscoverRoutesErrorResult\n  ) {\n    return {\n      boundaryId: findNearestBoundary(discoverResult.partialMatches).route.id,\n      error: getInternalRouterError(400, {\n        type: \"route-discovery\",\n        pathname,\n        message:\n          discoverResult.error != null && \"message\" in discoverResult.error\n            ? discoverResult.error\n            : String(discoverResult.error),\n      }),\n    };\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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function checkFogOfWar(\n    matches: AgnosticDataRouteMatch[] | null,\n    routesToUse: AgnosticDataRouteObject[],\n    pathname: string\n  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n    if (patchRoutesOnMissImpl) {\n      if (!matches) {\n        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n          routesToUse,\n          pathname,\n          basename,\n          true\n        );\n\n        return { active: true, matches: fogMatches || [] };\n      } else {\n        let leafRoute = matches[matches.length - 1].route;\n        if (\n          leafRoute.path &&\n          (leafRoute.path === \"*\" || leafRoute.path.endsWith(\"/*\"))\n        ) {\n          // If we matched a splat, it might only be because we haven't yet fetched\n          // the children that would match with a higher score, so let's fetch\n          // around and find out\n          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n            routesToUse,\n            pathname,\n            basename,\n            true\n          );\n          return { active: true, matches: partialMatches };\n        }\n      }\n    }\n\n    return { active: false, matches: null };\n  }\n\n  type DiscoverRoutesSuccessResult = {\n    type: \"success\";\n    matches: AgnosticDataRouteMatch[] | null;\n  };\n  type DiscoverRoutesErrorResult = {\n    type: \"error\";\n    error: any;\n    partialMatches: AgnosticDataRouteMatch[];\n  };\n  type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n  type DiscoverRoutesResult =\n    | DiscoverRoutesSuccessResult\n    | DiscoverRoutesErrorResult\n    | DiscoverRoutesAbortedResult;\n\n  async function discoverRoutes(\n    matches: AgnosticDataRouteMatch[],\n    pathname: string,\n    signal: AbortSignal\n  ): Promise<DiscoverRoutesResult> {\n    let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n    let route =\n      partialMatches.length > 0\n        ? partialMatches[partialMatches.length - 1].route\n        : null;\n    while (true) {\n      let isNonHMR = inFlightDataRoutes == null;\n      let routesToUse = inFlightDataRoutes || dataRoutes;\n      try {\n        await loadLazyRouteChildren(\n          patchRoutesOnMissImpl!,\n          pathname,\n          partialMatches,\n          routesToUse,\n          manifest,\n          mapRouteProperties,\n          pendingPatchRoutes,\n          signal\n        );\n      } catch (e) {\n        return { type: \"error\", error: e, partialMatches };\n      } finally {\n        // If we are not in the middle of an HMR revalidation and we changed the\n        // routes, provide a new identity so when we `updateState` at the end of\n        // this navigation/fetch `router.routes` will be a new identity and\n        // trigger a re-run of memoized `router.routes` dependencies.\n        // HMR will already update the identity and reflow when it lands\n        // `inFlightDataRoutes` in `completeNavigation`\n        if (isNonHMR) {\n          dataRoutes = [...dataRoutes];\n        }\n      }\n\n      if (signal.aborted) {\n        return { type: \"aborted\" };\n      }\n\n      let newMatches = matchRoutes(routesToUse, pathname, basename);\n      let matchedSplat = false;\n      if (newMatches) {\n        let leafRoute = newMatches[newMatches.length - 1].route;\n\n        if (leafRoute.index) {\n          // If we found an index route, we can stop\n          return { type: \"success\", matches: newMatches };\n        }\n\n        if (leafRoute.path && leafRoute.path.length > 0) {\n          if (leafRoute.path === \"*\") {\n            // If we found a splat route, we can't be sure there's not a\n            // higher-scoring route down some partial matches trail so we need\n            // to check that out\n            matchedSplat = true;\n          } else {\n            // If we found a non-splat route, we can stop\n            return { type: \"success\", matches: newMatches };\n          }\n        }\n      }\n\n      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n        routesToUse,\n        pathname,\n        basename,\n        true\n      );\n\n      // If we are no longer partially matching anything, this was either a\n      // legit splat match above, or it's a 404.  Also avoid loops if the\n      // second pass results in the same partial matches\n      if (\n        !newPartialMatches ||\n        partialMatches.map((m) => m.route.id).join(\"-\") ===\n          newPartialMatches.map((m) => m.route.id).join(\"-\")\n      ) {\n        return { type: \"success\", matches: matchedSplat ? newMatches : null };\n      }\n\n      partialMatches = newPartialMatches;\n      route = partialMatches[partialMatches.length - 1].route;\n      if (route.path === \"*\") {\n        // The splat is still our most accurate partial, so run with it\n        return { type: \"success\", matches: partialMatches };\n      }\n    }\n  }\n\n  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(\n      newRoutes,\n      mapRouteProperties,\n      undefined,\n      manifest\n    );\n  }\n\n  function patchRoutes(\n    routeId: string | null,\n    children: AgnosticRouteObject[]\n  ): void {\n    let isNonHMR = inFlightDataRoutes == null;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    patchRoutesImpl(\n      routeId,\n      children,\n      routesToUse,\n      manifest,\n      mapRouteProperties\n    );\n\n    // If we are not in the middle of an HMR revalidation and we changed the\n    // routes, provide a new identity and trigger a reflow via `updateState`\n    // to re-run memoized `router.routes` dependencies.\n    // HMR will already update the identity and reflow when it lands\n    // `inFlightDataRoutes` in `completeNavigation`\n    if (isNonHMR) {\n      dataRoutes = [...dataRoutes];\n      updateState({});\n    }\n  }\n\n  router = {\n    get basename() {\n      return basename;\n    },\n    get future() {\n      return future;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    get window() {\n      return routerWindow;\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: deleteFetcherAndUpdateState,\n    dispose,\n    getBlocker,\n    deleteBlocker,\n    patchRoutes,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n    // TODO: Remove setRoutes, it's temporary to avoid dealing with\n    // updating the tree while validating the update algorithm.\n    _internalSetRoutes,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let manifest: RouteManifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (opts?.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts?.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = opts.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n  // Config driven behavior flags\n  let future: StaticHandlerFutureConfig = {\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false,\n    ...(opts ? opts.future : null),\n  };\n\n  let dataRoutes = convertRoutesToDataRoutes(\n    routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\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   * - `opts.requestContext` is an optional server context that will be passed\n   *   to actions/loaders in the `context` parameter\n   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n   *   the bubbling of errors which allows single-fetch-type implementations\n   *   where the client will handle the bubbling and we may need to return data\n   *   for the handling route\n   */\n  async function query(\n    request: Request,\n    {\n      requestContext,\n      skipLoaderErrorBubbling,\n      unstable_dataStrategy,\n    }: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      unstable_dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\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        activeDeferreds: null,\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        activeDeferreds: null,\n      };\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      unstable_dataStrategy || null,\n      skipLoaderErrorBubbling === true,\n      null\n    );\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   * - `opts.routeId` allows you to specify the specific route handler to call.\n   *   If not provided the handler will determine the proper route by matching\n   *   against `request.url`\n   * - `opts.requestContext` is an optional server context that will be passed\n   *    to actions/loaders in the `context` parameter\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n      unstable_dataStrategy,\n    }: {\n      requestContext?: unknown;\n      routeId?: string;\n      unstable_dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method;\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\" && method !== \"OPTIONS\") {\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      unstable_dataStrategy || null,\n      false,\n      match\n    );\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    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n\n    if (result.loaderData) {\n      let data = Object.values(result.loaderData)[0];\n      if (result.activeDeferreds?.[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n\n    return undefined;\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    unstable_dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null\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          unstable_dataStrategy,\n          skipLoaderErrorBubbling,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        unstable_dataStrategy,\n        skipLoaderErrorBubbling,\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 for a\n      // `queryRoute` call, we throw the `HandlerResult` to bail out early\n      // and then return or throw the raw Response here accordingly\n      if (isHandlerResult(e) && isResponse(e.result)) {\n        if (e.type === ResultType.error) {\n          throw e.result;\n        }\n        return e.result;\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    unstable_dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\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      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        unstable_dataStrategy\n      );\n      result = results[0];\n\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\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.response.status,\n        headers: {\n          Location: result.response.headers.get(\"Location\")!,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, { type: \"defer-action\" });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\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        activeDeferreds: null,\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\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 = skipLoaderErrorBubbling\n        ? actionMatch\n        : findNearestBoundary(matches, actionMatch.route.id);\n\n      let context = await loadRouteData(\n        loaderRequest,\n        matches,\n        requestContext,\n        unstable_dataStrategy,\n        skipLoaderErrorBubbling,\n        null,\n        [boundaryMatch.route.id, result]\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          : result.statusCode != null\n          ? result.statusCode\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    let context = await loadRouteData(\n      loaderRequest,\n      matches,\n      requestContext,\n      unstable_dataStrategy,\n      skipLoaderErrorBubbling,\n      null\n    );\n\n    return {\n      ...context,\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionHeaders: result.headers\n        ? { [actionMatch.route.id]: result.headers }\n        : {},\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    unstable_dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null,\n    pendingActionResult?: PendingActionResult\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 (\n      isRouteRequest &&\n      !routeMatch?.route.loader &&\n      !routeMatch?.route.lazy\n    ) {\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      : pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) => m.route.loader || m.route.lazy\n    );\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:\n          pendingActionResult && isErrorResult(pendingActionResult[1])\n            ? {\n                [pendingActionResult[0]]: pendingActionResult[1].error,\n              }\n            : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let results = await callDataStrategy(\n      \"loader\",\n      request,\n      matchesToLoad,\n      matches,\n      isRouteRequest,\n      requestContext,\n      unstable_dataStrategy\n    );\n\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n\n    // Process and commit output from loaders\n    let activeDeferreds = new Map<string, DeferredData>();\n    let context = processRouteLoaderData(\n      matches,\n      matchesToLoad,\n      results,\n      pendingActionResult,\n      activeDeferreds,\n      skipLoaderErrorBubbling\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\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      activeDeferreds:\n        activeDeferreds.size > 0\n          ? Object.fromEntries(activeDeferreds.entries())\n          : null,\n    };\n  }\n\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    isRouteRequest: boolean,\n    requestContext: unknown,\n    unstable_dataStrategy: DataStrategyFunction | null\n  ): Promise<DataResult[]> {\n    let results = await callDataStrategyImpl(\n      unstable_dataStrategy || defaultDataStrategy,\n      type,\n      request,\n      matchesToLoad,\n      matches,\n      manifest,\n      mapRouteProperties,\n      requestContext\n    );\n\n    return await Promise.all(\n      results.map((result, i) => {\n        if (isRedirectHandlerResult(result)) {\n          let response = result.result as Response;\n          // Throw redirects and let the server handle them with an HTTP redirect\n          throw normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            matchesToLoad[i].route.id,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          );\n        }\n        if (isResponse(result.result) && isRouteRequest) {\n          // For SSR single-route requests, we want to hand Responses back\n          // directly without unwrapping\n          throw result;\n        }\n\n        return convertHandlerResultToDataResult(result);\n      })\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: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n  request: Request,\n  isRouteRequest: boolean,\n  future: StaticHandlerFutureConfig\n) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n  opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n  return (\n    opts != null &&\n    ((\"formData\" in opts && opts.formData != null) ||\n      (\"body\" in opts && opts.body !== undefined))\n  );\n}\n\nfunction normalizeTo(\n  location: Path,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  prependBasename: boolean,\n  to: To | null,\n  v7_relativeSplatPath: boolean,\n  fromRouteId?: string,\n  relative?: RelativeRoutingType\n) {\n  let contextualMatches: AgnosticDataRouteMatch[];\n  let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n  if (fromRouteId) {\n    // Grab matches up to the calling route so our route-relative logic is\n    // relative to the correct source route\n    contextualMatches = [];\n    for (let match of matches) {\n      contextualMatches.push(match);\n      if (match.route.id === fromRouteId) {\n        activeRouteMatch = match;\n        break;\n      }\n    }\n  } else {\n    contextualMatches = matches;\n    activeRouteMatch = matches[matches.length - 1];\n  }\n\n  // Resolve the relative path\n  let path = resolveTo(\n    to ? to : \".\",\n    getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n    stripBasename(location.pathname, basename) || location.pathname,\n    relative === \"path\"\n  );\n\n  // When `to` is not specified we inherit search/hash from the current\n  // location, unlike when to=\".\" and we just inherit the path.\n  // See https://github.com/remix-run/remix/issues/927\n  if (to == null) {\n    path.search = location.search;\n    path.hash = location.hash;\n  }\n\n  // Add an ?index param for matched index routes if we don't already have one\n  if (\n    (to == null || to === \"\" || to === \".\") &&\n    activeRouteMatch &&\n    activeRouteMatch.route.index &&\n    !hasNakedIndexQuery(path.search)\n  ) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname.  If\n  // this is a root navigation, then just use the raw basename which allows\n  // the basename to have full control over the presence of a trailing slash\n  // on root actions\n  if (prependBasename && basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\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  normalizeFormMethod: boolean,\n  isFetcher: boolean,\n  path: string,\n  opts?: BaseNavigateOrFetchOptions\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponseImpl;\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  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, { type: \"invalid-body\" }),\n  });\n\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod\n    ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n    : (rawFormMethod.toLowerCase() as FormMethod);\n  let formAction = stripHashFromPath(path);\n\n  if (opts.body !== undefined) {\n    if (opts.formEncType === \"text/plain\") {\n      // text only support POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      let text =\n        typeof opts.body === \"string\"\n          ? opts.body\n          : opts.body instanceof FormData ||\n            opts.body instanceof URLSearchParams\n          ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n            Array.from(opts.body.entries()).reduce(\n              (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n              \"\"\n            )\n          : String(opts.body);\n\n      return {\n        path,\n        submission: {\n          formMethod,\n          formAction,\n          formEncType: opts.formEncType,\n          formData: undefined,\n          json: undefined,\n          text,\n        },\n      };\n    } else if (opts.formEncType === \"application/json\") {\n      // json only supports POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      try {\n        let json =\n          typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n        return {\n          path,\n          submission: {\n            formMethod,\n            formAction,\n            formEncType: opts.formEncType,\n            formData: undefined,\n            json,\n            text: undefined,\n          },\n        };\n      } catch (e) {\n        return getInvalidBodyError();\n      }\n    }\n  }\n\n  invariant(\n    typeof FormData === \"function\",\n    \"FormData is not available in this environment\"\n  );\n\n  let searchParams: URLSearchParams;\n  let formData: FormData;\n\n  if (opts.formData) {\n    searchParams = convertFormDataToSearchParams(opts.formData);\n    formData = opts.formData;\n  } else if (opts.body instanceof FormData) {\n    searchParams = convertFormDataToSearchParams(opts.body);\n    formData = opts.body;\n  } else if (opts.body instanceof URLSearchParams) {\n    searchParams = opts.body;\n    formData = convertSearchParamsToFormData(searchParams);\n  } else if (opts.body == null) {\n    searchParams = new URLSearchParams();\n    formData = new FormData();\n  } else {\n    try {\n      searchParams = new URLSearchParams(opts.body);\n      formData = convertSearchParamsToFormData(searchParams);\n    } catch (e) {\n      return getInvalidBodyError();\n    }\n  }\n\n  let submission: Submission = {\n    formMethod,\n    formAction,\n    formEncType:\n      (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined,\n  };\n\n  if (isMutationMethod(submission.formMethod)) {\n    return { path, submission };\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  // On GET navigation submissions we can drop the ?index param from the\n  // resulting location since all loaders will run.  But fetcher GET submissions\n  // only run a single loader so we need to preserve any incoming ?index params\n  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n    searchParams.append(\"index\", \"\");\n  }\n  parsedPath.search = `?${searchParams}`;\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  history: History,\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  isInitialLoad: boolean,\n  skipActionErrorRevalidation: boolean,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: Set<string>,\n  deletedFetchers: Set<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryId =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[0]\n      : undefined;\n  let boundaryMatches = boundaryId\n    ? getLoaderMatchesUntilBoundary(matches, boundaryId)\n    : matches;\n\n  // Don't revalidate loaders by default after action 4xx/5xx responses\n  // when the flag is enabled.  They can still opt-into revalidation via\n  // `shouldRevalidate` via `actionResult`\n  let actionStatus = pendingActionResult\n    ? pendingActionResult[1].statusCode\n    : undefined;\n  let shouldSkipRevalidation =\n    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let { route } = match;\n    if (route.lazy) {\n      // We haven't loaded this route yet so we don't know if it's got a loader!\n      return true;\n    }\n\n    if (route.loader == null) {\n      return false;\n    }\n\n    if (isInitialLoad) {\n      if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n        return true;\n      }\n      return (\n        state.loaderData[route.id] === undefined &&\n        // Don't re-run if the loader ran and threw an error\n        (!state.errors || state.errors[route.id] === undefined)\n      );\n    }\n\n    // Always call the loader on new route instances and pending defer cancellations\n    if (\n      isNewLoader(state.loaderData, state.matches[index], match) ||\n      cancelledDeferredRoutes.some((id) => id === match.route.id)\n    ) {\n      return true;\n    }\n\n    // This is the default implementation for 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    let currentRouteMatch = state.matches[index];\n    let nextRouteMatch = match;\n\n    return shouldRevalidateLoader(match, {\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params,\n      ...submission,\n      actionResult,\n      actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation\n        ? false\n        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n          isRevalidationRequired ||\n          currentUrl.pathname + currentUrl.search ===\n            nextUrl.pathname + nextUrl.search ||\n          // Search params affect all loaders\n          currentUrl.search !== nextUrl.search ||\n          isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n    });\n  });\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches.forEach((f, key) => {\n    // Don't revalidate:\n    //  - on initial load (shouldn't be any fetchers then anyway)\n    //  - if fetcher won't be present in the subsequent render\n    //    - no longer matches the URL (v7_fetcherPersist=false)\n    //    - was unmounted but persisted due to v7_fetcherPersist=true\n    if (\n      isInitialLoad ||\n      !matches.some((m) => m.route.id === f.routeId) ||\n      deletedFetchers.has(key)\n    ) {\n      return;\n    }\n\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n    // If the fetcher path no longer matches, push it in with null matches so\n    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is\n    // currently only a use-case for Remix HMR where the route tree can change\n    // at runtime and remove a route previously loaded via a fetcher\n    if (!fetcherMatches) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: null,\n        match: null,\n        controller: null,\n      });\n      return;\n    }\n\n    // Revalidating fetchers are decoupled from the route matches since they\n    // load from a static href.  They revalidate based on explicit revalidation\n    // (submission, useRevalidator, or X-Remix-Revalidate)\n    let fetcher = state.fetchers.get(key);\n    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n    let shouldRevalidate = false;\n    if (fetchRedirectIds.has(key)) {\n      // Never trigger a revalidation of an actively redirecting fetcher\n      shouldRevalidate = false;\n    } else if (cancelledFetcherLoads.has(key)) {\n      // Always mark for revalidation if the fetcher was cancelled\n      cancelledFetcherLoads.delete(key);\n      shouldRevalidate = true;\n    } else if (\n      fetcher &&\n      fetcher.state !== \"idle\" &&\n      fetcher.data === undefined\n    ) {\n      // If the fetcher hasn't ever completed loading yet, then this isn't a\n      // revalidation, it would just be a brand new load if an explicit\n      // revalidation is required\n      shouldRevalidate = isRevalidationRequired;\n    } else {\n      // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n      // to explicit revalidations only\n      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n        currentUrl,\n        currentParams: state.matches[state.matches.length - 1].params,\n        nextUrl,\n        nextParams: matches[matches.length - 1].params,\n        ...submission,\n        actionResult,\n        actionStatus,\n        defaultShouldRevalidate: shouldSkipRevalidation\n          ? false\n          : isRevalidationRequired,\n      });\n    }\n\n    if (shouldRevalidate) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: fetcherMatches,\n        match: fetcherMatch,\n        controller: new AbortController(),\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 != null &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  loaderMatch: AgnosticDataRouteMatch,\n  arg: ShouldRevalidateFunctionArgs\n) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return arg.defaultShouldRevalidate;\n}\n\n/**\n * Idempotent utility to execute patchRoutesOnMiss() to lazily load route\n * definitions and update the routes/routeManifest\n */\nasync function loadLazyRouteChildren(\n  patchRoutesOnMissImpl: AgnosticPatchRoutesOnMissFunction,\n  path: string,\n  matches: AgnosticDataRouteMatch[],\n  routes: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  pendingRouteChildren: Map<string, ReturnType<typeof patchRoutesOnMissImpl>>,\n  signal: AbortSignal\n) {\n  let key = [path, ...matches.map((m) => m.route.id)].join(\"-\");\n  try {\n    let pending = pendingRouteChildren.get(key);\n    if (!pending) {\n      pending = patchRoutesOnMissImpl({\n        path,\n        matches,\n        patch: (routeId, children) => {\n          if (!signal.aborted) {\n            patchRoutesImpl(\n              routeId,\n              children,\n              routes,\n              manifest,\n              mapRouteProperties\n            );\n          }\n        },\n      });\n      pendingRouteChildren.set(key, pending);\n    }\n\n    if (pending && isPromise<AgnosticRouteObject[]>(pending)) {\n      await pending;\n    }\n  } finally {\n    pendingRouteChildren.delete(key);\n  }\n}\n\nfunction patchRoutesImpl(\n  routeId: string | null,\n  children: AgnosticRouteObject[],\n  routesToUse: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction\n) {\n  if (routeId) {\n    let route = manifest[routeId];\n    invariant(\n      route,\n      `No route found to patch children into: routeId = ${routeId}`\n    );\n    let dataChildren = convertRoutesToDataRoutes(\n      children,\n      mapRouteProperties,\n      [routeId, \"patch\", String(route.children?.length || \"0\")],\n      manifest\n    );\n    if (route.children) {\n      route.children.push(...dataChildren);\n    } else {\n      route.children = dataChildren;\n    }\n  } else {\n    let dataChildren = convertRoutesToDataRoutes(\n      children,\n      mapRouteProperties,\n      [\"patch\", String(routesToUse.length || \"0\")],\n      manifest\n    );\n    routesToUse.push(...dataChildren);\n  }\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n  route: AgnosticDataRouteObject,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  manifest: RouteManifest\n) {\n  if (!route.lazy) {\n    return;\n  }\n\n  let lazyRoute = await route.lazy();\n\n  // If the lazy route function was executed and removed by another parallel\n  // call then we can return - first lazy() to finish wins because the return\n  // value of lazy is expected to be static\n  if (!route.lazy) {\n    return;\n  }\n\n  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\n\n  // Update the route in place.  This should be safe because there's no way\n  // we could yet be sitting on this route as we can't get there without\n  // resolving lazy() first.\n  //\n  // This is different than the HMR \"update\" use-case where we may actively be\n  // on the route being updated.  The main concern boils down to \"does this\n  // mutation affect any ongoing navigations or any current state.matches\n  // values?\".  If not, it should be safe to update in place.\n  let routeUpdates: Record<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\n    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n    // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n    // the logic will differ between frameworks.\n    ...mapRouteProperties(routeToUpdate),\n    lazy: undefined,\n  });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nfunction defaultDataStrategy(\n  opts: DataStrategyFunctionArgs\n): ReturnType<DataStrategyFunction> {\n  return Promise.all(opts.matches.map((m) => m.resolve()));\n}\n\nasync function callDataStrategyImpl(\n  dataStrategyImpl: DataStrategyFunction,\n  type: \"loader\" | \"action\",\n  request: Request,\n  matchesToLoad: AgnosticDataRouteMatch[],\n  matches: AgnosticDataRouteMatch[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  requestContext?: unknown\n): Promise<HandlerResult[]> {\n  let routeIdsToLoad = matchesToLoad.reduce(\n    (acc, m) => acc.add(m.route.id),\n    new Set<string>()\n  );\n  let loadedMatches = new Set<string>();\n\n  // Send all matches here to allow for a middleware-type implementation.\n  // handler will be a no-op for unneeded routes and we filter those results\n  // back out below.\n  let results = await dataStrategyImpl({\n    matches: matches.map((match) => {\n      let shouldLoad = routeIdsToLoad.has(match.route.id);\n      // `resolve` encapsulates the route.lazy, executing the\n      // loader/action, and mapping return values/thrown errors to a\n      // HandlerResult.  Users can pass a callback to take fine-grained control\n      // over the execution of the loader/action\n      let resolve: DataStrategyMatch[\"resolve\"] = (handlerOverride) => {\n        loadedMatches.add(match.route.id);\n        return shouldLoad\n          ? callLoaderOrAction(\n              type,\n              request,\n              match,\n              manifest,\n              mapRouteProperties,\n              handlerOverride,\n              requestContext\n            )\n          : Promise.resolve({ type: ResultType.data, result: undefined });\n      };\n\n      return {\n        ...match,\n        shouldLoad,\n        resolve,\n      };\n    }),\n    request,\n    params: matches[0].params,\n    context: requestContext,\n  });\n\n  // Throw if any loadRoute implementations not called since they are what\n  // ensures a route is fully loaded\n  matches.forEach((m) =>\n    invariant(\n      loadedMatches.has(m.route.id),\n      `\\`match.resolve()\\` was not called for route id \"${m.route.id}\". ` +\n        \"You must call `match.resolve()` on every match passed to \" +\n        \"`dataStrategy` to ensure all routes are properly loaded.\"\n    )\n  );\n\n  // Filter out any middleware-only matches for which we didn't need to run handlers\n  return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<HandlerResult> {\n  let result: HandlerResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<HandlerResult> => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () => void;\n    // This will never resolve so safe to type it as Promise<HandlerResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<HandlerResult>((_, r) => (reject = r));\n    onReject = () => reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(\n          new Error(\n            `You cannot call the handler for a route which defines a boolean ` +\n              `\"${type}\" [routeId: ${match.route.id}]`\n          )\n        );\n      }\n      return handler(\n        {\n          request,\n          params: match.params,\n          context: staticContext,\n        },\n        ...(ctx !== undefined ? [ctx] : [])\n      );\n    };\n\n    let handlerPromise: Promise<HandlerResult>;\n    if (handlerOverride) {\n      handlerPromise = handlerOverride((ctx: unknown) => actualHandler(ctx));\n    } else {\n      handlerPromise = (async () => {\n        try {\n          let val = await actualHandler();\n          return { type: \"data\", result: val };\n        } catch (e) {\n          return { type: \"error\", result: e };\n        }\n      })();\n    }\n\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n\n  try {\n    let handler = match.route[type];\n\n    if (match.route.lazy) {\n      if (handler) {\n        // Run statically defined handler in parallel with lazy()\n        let handlerError;\n        let [value] = await Promise.all([\n          // If the handler throws, don't let it immediately bubble out,\n          // since we need to let the lazy() execution finish so we know if this\n          // route has a boundary that can handle the error\n          runHandler(handler).catch((e) => {\n            handlerError = e;\n          }),\n          loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n        ]);\n        if (handlerError !== undefined) {\n          throw handlerError;\n        }\n        result = value!;\n      } else {\n        // Load lazy route module, then run any returned handler\n        await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n        handler = match.route[type];\n        if (handler) {\n          // Handler still runs even if we got interrupted to maintain consistency\n          // with un-abortable behavior of handler execution on non-lazy or\n          // previously-lazy-loaded routes\n          result = await runHandler(handler);\n        } else if (type === \"action\") {\n          let url = new URL(request.url);\n          let pathname = url.pathname + url.search;\n          throw getInternalRouterError(405, {\n            method: request.method,\n            pathname,\n            routeId: match.route.id,\n          });\n        } else {\n          // lazy() route has no loader to run.  Short circuit here so we don't\n          // hit the invariant below that errors on returning undefined.\n          return { type: ResultType.data, result: undefined };\n        }\n      }\n    } else if (!handler) {\n      let url = new URL(request.url);\n      let pathname = url.pathname + url.search;\n      throw getInternalRouterError(404, {\n        pathname,\n      });\n    } else {\n      result = await runHandler(handler);\n    }\n\n    invariant(\n      result.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    // We should already be catching and converting normal handler executions to\n    // HandlerResults and returning them, so anything that throws here is an\n    // unexpected error we still need to wrap\n    return { type: ResultType.error, result: e };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n\n  return result;\n}\n\nasync function convertHandlerResultToDataResult(\n  handlerResult: HandlerResult\n): Promise<DataResult> {\n  let { result, type } = handlerResult;\n\n  if (isResponse(result)) {\n    let data: any;\n\n    try {\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        if (result.body == null) {\n          data = null;\n        } else {\n          data = await result.json();\n        }\n      } else {\n        data = await result.text();\n      }\n    } catch (e) {\n      return { type: ResultType.error, error: e };\n    }\n\n    if (type === ResultType.error) {\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(result.status, result.statusText, data),\n        statusCode: result.status,\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 (type === ResultType.error) {\n    if (isDataWithResponseInit(result)) {\n      if (result.data instanceof Error) {\n        return {\n          type: ResultType.error,\n          error: result.data,\n          statusCode: result.init?.status,\n        };\n      }\n\n      // Convert thrown unstable_data() to ErrorResponse instances\n      result = new ErrorResponseImpl(\n        result.init?.status || 500,\n        undefined,\n        result.data\n      );\n    }\n    return {\n      type: ResultType.error,\n      error: result,\n      statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n    };\n  }\n\n  if (isDeferredData(result)) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: result.init?.status,\n      headers: result.init?.headers && new Headers(result.init.headers),\n    };\n  }\n\n  if (isDataWithResponseInit(result)) {\n    return {\n      type: ResultType.data,\n      data: result.data,\n      statusCode: result.init?.status,\n      headers: result.init?.headers\n        ? new Headers(result.init.headers)\n        : undefined,\n    };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n  response: Response,\n  request: Request,\n  routeId: string,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  v7_relativeSplatPath: boolean\n) {\n  let location = response.headers.get(\"Location\");\n  invariant(\n    location,\n    \"Redirects returned/thrown from loaders/actions must have a Location header\"\n  );\n\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(\n      0,\n      matches.findIndex((m) => m.route.id === routeId) + 1\n    );\n    location = normalizeTo(\n      new URL(request.url),\n      trimmedMatches,\n      basename,\n      true,\n      location,\n      v7_relativeSplatPath\n    );\n    response.headers.set(\"Location\", location);\n  }\n\n  return response;\n}\n\nfunction normalizeRedirectLocation(\n  location: string,\n  currentUrl: URL,\n  basename: string\n): string {\n  if (ABSOLUTE_URL_REGEX.test(location)) {\n    // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n    let normalizedLocation = location;\n    let url = normalizedLocation.startsWith(\"//\")\n      ? new URL(currentUrl.protocol + normalizedLocation)\n      : new URL(normalizedLocation);\n    let isSameBasename = stripBasename(url.pathname, basename) != null;\n    if (url.origin === currentUrl.origin && isSameBasename) {\n      return url.pathname + url.search + url.hash;\n    }\n  }\n  return location;\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  history: History,\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType } = submission;\n    // Didn't think we needed this but it turns out unlike other methods, patch\n    // won't be properly normalized to uppercase and results in a 405 error.\n    // See: https://fetch.spec.whatwg.org/#concept-method\n    init.method = formMethod.toUpperCase();\n\n    if (formEncType === \"application/json\") {\n      init.headers = new Headers({ \"Content-Type\": formEncType });\n      init.body = JSON.stringify(submission.json);\n    } else if (formEncType === \"text/plain\") {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.text;\n    } else if (\n      formEncType === \"application/x-www-form-urlencoded\" &&\n      submission.formData\n    ) {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = convertFormDataToSearchParams(submission.formData);\n    } else {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.formData;\n    }\n  }\n\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    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n    searchParams.append(key, typeof value === \"string\" ? value : value.name);\n  }\n\n  return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n  searchParams: URLSearchParams\n): FormData {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  matchesToLoad: AgnosticDataRouteMatch[],\n  results: DataResult[],\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\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  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\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      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 !== undefined) {\n        error = pendingError;\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      if (skipLoaderErrorBubbling) {\n        errors[id] = error;\n      } else {\n        // Look upwards from the matched route for the closest ancestor error\n        // boundary, defaulting to the root match.  Prefer higher error values\n        // if lower errors bubble to the same boundary\n        let boundaryMatch = findNearestBoundary(matches, id);\n        if (errors[boundaryMatch.route.id] == null) {\n          errors[boundaryMatch.route.id] = error;\n        }\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 {\n      if (isDeferredResult(result)) {\n        activeDeferreds.set(id, result.deferredData);\n        loaderData[id] = result.deferredData.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      } 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 (result.statusCode && result.statusCode !== 200 && !foundError) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\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 !== undefined && pendingActionResult) {\n    errors = { [pendingActionResult[0]]: pendingError };\n    loaderData[pendingActionResult[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  pendingActionResult: PendingActionResult | 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    pendingActionResult,\n    activeDeferreds,\n    false // This method is only called client side so we always want to bubble\n  );\n\n  // Process results from our revalidating fetchers\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let { key, match, controller } = 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 (controller && controller.signal.aborted) {\n      // Nothing to do for aborted fetchers\n      continue;\n    } else 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      invariant(false, \"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      invariant(false, \"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = getDoneFetcher(result.data);\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 && match.route.loader) {\n      // Preserve existing keys not included in newLoaderData and where a loader\n      // wasn't removed by HMR\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\nfunction getActionDataForCommit(\n  pendingActionResult: PendingActionResult | undefined\n) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1])\n    ? {\n        // Clear out prior actionData on errors\n        actionData: {},\n      }\n    : {\n        actionData: {\n          [pendingActionResult[0]]: pendingActionResult[1].data,\n        },\n      };\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 =\n    routes.length === 1\n      ? routes[0]\n      : 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    type,\n    message,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n    type?: \"defer-action\" | \"invalid-body\" | \"route-discovery\";\n    message?: 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 (type === \"route-discovery\") {\n      errorMessage =\n        `Unable to match URL \"${pathname}\" - the \\`unstable_patchRoutesOnMiss()\\` ` +\n        `function threw the following error:\\n${message}`;\n    } else 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 if (type === \"defer-action\") {\n      errorMessage = \"defer() is not supported in actions\";\n    } else if (type === \"invalid-body\") {\n      errorMessage = \"Unable to encode submission body\";\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 ErrorResponseImpl(\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(\n  results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n  for (let i = results.length - 1; i >= 0; i--) {\n    let result = results[i];\n    if (isRedirectResult(result)) {\n      return { result, idx: i };\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  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\n  }\n\n  if (a.hash === \"\") {\n    // /page -> /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -> /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -> /page#other\n    return true;\n  }\n\n  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n  return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isHandlerResult(result: unknown): result is HandlerResult {\n  return (\n    result != null &&\n    typeof result === \"object\" &&\n    \"type\" in result &&\n    \"result\" in result &&\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectHandlerResult(result: HandlerResult) {\n  return (\n    isResponse(result.result) && redirectStatusCodes.has(result.result.status)\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\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    \"type\" in value &&\n    \"data\" in value &&\n    \"init\" in value &&\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred &&\n    typeof deferred === \"object\" &&\n    typeof deferred.data === \"object\" &&\n    typeof deferred.subscribe === \"function\" &&\n    typeof deferred.cancel === \"function\" &&\n    typeof deferred.resolveData === \"function\"\n  );\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 isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n  return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n  method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n  currentMatches: AgnosticDataRouteMatch[],\n  matchesToLoad: (AgnosticDataRouteMatch | null)[],\n  results: DataResult[],\n  signals: (AbortSignal | null)[],\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    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\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      let signal = signals[index];\n      invariant(\n        signal,\n        \"Expected an AbortSignal for revalidating fetcher deferred result\"\n      );\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\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\nfunction getSubmissionFromNavigation(\n  navigation: Navigation\n): Submission | undefined {\n  let { formMethod, formAction, formEncType, text, formData, json } =\n    navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\n  }\n\n  if (text != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json: undefined,\n      text,\n    };\n  } else if (formData != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData,\n      json: undefined,\n      text: undefined,\n    };\n  } else if (json !== undefined) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json,\n      text: undefined,\n    };\n  }\n}\n\nfunction getLoadingNavigation(\n  location: Location,\n  submission?: Submission\n): NavigationStates[\"Loading\"] {\n  if (submission) {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n    };\n    return navigation;\n  } else {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n    };\n    return navigation;\n  }\n}\n\nfunction getSubmittingNavigation(\n  location: Location,\n  submission: Submission\n): NavigationStates[\"Submitting\"] {\n  let navigation: NavigationStates[\"Submitting\"] = {\n    state: \"submitting\",\n    location,\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n  };\n  return navigation;\n}\n\nfunction getLoadingFetcher(\n  submission?: Submission,\n  data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n  if (submission) {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n      data,\n    };\n    return fetcher;\n  } else {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n      data,\n    };\n    return fetcher;\n  }\n}\n\nfunction getSubmittingFetcher(\n  submission: Submission,\n  existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n  let fetcher: FetcherStates[\"Submitting\"] = {\n    state: \"submitting\",\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n    data: existingFetcher ? existingFetcher.data : undefined,\n  };\n  return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n  let fetcher: FetcherStates[\"Idle\"] = {\n    state: \"idle\",\n    formMethod: undefined,\n    formAction: undefined,\n    formEncType: undefined,\n    formData: undefined,\n    json: undefined,\n    text: undefined,\n    data,\n  };\n  return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n//#endregion\n", "import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  unstable_flushSync?: boolean;\n  unstable_viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n", "import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>💿 Hey developer 👋</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnMiss`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n", "import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n", "import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  unstable_DataStrategyFunction,\n  unstable_DataStrategyFunctionArgs,\n  unstable_DataStrategyMatch,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  unstable_HandlerResult,\n  unstable_AgnosticPatchRoutesOnMissFunction,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  unstable_DataStrategyFunction,\n  unstable_DataStrategyFunctionArgs,\n  unstable_DataStrategyMatch,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n  unstable_HandlerResult,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport interface unstable_PatchRoutesOnMissFunction\n  extends unstable_AgnosticPatchRoutesOnMissFunction<RouteMatch> {}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    unstable_dataStrategy?: unstable_DataStrategyFunction;\n    unstable_patchRoutesOnMiss?: unstable_PatchRoutesOnMissFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    unstable_dataStrategy: opts?.unstable_dataStrategy,\n    unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n};\n", "import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  unstable_flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  unstable_viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n", "/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  unstable_PatchRoutesOnMissFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  unstable_DataStrategyFunction,\n  unstable_DataStrategyFunctionArgs,\n  unstable_DataStrategyMatch,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  unstable_DataStrategyFunction,\n  unstable_DataStrategyFunctionArgs,\n  unstable_DataStrategyMatch,\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  unstable_HandlerResult,\n  unstable_PatchRoutesOnMissFunction,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  unstable_dataStrategy?: unstable_DataStrategyFunction;\n  unstable_patchRoutesOnMiss?: unstable_PatchRoutesOnMissFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    unstable_dataStrategy: opts?.unstable_dataStrategy,\n    unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    unstable_dataStrategy: opts?.unstable_dataStrategy,\n    unstable_patchRoutesOnMiss: opts?.unstable_patchRoutesOnMiss,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        unstable_flushSync: flushSync,\n        unstable_viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  unstable_viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      unstable_viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      unstable_viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      unstable_viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      unstable_viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        unstable_viewTransition={unstable_viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  unstable_viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      unstable_viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        unstable_viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    unstable_viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    unstable_viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          unstable_viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      unstable_viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          unstable_flushSync: options.unstable_flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          unstable_flushSync: options.unstable_flushSync,\n          unstable_viewTransition: options.unstable_viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    if (params.has(\"index\") && params.get(\"index\") === \"\") {\n      params.delete(\"index\");\n      path.search = params.toString() ? `?${params.toString()}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { unstable_flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { unstable_flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`unstable_useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" unstable_viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" unstable_viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as unstable_useViewTransitionState };\n\n//#endregion\n"],
-  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOYA;CAAZ,SAAYA,SAAM;AAQhBA,EAAAA,QAAA,KAAA,IAAA;AAOAA,EAAAA,QAAA,MAAA,IAAA;AAMAA,EAAAA,QAAA,SAAA,IAAA;AACF,GAtBYA,WAAAA,SAsBX,CAAA,EAAA;AAqKD,IAAMC,oBAAoB;AAmCV,SAAAC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Q,UAEE,OAAA,iKACqE,IAHvEA,UAAS,KAAA,IAAA;AAMT,MAAI;IAAE/P;EAAQ,IAAK6P,sBACjBJ,gBAAevC,sBAAsB;AAEvC,MAAIxB,OAAOqB,gBAAgB3E,IAAI;IAAEqC,UAAUtJ,KAAKsJ;EAAQ,CAAE;AAC1D,MAAI,CAACrF,UAAU9B,iBAAiB;AAC9B,WAAO;EACR;AAED,MAAIwS,cACFvV,cAAc6E,UAAU6B,gBAAgB0E,UAAU3L,QAAQ,KAC1DoF,UAAU6B,gBAAgB0E;AAC5B,MAAIoK,WACFxV,cAAc6E,UAAU8B,aAAayE,UAAU3L,QAAQ,KACvDoF,UAAU8B,aAAayE;AAezB,SACEqK,UAAUtK,KAAKC,UAAUoK,QAAQ,KAAK,QACtCC,UAAUtK,KAAKC,UAAUmK,WAAW,KAAK;AAE7C;",
-  "names": ["Action", "PopStateEventType", "createMemoryHistory", "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", "createHref", "createPath", "history", "createURL", "URL", "encodeLocation", "path", "parsePath", "search", "hash", "push", "Push", "nextLocation", "splice", "delta", "replace", "Replace", "go", "nextIndex", "listen", "fn", "createBrowserHistory", "createBrowserLocation", "window", "globalHistory", "usr", "createBrowserHref", "getUrlBasedHistory", "createHashHistory", "createHashLocation", "substr", "startsWith", "createHashHref", "base", "document", "querySelector", "href", "getAttribute", "url", "hashIndex", "indexOf", "slice", "validateHashLocation", "invariant", "value", "message", "Error", "cond", "console", "warn", "e", "createKey", "random", "toString", "getHistoryState", "idx", "current", "_extends", "_ref", "parsedPath", "searchIndex", "getLocation", "validateLocation", "defaultView", "getIndex", "replaceState", "handlePop", "historyState", "pushState", "error", "DOMException", "name", "assign", "origin", "addEventListener", "removeEventListener", "ResultType", "immutableRouteKeys", "Set", "isIndexRoute", "route", "convertRoutesToDataRoutes", "routes", "mapRouteProperties", "parentPath", "manifest", "treePath", "String", "id", "join", "children", "indexRoute", "pathOrLayoutRoute", "matchRoutes", "locationArg", "basename", "matchRoutesImpl", "allowPartial", "stripBasename", "branches", "flattenRoutes", "rankRouteBranches", "matches", "i", "decoded", "decodePath", "matchRouteBranch", "convertRouteMatchToUiMatch", "match", "loaderData", "params", "data", "handle", "parentsMeta", "flattenRoute", "relativePath", "meta", "caseSensitive", "childrenIndex", "joinPaths", "routesMeta", "concat", "score", "computeScore", "forEach", "_route$path", "includes", "exploded", "explodeOptionalSegments", "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", "matchPath", "Object", "pathnameBase", "normalizePathname", "generatePath", "originalPath", "prefix", "p", "array", "isLastSegment", "star", "keyMatch", "optional", "param", "pattern", "matcher", "compiledParams", "compilePath", "captureGroups", "memo", "paramName", "splatValue", "regexpSource", "_", "RegExp", "v", "decodeURIComponent", "toLowerCase", "startIndex", "nextChar", "resolvePath", "fromPathname", "toPathname", "resolvePathname", "normalizeSearch", "normalizeHash", "relativeSegments", "pop", "getInvalidPathError", "char", "field", "dest", "getPathContributingMatches", "getResolveToMatches", "v7_relativeSplatPath", "pathMatches", "resolveTo", "toArg", "routePathnames", "locationPathname", "isPathRelative", "isEmptyPath", "from", "routePathnameIndex", "toSegments", "shift", "hasExplicitTrailingSlash", "hasCurrentTrailingSlash", "joinPaths", "paths", "join", "replace", "normalizePathname", "pathname", "normalizeSearch", "search", "startsWith", "normalizeHash", "hash", "json", "data", "init", "responseInit", "status", "headers", "Headers", "has", "set", "Response", "JSON", "stringify", "_extends", "AbortedDeferredError", "Error", "DeferredData", "constructor", "data", "responseInit", "pendingKeysSet", "Set", "subscribers", "deferredKeys", "invariant", "Array", "isArray", "reject", "abortPromise", "Promise", "_", "r", "controller", "AbortController", "onAbort", "unlistenAbortSignal", "signal", "removeEventListener", "addEventListener", "Object", "entries", "reduce", "acc", "_ref2", "key", "value", "assign", "trackPromise", "done", "init", "push", "add", "promise", "race", "then", "onSettle", "undefined", "error", "catch", "defineProperty", "get", "aborted", "delete", "undefinedError", "emit", "settledKey", "forEach", "subscriber", "subscribe", "fn", "cancel", "abort", "v", "k", "resolveData", "resolve", "size", "unwrappedData", "_ref3", "unwrapTrackedPromise", "pendingKeys", "from", "isTrackedPromise", "_tracked", "_error", "_data", "defer", "status", "redirect", "url", "headers", "Headers", "set", "Response", "_extends", "redirectDocument", "response", "replace", "ErrorResponseImpl", "statusText", "internal", "toString", "isRouteErrorResponse", "validMutationMethodsArr", "validMutationMethods", "validRequestMethodsArr", "validRequestMethods", "redirectStatusCodes", "redirectPreserveMethodStatusCodes", "IDLE_NAVIGATION", "state", "location", "formMethod", "formAction", "formEncType", "formData", "json", "text", "IDLE_FETCHER", "IDLE_BLOCKER", "proceed", "reset", "ABSOLUTE_URL_REGEX", "defaultMapRouteProperties", "route", "hasErrorBoundary", "Boolean", "TRANSITIONS_STORAGE_KEY", "createRouter", "routerWindow", "window", "isBrowser", "document", "createElement", "isServer", "routes", "length", "mapRouteProperties", "detectErrorBoundary", "manifest", "dataRoutes", "convertRoutesToDataRoutes", "inFlightDataRoutes", "basename", "dataStrategyImpl", "unstable_dataStrategy", "defaultDataStrategy", "patchRoutesOnMissImpl", "unstable_patchRoutesOnMiss", "future", "v7_fetcherPersist", "v7_normalizeFormMethod", "v7_partialHydration", "v7_prependBasename", "v7_relativeSplatPath", "v7_skipActionErrorRevalidation", "unlistenHistory", "savedScrollPositions", "getScrollRestorationKey", "getScrollPosition", "initialScrollRestored", "hydrationData", "initialMatches", "matchRoutes", "history", "initialErrors", "getInternalRouterError", "pathname", "matches", "getShortCircuitMatches", "id", "fogOfWar", "checkFogOfWar", "active", "initialized", "some", "m", "lazy", "loader", "loaderData", "errors", "isRouteInitialized", "hydrate", "idx", "findIndex", "slice", "every", "router", "historyAction", "action", "navigation", "restoreScrollPosition", "preventScrollReset", "revalidation", "actionData", "fetchers", "Map", "blockers", "pendingAction", "HistoryAction", "Pop", "pendingPreventScrollReset", "pendingNavigationController", "pendingViewTransitionEnabled", "appliedViewTransitions", "removePageHideEventListener", "isUninterruptedRevalidation", "isRevalidationRequired", "cancelledDeferredRoutes", "cancelledFetcherLoads", "fetchControllers", "incrementingLoadId", "pendingNavigationLoadId", "fetchReloadIds", "fetchRedirectIds", "fetchLoadMatches", "activeFetchers", "deletedFetchers", "activeDeferreds", "blockerFunctions", "pendingPatchRoutes", "ignoreNextHistoryUpdate", "initialize", "listen", "_ref", "delta", "warning", "blockerKey", "shouldBlockNavigation", "currentLocation", "nextLocation", "go", "updateBlocker", "updateState", "startNavigation", "restoreAppliedTransitions", "_saveAppliedTransitions", "persistAppliedTransitions", "initialHydration", "dispose", "clear", "deleteFetcher", "deleteBlocker", "newState", "opts", "completedFetchers", "deletedFetchersKeys", "fetcher", "has", "unstable_viewTransitionOpts", "viewTransitionOpts", "unstable_flushSync", "flushSync", "completeNavigation", "_temp", "_location$state", "_location$state2", "isActionReload", "isMutationMethod", "_isRedirect", "keys", "mergeLoaderData", "Push", "Replace", "priorPaths", "toPaths", "getSavedScrollPosition", "navigate", "to", "normalizedPath", "normalizeTo", "fromRouteId", "relative", "path", "submission", "normalizeNavigateOptions", "createLocation", "encodeLocation", "userReplace", "search", "pendingError", "enableViewTransition", "unstable_viewTransition", "revalidate", "interruptActiveLoads", "startUninterruptedRevalidation", "overrideNavigation", "saveScrollPosition", "routesToUse", "loadingNavigation", "notFoundMatches", "handleNavigational404", "isHashChangeOnly", "request", "createClientSideRequest", "pendingActionResult", "findNearestBoundary", "type", "ResultType", "actionResult", "handleAction", "shortCircuited", "routeId", "result", "isErrorResult", "getLoadingNavigation", "updatedMatches", "handleLoaders", "fetcherSubmission", "getActionDataForCommit", "isFogOfWar", "getSubmittingNavigation", "discoverResult", "discoverRoutes", "boundaryId", "handleDiscoverRouteError", "partialMatches", "actionMatch", "getTargetMatch", "method", "results", "callDataStrategy", "isRedirectResult", "normalizeRedirectLocation", "URL", "startRedirectNavigation", "isDeferredResult", "boundaryMatch", "activeSubmission", "getSubmissionFromNavigation", "shouldUpdateNavigationState", "getUpdatedActionData", "matchesToLoad", "revalidatingFetchers", "getMatchesToLoad", "cancelActiveDeferreds", "updatedFetchers", "markFetchRedirectsDone", "updates", "getUpdatedRevalidatingFetchers", "rf", "abortFetcher", "abortPendingFetchRevalidations", "f", "loaderResults", "fetcherResults", "callLoadersAndMaybeResolveData", "findRedirect", "fetcherKey", "processLoaderData", "deferredData", "filter", "didAbortFetchLoads", "abortStaleFetchLoads", "shouldUpdateFetchers", "revalidatingFetcher", "getLoadingFetcher", "fetch", "href", "setFetcherError", "match", "handleFetcherAction", "handleFetcherLoader", "requestMatches", "detectAndHandle405Error", "existingFetcher", "updateFetcherState", "getSubmittingFetcher", "abortController", "fetchRequest", "originatingLoadId", "actionResults", "getDoneFetcher", "revalidationRequest", "loadId", "loadFetcher", "staleKey", "doneFetcher", "resolveDeferredData", "_temp2", "redirectLocation", "isDocumentReload", "test", "createURL", "origin", "stripBasename", "redirectHistoryAction", "callDataStrategyImpl", "all", "map", "i", "isRedirectHandlerResult", "normalizeRelativeRoutingRedirectResponse", "convertHandlerResultToDataResult", "e", "currentMatches", "fetchersToLoad", "fetcherRequest", "resolveDeferredResults", "getFetcher", "deleteFetcherAndUpdateState", "count", "markFetchersDone", "doneKeys", "landedId", "yeetedKeys", "getBlocker", "blocker", "newBlocker", "_ref4", "blockerFunction", "message", "String", "predicate", "cancelledRouteIds", "dfd", "enableScrollRestoration", "positions", "getPosition", "getKey", "y", "getScrollKey", "convertRouteMatchToUiMatch", "fogMatches", "matchRoutesImpl", "leafRoute", "endsWith", "isNonHMR", "loadLazyRouteChildren", "newMatches", "matchedSplat", "index", "newPartialMatches", "join", "_internalSetRoutes", "newRoutes", "patchRoutes", "children", "patchRoutesImpl", "createHref", "_internalFetchControllers", "_internalActiveDeferreds", "UNSAFE_DEFERRED_SYMBOL", "Symbol", "isSubmissionNavigation", "opts", "formData", "body", "undefined", "normalizeTo", "location", "matches", "basename", "prependBasename", "to", "v7_relativeSplatPath", "fromRouteId", "relative", "contextualMatches", "activeRouteMatch", "match", "push", "route", "id", "length", "path", "resolveTo", "getResolveToMatches", "stripBasename", "pathname", "search", "hash", "index", "hasNakedIndexQuery", "replace", "joinPaths", "createPath", "normalizeNavigateOptions", "normalizeFormMethod", "isFetcher", "formMethod", "isValidMethod", "error", "getInternalRouterError", "method", "getInvalidBodyError", "type", "rawFormMethod", "toUpperCase", "toLowerCase", "formAction", "stripHashFromPath", "formEncType", "isMutationMethod", "text", "FormData", "URLSearchParams", "Array", "from", "entries", "reduce", "acc", "_ref5", "name", "value", "String", "submission", "json", "JSON", "parse", "e", "invariant", "searchParams", "convertFormDataToSearchParams", "convertSearchParamsToFormData", "parsedPath", "parsePath", "append", "getLoaderMatchesUntilBoundary", "boundaryId", "boundaryMatches", "findIndex", "m", "slice", "getMatchesToLoad", "history", "state", "isInitialLoad", "skipActionErrorRevalidation", "isRevalidationRequired", "cancelledDeferredRoutes", "cancelledFetcherLoads", "deletedFetchers", "fetchLoadMatches", "fetchRedirectIds", "routesToUse", "pendingActionResult", "actionResult", "isErrorResult", "data", "currentUrl", "createURL", "nextUrl", "actionStatus", "statusCode", "shouldSkipRevalidation", "navigationMatches", "filter", "lazy", "loader", "hydrate", "loaderData", "errors", "isNewLoader", "some", "currentRouteMatch", "nextRouteMatch", "shouldRevalidateLoader", "_extends", "currentParams", "params", "nextParams", "defaultShouldRevalidate", "isNewRouteInstance", "revalidatingFetchers", "forEach", "f", "key", "routeId", "has", "fetcherMatches", "matchRoutes", "controller", "fetcher", "fetchers", "get", "fetcherMatch", "getTargetMatch", "shouldRevalidate", "delete", "AbortController", "currentLoaderData", "currentMatch", "isNew", "isMissingData", "currentPath", "endsWith", "loaderMatch", "arg", "routeChoice", "loadLazyRouteChildren", "patchRoutesOnMissImpl", "routes", "manifest", "mapRouteProperties", "pendingRouteChildren", "signal", "map", "join", "pending", "patch", "children", "aborted", "patchRoutesImpl", "set", "isPromise", "_route$children", "dataChildren", "convertRoutesToDataRoutes", "loadLazyRouteModule", "lazyRoute", "routeToUpdate", "routeUpdates", "lazyRouteProperty", "staticRouteValue", "isPropertyStaticallyDefined", "warning", "immutableRouteKeys", "Object", "assign", "defaultDataStrategy", "Promise", "all", "resolve", "callDataStrategyImpl", "dataStrategyImpl", "request", "matchesToLoad", "requestContext", "routeIdsToLoad", "add", "Set", "loadedMatches", "results", "shouldLoad", "handlerOverride", "callLoaderOrAction", "ResultType", "result", "context", "_", "i", "staticContext", "onReject", "runHandler", "handler", "reject", "abortPromise", "r", "addEventListener", "actualHandler", "ctx", "Error", "handlerPromise", "val", "race", "handlerError", "catch", "url", "URL", "removeEventListener", "convertHandlerResultToDataResult", "handlerResult", "isResponse", "contentType", "headers", "test", "ErrorResponseImpl", "status", "statusText", "isDataWithResponseInit", "_result$init2", "_result$init", "init", "isRouteErrorResponse", "isDeferredData", "_result$init3", "_result$init4", "deferred", "deferredData", "Headers", "_result$init5", "_result$init6", "normalizeRelativeRoutingRedirectResponse", "response", "ABSOLUTE_URL_REGEX", "trimmedMatches", "normalizeRedirectLocation", "normalizedLocation", "startsWith", "protocol", "isSameBasename", "origin", "createClientSideRequest", "toString", "stringify", "Request", "processRouteLoaderData", "activeDeferreds", "skipLoaderErrorBubbling", "foundError", "loaderHeaders", "pendingError", "isRedirectResult", "boundaryMatch", "findNearestBoundary", "isDeferredResult", "processLoaderData", "fetcherResults", "doneFetcher", "getDoneFetcher", "mergeLoaderData", "newLoaderData", "mergedLoaderData", "hasOwnProperty", "getActionDataForCommit", "actionData", "eligibleMatches", "reverse", "find", "hasErrorBoundary", "getShortCircuitMatches", "pathnameBase", "_temp5", "message", "errorMessage", "findRedirect", "idx", "isHashChangeOnly", "a", "b", "isRedirectHandlerResult", "result", "isResponse", "redirectStatusCodes", "has", "status", "isDeferredResult", "type", "ResultType", "deferred", "isErrorResult", "error", "isRedirectResult", "redirect", "isDataWithResponseInit", "value", "isDeferredData", "data", "subscribe", "cancel", "resolveData", "statusText", "headers", "body", "isValidMethod", "method", "validRequestMethods", "has", "toLowerCase", "isMutationMethod", "validMutationMethods", "resolveDeferredResults", "currentMatches", "matchesToLoad", "results", "signals", "isFetcher", "currentLoaderData", "index", "length", "result", "match", "currentMatch", "find", "m", "route", "id", "isRevalidatingLoader", "isNewRouteInstance", "undefined", "isDeferredResult", "signal", "invariant", "resolveDeferredData", "then", "unwrap", "aborted", "deferredData", "resolveData", "type", "ResultType", "data", "unwrappedData", "e", "error", "hasNakedIndexQuery", "search", "URLSearchParams", "getAll", "some", "v", "getTargetMatch", "matches", "location", "parsePath", "pathMatches", "getPathContributingMatches", "getSubmissionFromNavigation", "navigation", "formMethod", "formAction", "formEncType", "text", "formData", "json", "getLoadingNavigation", "submission", "state", "getSubmittingNavigation", "getLoadingFetcher", "fetcher", "getSubmittingFetcher", "existingFetcher", "getDoneFetcher", "restoreAppliedTransitions", "_window", "transitions", "sessionPositions", "sessionStorage", "getItem", "TRANSITIONS_STORAGE_KEY", "JSON", "parse", "k", "Object", "entries", "Array", "isArray", "set", "Set", "persistAppliedTransitions", "size", "setItem", "stringify", "warning", "DataRouterContext", "createContext", "process", "displayName", "DataRouterStateContext", "AwaitContext", "NavigationContext", "LocationContext", "RouteContext", "outlet", "matches", "isDataRoute", "RouteErrorContext", "useHref", "to", "_temp", "relative", "useInRouterContext", "invariant", "basename", "navigator", "useContext", "hash", "pathname", "search", "useResolvedPath", "joinedPathname", "joinPaths", "createHref", "useLocation", "location", "useNavigationType", "navigationType", "useMatch", "pattern", "useMemo", "matchPath", "decodePath", "navigateEffectWarning", "useIsomorphicLayoutEffect", "cb", "isStatic", "static", "React", "useLayoutEffect", "useNavigate", "useNavigateStable", "useNavigateUnstable", "dataRouterContext", "future", "locationPathname", "routePathnamesJson", "JSON", "stringify", "getResolveToMatches", "v7_relativeSplatPath", "activeRef", "useRef", "current", "navigate", "useCallback", "options", "warning", "go", "path", "resolveTo", "parse", "replace", "push", "state", "OutletContext", "useOutletContext", "useOutlet", "context", "createElement", "Provider", "value", "useParams", "routeMatch", "length", "params", "_temp2", "useRoutes", "routes", "locationArg", "useRoutesImpl", "dataRouterState", "parentMatches", "parentParams", "parentPathname", "parentPathnameBase", "pathnameBase", "parentRoute", "route", "parentPath", "warningOnce", "endsWith", "locationFromContext", "_parsedLocationArg$pa", "parsedLocationArg", "parsePath", "startsWith", "remainingPathname", "parentSegments", "split", "segments", "slice", "join", "matchRoutes", "element", "undefined", "Component", "lazy", "renderedMatches", "_renderMatches", "map", "match", "Object", "assign", "encodeLocation", "_extends", "key", "NavigationType", "Pop", "DefaultErrorComponent", "error", "useRouteError", "message", "isRouteErrorResponse", "status", "statusText", "Error", "stack", "lightgrey", "preStyles", "padding", "backgroundColor", "codeStyles", "devInfo", "console", "Fragment", "style", "fontStyle", "defaultErrorElement", "RenderErrorBoundary", "constructor", "props", "revalidation", "getDerivedStateFromError", "getDerivedStateFromProps", "componentDidCatch", "errorInfo", "render", "routeContext", "children", "component", "RenderedRoute", "_ref", "staticContext", "errorElement", "ErrorBoundary", "_deepestRenderedBoundaryId", "id", "_dataRouterState", "_future", "errors", "v7_partialHydration", "initialized", "errorIndex", "findIndex", "m", "keys", "Math", "min", "renderFallback", "fallbackIndex", "i", "HydrateFallback", "hydrateFallbackElement", "loaderData", "needsToRunLoader", "loader", "reduceRight", "index", "shouldRenderHydrateFallback", "concat", "getChildren", "DataRouterHook", "DataRouterStateHook", "getDataRouterConsoleError", "hookName", "useDataRouterContext", "ctx", "useDataRouterState", "useRouteContext", "useCurrentRouteId", "thisRoute", "useRouteId", "UseRouteId", "useNavigation", "UseNavigation", "navigation", "useRevalidator", "UseRevalidator", "revalidate", "router", "useMatches", "UseMatches", "convertRouteMatchToUiMatch", "useLoaderData", "UseLoaderData", "routeId", "useRouteLoaderData", "UseRouteLoaderData", "useActionData", "UseActionData", "actionData", "_state$errors", "UseRouteError", "useAsyncValue", "_data", "useAsyncError", "_error", "blockerId", "useBlocker", "shouldBlock", "UseBlocker", "blockerKey", "setBlockerKey", "useState", "blockerFunction", "arg", "currentLocation", "nextLocation", "historyAction", "stripBasename", "useEffect", "String", "deleteBlocker", "getBlocker", "blockers", "has", "get", "IDLE_BLOCKER", "UseNavigateStable", "fromRouteId", "alreadyWarned", "cond", "START_TRANSITION", "startTransitionImpl", "MemoryRouter", "_ref3", "basename", "children", "initialEntries", "initialIndex", "future", "historyRef", "useRef", "current", "createMemoryHistory", "v5Compat", "history", "state", "setStateImpl", "useState", "action", "location", "v7_startTransition", "setState", "useCallback", "newState", "startTransitionImpl", "React", "useLayoutEffect", "listen", "createElement", "Router", "navigationType", "navigator", "Navigate", "_ref4", "to", "replace", "relative", "useInRouterContext", "process", "invariant", "static", "isStatic", "useContext", "NavigationContext", "warning", "matches", "RouteContext", "pathname", "locationPathname", "useLocation", "navigate", "useNavigate", "path", "resolveTo", "getResolveToMatches", "v7_relativeSplatPath", "jsonPath", "JSON", "stringify", "useEffect", "parse", "Outlet", "props", "useOutlet", "context", "Route", "_props", "_ref5", "basenameProp", "locationProp", "NavigationType", "Pop", "staticProp", "navigationContext", "useMemo", "_extends", "parsePath", "search", "hash", "key", "locationContext", "trailingPathname", "stripBasename", "Provider", "value", "LocationContext", "Routes", "_ref6", "useRoutes", "createRoutesFromChildren", "Await", "_ref7", "errorElement", "resolve", "AwaitErrorBoundary", "ResolveAwait", "AwaitRenderStatus", "neverSettledPromise", "Promise", "Component", "constructor", "error", "getDerivedStateFromError", "componentDidCatch", "errorInfo", "console", "render", "promise", "status", "pending", "success", "Object", "defineProperty", "get", "renderError", "reject", "catch", "_tracked", "then", "data", "_error", "AbortedDeferredError", "AwaitContext", "_ref8", "useAsyncValue", "toRender", "Fragment", "parentPath", "routes", "Children", "forEach", "element", "index", "isValidElement", "treePath", "type", "push", "apply", "name", "route", "id", "join", "caseSensitive", "loader", "ErrorBoundary", "hasErrorBoundary", "shouldRevalidate", "handle", "lazy", "renderMatches", "_renderMatches", "mapRouteProperties", "updates", "assign", "undefined", "HydrateFallback", "hydrateFallbackElement", "createMemoryRouter", "opts", "createRouter", "v7_prependBasename", "hydrationData", "unstable_dataStrategy", "unstable_patchRoutesOnMiss", "initialize", "defaultMethod", "defaultEncType", "isHtmlElement", "object", "tagName", "isButtonElement", "toLowerCase", "isFormElement", "isInputElement", "isModifiedEvent", "event", "metaKey", "altKey", "ctrlKey", "shiftKey", "shouldProcessLinkClick", "target", "button", "createSearchParams", "init", "URLSearchParams", "Array", "isArray", "Object", "keys", "reduce", "memo", "key", "value", "concat", "map", "v", "getSearchParamsForLocation", "locationSearch", "defaultSearchParams", "searchParams", "forEach", "_", "has", "getAll", "append", "_formDataSupportsSubmitter", "isFormDataSubmitterSupported", "FormData", "document", "createElement", "e", "supportedFormEncTypes", "Set", "getFormEncType", "encType", "process", "warning", "getFormSubmissionInfo", "basename", "method", "action", "formData", "body", "attr", "getAttribute", "stripBasename", "type", "form", "Error", "name", "prefix", "undefined", "REACT_ROUTER_VERSION", "window", "__reactRouterVersion", "createBrowserRouter", "routes", "opts", "createRouter", "future", "_extends", "v7_prependBasename", "history", "createBrowserHistory", "hydrationData", "parseHydrationData", "unstable_dataStrategy", "unstable_patchRoutesOnMiss", "initialize", "createHashRouter", "createHashHistory", "_window", "state", "__staticRouterHydrationData", "errors", "deserializeErrors", "entries", "serialized", "val", "__type", "ErrorResponseImpl", "status", "statusText", "data", "internal", "__subType", "ErrorConstructor", "error", "message", "stack", "ViewTransitionContext", "createContext", "isTransitioning", "displayName", "FetchersContext", "Map", "START_TRANSITION", "startTransitionImpl", "React", "FLUSH_SYNC", "flushSyncImpl", "ReactDOM", "USE_ID", "useIdImpl", "startTransitionSafe", "cb", "flushSyncSafe", "Deferred", "constructor", "promise", "Promise", "resolve", "reject", "reason", "RouterProvider", "_ref", "fallbackElement", "router", "setStateImpl", "useState", "pendingState", "setPendingState", "vtContext", "setVtContext", "renderDfd", "setRenderDfd", "transition", "setTransition", "interruption", "setInterruption", "fetcherData", "useRef", "v7_startTransition", "optInStartTransition", "useCallback", "setState", "newState", "_ref2", "deletedFetchers", "unstable_flushSync", "flushSync", "unstable_viewTransitionOpts", "viewTransitionOpts", "current", "delete", "fetchers", "fetcher", "set", "isViewTransitionUnavailable", "startViewTransition", "skipTransition", "currentLocation", "nextLocation", "t", "finished", "finally", "useLayoutEffect", "subscribe", "useEffect", "renderPromise", "location", "v7_partialHydration", "navigator", "useMemo", "createHref", "encodeLocation", "go", "n", "navigate", "push", "to", "preventScrollReset", "replace", "dataRouterContext", "static", "routerFuture", "v7_relativeSplatPath", "Fragment", "DataRouterContext", "Provider", "DataRouterStateContext", "Router", "navigationType", "historyAction", "initialized", "MemoizedDataRoutes", "DataRoutes", "_ref3", "useRoutesImpl", "BrowserRouter", "_ref4", "children", "historyRef", "v5Compat", "listen", "HashRouter", "_ref5", "HistoryRouter", "_ref6", "isBrowser", "ABSOLUTE_URL_REGEX", "Link", "forwardRef", "LinkWithRef", "_ref7", "ref", "onClick", "relative", "reloadDocument", "unstable_viewTransition", "rest", "_objectWithoutPropertiesLoose", "_excluded", "useContext", "NavigationContext", "absoluteHref", "isExternal", "test", "currentUrl", "URL", "href", "targetUrl", "startsWith", "protocol", "path", "pathname", "origin", "search", "hash", "useHref", "internalOnClick", "useLinkClickHandler", "handleClick", "defaultPrevented", "NavLink", "NavLinkWithRef", "_ref8", "ariaCurrentProp", "caseSensitive", "className", "classNameProp", "end", "style", "styleProp", "_excluded2", "useResolvedPath", "useLocation", "routerState", "useViewTransitionState", "toPathname", "locationPathname", "nextLocationPathname", "navigation", "endSlashPosition", "endsWith", "length", "isActive", "charAt", "isPending", "renderProps", "ariaCurrent", "filter", "Boolean", "join", "Form", "_ref9", "forwardedRef", "fetcherKey", "onSubmit", "props", "_excluded3", "submit", "useSubmit", "formAction", "useFormAction", "formMethod", "submitHandler", "preventDefault", "submitter", "nativeEvent", "submitMethod", "currentTarget", "ScrollRestoration", "_ref10", "getKey", "storageKey", "useScrollRestoration", "DataRouterHook", "DataRouterStateHook", "getDataRouterConsoleError", "hookName", "useDataRouterContext", "ctx", "invariant", "useDataRouterState", "_temp", "replaceProp", "useNavigate", "createPath", "useSearchParams", "defaultInit", "defaultSearchParamsRef", "hasSetSearchParamsRef", "setSearchParams", "nextInit", "navigateOptions", "newSearchParams", "validateClientSideSubmission", "fetcherId", "getUniqueFetcherId", "String", "UseSubmit", "currentRouteId", "useRouteId", "options", "fetch", "formEncType", "fromRouteId", "_temp2", "routeContext", "RouteContext", "match", "matches", "slice", "params", "get", "toString", "route", "index", "joinPaths", "useFetcher", "_temp3", "_route$matches", "UseFetcher", "routeId", "id", "defaultKey", "setFetcherKey", "getFetcher", "deleteFetcher", "load", "submitImpl", "FetcherForm", "IDLE_FETCHER", "fetcherWithComponents", "useFetchers", "UseFetchers", "from", "_ref11", "SCROLL_RESTORATION_STORAGE_KEY", "savedScrollPositions", "_temp4", "UseScrollRestoration", "restoreScrollPosition", "useMatches", "useNavigation", "scrollRestoration", "usePageHide", "scrollY", "sessionStorage", "setItem", "JSON", "stringify", "sessionPositions", "getItem", "parse", "getKeyWithoutBasename", "disableScrollRestoration", "enableScrollRestoration", "scrollTo", "el", "getElementById", "decodeURIComponent", "scrollIntoView", "useBeforeUnload", "callback", "capture", "addEventListener", "removeEventListener", "usePrompt", "_ref12", "when", "blocker", "useBlocker", "proceed", "confirm", "setTimeout", "reset", "currentPath", "nextPath", "matchPath"]
+  "sources": ["../../@remix-run/router/history.ts", "../../@remix-run/router/utils.ts", "../../@remix-run/router/router.ts", "../../react-router/lib/context.ts", "../../react-router/lib/hooks.tsx", "../../react-router/lib/deprecations.ts", "../../react-router/lib/components.tsx", "../../react-router/index.ts", "../../react-router-dom/dom.ts", "../../react-router-dom/index.tsx"],
+  "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// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\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<State = any> extends Path {\n  /**\n   * A value of arbitrary data associated with this location.\n   */\n  state: State;\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   * The delta between this location and the former location in the history stack\n   */\n  delta: number | null;\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`. This may be either a URL or the pieces\n * of a 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   * Returns a URL for the given `to` value\n   *\n   * @param to - The destination URL\n   */\n  createURL(to: To): URL;\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  idx: number;\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  function createHref(to: To) {\n    return typeof to === \"string\" ? to : createPath(to);\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,\n    createURL(to) {\n      return new URL(createHref(to), \"http://localhost\");\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, delta: 1 });\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, delta: 0 });\n      }\n    },\n    go(delta) {\n      action = Action.Pop;\n      let nextIndex = clampIndex(index + delta);\n      let nextLocation = entries[nextIndex];\n      index = nextIndex;\n      if (listener) {\n        listener({ action, location: nextLocation, delta });\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\n    // Hash URL should always have a leading / just like window.location.pathname\n    // does, so if an app ends up at a route like /#something then we add a\n    // leading slash so all of our path-matching behaves the same as if it would\n    // in a browser router.  This is particularly important when there exists a\n    // root splat route (<Route path=\"*\">) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n      pathname = \"/\" + pathname;\n    }\n\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\nexport function 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, index: number): HistoryState {\n  return {\n    usr: location.state,\n    key: location.key,\n    idx: index,\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 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  let index = getIndex()!;\n  // Index should only be null when we initialize. If not, it's because the\n  // user called history.pushState or history.replaceState directly, in which\n  // case we should log a warning as it will result in bugs.\n  if (index == null) {\n    index = 0;\n    globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n  }\n\n  function getIndex(): number {\n    let state = globalHistory.state || { idx: null };\n    return state.idx;\n  }\n\n  function handlePop() {\n    action = Action.Pop;\n    let nextIndex = getIndex();\n    let delta = nextIndex == null ? null : nextIndex - index;\n    index = nextIndex;\n    if (listener) {\n      listener({ action, location: history.location, delta });\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    index = getIndex() + 1;\n    let historyState = getHistoryState(location, index);\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      // If the exception is because `state` can't be serialized, let that throw\n      // outwards just like a replace call would so the dev knows the cause\n      // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n      // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n      if (error instanceof DOMException && error.name === \"DataCloneError\") {\n        throw error;\n      }\n      // They are going to lose state here, but there is no real\n      // way to warn them about it since the page will refresh...\n      window.location.assign(url);\n    }\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 1 });\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    index = getIndex();\n    let historyState = getHistoryState(location, index);\n    let url = history.createHref(location);\n    globalHistory.replaceState(historyState, \"\", url);\n\n    if (v5Compat && listener) {\n      listener({ action, location: history.location, delta: 0 });\n    }\n  }\n\n  function createURL(to: To): 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      window.location.origin !== \"null\"\n        ? window.location.origin\n        : window.location.href;\n\n    let href = typeof to === \"string\" ? to : createPath(to);\n    // Treating this as a full URL will strip any trailing spaces so we need to\n    // pre-encode them since they might be part of a matching splat param from\n    // an ancestor route\n    href = href.replace(/ $/, \"%20\");\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\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    createURL,\n    encodeLocation(to) {\n      // Encode a Location the same way window.location would\n      let url = createURL(to);\n      return {\n        pathname: url.pathname,\n        search: url.search,\n        hash: url.hash,\n      };\n    },\n    push,\n    replace,\n    go(n) {\n      return globalHistory.go(n);\n    },\n  };\n\n  return history;\n}\n\n//#endregion\n", "import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } 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: unknown;\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  statusCode?: number;\n  headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n  type: ResultType.redirect;\n  // We keep the raw Response for redirects so we can return it verbatim\n  response: Response;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n  type: ResultType.error;\n  error: unknown;\n  statusCode?: number;\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\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `<Form>`,\n * useSubmit(), `<fetcher.Form>`, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude<FormMethod, \"get\">;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState.  This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude<V7_FormMethod, \"GET\">;\n\nexport type FormEncType =\n  | \"application/x-www-form-urlencoded\"\n  | \"multipart/form-data\"\n  | \"application/json\"\n  | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: FormData;\n      json: undefined;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: JsonValue;\n      text: undefined;\n    }\n  | {\n      formMethod: FormMethod | V7_FormMethod;\n      formAction: string;\n      formEncType: FormEncType;\n      formData: undefined;\n      json: undefined;\n      text: string;\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<Context> {\n  request: Request;\n  params: Params;\n  context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n//   ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n//   Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return).  Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable<unknown> | null;\n\ntype DataFunctionReturnValue = Promise<DataFunctionValue> | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction<Context = any> = {\n  (\n    args: LoaderFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction<Context = any> {\n  (\n    args: ActionFunctionArgs<Context>,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\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  text?: Submission[\"text\"];\n  formData?: Submission[\"formData\"];\n  json?: Submission[\"json\"];\n  actionStatus?: number;\n  actionResult?: any;\n  defaultShouldRevalidate: boolean;\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: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n  (route: AgnosticRouteObject): boolean;\n}\n\nexport interface DataStrategyMatch\n  extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) => DataFunctionReturnValue\n    ) => DataFunctionReturnValue\n  ) => Promise<DataStrategyResult>;\n}\n\nexport interface DataStrategyFunctionArgs<Context = any>\n  extends DataFunctionArgs<Context> {\n  matches: DataStrategyMatch[];\n  fetcherKey: string | null;\n}\n\n/**\n * Result from a loader or action called via dataStrategy\n */\nexport interface DataStrategyResult {\n  type: \"data\" | \"error\";\n  result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit\n}\n\nexport interface DataStrategyFunction {\n  (args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = {\n  path: string;\n  matches: M[];\n  patch: (routeId: string | null, children: O[]) => void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction<\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n> = (\n  opts: AgnosticPatchRoutesOnNavigationFunctionArgs<O, M>\n) => void | Promise<void>;\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n  (route: AgnosticRouteObject): {\n    hasErrorBoundary: boolean;\n  } & Record<string, any>;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n  | \"lazy\"\n  | \"caseSensitive\"\n  | \"path\"\n  | \"id\"\n  | \"index\"\n  | \"children\";\n\nexport const immutableRouteKeys = new Set<ImmutableRouteKey>([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne<T, Key = keyof T> = Exclude<\n  {\n    [K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;\n  }[keyof T],\n  undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction<R extends AgnosticRouteObject> {\n  (): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;\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 | boolean;\n  action?: ActionFunction | boolean;\n  hasErrorBoundary?: boolean;\n  shouldRevalidate?: ShouldRevalidateFunction;\n  handle?: any;\n  lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;\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\nexport type RouteManifest = Record<string, AgnosticDataRouteObject | undefined>;\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 extends `${infer Optional}?`\n      ? Optional\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 */\nexport type 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 you 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  mapRouteProperties: MapRoutePropertiesFunction,\n  parentPath: string[] = [],\n  manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n  return routes.map((route, index) => {\n    let treePath = [...parentPath, String(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      !manifest[id],\n      `Found a route id collision on id \"${id}\".  Route ` +\n        \"id's must be globally unique within Data Router usages\"\n    );\n\n    if (isIndexRoute(route)) {\n      let indexRoute: AgnosticDataIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n      };\n      manifest[id] = indexRoute;\n      return indexRoute;\n    } else {\n      let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n        ...route,\n        ...mapRouteProperties(route),\n        id,\n        children: undefined,\n      };\n      manifest[id] = pathOrLayoutRoute;\n\n      if (route.children) {\n        pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n          route.children,\n          mapRouteProperties,\n          treePath,\n          manifest\n        );\n      }\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/v6/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  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl<\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n  routes: RouteObjectType[],\n  locationArg: Partial<Location> | string,\n  basename: string,\n  allowPartial: boolean\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    // 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    let decoded = decodePath(pathname);\n    matches = matchRouteBranch<string, RouteObjectType>(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch<Data = unknown, Handle = unknown> {\n  id: string;\n  pathname: string;\n  params: AgnosticRouteMatch[\"params\"];\n  data: Data;\n  handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n  match: AgnosticDataRouteMatch,\n  loaderData: RouteData\n): UIMatch {\n  let { route, pathname, params } = match;\n  return {\n    id: route.id,\n    pathname,\n    params,\n    data: loaderData[route.id],\n    handle: route.handle,\n  };\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      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 explode _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  allowPartial = false\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    let route = meta.route;\n\n    if (\n      !match &&\n      end &&\n      allowPartial &&\n      !routesMeta[routesMeta.length - 1].route.index\n    ) {\n      match = matchPath(\n        {\n          path: meta.relativePath,\n          caseSensitive: meta.caseSensitive,\n          end: false,\n        },\n        remainingPathname\n      );\n    }\n\n    if (!match) {\n      return null;\n    }\n\n    Object.assign(matchedParams, match.params);\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/v6/utils/generate-path\n */\nexport function generatePath<Path extends string>(\n  originalPath: Path,\n  params: {\n    [key in PathParam<Path>]: string | null;\n  } = {} as any\n): string {\n  let path: string = 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  // ensure `/` is added at the beginning if the path is absolute\n  const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n  const stringify = (p: any) =>\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) => {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment && segment === \"*\") {\n        const star = \"*\" as PathParam<Path>;\n        // Apply the splat\n        return stringify(params[star]);\n      }\n\n      const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n      if (keyMatch) {\n        const [, key, optional] = keyMatch;\n        let param = params[key as PathParam<Path>];\n        invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n        return stringify(param);\n      }\n\n      // Remove any optional markers from optional static segments\n      return segment.replace(/\\?$/g, \"\");\n    })\n    // Remove empty segments\n    .filter((segment) => !!segment);\n\n  return prefix + segments.join(\"/\");\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/v6/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, compiledParams] = 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 = compiledParams.reduce<Mutable<Params>>(\n    (memo, { paramName, isOptional }, 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      const value = captureGroups[index];\n      if (isOptional && !value) {\n        memo[paramName] = undefined;\n      } else {\n        memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n      }\n      return memo;\n    },\n    {}\n  );\n\n  return {\n    params,\n    pathname: matchedPathname,\n    pathnameBase,\n    pattern,\n  };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n  path: string,\n  caseSensitive = false,\n  end = true\n): [RegExp, CompiledPathParam[]] {\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 params: CompiledPathParam[] = [];\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(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) => {\n          params.push({ paramName, isOptional: isOptional != null });\n          return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n        }\n      );\n\n  if (path.endsWith(\"*\")) {\n    params.push({ paramName: \"*\" });\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, params];\n}\n\nexport function decodePath(value: string) {\n  try {\n    return value\n      .split(\"/\")\n      .map((v) => decodeURIComponent(v).replace(/\\//g, \"%2F\"))\n      .join(\"/\");\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\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 * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/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// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n  let pathMatches = getPathContributingMatches(matches);\n\n  // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n  // match so we include splat values for \".\" links.  See:\n  // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n  if (v7_relativeSplatPath) {\n    return pathMatches.map((match, idx) =>\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) => match.pathnameBase);\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 (toPathname == null) {\n    from = locationPathname;\n  } else {\n    let routePathnameIndex = routePathnames.length - 1;\n\n    // With relative=\"route\" (the default), each leading .. segment means\n    // \"go up one route\" instead of \"go up one URL segment\".  This is a key\n    // difference from how <a href> works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative && toPathname.startsWith(\"..\")) {\n      let toSegments = toPathname.split(\"/\");\n\n      while (toSegments[0] === \"..\") {\n        toSegments.shift();\n        routePathnameIndex -= 1;\n      }\n\n      to.pathname = toSegments.join(\"/\");\n    }\n\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 *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\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 class DataWithResponseInit<D> {\n  type: string = \"DataWithResponseInit\";\n  data: D;\n  init: ResponseInit | null;\n\n  constructor(data: D, init?: ResponseInit) {\n    this.data = data;\n    this.init = init || null;\n  }\n}\n\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nexport function data<D>(data: D, init?: number | ResponseInit) {\n  return new DataWithResponseInit(\n    data,\n    typeof init === \"number\" ? { status: init } : init\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 pendingKeysSet: Set<string> = new Set<string>();\n  private controller: AbortController;\n  private abortPromise: Promise<void>;\n  private unlistenAbortSignal: () => void;\n  private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n    new Set();\n  data: Record<string, unknown>;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record<string, unknown>, responseInit?: ResponseInit) {\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    if (this.done) {\n      // All incoming values were resolved\n      this.unlistenAbortSignal();\n    }\n\n    this.init = responseInit;\n  }\n\n  private trackPromise(\n    key: string,\n    value: Promise<unknown> | unknown\n  ): TrackedPromise | unknown {\n    if (!(value instanceof Promise)) {\n      return value;\n    }\n\n    this.deferredKeys.push(key);\n    this.pendingKeysSet.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, undefined, 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,\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.pendingKeysSet.delete(key);\n\n    if (this.done) {\n      // Nothing left to abort!\n      this.unlistenAbortSignal();\n    }\n\n    // If the promise was resolved/rejected with undefined, we'll throw an error as you\n    // should always resolve with a value or null\n    if (error === undefined && data === undefined) {\n      let undefinedError = new Error(\n        `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n          `you must resolve/reject with a value or \\`null\\`.`\n      );\n      Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () => error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () => data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n    this.subscribers.add(fn);\n    return () => this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n    this.emit(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.pendingKeysSet.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  get pendingKeys() {\n    return Array.from(this.pendingKeysSet);\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 type DeferFunction = (\n  data: Record<string, unknown>,\n  init?: number | ResponseInit\n) => DeferredData;\n\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nexport const defer: DeferFunction = (data, init = {}) => {\n  let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n  return new DeferredData(data, responseInit);\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 * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n  return response;\n};\n\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const replace: RedirectFunction = (url, init) => {\n  let response = redirect(url, init);\n  response.headers.set(\"X-Remix-Replace\", \"true\");\n  return response;\n};\n\nexport type ErrorResponse = {\n  status: number;\n  statusText: string;\n  data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n  status: number;\n  statusText: string;\n  data: any;\n  private error?: Error;\n  private 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 thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n  return (\n    error != null &&\n    typeof error.status === \"number\" &&\n    typeof error.statusText === \"string\" &&\n    typeof error.internal === \"boolean\" &&\n    \"data\" in error\n  );\n}\n", "import type { History, Location, Path, To } from \"./history\";\nimport {\n  Action as HistoryAction,\n  createLocation,\n  createPath,\n  invariant,\n  parsePath,\n  warning,\n} from \"./history\";\nimport type {\n  AgnosticDataRouteMatch,\n  AgnosticDataRouteObject,\n  DataStrategyMatch,\n  AgnosticRouteObject,\n  DataResult,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DeferredData,\n  DeferredResult,\n  DetectErrorBoundaryFunction,\n  ErrorResult,\n  FormEncType,\n  FormMethod,\n  HTMLFormMethod,\n  DataStrategyResult,\n  ImmutableRouteKey,\n  MapRoutePropertiesFunction,\n  MutationFormMethod,\n  RedirectResult,\n  RouteData,\n  RouteManifest,\n  ShouldRevalidateFunctionArgs,\n  Submission,\n  SuccessResult,\n  UIMatch,\n  V7_FormMethod,\n  V7_MutationFormMethod,\n  AgnosticPatchRoutesOnNavigationFunction,\n  DataWithResponseInit,\n} from \"./utils\";\nimport {\n  ErrorResponseImpl,\n  ResultType,\n  convertRouteMatchToUiMatch,\n  convertRoutesToDataRoutes,\n  getPathContributingMatches,\n  getResolveToMatches,\n  immutableRouteKeys,\n  isRouteErrorResponse,\n  joinPaths,\n  matchRoutes,\n  matchRoutesImpl,\n  resolveTo,\n  stripBasename,\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 future config for the router\n   */\n  get future(): FutureConfig;\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   * Return the window associated with the router\n   */\n  get window(): RouterInit[\"window\"];\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): Promise<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 | null, opts?: RouterNavigateOptions): Promise<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 | null,\n    opts?: RouterFetchOptions\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   * Get a navigation blocker\n   * @param key The identifier for the blocker\n   * @param fn The blocker function implementation\n   */\n  getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Delete a navigation blocker\n   * @param key The identifier for the blocker\n   */\n  deleteBlocker(key: string): void;\n\n  /**\n   * @internal\n   * PRIVATE DO NOT USE\n   *\n   * Patch additional children routes into an existing parent route\n   * @param routeId The parent route id or a callback function accepting `patch`\n   *                to perform batch patching\n   * @param children The additional children routes\n   */\n  patchRoutes(routeId: string | null, children: AgnosticRouteObject[]): void;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * HMR needs to pass in-flight route updates to React Router\n   * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n   */\n  _internalSetRoutes(routes: AgnosticRouteObject[]): 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   * Map of current blockers\n   */\n  blockers: Map<string, Blocker>;\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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n  v7_fetcherPersist: boolean;\n  v7_normalizeFormMethod: boolean;\n  v7_partialHydration: boolean;\n  v7_prependBasename: boolean;\n  v7_relativeSplatPath: boolean;\n  v7_skipActionErrorRevalidation: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n  routes: AgnosticRouteObject[];\n  history: History;\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<FutureConfig>;\n  hydrationData?: HydrationState;\n  window?: Window;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;\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  activeDeferreds: Record<string, DeferredData> | null;\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?: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<StaticHandlerContext | Response>;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise<any>;\n}\n\ntype ViewTransitionOpts = {\n  currentLocation: Location;\n  nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n  (\n    state: RouterState,\n    opts: {\n      deletedFetchers: string[];\n      viewTransitionOpts?: ViewTransitionOpts;\n      flushSync: boolean;\n    }\n  ): void;\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: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n  (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n  replace?: boolean;\n  state?: any;\n  fromRouteId?: string;\n  viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n  formMethod?: HTMLFormMethod;\n  formEncType?: FormEncType;\n} & (\n  | { formData: FormData; body?: undefined }\n  | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n  | LinkNavigateOptions\n  | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\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    json: undefined;\n    text: undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    location: Location;\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    text: Submission[\"text\"];\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    text: undefined;\n    formData: undefined;\n    json: undefined;\n    data: TData | undefined;\n  };\n  Loading: {\n    state: \"loading\";\n    formMethod: Submission[\"formMethod\"] | undefined;\n    formAction: Submission[\"formAction\"] | undefined;\n    formEncType: Submission[\"formEncType\"] | undefined;\n    text: Submission[\"text\"] | undefined;\n    formData: Submission[\"formData\"] | undefined;\n    json: Submission[\"json\"] | undefined;\n    data: TData | undefined;\n  };\n  Submitting: {\n    state: \"submitting\";\n    formMethod: Submission[\"formMethod\"];\n    formAction: Submission[\"formAction\"];\n    formEncType: Submission[\"formEncType\"];\n    text: Submission[\"text\"];\n    formData: Submission[\"formData\"];\n    json: Submission[\"json\"];\n    data: TData | undefined;\n  };\n};\n\nexport type Fetcher<TData = any> =\n  FetcherStates<TData>[keyof FetcherStates<TData>];\n\ninterface BlockerBlocked {\n  state: \"blocked\";\n  reset(): void;\n  proceed(): void;\n  location: Location;\n}\n\ninterface BlockerUnblocked {\n  state: \"unblocked\";\n  reset: undefined;\n  proceed: undefined;\n  location: undefined;\n}\n\ninterface BlockerProceeding {\n  state: \"proceeding\";\n  reset: undefined;\n  proceed: undefined;\n  location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n  currentLocation: Location;\n  nextLocation: Location;\n  historyAction: HistoryAction;\n}) => boolean;\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\ntype PendingActionResult = [string, SuccessResult | ErrorResult];\n\ninterface HandleActionResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\n  /**\n   * Tuple for the returned or thrown value from the current action.  The routeId\n   * is the action route for success and the bubbled boundary route for errors.\n   */\n  pendingActionResult?: PendingActionResult;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n  /**\n   * Route matches which may have been updated from fog of war discovery\n   */\n  matches?: RouterState[\"matches\"];\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n  routeId: string;\n  path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n  key: string;\n  match: AgnosticDataRouteMatch | null;\n  matches: AgnosticDataRouteMatch[] | null;\n  controller: AbortController | null;\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  json: undefined,\n  text: 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  json: undefined,\n  text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n  state: \"unblocked\",\n  proceed: undefined,\n  reset: undefined,\n  location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n  hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\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  const routerWindow = init.window\n    ? init.window\n    : typeof window !== \"undefined\"\n    ? window\n    : undefined;\n  const isBrowser =\n    typeof routerWindow !== \"undefined\" &&\n    typeof routerWindow.document !== \"undefined\" &&\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length > 0,\n    \"You must provide a non-empty routes array to createRouter\"\n  );\n\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (init.mapRouteProperties) {\n    mapRouteProperties = init.mapRouteProperties;\n  } else if (init.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = init.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n\n  // Routes keyed by ID\n  let manifest: RouteManifest = {};\n  // Routes in tree format for matching\n  let dataRoutes = convertRoutesToDataRoutes(\n    init.routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\n  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n  let basename = init.basename || \"/\";\n  let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n  let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n\n  // Config driven behavior flags\n  let future: FutureConfig = {\n    v7_fetcherPersist: false,\n    v7_normalizeFormMethod: false,\n    v7_partialHydration: false,\n    v7_prependBasename: false,\n    v7_relativeSplatPath: false,\n    v7_skipActionErrorRevalidation: false,\n    ...init.future,\n  };\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(dataRoutes, init.history.location, basename);\n  let initialErrors: RouteData | null = null;\n\n  if (initialMatches == null && !patchRoutesOnNavigationImpl) {\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  // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n  // our initial match is a splat route, clear them out so we run through lazy\n  // discovery on hydration in case there's a more accurate lazy route match.\n  // In SSR apps (with `hydrationData`), we expect that the server will send\n  // up the proper matched routes so we don't want to run lazy discovery on\n  // initial hydration and want to hydrate into the splat route.\n  if (initialMatches && !init.hydrationData) {\n    let fogOfWar = checkFogOfWar(\n      initialMatches,\n      dataRoutes,\n      init.history.location.pathname\n    );\n    if (fogOfWar.active) {\n      initialMatches = null;\n    }\n  }\n\n  let initialized: boolean;\n  if (!initialMatches) {\n    initialized = false;\n    initialMatches = [];\n\n    // If partial hydration and fog of war is enabled, we will be running\n    // `patchRoutesOnNavigation` during hydration so include any partial matches as\n    // the initial matches so we can properly render `HydrateFallback`'s\n    if (future.v7_partialHydration) {\n      let fogOfWar = checkFogOfWar(\n        null,\n        dataRoutes,\n        init.history.location.pathname\n      );\n      if (fogOfWar.active && fogOfWar.matches) {\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) => m.route.lazy)) {\n    // All initialMatches need to be loaded before we're ready.  If we have lazy\n    // functions around still then we'll need to run them in initialize()\n    initialized = false;\n  } else if (!initialMatches.some((m) => m.route.loader)) {\n    // If we've got no loaders to run, then we're good to go\n    initialized = true;\n  } else if (future.v7_partialHydration) {\n    // If partial hydration is enabled, we're initialized so long as we were\n    // provided with hydrationData for every route with a loader, and no loaders\n    // were marked for explicit hydration\n    let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n    let errors = init.hydrationData ? init.hydrationData.errors : null;\n    // If errors exist, don't consider routes below the boundary\n    if (errors) {\n      let idx = initialMatches.findIndex(\n        (m) => errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches\n        .slice(0, idx + 1)\n        .every((m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n    } else {\n      initialized = initialMatches.every(\n        (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)\n      );\n    }\n  } else {\n    // Without partial hydration - we're initialized if we were provided any\n    // hydrationData - which is expected to be complete\n    initialized = init.hydrationData != null;\n  }\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    blockers: 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\n  // Should the current navigation prevent the scroll reset if scroll cannot\n  // be restored?\n  let pendingPreventScrollReset = false;\n\n  // AbortController for the active navigation\n  let pendingNavigationController: AbortController | null;\n\n  // Should the current navigation enable document.startViewTransition?\n  let pendingViewTransitionEnabled = false;\n\n  // Store applied view transitions so we can apply them on POP\n  let appliedViewTransitions: Map<string, Set<string>> = new Map<\n    string,\n    Set<string>\n  >();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() => void) | null = null;\n\n  // We use this to avoid touching history in completeNavigation if a\n  // revalidation is entirely uninterrupted\n  let isUninterruptedRevalidation = false;\n\n  // Use this internal flag to force revalidation of all loaders:\n  //  - submissions (completed or interrupted)\n  //  - useRevalidator()\n  //  - X-Remix-Revalidate (from redirect)\n  let isRevalidationRequired = false;\n\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\n  // Use this internal array to capture fetcher loads that were cancelled by an\n  // action navigation and require revalidation\n  let cancelledFetcherLoads: Set<string> = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map<string, AbortController>();\n\n  // Track loads based on the order in which they started\n  let incrementingLoadId = 0;\n\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\n  // Fetchers that triggered data reloads as a result of their actions\n  let fetchReloadIds = new Map<string, number>();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set<string>();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map<string, FetchLoadMatch>();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map<string, number>();\n\n  // Fetchers that have requested a delete when using v7_fetcherPersist,\n  // they'll be officially removed after they return to idle\n  let deletedFetchers = new Set<string>();\n\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  // Store blocker functions in a separate Map outside of router state since\n  // we don't need to update UI state if they change\n  let blockerFunctions = new Map<string, BlockerFunction>();\n\n  // Map of pending patchRoutesOnNavigation() promises (keyed by path/matches) so\n  // that we only kick them off once for a given combo\n  let pendingPatchRoutes = new Map<\n    string,\n    ReturnType<AgnosticPatchRoutesOnNavigationFunction>\n  >();\n\n  // Flag to ignore the next history update, so we can revert the URL change on\n  // a POP navigation that was blocked by the user without touching router state\n  let unblockBlockerHistoryUpdate: (() => void) | undefined = undefined;\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, delta }) => {\n        // Ignore this event if it was just us resetting the URL from a\n        // blocked POP navigation\n        if (unblockBlockerHistoryUpdate) {\n          unblockBlockerHistoryUpdate();\n          unblockBlockerHistoryUpdate = undefined;\n          return;\n        }\n\n        warning(\n          blockerFunctions.size === 0 || delta != null,\n          \"You are trying to use a blocker on a POP navigation to a location \" +\n            \"that was not created by @remix-run/router. This will fail silently in \" +\n            \"production. This can happen if you are navigating outside the router \" +\n            \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n            \"router navigation APIs.  This can also happen if you are using \" +\n            \"createHashRouter and the user manually changes the URL.\"\n        );\n\n        let blockerKey = shouldBlockNavigation({\n          currentLocation: state.location,\n          nextLocation: location,\n          historyAction,\n        });\n\n        if (blockerKey && delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          let nextHistoryUpdatePromise = new Promise<void>((resolve) => {\n            unblockBlockerHistoryUpdate = resolve;\n          });\n          init.history.go(delta * -1);\n\n          // Put the blocker into a blocked state\n          updateBlocker(blockerKey, {\n            state: \"blocked\",\n            location,\n            proceed() {\n              updateBlocker(blockerKey!, {\n                state: \"proceeding\",\n                proceed: undefined,\n                reset: undefined,\n                location,\n              });\n              // Re-do the same POP navigation we just blocked, after the url\n              // restoration is also complete.  See:\n              // https://github.com/remix-run/react-router/issues/11613\n              nextHistoryUpdatePromise.then(() => init.history.go(delta));\n            },\n            reset() {\n              let blockers = new Map(state.blockers);\n              blockers.set(blockerKey!, IDLE_BLOCKER);\n              updateState({ blockers });\n            },\n          });\n          return;\n        }\n\n        return startNavigation(historyAction, location);\n      }\n    );\n\n    if (isBrowser) {\n      // FIXME: This feels gross.  How can we cleanup the lines between\n      // scrollRestoration/appliedTransitions persistance?\n      restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n      let _saveAppliedTransitions = () =>\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =>\n        routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n    }\n\n    // Kick off initial data load if needed.  Use Pop to avoid modifying history\n    // Note we don't do any handling of lazy here.  For SPA's it'll get handled\n    // in the normal navigation flow.  For SSR it's expected that lazy modules are\n    // resolved prior to router creation since we can't go into a fallbackElement\n    // UI for SSR'd apps\n    if (!state.initialized) {\n      startNavigation(HistoryAction.Pop, state.location, {\n        initialHydration: true,\n      });\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    if (removePageHideEventListener) {\n      removePageHideEventListener();\n    }\n    subscribers.clear();\n    pendingNavigationController && pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) => deleteFetcher(key));\n    state.blockers.forEach((_, key) => deleteBlocker(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(\n    newState: Partial<RouterState>,\n    opts: {\n      flushSync?: boolean;\n      viewTransitionOpts?: ViewTransitionOpts;\n    } = {}\n  ): void {\n    state = {\n      ...state,\n      ...newState,\n    };\n\n    // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n    // can be removed\n    let completedFetchers: string[] = [];\n    let deletedFetchersKeys: string[] = [];\n\n    if (future.v7_fetcherPersist) {\n      state.fetchers.forEach((fetcher, key) => {\n        if (fetcher.state === \"idle\") {\n          if (deletedFetchers.has(key)) {\n            // Unmounted from the UI and can be totally removed\n            deletedFetchersKeys.push(key);\n          } else {\n            // Returned to idle but still mounted in the UI, so semi-remains for\n            // revalidations and such\n            completedFetchers.push(key);\n          }\n        }\n      });\n    }\n\n    // Iterate over a local copy so that if flushSync is used and we end up\n    // removing and adding a new subscriber due to the useCallback dependencies,\n    // we don't get ourselves into a loop calling the new subscriber immediately\n    [...subscribers].forEach((subscriber) =>\n      subscriber(state, {\n        deletedFetchers: deletedFetchersKeys,\n        viewTransitionOpts: opts.viewTransitionOpts,\n        flushSync: opts.flushSync === true,\n      })\n    );\n\n    // Remove idle fetchers from state since we only care about in-flight fetchers.\n    if (future.v7_fetcherPersist) {\n      completedFetchers.forEach((key) => state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n    }\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    { flushSync }: { flushSync?: boolean } = {}\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    // On a successful navigation we can assume we got through all blockers\n    // so we can start fresh\n    let blockers = state.blockers;\n    if (blockers.size > 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n    }\n\n    // Always respect the user flag.  Otherwise don't reset on mutation\n    // submission navigations unless they redirect\n    let preventScrollReset =\n      pendingPreventScrollReset === true ||\n      (state.navigation.formMethod != null &&\n        isMutationMethod(state.navigation.formMethod) &&\n        location.state?._isRedirect !== true);\n\n    // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n    if (inFlightDataRoutes) {\n      dataRoutes = inFlightDataRoutes;\n      inFlightDataRoutes = undefined;\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    let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n    // On POP, enable transitions if they were enabled on the original navigation\n    if (pendingAction === HistoryAction.Pop) {\n      // Forward takes precedence so they behave like the original navigation\n      let priorPaths = appliedViewTransitions.get(state.location.pathname);\n      if (priorPaths && priorPaths.has(location.pathname)) {\n        viewTransitionOpts = {\n          currentLocation: state.location,\n          nextLocation: location,\n        };\n      } else if (appliedViewTransitions.has(location.pathname)) {\n        // If we don't have a previous forward nav, assume we're popping back to\n        // the new location and enable if that location previously enabled\n        viewTransitionOpts = {\n          currentLocation: location,\n          nextLocation: state.location,\n        };\n      }\n    } else if (pendingViewTransitionEnabled) {\n      // Store the applied transition on PUSH/REPLACE\n      let toPaths = appliedViewTransitions.get(state.location.pathname);\n      if (toPaths) {\n        toPaths.add(location.pathname);\n      } else {\n        toPaths = new Set<string>([location.pathname]);\n        appliedViewTransitions.set(state.location.pathname, toPaths);\n      }\n      viewTransitionOpts = {\n        currentLocation: state.location,\n        nextLocation: location,\n      };\n    }\n\n    updateState(\n      {\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        restoreScrollPosition: getSavedScrollPosition(\n          location,\n          newState.matches || state.matches\n        ),\n        preventScrollReset,\n        blockers,\n      },\n      {\n        viewTransitionOpts,\n        flushSync: flushSync === true,\n      }\n    );\n\n    // Reset stateful navigation vars\n    pendingAction = HistoryAction.Pop;\n    pendingPreventScrollReset = false;\n    pendingViewTransitionEnabled = false;\n    isUninterruptedRevalidation = false;\n    isRevalidationRequired = false;\n    cancelledDeferredRoutes = [];\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 | null,\n    opts?: RouterNavigateOptions\n  ): Promise<void> {\n    if (typeof to === \"number\") {\n      init.history.go(to);\n      return;\n    }\n\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      to,\n      future.v7_relativeSplatPath,\n      opts?.fromRouteId,\n      opts?.relative\n    );\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      false,\n      normalizedPath,\n      opts\n    );\n\n    let currentLocation = state.location;\n    let nextLocation = 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    nextLocation = {\n      ...nextLocation,\n      ...init.history.encodeLocation(nextLocation),\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    let flushSync = (opts && opts.flushSync) === true;\n\n    let blockerKey = shouldBlockNavigation({\n      currentLocation,\n      nextLocation,\n      historyAction,\n    });\n\n    if (blockerKey) {\n      // Put the blocker into a blocked state\n      updateBlocker(blockerKey, {\n        state: \"blocked\",\n        location: nextLocation,\n        proceed() {\n          updateBlocker(blockerKey!, {\n            state: \"proceeding\",\n            proceed: undefined,\n            reset: undefined,\n            location: nextLocation,\n          });\n          // Send the same navigation through\n          navigate(to, opts);\n        },\n        reset() {\n          let blockers = new Map(state.blockers);\n          blockers.set(blockerKey!, IDLE_BLOCKER);\n          updateState({ blockers });\n        },\n      });\n      return;\n    }\n\n    return await startNavigation(historyAction, nextLocation, {\n      submission,\n      // Send through the formData serialization error if we have one so we can\n      // render at the right error boundary after we match routes\n      pendingError: error,\n      preventScrollReset,\n      replace: opts && opts.replace,\n      enableViewTransition: opts && opts.viewTransition,\n      flushSync,\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      {\n        overrideNavigation: state.navigation,\n        // Proxy through any rending view transition\n        enableViewTransition: pendingViewTransitionEnabled === true,\n      }\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      initialHydration?: boolean;\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      overrideNavigation?: Navigation;\n      pendingError?: ErrorResponseImpl;\n      startUninterruptedRevalidation?: boolean;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n      enableViewTransition?: boolean;\n      flushSync?: 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    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts && opts.overrideNavigation;\n    let matches = matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    // Short circuit with a 404 on the root error boundary if we match nothing\n    if (!matches) {\n      let { error, notFoundMatches, route } = handleNavigational404(\n        location.pathname\n      );\n      completeNavigation(\n        location,\n        {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        },\n        { flushSync }\n      );\n      return;\n    }\n\n    // Short circuit if it's only a hash change and not a revalidation or\n    // mutation submission.\n    //\n    // Ignore on initial page loads because since the initial hydration will always\n    // be \"same hash\".  For example, on /page#hash and submit a <Form method=\"post\">\n    // which will default to a navigation to /page\n    if (\n      state.initialized &&\n      !isRevalidationRequired &&\n      isHashChangeOnly(state.location, location) &&\n      !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n    ) {\n      completeNavigation(location, { matches }, { flushSync });\n      return;\n    }\n\n    // Create a controller/Request for this navigation\n    pendingNavigationController = new AbortController();\n    let request = createClientSideRequest(\n      init.history,\n      location,\n      pendingNavigationController.signal,\n      opts && opts.submission\n    );\n    let pendingActionResult: PendingActionResult | 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      pendingActionResult = [\n        findNearestBoundary(matches).route.id,\n        { type: ResultType.error, error: 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 actionResult = await handleAction(\n        request,\n        location,\n        opts.submission,\n        matches,\n        fogOfWar.active,\n        { replace: opts.replace, flushSync }\n      );\n\n      if (actionResult.shortCircuited) {\n        return;\n      }\n\n      // If we received a 404 from handleAction, it's because we couldn't lazily\n      // discover the destination route so we don't want to call loaders\n      if (actionResult.pendingActionResult) {\n        let [routeId, result] = actionResult.pendingActionResult;\n        if (\n          isErrorResult(result) &&\n          isRouteErrorResponse(result.error) &&\n          result.error.status === 404\n        ) {\n          pendingNavigationController = null;\n\n          completeNavigation(location, {\n            matches: actionResult.matches,\n            loaderData: {},\n            errors: {\n              [routeId]: result.error,\n            },\n          });\n          return;\n        }\n      }\n\n      matches = actionResult.matches || matches;\n      pendingActionResult = actionResult.pendingActionResult;\n      loadingNavigation = getLoadingNavigation(location, opts.submission);\n      flushSync = false;\n      // No need to do fog of war matching again on loader execution\n      fogOfWar.active = false;\n\n      // Create a GET request for the loaders\n      request = createClientSideRequest(\n        init.history,\n        request.url,\n        request.signal\n      );\n    }\n\n    // Call loaders\n    let {\n      shortCircuited,\n      matches: updatedMatches,\n      loaderData,\n      errors,\n    } = await handleLoaders(\n      request,\n      location,\n      matches,\n      fogOfWar.active,\n      loadingNavigation,\n      opts && opts.submission,\n      opts && opts.fetcherSubmission,\n      opts && opts.replace,\n      opts && opts.initialHydration === true,\n      flushSync,\n      pendingActionResult\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: updatedMatches || matches,\n      ...getActionDataForCommit(pendingActionResult),\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    isFogOfWar: boolean,\n    opts: { replace?: boolean; flushSync?: boolean } = {}\n  ): Promise<HandleActionResult> {\n    interruptActiveLoads();\n\n    // Put us in a submitting state\n    let navigation = getSubmittingNavigation(location, submission);\n    updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          pendingActionResult: [\n            boundaryId,\n            {\n              type: ResultType.error,\n              error: discoverResult.error,\n            },\n          ],\n        };\n      } else if (!discoverResult.matches) {\n        let { notFoundMatches, error, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          pendingActionResult: [\n            route.id,\n            {\n              type: ResultType.error,\n              error,\n            },\n          ],\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\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 && !actionMatch.route.lazy) {\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      let results = await callDataStrategy(\n        \"action\",\n        state,\n        request,\n        [actionMatch],\n        matches,\n        null\n      );\n      result = results[actionMatch.route.id];\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        let location = normalizeRedirectLocation(\n          result.response.headers.get(\"Location\")!,\n          new URL(request.url),\n          basename\n        );\n        replace = location === state.location.pathname + state.location.search;\n      }\n      await startRedirectNavigation(request, result, true, {\n        submission,\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    if (isDeferredResult(result)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\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 to the current location are REPLACE\n      // navigations, but if the action threw an error that'll be rendered in\n      // an errorElement, we fall back to PUSH so that the user can use the\n      // back button to get back to the pre-submission form location to try\n      // again\n      if ((opts && opts.replace) !== true) {\n        pendingAction = HistoryAction.Push;\n      }\n\n      return {\n        matches,\n        pendingActionResult: [boundaryMatch.route.id, result],\n      };\n    }\n\n    return {\n      matches,\n      pendingActionResult: [actionMatch.route.id, result],\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    isFogOfWar: boolean,\n    overrideNavigation?: Navigation,\n    submission?: Submission,\n    fetcherSubmission?: Submission,\n    replace?: boolean,\n    initialHydration?: boolean,\n    flushSync?: boolean,\n    pendingActionResult?: PendingActionResult\n  ): Promise<HandleLoadersResult> {\n    // Figure out the right navigation we want to use for data loading\n    let loadingNavigation =\n      overrideNavigation || getLoadingNavigation(location, submission);\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 =\n      submission ||\n      fetcherSubmission ||\n      getSubmissionFromNavigation(loadingNavigation);\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 we have partialHydration enabled, then don't update the state for the\n    // initial data load since it's not a \"navigation\"\n    let shouldUpdateNavigationState =\n      !isUninterruptedRevalidation &&\n      (!future.v7_partialHydration || !initialHydration);\n\n    // When fog of war is enabled, we enter our `loading` state earlier so we\n    // can discover new routes during the `loading` state.  We skip this if\n    // we've already run actions since we would have done our matching already.\n    // If the children() function threw then, we want to proceed with the\n    // partial matches it discovered.\n    if (isFogOfWar) {\n      if (shouldUpdateNavigationState) {\n        let actionData = getUpdatedActionData(pendingActionResult);\n        updateState(\n          {\n            navigation: loadingNavigation,\n            ...(actionData !== undefined ? { actionData } : {}),\n          },\n          {\n            flushSync,\n          }\n        );\n      }\n\n      let discoverResult = await discoverRoutes(\n        matches,\n        location.pathname,\n        request.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return { shortCircuited: true };\n      } else if (discoverResult.type === \"error\") {\n        let boundaryId = findNearestBoundary(discoverResult.partialMatches)\n          .route.id;\n        return {\n          matches: discoverResult.partialMatches,\n          loaderData: {},\n          errors: {\n            [boundaryId]: discoverResult.error,\n          },\n        };\n      } else if (!discoverResult.matches) {\n        let { error, notFoundMatches, route } = handleNavigational404(\n          location.pathname\n        );\n        return {\n          matches: notFoundMatches,\n          loaderData: {},\n          errors: {\n            [route.id]: error,\n          },\n        };\n      } else {\n        matches = discoverResult.matches;\n      }\n    }\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      activeSubmission,\n      location,\n      future.v7_partialHydration && initialHydration === true,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      pendingActionResult\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    pendingNavigationLoadId = ++incrementingLoadId;\n\n    // Short circuit if we have no loaders to run\n    if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n      let updatedFetchers = markFetchRedirectsDone();\n      completeNavigation(\n        location,\n        {\n          matches,\n          loaderData: {},\n          // Commit pending error if we're short circuiting\n          errors:\n            pendingActionResult && isErrorResult(pendingActionResult[1])\n              ? { [pendingActionResult[0]]: pendingActionResult[1].error }\n              : null,\n          ...getActionDataForCommit(pendingActionResult),\n          ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n        },\n        { flushSync }\n      );\n      return { shortCircuited: true };\n    }\n\n    if (shouldUpdateNavigationState) {\n      let updates: Partial<RouterState> = {};\n      if (!isFogOfWar) {\n        // Only update navigation/actionNData if we didn't already do it above\n        updates.navigation = loadingNavigation;\n        let actionData = getUpdatedActionData(pendingActionResult);\n        if (actionData !== undefined) {\n          updates.actionData = actionData;\n        }\n      }\n      if (revalidatingFetchers.length > 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) => {\n      abortFetcher(rf.key);\n      if (rf.controller) {\n        // Fetchers use an independent AbortController so that aborting a fetcher\n        // (via deleteFetcher) does not abort the triggering navigation that\n        // triggered the revalidation\n        fetchControllers.set(rf.key, rf.controller);\n      }\n    });\n\n    // Proxy navigation abort through to revalidation fetchers\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n    if (pendingNavigationController) {\n      pendingNavigationController.signal.addEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\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    if (pendingNavigationController) {\n      pendingNavigationController.signal.removeEventListener(\n        \"abort\",\n        abortPendingFetchRevalidations\n      );\n    }\n\n    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n    // If any loaders returned a redirect Response, start a new REPLACE navigation\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      await startRedirectNavigation(request, redirect.result, true, {\n        replace,\n      });\n      return { shortCircuited: true };\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      pendingActionResult,\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    // Preserve SSR errors during partial hydration\n    if (future.v7_partialHydration && initialHydration && state.errors) {\n      errors = { ...state.errors, ...errors };\n    }\n\n    let updatedFetchers = markFetchRedirectsDone();\n    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n    let shouldUpdateFetchers =\n      updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n    return {\n      matches,\n      loaderData,\n      errors,\n      ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n    };\n  }\n\n  function getUpdatedActionData(\n    pendingActionResult: PendingActionResult | undefined\n  ): Record<string, RouteData> | null | undefined {\n    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n      // This is cast to `any` currently because `RouteData`uses any and it\n      // would be a breaking change to use any.\n      // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n      return {\n        [pendingActionResult[0]]: pendingActionResult[1].data as any,\n      };\n    } else if (state.actionData) {\n      if (Object.keys(state.actionData).length === 0) {\n        return null;\n      } else {\n        return state.actionData;\n      }\n    }\n  }\n\n  function getUpdatedRevalidatingFetchers(\n    revalidatingFetchers: RevalidatingFetcher[]\n  ) {\n    revalidatingFetchers.forEach((rf) => {\n      let fetcher = state.fetchers.get(rf.key);\n      let revalidatingFetcher = getLoadingFetcher(\n        undefined,\n        fetcher ? fetcher.data : undefined\n      );\n      state.fetchers.set(rf.key, revalidatingFetcher);\n    });\n    return new Map(state.fetchers);\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 | null,\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    abortFetcher(key);\n\n    let flushSync = (opts && opts.flushSync) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let normalizedPath = normalizeTo(\n      state.location,\n      state.matches,\n      basename,\n      future.v7_prependBasename,\n      href,\n      future.v7_relativeSplatPath,\n      routeId,\n      opts?.relative\n    );\n    let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n    if (fogOfWar.active && fogOfWar.matches) {\n      matches = fogOfWar.matches;\n    }\n\n    if (!matches) {\n      setFetcherError(\n        key,\n        routeId,\n        getInternalRouterError(404, { pathname: normalizedPath }),\n        { flushSync }\n      );\n      return;\n    }\n\n    let { path, submission, error } = normalizeNavigateOptions(\n      future.v7_normalizeFormMethod,\n      true,\n      normalizedPath,\n      opts\n    );\n\n    if (error) {\n      setFetcherError(key, routeId, error, { flushSync });\n      return;\n    }\n\n    let match = getTargetMatch(matches, path);\n\n    let preventScrollReset = (opts && opts.preventScrollReset) === true;\n\n    if (submission && isMutationMethod(submission.formMethod)) {\n      handleFetcherAction(\n        key,\n        routeId,\n        path,\n        match,\n        matches,\n        fogOfWar.active,\n        flushSync,\n        preventScrollReset,\n        submission\n      );\n      return;\n    }\n\n    // Store off the match so we can call it's shouldRevalidate on subsequent\n    // revalidations\n    fetchLoadMatches.set(key, { routeId, path });\n    handleFetcherLoader(\n      key,\n      routeId,\n      path,\n      match,\n      matches,\n      fogOfWar.active,\n      flushSync,\n      preventScrollReset,\n      submission\n    );\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    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission: Submission\n  ) {\n    interruptActiveLoads();\n    fetchLoadMatches.delete(key);\n\n    function detectAndHandle405Error(m: AgnosticDataRouteMatch) {\n      if (!m.route.action && !m.route.lazy) {\n        let error = getInternalRouterError(405, {\n          method: submission.formMethod,\n          pathname: path,\n          routeId: routeId,\n        });\n        setFetcherError(key, routeId, error, { flushSync });\n        return true;\n      }\n      return false;\n    }\n\n    if (!isFogOfWar && detectAndHandle405Error(match)) {\n      return;\n    }\n\n    // Put this fetcher into it's submitting state\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n      flushSync,\n    });\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal,\n      submission\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        requestMatches,\n        path,\n        fetchRequest.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        requestMatches = discoverResult.matches;\n        match = getTargetMatch(requestMatches, path);\n\n        if (detectAndHandle405Error(match)) {\n          return;\n        }\n      }\n    }\n\n    // Call the action for the fetcher\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let actionResults = await callDataStrategy(\n      \"action\",\n      state,\n      fetchRequest,\n      [match],\n      requestMatches,\n      key\n    );\n    let actionResult = actionResults[match.route.id];\n\n    if (fetchRequest.signal.aborted) {\n      // We can delete this so long as we weren't aborted by 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    // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n    // or redirects processed for unmounted fetchers so we just revert them to\n    // idle\n    if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      }\n      // Let SuccessResult's fall through for revalidation\n    } else {\n      if (isRedirectResult(actionResult)) {\n        fetchControllers.delete(key);\n        if (pendingNavigationLoadId > originatingLoadId) {\n          // A new navigation was kicked off after our action started, so that\n          // should take precedence over this redirect navigation.  We already\n          // set isRevalidationRequired so all loaders for the new route should\n          // fire unless opted out via shouldRevalidate\n          updateFetcherState(key, getDoneFetcher(undefined));\n          return;\n        } else {\n          fetchRedirectIds.add(key);\n          updateFetcherState(key, getLoadingFetcher(submission));\n          return startRedirectNavigation(fetchRequest, actionResult, false, {\n            fetcherSubmission: submission,\n            preventScrollReset,\n          });\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\n    if (isDeferredResult(actionResult)) {\n      throw getInternalRouterError(400, { type: \"defer-action\" });\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      init.history,\n      nextLocation,\n      abortController.signal\n    );\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let matches =\n      state.navigation.state !== \"idle\"\n        ? matchRoutes(routesToUse, state.navigation.location, 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 = getLoadingFetcher(submission, actionResult.data);\n    state.fetchers.set(key, loadFetcher);\n\n    let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n      init.history,\n      state,\n      matches,\n      submission,\n      nextLocation,\n      false,\n      future.v7_skipActionErrorRevalidation,\n      isRevalidationRequired,\n      cancelledDeferredRoutes,\n      cancelledFetcherLoads,\n      deletedFetchers,\n      fetchLoadMatches,\n      fetchRedirectIds,\n      routesToUse,\n      basename,\n      [match.route.id, actionResult]\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((rf) => rf.key !== key)\n      .forEach((rf) => {\n        let staleKey = rf.key;\n        let existingFetcher = state.fetchers.get(staleKey);\n        let revalidatingFetcher = getLoadingFetcher(\n          undefined,\n          existingFetcher ? existingFetcher.data : undefined\n        );\n        state.fetchers.set(staleKey, revalidatingFetcher);\n        abortFetcher(staleKey);\n        if (rf.controller) {\n          fetchControllers.set(staleKey, rf.controller);\n        }\n      });\n\n    updateState({ fetchers: new Map(state.fetchers) });\n\n    let abortPendingFetchRevalidations = () =>\n      revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n    abortController.signal.addEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    let { loaderResults, fetcherResults } =\n      await callLoadersAndMaybeResolveData(\n        state,\n        matches,\n        matchesToLoad,\n        revalidatingFetchers,\n        revalidationRequest\n      );\n\n    if (abortController.signal.aborted) {\n      return;\n    }\n\n    abortController.signal.removeEventListener(\n      \"abort\",\n      abortPendingFetchRevalidations\n    );\n\n    fetchReloadIds.delete(key);\n    fetchControllers.delete(key);\n    revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n    let redirect = findRedirect(loaderResults);\n    if (redirect) {\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    redirect = findRedirect(fetcherResults);\n    if (redirect) {\n      // If this redirect came from a fetcher make sure we mark it in\n      // fetchRedirectIds so it doesn't get revalidated on the next set of\n      // loader executions\n      fetchRedirectIds.add(redirect.key);\n      return startRedirectNavigation(\n        revalidationRequest,\n        redirect.result,\n        false,\n        { preventScrollReset }\n      );\n    }\n\n    // Process and commit output from loaders\n    let { loaderData, errors } = processLoaderData(\n      state,\n      matches,\n      loaderResults,\n      undefined,\n      revalidatingFetchers,\n      fetcherResults,\n      activeDeferreds\n    );\n\n    // Since we let revalidations complete even if the submitting fetcher was\n    // deleted, only put it back to idle if it hasn't been deleted\n    if (state.fetchers.has(key)) {\n      let doneFetcher = getDoneFetcher(actionResult.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n\n    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        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    isFogOfWar: boolean,\n    flushSync: boolean,\n    preventScrollReset: boolean,\n    submission?: Submission\n  ) {\n    let existingFetcher = state.fetchers.get(key);\n    updateFetcherState(\n      key,\n      getLoadingFetcher(\n        submission,\n        existingFetcher ? existingFetcher.data : undefined\n      ),\n      { flushSync }\n    );\n\n    let abortController = new AbortController();\n    let fetchRequest = createClientSideRequest(\n      init.history,\n      path,\n      abortController.signal\n    );\n\n    if (isFogOfWar) {\n      let discoverResult = await discoverRoutes(\n        matches,\n        path,\n        fetchRequest.signal\n      );\n\n      if (discoverResult.type === \"aborted\") {\n        return;\n      } else if (discoverResult.type === \"error\") {\n        setFetcherError(key, routeId, discoverResult.error, { flushSync });\n        return;\n      } else if (!discoverResult.matches) {\n        setFetcherError(\n          key,\n          routeId,\n          getInternalRouterError(404, { pathname: path }),\n          { flushSync }\n        );\n        return;\n      } else {\n        matches = discoverResult.matches;\n        match = getTargetMatch(matches, path);\n      }\n    }\n\n    // Call the loader for this fetcher route match\n    fetchControllers.set(key, abortController);\n\n    let originatingLoadId = incrementingLoadId;\n    let results = await callDataStrategy(\n      \"loader\",\n      state,\n      fetchRequest,\n      [match],\n      matches,\n      key\n    );\n    let result = results[match.route.id];\n\n    // Deferred isn't supported for 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 our 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    // We don't want errors bubbling up or redirects followed for unmounted\n    // fetchers, so short circuit here if it was removed from the UI\n    if (deletedFetchers.has(key)) {\n      updateFetcherState(key, getDoneFetcher(undefined));\n      return;\n    }\n\n    // If the loader threw a redirect Response, start a new REPLACE navigation\n    if (isRedirectResult(result)) {\n      if (pendingNavigationLoadId > originatingLoadId) {\n        // A new navigation was kicked off after our loader started, so that\n        // should take precedence over this redirect navigation\n        updateFetcherState(key, getDoneFetcher(undefined));\n        return;\n      } else {\n        fetchRedirectIds.add(key);\n        await startRedirectNavigation(fetchRequest, result, false, {\n          preventScrollReset,\n        });\n        return;\n      }\n    }\n\n    // Process any non-redirect errors thrown\n    if (isErrorResult(result)) {\n      setFetcherError(key, routeId, result.error);\n      return;\n    }\n\n    invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n    // Put the fetcher back into an idle state\n    updateFetcherState(key, getDoneFetcher(result.data));\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    request: Request,\n    redirect: RedirectResult,\n    isNavigation: boolean,\n    {\n      submission,\n      fetcherSubmission,\n      preventScrollReset,\n      replace,\n    }: {\n      submission?: Submission;\n      fetcherSubmission?: Submission;\n      preventScrollReset?: boolean;\n      replace?: boolean;\n    } = {}\n  ) {\n    if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n      isRevalidationRequired = true;\n    }\n\n    let location = redirect.response.headers.get(\"Location\");\n    invariant(location, \"Expected a Location header on the redirect Response\");\n    location = normalizeRedirectLocation(\n      location,\n      new URL(request.url),\n      basename\n    );\n    let redirectLocation = createLocation(state.location, location, {\n      _isRedirect: true,\n    });\n\n    if (isBrowser) {\n      let isDocumentReload = false;\n\n      if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n        // Hard reload if the response contained X-Remix-Reload-Document\n        isDocumentReload = true;\n      } else if (ABSOLUTE_URL_REGEX.test(location)) {\n        const url = init.history.createURL(location);\n        isDocumentReload =\n          // Hard reload if it's an absolute URL to a new origin\n          url.origin !== routerWindow.location.origin ||\n          // Hard reload if it's an absolute URL that does not match our basename\n          stripBasename(url.pathname, basename) == null;\n      }\n\n      if (isDocumentReload) {\n        if (replace) {\n          routerWindow.location.replace(location);\n        } else {\n          routerWindow.location.assign(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 || redirect.response.headers.has(\"X-Remix-Replace\")\n        ? HistoryAction.Replace\n        : HistoryAction.Push;\n\n    // Use the incoming submission if provided, fallback on the active one in\n    // state.navigation\n    let { formMethod, formAction, formEncType } = state.navigation;\n    if (\n      !submission &&\n      !fetcherSubmission &&\n      formMethod &&\n      formAction &&\n      formEncType\n    ) {\n      submission = getSubmissionFromNavigation(state.navigation);\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    let activeSubmission = submission || fetcherSubmission;\n    if (\n      redirectPreserveMethodStatusCodes.has(redirect.response.status) &&\n      activeSubmission &&\n      isMutationMethod(activeSubmission.formMethod)\n    ) {\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        submission: {\n          ...activeSubmission,\n          formAction: location,\n        },\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    } else {\n      // If we have a navigation submission, we will preserve it through the\n      // redirect navigation\n      let overrideNavigation = getLoadingNavigation(\n        redirectLocation,\n        submission\n      );\n      await startNavigation(redirectHistoryAction, redirectLocation, {\n        overrideNavigation,\n        // Send fetcher submissions through for shouldRevalidate\n        fetcherSubmission,\n        // Preserve these flags across redirects\n        preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n        enableViewTransition: isNavigation\n          ? pendingViewTransitionEnabled\n          : undefined,\n      });\n    }\n  }\n\n  // Utility wrapper for calling dataStrategy client-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    state: RouterState,\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    fetcherKey: string | null\n  ): Promise<Record<string, DataResult>> {\n    let results: Record<string, DataStrategyResult>;\n    let dataResults: Record<string, DataResult> = {};\n    try {\n      results = await callDataStrategyImpl(\n        dataStrategyImpl,\n        type,\n        state,\n        request,\n        matchesToLoad,\n        matches,\n        fetcherKey,\n        manifest,\n        mapRouteProperties\n      );\n    } catch (e) {\n      // If the outer dataStrategy method throws, just return the error for all\n      // matches - and it'll naturally bubble to the root\n      matchesToLoad.forEach((m) => {\n        dataResults[m.route.id] = {\n          type: ResultType.error,\n          error: e,\n        };\n      });\n      return dataResults;\n    }\n\n    for (let [routeId, result] of Object.entries(results)) {\n      if (isRedirectDataStrategyResultResult(result)) {\n        let response = result.result as Response;\n        dataResults[routeId] = {\n          type: ResultType.redirect,\n          response: normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            routeId,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          ),\n        };\n      } else {\n        dataResults[routeId] = await convertDataStrategyResultToDataResult(\n          result\n        );\n      }\n    }\n\n    return dataResults;\n  }\n\n  async function callLoadersAndMaybeResolveData(\n    state: RouterState,\n    matches: AgnosticDataRouteMatch[],\n    matchesToLoad: AgnosticDataRouteMatch[],\n    fetchersToLoad: RevalidatingFetcher[],\n    request: Request\n  ) {\n    let currentMatches = state.matches;\n\n    // Kick off loaders and fetchers in parallel\n    let loaderResultsPromise = callDataStrategy(\n      \"loader\",\n      state,\n      request,\n      matchesToLoad,\n      matches,\n      null\n    );\n\n    let fetcherResultsPromise = Promise.all(\n      fetchersToLoad.map(async (f) => {\n        if (f.matches && f.match && f.controller) {\n          let results = await callDataStrategy(\n            \"loader\",\n            state,\n            createClientSideRequest(init.history, f.path, f.controller.signal),\n            [f.match],\n            f.matches,\n            f.key\n          );\n          let result = results[f.match.route.id];\n          // Fetcher results are keyed by fetcher key from here on out, not routeId\n          return { [f.key]: result };\n        } else {\n          return Promise.resolve({\n            [f.key]: {\n              type: ResultType.error,\n              error: getInternalRouterError(404, {\n                pathname: f.path,\n              }),\n            } as ErrorResult,\n          });\n        }\n      })\n    );\n\n    let loaderResults = await loaderResultsPromise;\n    let fetcherResults = (await fetcherResultsPromise).reduce(\n      (acc, r) => Object.assign(acc, r),\n      {}\n    );\n\n    await Promise.all([\n      resolveNavigationDeferredResults(\n        matches,\n        loaderResults,\n        request.signal,\n        currentMatches,\n        state.loaderData\n      ),\n      resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad),\n    ]);\n\n    return {\n      loaderResults,\n      fetcherResults,\n    };\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.add(key);\n      }\n      abortFetcher(key);\n    });\n  }\n\n  function updateFetcherState(\n    key: string,\n    fetcher: Fetcher,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    state.fetchers.set(key, fetcher);\n    updateState(\n      { fetchers: new Map(state.fetchers) },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function setFetcherError(\n    key: string,\n    routeId: string,\n    error: any,\n    opts: { flushSync?: boolean } = {}\n  ) {\n    let boundaryMatch = findNearestBoundary(state.matches, routeId);\n    deleteFetcher(key);\n    updateState(\n      {\n        errors: {\n          [boundaryMatch.route.id]: error,\n        },\n        fetchers: new Map(state.fetchers),\n      },\n      { flushSync: (opts && opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher<TData = any>(key: string): Fetcher<TData> {\n    if (future.v7_fetcherPersist) {\n      activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n      // If this fetcher was previously marked for deletion, unmark it since we\n      // have a new instance\n      if (deletedFetchers.has(key)) {\n        deletedFetchers.delete(key);\n      }\n    }\n    return state.fetchers.get(key) || IDLE_FETCHER;\n  }\n\n  function deleteFetcher(key: string): void {\n    let fetcher = state.fetchers.get(key);\n    // Don't abort the controller if this is a deletion of a fetcher.submit()\n    // in it's loading phase since - we don't want to abort the corresponding\n    // revalidation and want them to complete and land\n    if (\n      fetchControllers.has(key) &&\n      !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n    ) {\n      abortFetcher(key);\n    }\n    fetchLoadMatches.delete(key);\n    fetchReloadIds.delete(key);\n    fetchRedirectIds.delete(key);\n    deletedFetchers.delete(key);\n    cancelledFetcherLoads.delete(key);\n    state.fetchers.delete(key);\n  }\n\n  function deleteFetcherAndUpdateState(key: string): void {\n    if (future.v7_fetcherPersist) {\n      let count = (activeFetchers.get(key) || 0) - 1;\n      if (count <= 0) {\n        activeFetchers.delete(key);\n        deletedFetchers.add(key);\n      } else {\n        activeFetchers.set(key, count);\n      }\n    } else {\n      deleteFetcher(key);\n    }\n    updateState({ fetchers: new Map(state.fetchers) });\n  }\n\n  function abortFetcher(key: string) {\n    let controller = fetchControllers.get(key);\n    if (controller) {\n      controller.abort();\n      fetchControllers.delete(key);\n    }\n  }\n\n  function markFetchersDone(keys: string[]) {\n    for (let key of keys) {\n      let fetcher = getFetcher(key);\n      let doneFetcher = getDoneFetcher(fetcher.data);\n      state.fetchers.set(key, doneFetcher);\n    }\n  }\n\n  function markFetchRedirectsDone(): boolean {\n    let doneKeys = [];\n    let updatedFetchers = false;\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        updatedFetchers = true;\n      }\n    }\n    markFetchersDone(doneKeys);\n    return updatedFetchers;\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 getBlocker(key: string, fn: BlockerFunction) {\n    let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    if (blockerFunctions.get(key) !== fn) {\n      blockerFunctions.set(key, fn);\n    }\n\n    return blocker;\n  }\n\n  function deleteBlocker(key: string) {\n    state.blockers.delete(key);\n    blockerFunctions.delete(key);\n  }\n\n  // Utility function to update blockers, ensuring valid state transitions\n  function updateBlocker(key: string, newBlocker: Blocker) {\n    let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n    // Poor mans state machine :)\n    // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n    invariant(\n      (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n    );\n\n    let blockers = new Map(state.blockers);\n    blockers.set(key, newBlocker);\n    updateState({ blockers });\n  }\n\n  function shouldBlockNavigation({\n    currentLocation,\n    nextLocation,\n    historyAction,\n  }: {\n    currentLocation: Location;\n    nextLocation: Location;\n    historyAction: HistoryAction;\n  }): string | undefined {\n    if (blockerFunctions.size === 0) {\n      return;\n    }\n\n    // We ony support a single active blocker at the moment since we don't have\n    // any compelling use cases for multi-blocker yet\n    if (blockerFunctions.size > 1) {\n      warning(false, \"A router only supports one blocker at a time\");\n    }\n\n    let entries = Array.from(blockerFunctions.entries());\n    let [blockerKey, blockerFunction] = entries[entries.length - 1];\n    let blocker = state.blockers.get(blockerKey);\n\n    if (blocker && blocker.state === \"proceeding\") {\n      // If the blocker is currently proceeding, we don't need to re-check\n      // it and can let this navigation continue\n      return;\n    }\n\n    // At this point, we know we're unblocked/blocked so we need to check the\n    // user-provided blocker function\n    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n      return blockerKey;\n    }\n  }\n\n  function handleNavigational404(pathname: string) {\n    let error = getInternalRouterError(404, { pathname });\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let { matches, route } = getShortCircuitMatches(routesToUse);\n\n    // Cancel all pending deferred on 404s since we don't keep any routes\n    cancelActiveDeferreds();\n\n    return { notFoundMatches: matches, route, error };\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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n    if (getScrollRestorationKey) {\n      let key = getScrollRestorationKey(\n        location,\n        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n      );\n      return key || location.key;\n    }\n    return location.key;\n  }\n\n  function saveScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): void {\n    if (savedScrollPositions && getScrollPosition) {\n      let key = getScrollKey(location, matches);\n      savedScrollPositions[key] = getScrollPosition();\n    }\n  }\n\n  function getSavedScrollPosition(\n    location: Location,\n    matches: AgnosticDataRouteMatch[]\n  ): number | null {\n    if (savedScrollPositions) {\n      let key = getScrollKey(location, matches);\n      let y = savedScrollPositions[key];\n      if (typeof y === \"number\") {\n        return y;\n      }\n    }\n    return null;\n  }\n\n  function checkFogOfWar(\n    matches: AgnosticDataRouteMatch[] | null,\n    routesToUse: AgnosticDataRouteObject[],\n    pathname: string\n  ): { active: boolean; matches: AgnosticDataRouteMatch[] | null } {\n    if (patchRoutesOnNavigationImpl) {\n      if (!matches) {\n        let fogMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n          routesToUse,\n          pathname,\n          basename,\n          true\n        );\n\n        return { active: true, matches: fogMatches || [] };\n      } else {\n        if (Object.keys(matches[0].params).length > 0) {\n          // If we matched a dynamic param or a splat, it might only be because\n          // we haven't yet discovered other routes that would match with a\n          // higher score.  Call patchRoutesOnNavigation just to be sure\n          let partialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n            routesToUse,\n            pathname,\n            basename,\n            true\n          );\n          return { active: true, matches: partialMatches };\n        }\n      }\n    }\n\n    return { active: false, matches: null };\n  }\n\n  type DiscoverRoutesSuccessResult = {\n    type: \"success\";\n    matches: AgnosticDataRouteMatch[] | null;\n  };\n  type DiscoverRoutesErrorResult = {\n    type: \"error\";\n    error: any;\n    partialMatches: AgnosticDataRouteMatch[];\n  };\n  type DiscoverRoutesAbortedResult = { type: \"aborted\" };\n  type DiscoverRoutesResult =\n    | DiscoverRoutesSuccessResult\n    | DiscoverRoutesErrorResult\n    | DiscoverRoutesAbortedResult;\n\n  async function discoverRoutes(\n    matches: AgnosticDataRouteMatch[],\n    pathname: string,\n    signal: AbortSignal\n  ): Promise<DiscoverRoutesResult> {\n    if (!patchRoutesOnNavigationImpl) {\n      return { type: \"success\", matches };\n    }\n\n    let partialMatches: AgnosticDataRouteMatch[] | null = matches;\n    while (true) {\n      let isNonHMR = inFlightDataRoutes == null;\n      let routesToUse = inFlightDataRoutes || dataRoutes;\n      let localManifest = manifest;\n      try {\n        await patchRoutesOnNavigationImpl({\n          path: pathname,\n          matches: partialMatches,\n          patch: (routeId, children) => {\n            if (signal.aborted) return;\n            patchRoutesImpl(\n              routeId,\n              children,\n              routesToUse,\n              localManifest,\n              mapRouteProperties\n            );\n          },\n        });\n      } catch (e) {\n        return { type: \"error\", error: e, partialMatches };\n      } finally {\n        // If we are not in the middle of an HMR revalidation and we changed the\n        // routes, provide a new identity so when we `updateState` at the end of\n        // this navigation/fetch `router.routes` will be a new identity and\n        // trigger a re-run of memoized `router.routes` dependencies.\n        // HMR will already update the identity and reflow when it lands\n        // `inFlightDataRoutes` in `completeNavigation`\n        if (isNonHMR && !signal.aborted) {\n          dataRoutes = [...dataRoutes];\n        }\n      }\n\n      if (signal.aborted) {\n        return { type: \"aborted\" };\n      }\n\n      let newMatches = matchRoutes(routesToUse, pathname, basename);\n      if (newMatches) {\n        return { type: \"success\", matches: newMatches };\n      }\n\n      let newPartialMatches = matchRoutesImpl<AgnosticDataRouteObject>(\n        routesToUse,\n        pathname,\n        basename,\n        true\n      );\n\n      // Avoid loops if the second pass results in the same partial matches\n      if (\n        !newPartialMatches ||\n        (partialMatches.length === newPartialMatches.length &&\n          partialMatches.every(\n            (m, i) => m.route.id === newPartialMatches![i].route.id\n          ))\n      ) {\n        return { type: \"success\", matches: null };\n      }\n\n      partialMatches = newPartialMatches;\n    }\n  }\n\n  function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n    manifest = {};\n    inFlightDataRoutes = convertRoutesToDataRoutes(\n      newRoutes,\n      mapRouteProperties,\n      undefined,\n      manifest\n    );\n  }\n\n  function patchRoutes(\n    routeId: string | null,\n    children: AgnosticRouteObject[]\n  ): void {\n    let isNonHMR = inFlightDataRoutes == null;\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    patchRoutesImpl(\n      routeId,\n      children,\n      routesToUse,\n      manifest,\n      mapRouteProperties\n    );\n\n    // If we are not in the middle of an HMR revalidation and we changed the\n    // routes, provide a new identity and trigger a reflow via `updateState`\n    // to re-run memoized `router.routes` dependencies.\n    // HMR will already update the identity and reflow when it lands\n    // `inFlightDataRoutes` in `completeNavigation`\n    if (isNonHMR) {\n      dataRoutes = [...dataRoutes];\n      updateState({});\n    }\n  }\n\n  router = {\n    get basename() {\n      return basename;\n    },\n    get future() {\n      return future;\n    },\n    get state() {\n      return state;\n    },\n    get routes() {\n      return dataRoutes;\n    },\n    get window() {\n      return routerWindow;\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: deleteFetcherAndUpdateState,\n    dispose,\n    getBlocker,\n    deleteBlocker,\n    patchRoutes,\n    _internalFetchControllers: fetchControllers,\n    _internalActiveDeferreds: activeDeferreds,\n    // TODO: Remove setRoutes, it's temporary to avoid dealing with\n    // updating the tree while validating the update algorithm.\n    _internalSetRoutes,\n  };\n\n  return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_throwAbortReason: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n  basename?: string;\n  /**\n   * @deprecated Use `mapRouteProperties` instead\n   */\n  detectErrorBoundary?: DetectErrorBoundaryFunction;\n  mapRouteProperties?: MapRoutePropertiesFunction;\n  future?: Partial<StaticHandlerFutureConfig>;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length > 0,\n    \"You must provide a non-empty routes array to createStaticHandler\"\n  );\n\n  let manifest: RouteManifest = {};\n  let basename = (opts ? opts.basename : null) || \"/\";\n  let mapRouteProperties: MapRoutePropertiesFunction;\n  if (opts?.mapRouteProperties) {\n    mapRouteProperties = opts.mapRouteProperties;\n  } else if (opts?.detectErrorBoundary) {\n    // If they are still using the deprecated version, wrap it with the new API\n    let detectErrorBoundary = opts.detectErrorBoundary;\n    mapRouteProperties = (route) => ({\n      hasErrorBoundary: detectErrorBoundary(route),\n    });\n  } else {\n    mapRouteProperties = defaultMapRouteProperties;\n  }\n  // Config driven behavior flags\n  let future: StaticHandlerFutureConfig = {\n    v7_relativeSplatPath: false,\n    v7_throwAbortReason: false,\n    ...(opts ? opts.future : null),\n  };\n\n  let dataRoutes = convertRoutesToDataRoutes(\n    routes,\n    mapRouteProperties,\n    undefined,\n    manifest\n  );\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   * - `opts.requestContext` is an optional server context that will be passed\n   *   to actions/loaders in the `context` parameter\n   * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n   *   the bubbling of errors which allows single-fetch-type implementations\n   *   where the client will handle the bubbling and we may need to return data\n   *   for the handling route\n   */\n  async function query(\n    request: Request,\n    {\n      requestContext,\n      skipLoaderErrorBubbling,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      skipLoaderErrorBubbling?: boolean;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<StaticHandlerContext | Response> {\n    let url = new URL(request.url);\n    let method = request.method;\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        activeDeferreds: null,\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        activeDeferreds: null,\n      };\n    }\n\n    let result = await queryImpl(\n      request,\n      location,\n      matches,\n      requestContext,\n      dataStrategy || null,\n      skipLoaderErrorBubbling === true,\n      null\n    );\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   * - `opts.routeId` allows you to specify the specific route handler to call.\n   *   If not provided the handler will determine the proper route by matching\n   *   against `request.url`\n   * - `opts.requestContext` is an optional server context that will be passed\n   *    to actions/loaders in the `context` parameter\n   */\n  async function queryRoute(\n    request: Request,\n    {\n      routeId,\n      requestContext,\n      dataStrategy,\n    }: {\n      requestContext?: unknown;\n      routeId?: string;\n      dataStrategy?: DataStrategyFunction;\n    } = {}\n  ): Promise<any> {\n    let url = new URL(request.url);\n    let method = request.method;\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\" && method !== \"OPTIONS\") {\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      dataStrategy || null,\n      false,\n      match\n    );\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    if (result.actionData) {\n      return Object.values(result.actionData)[0];\n    }\n\n    if (result.loaderData) {\n      let data = Object.values(result.loaderData)[0];\n      if (result.activeDeferreds?.[match.route.id]) {\n        data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n      }\n      return data;\n    }\n\n    return undefined;\n  }\n\n  async function queryImpl(\n    request: Request,\n    location: Location,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null\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          dataStrategy,\n          skipLoaderErrorBubbling,\n          routeMatch != null\n        );\n        return result;\n      }\n\n      let result = await loadRouteData(\n        request,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\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 for a\n      // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n      // and then return or throw the raw Response here accordingly\n      if (isDataStrategyResult(e) && isResponse(e.result)) {\n        if (e.type === ResultType.error) {\n          throw e.result;\n        }\n        return e.result;\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    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    isRouteRequest: boolean\n  ): Promise<Omit<StaticHandlerContext, \"location\" | \"basename\"> | Response> {\n    let result: DataResult;\n\n    if (!actionMatch.route.action && !actionMatch.route.lazy) {\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      let results = await callDataStrategy(\n        \"action\",\n        request,\n        [actionMatch],\n        matches,\n        isRouteRequest,\n        requestContext,\n        dataStrategy\n      );\n      result = results[actionMatch.route.id];\n\n      if (request.signal.aborted) {\n        throwStaticHandlerAbortedError(request, isRouteRequest, future);\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.response.status,\n        headers: {\n          Location: result.response.headers.get(\"Location\")!,\n        },\n      });\n    }\n\n    if (isDeferredResult(result)) {\n      let error = getInternalRouterError(400, { type: \"defer-action\" });\n      if (isRouteRequest) {\n        throw error;\n      }\n      result = {\n        type: ResultType.error,\n        error,\n      };\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        activeDeferreds: null,\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\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 = skipLoaderErrorBubbling\n        ? actionMatch\n        : findNearestBoundary(matches, actionMatch.route.id);\n\n      let context = await loadRouteData(\n        loaderRequest,\n        matches,\n        requestContext,\n        dataStrategy,\n        skipLoaderErrorBubbling,\n        null,\n        [boundaryMatch.route.id, result]\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          : result.statusCode != null\n          ? result.statusCode\n          : 500,\n        actionData: null,\n        actionHeaders: {\n          ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n        },\n      };\n    }\n\n    let context = await loadRouteData(\n      loaderRequest,\n      matches,\n      requestContext,\n      dataStrategy,\n      skipLoaderErrorBubbling,\n      null\n    );\n\n    return {\n      ...context,\n      actionData: {\n        [actionMatch.route.id]: result.data,\n      },\n      // action status codes take precedence over loader status codes\n      ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n      actionHeaders: result.headers\n        ? { [actionMatch.route.id]: result.headers }\n        : {},\n    };\n  }\n\n  async function loadRouteData(\n    request: Request,\n    matches: AgnosticDataRouteMatch[],\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null,\n    skipLoaderErrorBubbling: boolean,\n    routeMatch: AgnosticDataRouteMatch | null,\n    pendingActionResult?: PendingActionResult\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 (\n      isRouteRequest &&\n      !routeMatch?.route.loader &&\n      !routeMatch?.route.lazy\n    ) {\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      : pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) => m.route.loader || m.route.lazy\n    );\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:\n          pendingActionResult && isErrorResult(pendingActionResult[1])\n            ? {\n                [pendingActionResult[0]]: pendingActionResult[1].error,\n              }\n            : null,\n        statusCode: 200,\n        loaderHeaders: {},\n        activeDeferreds: null,\n      };\n    }\n\n    let results = await callDataStrategy(\n      \"loader\",\n      request,\n      matchesToLoad,\n      matches,\n      isRouteRequest,\n      requestContext,\n      dataStrategy\n    );\n\n    if (request.signal.aborted) {\n      throwStaticHandlerAbortedError(request, isRouteRequest, future);\n    }\n\n    // Process and commit output from loaders\n    let activeDeferreds = new Map<string, DeferredData>();\n    let context = processRouteLoaderData(\n      matches,\n      results,\n      pendingActionResult,\n      activeDeferreds,\n      skipLoaderErrorBubbling\n    );\n\n    // Add a null for any non-loader matches for proper revalidation on the client\n    let executedLoaders = new Set<string>(\n      matchesToLoad.map((match) => match.route.id)\n    );\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      activeDeferreds:\n        activeDeferreds.size > 0\n          ? Object.fromEntries(activeDeferreds.entries())\n          : null,\n    };\n  }\n\n  // Utility wrapper for calling dataStrategy server-side without having to\n  // pass around the manifest, mapRouteProperties, etc.\n  async function callDataStrategy(\n    type: \"loader\" | \"action\",\n    request: Request,\n    matchesToLoad: AgnosticDataRouteMatch[],\n    matches: AgnosticDataRouteMatch[],\n    isRouteRequest: boolean,\n    requestContext: unknown,\n    dataStrategy: DataStrategyFunction | null\n  ): Promise<Record<string, DataResult>> {\n    let results = await callDataStrategyImpl(\n      dataStrategy || defaultDataStrategy,\n      type,\n      null,\n      request,\n      matchesToLoad,\n      matches,\n      null,\n      manifest,\n      mapRouteProperties,\n      requestContext\n    );\n\n    let dataResults: Record<string, DataResult> = {};\n    await Promise.all(\n      matches.map(async (match) => {\n        if (!(match.route.id in results)) {\n          return;\n        }\n        let result = results[match.route.id];\n        if (isRedirectDataStrategyResultResult(result)) {\n          let response = result.result as Response;\n          // Throw redirects and let the server handle them with an HTTP redirect\n          throw normalizeRelativeRoutingRedirectResponse(\n            response,\n            request,\n            match.route.id,\n            matches,\n            basename,\n            future.v7_relativeSplatPath\n          );\n        }\n        if (isResponse(result.result) && isRouteRequest) {\n          // For SSR single-route requests, we want to hand Responses back\n          // directly without unwrapping\n          throw result;\n        }\n\n        dataResults[match.route.id] =\n          await convertDataStrategyResultToDataResult(result);\n      })\n    );\n    return dataResults;\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: isRouteErrorResponse(error) ? error.status : 500,\n    errors: {\n      [context._deepestRenderedBoundaryId || routes[0].id]: error,\n    },\n  };\n  return newContext;\n}\n\nfunction throwStaticHandlerAbortedError(\n  request: Request,\n  isRouteRequest: boolean,\n  future: StaticHandlerFutureConfig\n) {\n  if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n    throw request.signal.reason;\n  }\n\n  let method = isRouteRequest ? \"queryRoute\" : \"query\";\n  throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);\n}\n\nfunction isSubmissionNavigation(\n  opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n  return (\n    opts != null &&\n    ((\"formData\" in opts && opts.formData != null) ||\n      (\"body\" in opts && opts.body !== undefined))\n  );\n}\n\nfunction normalizeTo(\n  location: Path,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  prependBasename: boolean,\n  to: To | null,\n  v7_relativeSplatPath: boolean,\n  fromRouteId?: string,\n  relative?: RelativeRoutingType\n) {\n  let contextualMatches: AgnosticDataRouteMatch[];\n  let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n  if (fromRouteId) {\n    // Grab matches up to the calling route so our route-relative logic is\n    // relative to the correct source route\n    contextualMatches = [];\n    for (let match of matches) {\n      contextualMatches.push(match);\n      if (match.route.id === fromRouteId) {\n        activeRouteMatch = match;\n        break;\n      }\n    }\n  } else {\n    contextualMatches = matches;\n    activeRouteMatch = matches[matches.length - 1];\n  }\n\n  // Resolve the relative path\n  let path = resolveTo(\n    to ? to : \".\",\n    getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n    stripBasename(location.pathname, basename) || location.pathname,\n    relative === \"path\"\n  );\n\n  // When `to` is not specified we inherit search/hash from the current\n  // location, unlike when to=\".\" and we just inherit the path.\n  // See https://github.com/remix-run/remix/issues/927\n  if (to == null) {\n    path.search = location.search;\n    path.hash = location.hash;\n  }\n\n  // Account for `?index` params when routing to the current location\n  if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n    let nakedIndex = hasNakedIndexQuery(path.search);\n    if (activeRouteMatch.route.index && !nakedIndex) {\n      // Add one when we're targeting an index route\n      path.search = path.search\n        ? path.search.replace(/^\\?/, \"?index&\")\n        : \"?index\";\n    } else if (!activeRouteMatch.route.index && nakedIndex) {\n      // Remove existing ones when we're not\n      let params = new URLSearchParams(path.search);\n      let indexValues = params.getAll(\"index\");\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  // If we're operating within a basename, prepend it to the pathname.  If\n  // this is a root navigation, then just use the raw basename which allows\n  // the basename to have full control over the presence of a trailing slash\n  // on root actions\n  if (prependBasename && basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\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  normalizeFormMethod: boolean,\n  isFetcher: boolean,\n  path: string,\n  opts?: BaseNavigateOrFetchOptions\n): {\n  path: string;\n  submission?: Submission;\n  error?: ErrorResponseImpl;\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  let getInvalidBodyError = () => ({\n    path,\n    error: getInternalRouterError(400, { type: \"invalid-body\" }),\n  });\n\n  // Create a Submission on non-GET navigations\n  let rawFormMethod = opts.formMethod || \"get\";\n  let formMethod = normalizeFormMethod\n    ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n    : (rawFormMethod.toLowerCase() as FormMethod);\n  let formAction = stripHashFromPath(path);\n\n  if (opts.body !== undefined) {\n    if (opts.formEncType === \"text/plain\") {\n      // text only support POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      let text =\n        typeof opts.body === \"string\"\n          ? opts.body\n          : opts.body instanceof FormData ||\n            opts.body instanceof URLSearchParams\n          ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n            Array.from(opts.body.entries()).reduce(\n              (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n              \"\"\n            )\n          : String(opts.body);\n\n      return {\n        path,\n        submission: {\n          formMethod,\n          formAction,\n          formEncType: opts.formEncType,\n          formData: undefined,\n          json: undefined,\n          text,\n        },\n      };\n    } else if (opts.formEncType === \"application/json\") {\n      // json only supports POST/PUT/PATCH/DELETE submissions\n      if (!isMutationMethod(formMethod)) {\n        return getInvalidBodyError();\n      }\n\n      try {\n        let json =\n          typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n        return {\n          path,\n          submission: {\n            formMethod,\n            formAction,\n            formEncType: opts.formEncType,\n            formData: undefined,\n            json,\n            text: undefined,\n          },\n        };\n      } catch (e) {\n        return getInvalidBodyError();\n      }\n    }\n  }\n\n  invariant(\n    typeof FormData === \"function\",\n    \"FormData is not available in this environment\"\n  );\n\n  let searchParams: URLSearchParams;\n  let formData: FormData;\n\n  if (opts.formData) {\n    searchParams = convertFormDataToSearchParams(opts.formData);\n    formData = opts.formData;\n  } else if (opts.body instanceof FormData) {\n    searchParams = convertFormDataToSearchParams(opts.body);\n    formData = opts.body;\n  } else if (opts.body instanceof URLSearchParams) {\n    searchParams = opts.body;\n    formData = convertSearchParamsToFormData(searchParams);\n  } else if (opts.body == null) {\n    searchParams = new URLSearchParams();\n    formData = new FormData();\n  } else {\n    try {\n      searchParams = new URLSearchParams(opts.body);\n      formData = convertSearchParamsToFormData(searchParams);\n    } catch (e) {\n      return getInvalidBodyError();\n    }\n  }\n\n  let submission: Submission = {\n    formMethod,\n    formAction,\n    formEncType:\n      (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n    formData,\n    json: undefined,\n    text: undefined,\n  };\n\n  if (isMutationMethod(submission.formMethod)) {\n    return { path, submission };\n  }\n\n  // Flatten submission onto URLSearchParams for GET submissions\n  let parsedPath = parsePath(path);\n  // On GET navigation submissions we can drop the ?index param from the\n  // resulting location since all loaders will run.  But fetcher GET submissions\n  // only run a single loader so we need to preserve any incoming ?index params\n  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n    searchParams.append(\"index\", \"\");\n  }\n  parsedPath.search = `?${searchParams}`;\n\n  return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes at/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  includeBoundary = false\n) {\n  let index = matches.findIndex((m) => m.route.id === boundaryId);\n  if (index >= 0) {\n    return matches.slice(0, includeBoundary ? index + 1 : index);\n  }\n  return matches;\n}\n\nfunction getMatchesToLoad(\n  history: History,\n  state: RouterState,\n  matches: AgnosticDataRouteMatch[],\n  submission: Submission | undefined,\n  location: Location,\n  initialHydration: boolean,\n  skipActionErrorRevalidation: boolean,\n  isRevalidationRequired: boolean,\n  cancelledDeferredRoutes: string[],\n  cancelledFetcherLoads: Set<string>,\n  deletedFetchers: Set<string>,\n  fetchLoadMatches: Map<string, FetchLoadMatch>,\n  fetchRedirectIds: Set<string>,\n  routesToUse: AgnosticDataRouteObject[],\n  basename: string | undefined,\n  pendingActionResult?: PendingActionResult\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n  let actionResult = pendingActionResult\n    ? isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : pendingActionResult[1].data\n    : undefined;\n  let currentUrl = history.createURL(state.location);\n  let nextUrl = history.createURL(location);\n\n  // Pick navigation matches that are net-new or qualify for revalidation\n  let boundaryMatches = matches;\n  if (initialHydration && state.errors) {\n    // On initial hydration, only consider matches up to _and including_ the boundary.\n    // This is inclusive to handle cases where a server loader ran successfully,\n    // a child server loader bubbled up to this route, but this route has\n    // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n    // we have a complete version of `loaderData`\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      Object.keys(state.errors)[0],\n      true\n    );\n  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n    // If an action threw an error, we call loaders up to, but not including the\n    // boundary\n    boundaryMatches = getLoaderMatchesUntilBoundary(\n      matches,\n      pendingActionResult[0]\n    );\n  }\n\n  // Don't revalidate loaders by default after action 4xx/5xx responses\n  // when the flag is enabled.  They can still opt-into revalidation via\n  // `shouldRevalidate` via `actionResult`\n  let actionStatus = pendingActionResult\n    ? pendingActionResult[1].statusCode\n    : undefined;\n  let shouldSkipRevalidation =\n    skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) => {\n    let { route } = match;\n    if (route.lazy) {\n      // We haven't loaded this route yet so we don't know if it's got a loader!\n      return true;\n    }\n\n    if (route.loader == null) {\n      return false;\n    }\n\n    if (initialHydration) {\n      return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n    }\n\n    // Always call the loader on new route instances and pending defer cancellations\n    if (\n      isNewLoader(state.loaderData, state.matches[index], match) ||\n      cancelledDeferredRoutes.some((id) => id === match.route.id)\n    ) {\n      return true;\n    }\n\n    // This is the default implementation for 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    let currentRouteMatch = state.matches[index];\n    let nextRouteMatch = match;\n\n    return shouldRevalidateLoader(match, {\n      currentUrl,\n      currentParams: currentRouteMatch.params,\n      nextUrl,\n      nextParams: nextRouteMatch.params,\n      ...submission,\n      actionResult,\n      actionStatus,\n      defaultShouldRevalidate: shouldSkipRevalidation\n        ? false\n        : // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n          isRevalidationRequired ||\n          currentUrl.pathname + currentUrl.search ===\n            nextUrl.pathname + nextUrl.search ||\n          // Search params affect all loaders\n          currentUrl.search !== nextUrl.search ||\n          isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n    });\n  });\n\n  // Pick fetcher.loads that need to be revalidated\n  let revalidatingFetchers: RevalidatingFetcher[] = [];\n  fetchLoadMatches.forEach((f, key) => {\n    // Don't revalidate:\n    //  - on initial hydration (shouldn't be any fetchers then anyway)\n    //  - if fetcher won't be present in the subsequent render\n    //    - no longer matches the URL (v7_fetcherPersist=false)\n    //    - was unmounted but persisted due to v7_fetcherPersist=true\n    if (\n      initialHydration ||\n      !matches.some((m) => m.route.id === f.routeId) ||\n      deletedFetchers.has(key)\n    ) {\n      return;\n    }\n\n    let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n    // If the fetcher path no longer matches, push it in with null matches so\n    // we can trigger a 404 in callLoadersAndMaybeResolveData.  Note this is\n    // currently only a use-case for Remix HMR where the route tree can change\n    // at runtime and remove a route previously loaded via a fetcher\n    if (!fetcherMatches) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: null,\n        match: null,\n        controller: null,\n      });\n      return;\n    }\n\n    // Revalidating fetchers are decoupled from the route matches since they\n    // load from a static href.  They revalidate based on explicit revalidation\n    // (submission, useRevalidator, or X-Remix-Revalidate)\n    let fetcher = state.fetchers.get(key);\n    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n    let shouldRevalidate = false;\n    if (fetchRedirectIds.has(key)) {\n      // Never trigger a revalidation of an actively redirecting fetcher\n      shouldRevalidate = false;\n    } else if (cancelledFetcherLoads.has(key)) {\n      // Always mark for revalidation if the fetcher was cancelled\n      cancelledFetcherLoads.delete(key);\n      shouldRevalidate = true;\n    } else if (\n      fetcher &&\n      fetcher.state !== \"idle\" &&\n      fetcher.data === undefined\n    ) {\n      // If the fetcher hasn't ever completed loading yet, then this isn't a\n      // revalidation, it would just be a brand new load if an explicit\n      // revalidation is required\n      shouldRevalidate = isRevalidationRequired;\n    } else {\n      // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n      // to explicit revalidations only\n      shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n        currentUrl,\n        currentParams: state.matches[state.matches.length - 1].params,\n        nextUrl,\n        nextParams: matches[matches.length - 1].params,\n        ...submission,\n        actionResult,\n        actionStatus,\n        defaultShouldRevalidate: shouldSkipRevalidation\n          ? false\n          : isRevalidationRequired,\n      });\n    }\n\n    if (shouldRevalidate) {\n      revalidatingFetchers.push({\n        key,\n        routeId: f.routeId,\n        path: f.path,\n        matches: fetcherMatches,\n        match: fetcherMatch,\n        controller: new AbortController(),\n      });\n    }\n  });\n\n  return [navigationMatches, revalidatingFetchers];\n}\n\nfunction shouldLoadRouteOnHydration(\n  route: AgnosticDataRouteObject,\n  loaderData: RouteData | null | undefined,\n  errors: RouteData | null | undefined\n) {\n  // We dunno if we have a loader - gotta find out!\n  if (route.lazy) {\n    return true;\n  }\n\n  // No loader, nothing to initialize\n  if (!route.loader) {\n    return false;\n  }\n\n  let hasData = loaderData != null && loaderData[route.id] !== undefined;\n  let hasError = errors != null && errors[route.id] !== undefined;\n\n  // Don't run if we error'd during SSR\n  if (!hasData && hasError) {\n    return false;\n  }\n\n  // Explicitly opting-in to running on hydration\n  if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n    return true;\n  }\n\n  // Otherwise, run if we're not yet initialized with anything\n  return !hasData && !hasError;\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 != null &&\n      currentPath.endsWith(\"*\") &&\n      currentMatch.params[\"*\"] !== match.params[\"*\"])\n  );\n}\n\nfunction shouldRevalidateLoader(\n  loaderMatch: AgnosticDataRouteMatch,\n  arg: ShouldRevalidateFunctionArgs\n) {\n  if (loaderMatch.route.shouldRevalidate) {\n    let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n    if (typeof routeChoice === \"boolean\") {\n      return routeChoice;\n    }\n  }\n\n  return arg.defaultShouldRevalidate;\n}\n\nfunction patchRoutesImpl(\n  routeId: string | null,\n  children: AgnosticRouteObject[],\n  routesToUse: AgnosticDataRouteObject[],\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction\n) {\n  let childrenToPatch: AgnosticDataRouteObject[];\n  if (routeId) {\n    let route = manifest[routeId];\n    invariant(\n      route,\n      `No route found to patch children into: routeId = ${routeId}`\n    );\n    if (!route.children) {\n      route.children = [];\n    }\n    childrenToPatch = route.children;\n  } else {\n    childrenToPatch = routesToUse;\n  }\n\n  // Don't patch in routes we already know about so that `patch` is idempotent\n  // to simplify user-land code. This is useful because we re-call the\n  // `patchRoutesOnNavigation` function for matched routes with params.\n  let uniqueChildren = children.filter(\n    (newRoute) =>\n      !childrenToPatch.some((existingRoute) =>\n        isSameRoute(newRoute, existingRoute)\n      )\n  );\n\n  let newRoutes = convertRoutesToDataRoutes(\n    uniqueChildren,\n    mapRouteProperties,\n    [routeId || \"_\", \"patch\", String(childrenToPatch?.length || \"0\")],\n    manifest\n  );\n\n  childrenToPatch.push(...newRoutes);\n}\n\nfunction isSameRoute(\n  newRoute: AgnosticRouteObject,\n  existingRoute: AgnosticRouteObject\n): boolean {\n  // Most optimal check is by id\n  if (\n    \"id\" in newRoute &&\n    \"id\" in existingRoute &&\n    newRoute.id === existingRoute.id\n  ) {\n    return true;\n  }\n\n  // Second is by pathing differences\n  if (\n    !(\n      newRoute.index === existingRoute.index &&\n      newRoute.path === existingRoute.path &&\n      newRoute.caseSensitive === existingRoute.caseSensitive\n    )\n  ) {\n    return false;\n  }\n\n  // Pathless layout routes are trickier since we need to check children.\n  // If they have no children then they're the same as far as we can tell\n  if (\n    (!newRoute.children || newRoute.children.length === 0) &&\n    (!existingRoute.children || existingRoute.children.length === 0)\n  ) {\n    return true;\n  }\n\n  // Otherwise, we look to see if every child in the new route is already\n  // represented in the existing route's children\n  return newRoute.children!.every((aChild, i) =>\n    existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))\n  );\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n  route: AgnosticDataRouteObject,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  manifest: RouteManifest\n) {\n  if (!route.lazy) {\n    return;\n  }\n\n  let lazyRoute = await route.lazy();\n\n  // If the lazy route function was executed and removed by another parallel\n  // call then we can return - first lazy() to finish wins because the return\n  // value of lazy is expected to be static\n  if (!route.lazy) {\n    return;\n  }\n\n  let routeToUpdate = manifest[route.id];\n  invariant(routeToUpdate, \"No route found in manifest\");\n\n  // Update the route in place.  This should be safe because there's no way\n  // we could yet be sitting on this route as we can't get there without\n  // resolving lazy() first.\n  //\n  // This is different than the HMR \"update\" use-case where we may actively be\n  // on the route being updated.  The main concern boils down to \"does this\n  // mutation affect any ongoing navigations or any current state.matches\n  // values?\".  If not, it should be safe to update in place.\n  let routeUpdates: Record<string, any> = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined &&\n      // This property isn't static since it should always be updated based\n      // on the route updates\n      lazyRouteProperty !== \"hasErrorBoundary\";\n\n    warning(\n      !isPropertyStaticallyDefined,\n      `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n        `defined but its lazy function is also returning a value for this property. ` +\n        `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n    );\n\n    if (\n      !isPropertyStaticallyDefined &&\n      !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n    ) {\n      routeUpdates[lazyRouteProperty] =\n        lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n    }\n  }\n\n  // Mutate the route with the provided updates.  Do this first so we pass\n  // the updated version to mapRouteProperties\n  Object.assign(routeToUpdate, routeUpdates);\n\n  // Mutate the `hasErrorBoundary` property on the route based on the route\n  // updates and remove the `lazy` function so we don't resolve the lazy\n  // route again.\n  Object.assign(routeToUpdate, {\n    // To keep things framework agnostic, we use the provided\n    // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n    // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n    // the logic will differ between frameworks.\n    ...mapRouteProperties(routeToUpdate),\n    lazy: undefined,\n  });\n}\n\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy({\n  matches,\n}: DataStrategyFunctionArgs): ReturnType<DataStrategyFunction> {\n  let matchesToLoad = matches.filter((m) => m.shouldLoad);\n  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));\n  return results.reduce(\n    (acc, result, i) =>\n      Object.assign(acc, { [matchesToLoad[i].route.id]: result }),\n    {}\n  );\n}\n\nasync function callDataStrategyImpl(\n  dataStrategyImpl: DataStrategyFunction,\n  type: \"loader\" | \"action\",\n  state: RouterState | null,\n  request: Request,\n  matchesToLoad: AgnosticDataRouteMatch[],\n  matches: AgnosticDataRouteMatch[],\n  fetcherKey: string | null,\n  manifest: RouteManifest,\n  mapRouteProperties: MapRoutePropertiesFunction,\n  requestContext?: unknown\n): Promise<Record<string, DataStrategyResult>> {\n  let loadRouteDefinitionsPromises = matches.map((m) =>\n    m.route.lazy\n      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n      : undefined\n  );\n\n  let dsMatches = matches.map((match, i) => {\n    let loadRoutePromise = loadRouteDefinitionsPromises[i];\n    let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);\n    // `resolve` encapsulates route.lazy(), executing the loader/action,\n    // and mapping return values/thrown errors to a `DataStrategyResult`.  Users\n    // can pass a callback to take fine-grained control over the execution\n    // of the loader/action\n    let resolve: DataStrategyMatch[\"resolve\"] = async (handlerOverride) => {\n      if (\n        handlerOverride &&\n        request.method === \"GET\" &&\n        (match.route.lazy || match.route.loader)\n      ) {\n        shouldLoad = true;\n      }\n      return shouldLoad\n        ? callLoaderOrAction(\n            type,\n            request,\n            match,\n            loadRoutePromise,\n            handlerOverride,\n            requestContext\n          )\n        : Promise.resolve({ type: ResultType.data, result: undefined });\n    };\n\n    return {\n      ...match,\n      shouldLoad,\n      resolve,\n    };\n  });\n\n  // Send all matches here to allow for a middleware-type implementation.\n  // handler will be a no-op for unneeded routes and we filter those results\n  // back out below.\n  let results = await dataStrategyImpl({\n    matches: dsMatches,\n    request,\n    params: matches[0].params,\n    fetcherKey,\n    context: requestContext,\n  });\n\n  // Wait for all routes to load here but 'swallow the error since we want\n  // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n  // called from `match.resolve()`\n  try {\n    await Promise.all(loadRouteDefinitionsPromises);\n  } catch (e) {\n    // No-op\n  }\n\n  return results;\n}\n\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(\n  type: \"loader\" | \"action\",\n  request: Request,\n  match: AgnosticDataRouteMatch,\n  loadRoutePromise: Promise<void> | undefined,\n  handlerOverride: Parameters<DataStrategyMatch[\"resolve\"]>[0],\n  staticContext?: unknown\n): Promise<DataStrategyResult> {\n  let result: DataStrategyResult;\n  let onReject: (() => void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise<DataStrategyResult> => {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () => void;\n    // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n    // satisfy the function return value\n    let abortPromise = new Promise<DataStrategyResult>((_, r) => (reject = r));\n    onReject = () => reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) => {\n      if (typeof handler !== \"function\") {\n        return Promise.reject(\n          new Error(\n            `You cannot call the handler for a route which defines a boolean ` +\n              `\"${type}\" [routeId: ${match.route.id}]`\n          )\n        );\n      }\n      return handler(\n        {\n          request,\n          params: match.params,\n          context: staticContext,\n        },\n        ...(ctx !== undefined ? [ctx] : [])\n      );\n    };\n\n    let handlerPromise: Promise<DataStrategyResult> = (async () => {\n      try {\n        let val = await (handlerOverride\n          ? handlerOverride((ctx: unknown) => actualHandler(ctx))\n          : actualHandler());\n        return { type: \"data\", result: val };\n      } catch (e) {\n        return { type: \"error\", result: e };\n      }\n    })();\n\n    return Promise.race([handlerPromise, abortPromise]);\n  };\n\n  try {\n    let handler = match.route[type];\n\n    // If we have a route.lazy promise, await that first\n    if (loadRoutePromise) {\n      if (handler) {\n        // Run statically defined handler in parallel with lazy()\n        let handlerError;\n        let [value] = await Promise.all([\n          // If the handler throws, don't let it immediately bubble out,\n          // since we need to let the lazy() execution finish so we know if this\n          // route has a boundary that can handle the error\n          runHandler(handler).catch((e) => {\n            handlerError = e;\n          }),\n          loadRoutePromise,\n        ]);\n        if (handlerError !== undefined) {\n          throw handlerError;\n        }\n        result = value!;\n      } else {\n        // Load lazy route module, then run any returned handler\n        await loadRoutePromise;\n\n        handler = match.route[type];\n        if (handler) {\n          // Handler still runs even if we got interrupted to maintain consistency\n          // with un-abortable behavior of handler execution on non-lazy or\n          // previously-lazy-loaded routes\n          result = await runHandler(handler);\n        } else if (type === \"action\") {\n          let url = new URL(request.url);\n          let pathname = url.pathname + url.search;\n          throw getInternalRouterError(405, {\n            method: request.method,\n            pathname,\n            routeId: match.route.id,\n          });\n        } else {\n          // lazy() route has no loader to run.  Short circuit here so we don't\n          // hit the invariant below that errors on returning undefined.\n          return { type: ResultType.data, result: undefined };\n        }\n      }\n    } else if (!handler) {\n      let url = new URL(request.url);\n      let pathname = url.pathname + url.search;\n      throw getInternalRouterError(404, {\n        pathname,\n      });\n    } else {\n      result = await runHandler(handler);\n    }\n\n    invariant(\n      result.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    // We should already be catching and converting normal handler executions to\n    // DataStrategyResults and returning them, so anything that throws here is an\n    // unexpected error we still need to wrap\n    return { type: ResultType.error, result: e };\n  } finally {\n    if (onReject) {\n      request.signal.removeEventListener(\"abort\", onReject);\n    }\n  }\n\n  return result;\n}\n\nasync function convertDataStrategyResultToDataResult(\n  dataStrategyResult: DataStrategyResult\n): Promise<DataResult> {\n  let { result, type } = dataStrategyResult;\n\n  if (isResponse(result)) {\n    let data: any;\n\n    try {\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        if (result.body == null) {\n          data = null;\n        } else {\n          data = await result.json();\n        }\n      } else {\n        data = await result.text();\n      }\n    } catch (e) {\n      return { type: ResultType.error, error: e };\n    }\n\n    if (type === ResultType.error) {\n      return {\n        type: ResultType.error,\n        error: new ErrorResponseImpl(result.status, result.statusText, data),\n        statusCode: result.status,\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 (type === ResultType.error) {\n    if (isDataWithResponseInit(result)) {\n      if (result.data instanceof Error) {\n        return {\n          type: ResultType.error,\n          error: result.data,\n          statusCode: result.init?.status,\n        };\n      }\n\n      // Convert thrown data() to ErrorResponse instances\n      result = new ErrorResponseImpl(\n        result.init?.status || 500,\n        undefined,\n        result.data\n      );\n    }\n    return {\n      type: ResultType.error,\n      error: result,\n      statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n    };\n  }\n\n  if (isDeferredData(result)) {\n    return {\n      type: ResultType.deferred,\n      deferredData: result,\n      statusCode: result.init?.status,\n      headers: result.init?.headers && new Headers(result.init.headers),\n    };\n  }\n\n  if (isDataWithResponseInit(result)) {\n    return {\n      type: ResultType.data,\n      data: result.data,\n      statusCode: result.init?.status,\n      headers: result.init?.headers\n        ? new Headers(result.init.headers)\n        : undefined,\n    };\n  }\n\n  return { type: ResultType.data, data: result };\n}\n\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(\n  response: Response,\n  request: Request,\n  routeId: string,\n  matches: AgnosticDataRouteMatch[],\n  basename: string,\n  v7_relativeSplatPath: boolean\n) {\n  let location = response.headers.get(\"Location\");\n  invariant(\n    location,\n    \"Redirects returned/thrown from loaders/actions must have a Location header\"\n  );\n\n  if (!ABSOLUTE_URL_REGEX.test(location)) {\n    let trimmedMatches = matches.slice(\n      0,\n      matches.findIndex((m) => m.route.id === routeId) + 1\n    );\n    location = normalizeTo(\n      new URL(request.url),\n      trimmedMatches,\n      basename,\n      true,\n      location,\n      v7_relativeSplatPath\n    );\n    response.headers.set(\"Location\", location);\n  }\n\n  return response;\n}\n\nfunction normalizeRedirectLocation(\n  location: string,\n  currentUrl: URL,\n  basename: string\n): string {\n  if (ABSOLUTE_URL_REGEX.test(location)) {\n    // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n    let normalizedLocation = location;\n    let url = normalizedLocation.startsWith(\"//\")\n      ? new URL(currentUrl.protocol + normalizedLocation)\n      : new URL(normalizedLocation);\n    let isSameBasename = stripBasename(url.pathname, basename) != null;\n    if (url.origin === currentUrl.origin && isSameBasename) {\n      return url.pathname + url.search + url.hash;\n    }\n  }\n  return location;\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  history: History,\n  location: string | Location,\n  signal: AbortSignal,\n  submission?: Submission\n): Request {\n  let url = history.createURL(stripHashFromPath(location)).toString();\n  let init: RequestInit = { signal };\n\n  if (submission && isMutationMethod(submission.formMethod)) {\n    let { formMethod, formEncType } = submission;\n    // Didn't think we needed this but it turns out unlike other methods, patch\n    // won't be properly normalized to uppercase and results in a 405 error.\n    // See: https://fetch.spec.whatwg.org/#concept-method\n    init.method = formMethod.toUpperCase();\n\n    if (formEncType === \"application/json\") {\n      init.headers = new Headers({ \"Content-Type\": formEncType });\n      init.body = JSON.stringify(submission.json);\n    } else if (formEncType === \"text/plain\") {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.text;\n    } else if (\n      formEncType === \"application/x-www-form-urlencoded\" &&\n      submission.formData\n    ) {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = convertFormDataToSearchParams(submission.formData);\n    } else {\n      // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n      init.body = submission.formData;\n    }\n  }\n\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    // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n    searchParams.append(key, typeof value === \"string\" ? value : value.name);\n  }\n\n  return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n  searchParams: URLSearchParams\n): FormData {\n  let formData = new FormData();\n  for (let [key, value] of searchParams.entries()) {\n    formData.append(key, value);\n  }\n  return formData;\n}\n\nfunction processRouteLoaderData(\n  matches: AgnosticDataRouteMatch[],\n  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map<string, DeferredData>,\n  skipLoaderErrorBubbling: boolean\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  let pendingError =\n    pendingActionResult && isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  matches.forEach((match) => {\n    if (!(match.route.id in results)) {\n      return;\n    }\n    let id = match.route.id;\n    let result = results[id];\n    invariant(\n      !isRedirectResult(result),\n      \"Cannot handle redirect results in processLoaderData\"\n    );\n    if (isErrorResult(result)) {\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 !== undefined) {\n        error = pendingError;\n        pendingError = undefined;\n      }\n\n      errors = errors || {};\n\n      if (skipLoaderErrorBubbling) {\n        errors[id] = error;\n      } else {\n        // Look upwards from the matched route for the closest ancestor error\n        // boundary, defaulting to the root match.  Prefer higher error values\n        // if lower errors bubble to the same boundary\n        let boundaryMatch = findNearestBoundary(matches, id);\n        if (errors[boundaryMatch.route.id] == null) {\n          errors[boundaryMatch.route.id] = error;\n        }\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 {\n      if (isDeferredResult(result)) {\n        activeDeferreds.set(id, result.deferredData);\n        loaderData[id] = result.deferredData.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      } 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 (result.statusCode && result.statusCode !== 200 && !foundError) {\n          statusCode = result.statusCode;\n        }\n        if (result.headers) {\n          loaderHeaders[id] = result.headers;\n        }\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 !== undefined && pendingActionResult) {\n    errors = { [pendingActionResult[0]]: pendingError };\n    loaderData[pendingActionResult[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  results: Record<string, DataResult>,\n  pendingActionResult: PendingActionResult | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: Record<string, DataResult>,\n  activeDeferreds: Map<string, DeferredData>\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors?: RouterState[\"errors\"];\n} {\n  let { loaderData, errors } = processRouteLoaderData(\n    matches,\n    results,\n    pendingActionResult,\n    activeDeferreds,\n    false // This method is only called client side so we always want to bubble\n  );\n\n  // Process results from our revalidating fetchers\n  revalidatingFetchers.forEach((rf) => {\n    let { key, match, controller } = rf;\n    let result = fetcherResults[key];\n    invariant(result, \"Did not find corresponding fetcher result\");\n\n    // Process fetcher non-redirect errors\n    if (controller && controller.signal.aborted) {\n      // Nothing to do for aborted fetchers\n      return;\n    } else 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      invariant(false, \"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      invariant(false, \"Unhandled fetcher deferred data\");\n    } else {\n      let doneFetcher = getDoneFetcher(result.data);\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 && match.route.loader) {\n      // Preserve existing keys not included in newLoaderData and where a loader\n      // wasn't removed by HMR\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\nfunction getActionDataForCommit(\n  pendingActionResult: PendingActionResult | undefined\n) {\n  if (!pendingActionResult) {\n    return {};\n  }\n  return isErrorResult(pendingActionResult[1])\n    ? {\n        // Clear out prior actionData on errors\n        actionData: {},\n      }\n    : {\n        actionData: {\n          [pendingActionResult[0]]: pendingActionResult[1].data,\n        },\n      };\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 =\n    routes.length === 1\n      ? routes[0]\n      : 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    type,\n    message,\n  }: {\n    pathname?: string;\n    routeId?: string;\n    method?: string;\n    type?: \"defer-action\" | \"invalid-body\";\n    message?: 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 if (type === \"defer-action\") {\n      errorMessage = \"defer() is not supported in actions\";\n    } else if (type === \"invalid-body\") {\n      errorMessage = \"Unable to encode submission body\";\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 ErrorResponseImpl(\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(\n  results: Record<string, DataResult>\n): { key: string; result: RedirectResult } | undefined {\n  let entries = Object.entries(results);\n  for (let i = entries.length - 1; i >= 0; i--) {\n    let [key, result] = entries[i];\n    if (isRedirectResult(result)) {\n      return { key, 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  if (a.pathname !== b.pathname || a.search !== b.search) {\n    return false;\n  }\n\n  if (a.hash === \"\") {\n    // /page -> /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -> /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -> /page#other\n    return true;\n  }\n\n  // If the hash is removed the browser will re-perform a request to the server\n  // /page#hash -> /page\n  return false;\n}\n\nfunction isPromise<T = unknown>(val: unknown): val is Promise<T> {\n  return typeof val === \"object\" && val != null && \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n  return (\n    result != null &&\n    typeof result === \"object\" &&\n    \"type\" in result &&\n    \"result\" in result &&\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n  return (\n    isResponse(result.result) && redirectStatusCodes.has(result.result.status)\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\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value != null &&\n    \"type\" in value &&\n    \"data\" in value &&\n    \"init\" in value &&\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred &&\n    typeof deferred === \"object\" &&\n    typeof deferred.data === \"object\" &&\n    typeof deferred.subscribe === \"function\" &&\n    typeof deferred.cancel === \"function\" &&\n    typeof deferred.resolveData === \"function\"\n  );\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 isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n  return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n  method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n  return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveNavigationDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  signal: AbortSignal,\n  currentMatches: AgnosticDataRouteMatch[],\n  currentLoaderData: RouteData\n) {\n  let entries = Object.entries(results);\n  for (let index = 0; index < entries.length; index++) {\n    let [routeId, result] = entries[index];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\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) && 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, false).then((result) => {\n        if (result) {\n          results[routeId] = result;\n        }\n      });\n    }\n  }\n}\n\nasync function resolveFetcherDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record<string, DataResult>,\n  revalidatingFetchers: RevalidatingFetcher[]\n) {\n  for (let index = 0; index < revalidatingFetchers.length; index++) {\n    let { key, routeId, controller } = revalidatingFetchers[index];\n    let result = results[key];\n    let match = matches.find((m) => m?.route.id === routeId);\n    // If we don't have a match, then we can have a deferred result to do\n    // anything with.  This is for revalidating fetchers where the route was\n    // removed during HMR\n    if (!match) {\n      continue;\n    }\n\n    if (isDeferredResult(result)) {\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      invariant(\n        controller,\n        \"Expected an AbortController for revalidating fetcher deferred result\"\n      );\n      await resolveDeferredData(result, controller.signal, true).then(\n        (result) => {\n          if (result) {\n            results[key] = result;\n          }\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\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\nfunction getSubmissionFromNavigation(\n  navigation: Navigation\n): Submission | undefined {\n  let { formMethod, formAction, formEncType, text, formData, json } =\n    navigation;\n  if (!formMethod || !formAction || !formEncType) {\n    return;\n  }\n\n  if (text != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json: undefined,\n      text,\n    };\n  } else if (formData != null) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData,\n      json: undefined,\n      text: undefined,\n    };\n  } else if (json !== undefined) {\n    return {\n      formMethod,\n      formAction,\n      formEncType,\n      formData: undefined,\n      json,\n      text: undefined,\n    };\n  }\n}\n\nfunction getLoadingNavigation(\n  location: Location,\n  submission?: Submission\n): NavigationStates[\"Loading\"] {\n  if (submission) {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n    };\n    return navigation;\n  } else {\n    let navigation: NavigationStates[\"Loading\"] = {\n      state: \"loading\",\n      location,\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n    };\n    return navigation;\n  }\n}\n\nfunction getSubmittingNavigation(\n  location: Location,\n  submission: Submission\n): NavigationStates[\"Submitting\"] {\n  let navigation: NavigationStates[\"Submitting\"] = {\n    state: \"submitting\",\n    location,\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n  };\n  return navigation;\n}\n\nfunction getLoadingFetcher(\n  submission?: Submission,\n  data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n  if (submission) {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: submission.formMethod,\n      formAction: submission.formAction,\n      formEncType: submission.formEncType,\n      formData: submission.formData,\n      json: submission.json,\n      text: submission.text,\n      data,\n    };\n    return fetcher;\n  } else {\n    let fetcher: FetcherStates[\"Loading\"] = {\n      state: \"loading\",\n      formMethod: undefined,\n      formAction: undefined,\n      formEncType: undefined,\n      formData: undefined,\n      json: undefined,\n      text: undefined,\n      data,\n    };\n    return fetcher;\n  }\n}\n\nfunction getSubmittingFetcher(\n  submission: Submission,\n  existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n  let fetcher: FetcherStates[\"Submitting\"] = {\n    state: \"submitting\",\n    formMethod: submission.formMethod,\n    formAction: submission.formAction,\n    formEncType: submission.formEncType,\n    formData: submission.formData,\n    json: submission.json,\n    text: submission.text,\n    data: existingFetcher ? existingFetcher.data : undefined,\n  };\n  return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n  let fetcher: FetcherStates[\"Idle\"] = {\n    state: \"idle\",\n    formMethod: undefined,\n    formAction: undefined,\n    formEncType: undefined,\n    formData: undefined,\n    json: undefined,\n    text: undefined,\n    data,\n  };\n  return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  try {\n    let sessionPositions = _window.sessionStorage.getItem(\n      TRANSITIONS_STORAGE_KEY\n    );\n    if (sessionPositions) {\n      let json = JSON.parse(sessionPositions);\n      for (let [k, v] of Object.entries(json || {})) {\n        if (v && Array.isArray(v)) {\n          transitions.set(k, new Set(v || []));\n        }\n      }\n    }\n  } catch (e) {\n    // no-op, use default empty object\n  }\n}\n\nfunction persistAppliedTransitions(\n  _window: Window,\n  transitions: Map<string, Set<string>>\n) {\n  if (transitions.size > 0) {\n    let json: Record<string, string[]> = {};\n    for (let [k, v] of transitions) {\n      json[k] = [...v];\n    }\n    try {\n      _window.sessionStorage.setItem(\n        TRANSITIONS_STORAGE_KEY,\n        JSON.stringify(json)\n      );\n    } catch (error) {\n      warning(\n        false,\n        `Failed to save applied view transitions in sessionStorage (${error}).`\n      );\n    }\n  }\n}\n//#endregion\n", "import * as React from \"react\";\nimport type {\n  AgnosticIndexRouteObject,\n  AgnosticNonIndexRouteObject,\n  AgnosticRouteMatch,\n  History,\n  LazyRouteFunction,\n  Location,\n  Action as NavigationType,\n  RelativeRoutingType,\n  Router,\n  StaticHandlerContext,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n  caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticIndexRouteObject[\"path\"];\n  id?: AgnosticIndexRouteObject[\"id\"];\n  loader?: AgnosticIndexRouteObject[\"loader\"];\n  action?: AgnosticIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticIndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport interface NonIndexRouteObject {\n  caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n  path?: AgnosticNonIndexRouteObject[\"path\"];\n  id?: AgnosticNonIndexRouteObject[\"id\"];\n  loader?: AgnosticNonIndexRouteObject[\"loader\"];\n  action?: AgnosticNonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: AgnosticNonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: RouteObject[];\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n  lazy?: LazyRouteFunction<RouteObject>;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n  children?: DataRouteObject[];\n  id: string;\n};\n\nexport interface RouteMatch<\n  ParamKey extends string = string,\n  RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}\n\nexport interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}\n\nexport interface DataRouterContextObject\n  // Omit `future` since those can be pulled from the `router`\n  // `NavigationContext` needs future since it doesn't have a `router` in all cases\n  extends Omit<NavigationContextObject, \"future\"> {\n  router: Router;\n  staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n  React.createContext<DataRouterContextObject | null>(null);\nif (__DEV__) {\n  DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n  Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n  DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext<TrackedPromise | null>(null);\nif (__DEV__) {\n  AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  flushSync?: boolean;\n  viewTransition?: boolean;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n  createHref: History[\"createHref\"];\n  // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n  encodeLocation?: History[\"encodeLocation\"];\n  go: History[\"go\"];\n  push(to: To, state?: any, opts?: NavigateOptions): void;\n  replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n  basename: string;\n  navigator: Navigator;\n  static: boolean;\n  future: {\n    v7_relativeSplatPath: boolean;\n  };\n}\n\nexport const NavigationContext = React.createContext<NavigationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n  location: Location;\n  navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext<LocationContextObject>(\n  null!\n);\n\nif (__DEV__) {\n  LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n  outlet: React.ReactElement | null;\n  matches: RouteMatch[];\n  isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext<RouteContextObject>({\n  outlet: null,\n  matches: [],\n  isDataRoute: false,\n});\n\nif (__DEV__) {\n  RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext<any>(null);\n\nif (__DEV__) {\n  RouteErrorContext.displayName = \"RouteError\";\n}\n", "import * as React from \"react\";\nimport type {\n  Blocker,\n  BlockerFunction,\n  Location,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathPattern,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RevalidationState,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  IDLE_BLOCKER,\n  Action as NavigationType,\n  UNSAFE_convertRouteMatchToUiMatch as convertRouteMatchToUiMatch,\n  UNSAFE_decodePath as decodePath,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  isRouteErrorResponse,\n  joinPaths,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  DataRouteMatch,\n  NavigateOptions,\n  RouteContextObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n  RouteErrorContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nexport function useHref(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useHref() may be used only in the context of a <Router> component.`\n  );\n\n  let { basename, navigator } = React.useContext(NavigationContext);\n  let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n  let joinedPathname = pathname;\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the href.  If this is a root navigation, then just use the raw\n  // basename which allows the basename to have full control over the presence\n  // of a trailing slash on root links\n  if (basename !== \"/\") {\n    joinedPathname =\n      pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n  }\n\n  return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n  return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nexport function useLocation(): Location {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useLocation() may be used only in the context of a <Router> component.`\n  );\n\n  return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n  return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nexport function useMatch<\n  ParamKey extends ParamParseKey<Path>,\n  Path extends string\n>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useMatch() may be used only in the context of a <Router> component.`\n  );\n\n  let { pathname } = useLocation();\n  return React.useMemo(\n    () => matchPath<ParamKey, Path>(pattern, decodePath(pathname)),\n    [pathname, pattern]\n  );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n  (to: To, options?: NavigateOptions): void;\n  (delta: number): void;\n}\n\nconst navigateEffectWarning =\n  `You should call navigate() in a React.useEffect(), not when ` +\n  `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n  cb: Parameters<typeof React.useLayoutEffect>[0]\n) {\n  let isStatic = React.useContext(NavigationContext).static;\n  if (!isStatic) {\n    // We should be able to get rid of this once react 18.3 is released\n    // See: https://github.com/facebook/react/pull/26395\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(cb);\n  }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n  let { isDataRoute } = React.useContext(RouteContext);\n  // Conditional usage is OK here because the usage of a data router is static\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useNavigate() may be used only in the context of a <Router> component.`\n  );\n\n  let dataRouterContext = React.useContext(DataRouterContext);\n  let { basename, future, navigator } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our history listener yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        navigator.go(to);\n        return;\n      }\n\n      let path = resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        options.relative === \"path\"\n      );\n\n      // If we're operating within a basename, prepend it to the pathname prior\n      // to handing off to history (but only if we're not in a data router,\n      // otherwise it'll prepend the basename inside of the router).\n      // If this is a root navigation, then we navigate to the raw basename\n      // which allows the basename to have full control over the presence of a\n      // trailing slash on root links\n      if (dataRouterContext == null && basename !== \"/\") {\n        path.pathname =\n          path.pathname === \"/\"\n            ? basename\n            : joinPaths([basename, path.pathname]);\n      }\n\n      (!!options.replace ? navigator.replace : navigator.push)(\n        path,\n        options.state,\n        options\n      );\n    },\n    [\n      basename,\n      navigator,\n      routePathnamesJson,\n      locationPathname,\n      dataRouterContext,\n    ]\n  );\n\n  return navigate;\n}\n\nconst OutletContext = React.createContext<unknown>(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nexport function useOutletContext<Context = unknown>(): Context {\n  return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n  let outlet = React.useContext(RouteContext).outlet;\n  if (outlet) {\n    return (\n      <OutletContext.Provider value={context}>{outlet}</OutletContext.Provider>\n    );\n  }\n  return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nexport function useParams<\n  ParamsOrKey extends string | Record<string, string | undefined> = string\n>(): Readonly<\n  [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>\n> {\n  let { matches } = React.useContext(RouteContext);\n  let routeMatch = matches[matches.length - 1];\n  return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n  to: To,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n  let { future } = React.useContext(NavigationContext);\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let routePathnamesJson = JSON.stringify(\n    getResolveToMatches(matches, future.v7_relativeSplatPath)\n  );\n\n  return React.useMemo(\n    () =>\n      resolveTo(\n        to,\n        JSON.parse(routePathnamesJson),\n        locationPathname,\n        relative === \"path\"\n      ),\n    [to, routePathnamesJson, locationPathname, relative]\n  );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nexport function useRoutes(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string\n): React.ReactElement | null {\n  return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n  routes: RouteObject[],\n  locationArg?: Partial<Location> | string,\n  dataRouterState?: RemixRouter[\"state\"],\n  future?: RemixRouter[\"future\"]\n): React.ReactElement | null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of the\n    // router loaded. We can help them understand how to avoid that.\n    `useRoutes() may be used only in the context of a <Router> component.`\n  );\n\n  let { navigator } = React.useContext(NavigationContext);\n  let { matches: parentMatches } = React.useContext(RouteContext);\n  let routeMatch = parentMatches[parentMatches.length - 1];\n  let parentParams = routeMatch ? routeMatch.params : {};\n  let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n  let parentRoute = routeMatch && routeMatch.route;\n\n  if (__DEV__) {\n    // You won't get a warning about 2 different <Routes> under a <Route>\n    // without a trailing *, but this is a best-effort warning anyway since we\n    // cannot even give the warning unless they land at the parent route.\n    //\n    // Example:\n    //\n    // <Routes>\n    //   {/* This route path MUST end with /* because otherwise\n    //       it will never match /blog/post/123 */}\n    //   <Route path=\"blog\" element={<Blog />} />\n    //   <Route path=\"blog/feed\" element={<BlogFeed />} />\n    // </Routes>\n    //\n    // function Blog() {\n    //   return (\n    //     <Routes>\n    //       <Route path=\"post/:id\" element={<Post />} />\n    //     </Routes>\n    //   );\n    // }\n    let parentPath = (parentRoute && parentRoute.path) || \"\";\n    warningOnce(\n      parentPathname,\n      !parentRoute || parentPath.endsWith(\"*\"),\n      `You rendered descendant <Routes> (or called \\`useRoutes()\\`) at ` +\n        `\"${parentPathname}\" (under <Route path=\"${parentPath}\">) but the ` +\n        `parent route path has no trailing \"*\". This means if you navigate ` +\n        `deeper, the parent won't match anymore and therefore the child ` +\n        `routes will never render.\\n\\n` +\n        `Please change the parent <Route path=\"${parentPath}\"> to <Route ` +\n        `path=\"${parentPath === \"/\" ? \"*\" : `${parentPath}/*`}\">.`\n    );\n  }\n\n  let locationFromContext = useLocation();\n\n  let location;\n  if (locationArg) {\n    let parsedLocationArg =\n      typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n    invariant(\n      parentPathnameBase === \"/\" ||\n        parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n      `When overriding the location using \\`<Routes location>\\` or \\`useRoutes(routes, location)\\`, ` +\n        `the location pathname must begin with the portion of the URL pathname that was ` +\n        `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n        `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n    );\n\n    location = parsedLocationArg;\n  } else {\n    location = locationFromContext;\n  }\n\n  let pathname = location.pathname || \"/\";\n\n  let remainingPathname = pathname;\n  if (parentPathnameBase !== \"/\") {\n    // Determine the remaining pathname by removing the # of URL segments the\n    // parentPathnameBase has, instead of removing based on character count.\n    // This is because we can't guarantee that incoming/outgoing encodings/\n    // decodings will match exactly.\n    // We decode paths before matching on a per-segment basis with\n    // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n    // match what `window.location.pathname` would reflect.  Those don't 100%\n    // align when it comes to encoded URI characters such as % and &.\n    //\n    // So we may end up with:\n    //   pathname:           \"/descendant/a%25b/match\"\n    //   parentPathnameBase: \"/descendant/a%b\"\n    //\n    // And the direct substring removal approach won't work :/\n    let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n    let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n    remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n  }\n\n  let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n  if (__DEV__) {\n    warning(\n      parentRoute || matches != null,\n      `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n    );\n\n    warning(\n      matches == null ||\n        matches[matches.length - 1].route.element !== undefined ||\n        matches[matches.length - 1].route.Component !== undefined ||\n        matches[matches.length - 1].route.lazy !== undefined,\n      `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n        `does not have an element or Component. This means it will render an <Outlet /> with a ` +\n        `null value by default resulting in an \"empty\" page.`\n    );\n  }\n\n  let renderedMatches = _renderMatches(\n    matches &&\n      matches.map((match) =>\n        Object.assign({}, match, {\n          params: Object.assign({}, parentParams, match.params),\n          pathname: joinPaths([\n            parentPathnameBase,\n            // Re-encode pathnames that were decoded inside matchRoutes\n            navigator.encodeLocation\n              ? navigator.encodeLocation(match.pathname).pathname\n              : match.pathname,\n          ]),\n          pathnameBase:\n            match.pathnameBase === \"/\"\n              ? parentPathnameBase\n              : joinPaths([\n                  parentPathnameBase,\n                  // Re-encode pathnames that were decoded inside matchRoutes\n                  navigator.encodeLocation\n                    ? navigator.encodeLocation(match.pathnameBase).pathname\n                    : match.pathnameBase,\n                ]),\n        })\n      ),\n    parentMatches,\n    dataRouterState,\n    future\n  );\n\n  // When a user passes in a `locationArg`, the associated routes need to\n  // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n  // to use the scoped location instead of the global location.\n  if (locationArg && renderedMatches) {\n    return (\n      <LocationContext.Provider\n        value={{\n          location: {\n            pathname: \"/\",\n            search: \"\",\n            hash: \"\",\n            state: null,\n            key: \"default\",\n            ...location,\n          },\n          navigationType: NavigationType.Pop,\n        }}\n      >\n        {renderedMatches}\n      </LocationContext.Provider>\n    );\n  }\n\n  return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n  let error = useRouteError();\n  let message = isRouteErrorResponse(error)\n    ? `${error.status} ${error.statusText}`\n    : error instanceof Error\n    ? error.message\n    : JSON.stringify(error);\n  let stack = error instanceof Error ? error.stack : null;\n  let lightgrey = \"rgba(200,200,200, 0.5)\";\n  let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n  let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n  let devInfo = null;\n  if (__DEV__) {\n    console.error(\n      \"Error handled by React Router default ErrorBoundary:\",\n      error\n    );\n\n    devInfo = (\n      <>\n        <p>💿 Hey developer 👋</p>\n        <p>\n          You can provide a way better UX than this when your app throws errors\n          by providing your own <code style={codeStyles}>ErrorBoundary</code> or{\" \"}\n          <code style={codeStyles}>errorElement</code> prop on your route.\n        </p>\n      </>\n    );\n  }\n\n  return (\n    <>\n      <h2>Unexpected Application Error!</h2>\n      <h3 style={{ fontStyle: \"italic\" }}>{message}</h3>\n      {stack ? <pre style={preStyles}>{stack}</pre> : null}\n      {devInfo}\n    </>\n  );\n}\n\nconst defaultErrorElement = <DefaultErrorComponent />;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n  component: React.ReactNode;\n  routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n  location: Location;\n  revalidation: RevalidationState;\n  error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n  RenderErrorBoundaryProps,\n  RenderErrorBoundaryState\n> {\n  constructor(props: RenderErrorBoundaryProps) {\n    super(props);\n    this.state = {\n      location: props.location,\n      revalidation: props.revalidation,\n      error: props.error,\n    };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error: error };\n  }\n\n  static getDerivedStateFromProps(\n    props: RenderErrorBoundaryProps,\n    state: RenderErrorBoundaryState\n  ) {\n    // When we get into an error state, the user will likely click \"back\" to the\n    // previous page that didn't have an error. Because this wraps the entire\n    // application, that will have no effect--the error page continues to display.\n    // This gives us a mechanism to recover from the error when the location changes.\n    //\n    // Whether we're in an error state or not, we update the location in state\n    // so that when we are in an error state, it gets reset when a new location\n    // comes in and the user recovers from the error.\n    if (\n      state.location !== props.location ||\n      (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n    ) {\n      return {\n        error: props.error,\n        location: props.location,\n        revalidation: props.revalidation,\n      };\n    }\n\n    // If we're not changing locations, preserve the location but still surface\n    // any new errors that may come through. We retain the existing error, we do\n    // this because the error provided from the app state may be cleared without\n    // the location changing.\n    return {\n      error: props.error !== undefined ? props.error : state.error,\n      location: state.location,\n      revalidation: props.revalidation || state.revalidation,\n    };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"React Router caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    return this.state.error !== undefined ? (\n      <RouteContext.Provider value={this.props.routeContext}>\n        <RouteErrorContext.Provider\n          value={this.state.error}\n          children={this.props.component}\n        />\n      </RouteContext.Provider>\n    ) : (\n      this.props.children\n    );\n  }\n}\n\ninterface RenderedRouteProps {\n  routeContext: RouteContextObject;\n  match: RouteMatch<string, RouteObject>;\n  children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n  let dataRouterContext = React.useContext(DataRouterContext);\n\n  // Track how deep we got in our render pass to emulate SSR componentDidCatch\n  // in a DataStaticRouter\n  if (\n    dataRouterContext &&\n    dataRouterContext.static &&\n    dataRouterContext.staticContext &&\n    (match.route.errorElement || match.route.ErrorBoundary)\n  ) {\n    dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n  }\n\n  return (\n    <RouteContext.Provider value={routeContext}>\n      {children}\n    </RouteContext.Provider>\n  );\n}\n\nexport function _renderMatches(\n  matches: RouteMatch[] | null,\n  parentMatches: RouteMatch[] = [],\n  dataRouterState: RemixRouter[\"state\"] | null = null,\n  future: RemixRouter[\"future\"] | null = null\n): React.ReactElement | null {\n  if (matches == null) {\n    if (!dataRouterState) {\n      return null;\n    }\n\n    if (dataRouterState.errors) {\n      // Don't bail if we have data router errors so we can render them in the\n      // boundary.  Use the pre-matched (or shimmed) matches\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else if (\n      future?.v7_partialHydration &&\n      parentMatches.length === 0 &&\n      !dataRouterState.initialized &&\n      dataRouterState.matches.length > 0\n    ) {\n      // Don't bail if we're initializing with partial hydration and we have\n      // router matches.  That means we're actively running `patchRoutesOnNavigation`\n      // so we should render down the partial matches to the appropriate\n      // `HydrateFallback`.  We only do this if `parentMatches` is empty so it\n      // only impacts the root matches for `RouterProvider` and no descendant\n      // `<Routes>`\n      matches = dataRouterState.matches as DataRouteMatch[];\n    } else {\n      return null;\n    }\n  }\n\n  let renderedMatches = matches;\n\n  // If we have data errors, trim matches to the highest error boundary\n  let errors = dataRouterState?.errors;\n  if (errors != null) {\n    let errorIndex = renderedMatches.findIndex(\n      (m) => m.route.id && errors?.[m.route.id] !== undefined\n    );\n    invariant(\n      errorIndex >= 0,\n      `Could not find a matching route for errors on route IDs: ${Object.keys(\n        errors\n      ).join(\",\")}`\n    );\n    renderedMatches = renderedMatches.slice(\n      0,\n      Math.min(renderedMatches.length, errorIndex + 1)\n    );\n  }\n\n  // If we're in a partial hydration mode, detect if we need to render down to\n  // a given HydrateFallback while we load the rest of the hydration data\n  let renderFallback = false;\n  let fallbackIndex = -1;\n  if (dataRouterState && future && future.v7_partialHydration) {\n    for (let i = 0; i < renderedMatches.length; i++) {\n      let match = renderedMatches[i];\n      // Track the deepest fallback up until the first route without data\n      if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n        fallbackIndex = i;\n      }\n\n      if (match.route.id) {\n        let { loaderData, errors } = dataRouterState;\n        let needsToRunLoader =\n          match.route.loader &&\n          loaderData[match.route.id] === undefined &&\n          (!errors || errors[match.route.id] === undefined);\n        if (match.route.lazy || needsToRunLoader) {\n          // We found the first route that's not ready to render (waiting on\n          // lazy, or has a loader that hasn't run yet).  Flag that we need to\n          // render a fallback and render up until the appropriate fallback\n          renderFallback = true;\n          if (fallbackIndex >= 0) {\n            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n          } else {\n            renderedMatches = [renderedMatches[0]];\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  return renderedMatches.reduceRight((outlet, match, index) => {\n    // Only data routers handle errors/fallbacks\n    let error: any;\n    let shouldRenderHydrateFallback = false;\n    let errorElement: React.ReactNode | null = null;\n    let hydrateFallbackElement: React.ReactNode | null = null;\n    if (dataRouterState) {\n      error = errors && match.route.id ? errors[match.route.id] : undefined;\n      errorElement = match.route.errorElement || defaultErrorElement;\n\n      if (renderFallback) {\n        if (fallbackIndex < 0 && index === 0) {\n          warningOnce(\n            \"route-fallback\",\n            false,\n            \"No `HydrateFallback` element provided to render during initial hydration\"\n          );\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = null;\n        } else if (fallbackIndex === index) {\n          shouldRenderHydrateFallback = true;\n          hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n        }\n      }\n    }\n\n    let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n    let getChildren = () => {\n      let children: React.ReactNode;\n      if (error) {\n        children = errorElement;\n      } else if (shouldRenderHydrateFallback) {\n        children = hydrateFallbackElement;\n      } else if (match.route.Component) {\n        // Note: This is a de-optimized path since React won't re-use the\n        // ReactElement since it's identity changes with each new\n        // React.createElement call.  We keep this so folks can use\n        // `<Route Component={...}>` in `<Routes>` but generally `Component`\n        // usage is only advised in `RouterProvider` when we can convert it to\n        // `element` ahead of time.\n        children = <match.route.Component />;\n      } else if (match.route.element) {\n        children = match.route.element;\n      } else {\n        children = outlet;\n      }\n      return (\n        <RenderedRoute\n          match={match}\n          routeContext={{\n            outlet,\n            matches,\n            isDataRoute: dataRouterState != null,\n          }}\n          children={children}\n        />\n      );\n    };\n    // Only wrap in an error boundary within data router usages when we have an\n    // ErrorBoundary/errorElement on this route.  Otherwise let it bubble up to\n    // an ancestor ErrorBoundary/errorElement\n    return dataRouterState &&\n      (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n      <RenderErrorBoundary\n        location={dataRouterState.location}\n        revalidation={dataRouterState.revalidation}\n        component={errorElement}\n        error={error}\n        children={getChildren()}\n        routeContext={{ outlet: null, matches, isDataRoute: true }}\n      />\n    ) : (\n      getChildren()\n    );\n  }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n  UseBlocker = \"useBlocker\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n  UseBlocker = \"useBlocker\",\n  UseLoaderData = \"useLoaderData\",\n  UseActionData = \"useActionData\",\n  UseRouteError = \"useRouteError\",\n  UseNavigation = \"useNavigation\",\n  UseRouteLoaderData = \"useRouteLoaderData\",\n  UseMatches = \"useMatches\",\n  UseRevalidator = \"useRevalidator\",\n  UseNavigateStable = \"useNavigate\",\n  UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n  let route = React.useContext(RouteContext);\n  invariant(route, getDataRouterConsoleError(hookName));\n  return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n  let route = useRouteContext(hookName);\n  let thisRoute = route.matches[route.matches.length - 1];\n  invariant(\n    thisRoute.route.id,\n    `${hookName} can only be used on routes that contain a unique \"id\"`\n  );\n  return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n  return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n  let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n  return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n  let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n  let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n  return React.useMemo(\n    () => ({\n      revalidate: dataRouterContext.router.revalidate,\n      state: state.revalidation,\n    }),\n    [dataRouterContext.router.revalidate, state.revalidation]\n  );\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches(): UIMatch[] {\n  let { matches, loaderData } = useDataRouterState(\n    DataRouterStateHook.UseMatches\n  );\n  return React.useMemo(\n    () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),\n    [matches, loaderData]\n  );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n  if (state.errors && state.errors[routeId] != null) {\n    console.error(\n      `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n    );\n    return undefined;\n  }\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n  return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n  let state = useDataRouterState(DataRouterStateHook.UseActionData);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n  return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error.  This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n  let error = React.useContext(RouteErrorContext);\n  let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n  let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n  // If this was a render error, we put it in a RouteError context inside\n  // of RenderErrorBoundary\n  if (error !== undefined) {\n    return error;\n  }\n\n  // Otherwise look for errors from our data router state\n  return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nexport function useAsyncValue(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nexport function useAsyncError(): unknown {\n  let value = React.useContext(AwaitContext);\n  return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation.  Mostly used to avoid\n * using half-filled form data.  This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n  let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n  let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n  let [blockerKey, setBlockerKey] = React.useState(\"\");\n  let blockerFunction = React.useCallback<BlockerFunction>(\n    (arg) => {\n      if (typeof shouldBlock !== \"function\") {\n        return !!shouldBlock;\n      }\n      if (basename === \"/\") {\n        return shouldBlock(arg);\n      }\n\n      // If they provided us a function and we've got an active basename, strip\n      // it from the locations we expose to the user to match the behavior of\n      // useLocation\n      let { currentLocation, nextLocation, historyAction } = arg;\n      return shouldBlock({\n        currentLocation: {\n          ...currentLocation,\n          pathname:\n            stripBasename(currentLocation.pathname, basename) ||\n            currentLocation.pathname,\n        },\n        nextLocation: {\n          ...nextLocation,\n          pathname:\n            stripBasename(nextLocation.pathname, basename) ||\n            nextLocation.pathname,\n        },\n        historyAction,\n      });\n    },\n    [basename, shouldBlock]\n  );\n\n  // This effect is in charge of blocker key assignment and deletion (which is\n  // tightly coupled to the key)\n  React.useEffect(() => {\n    let key = String(++blockerId);\n    setBlockerKey(key);\n    return () => router.deleteBlocker(key);\n  }, [router]);\n\n  // This effect handles assigning the blockerFunction.  This is to handle\n  // unstable blocker function identities, and happens only after the prior\n  // effect so we don't get an orphaned blockerFunction in the router with a\n  // key of \"\".  Until then we just have the IDLE_BLOCKER.\n  React.useEffect(() => {\n    if (blockerKey !== \"\") {\n      router.getBlocker(blockerKey, blockerFunction);\n    }\n  }, [router, blockerKey, blockerFunction]);\n\n  // Prefer the blocker from `state` not `router.state` since DataRouterContext\n  // is memoized so this ensures we update on blocker state updates\n  return blockerKey && state.blockers.has(blockerKey)\n    ? state.blockers.get(blockerKey)!\n    : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n  let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n  let activeRef = React.useRef(false);\n  useIsomorphicLayoutEffect(() => {\n    activeRef.current = true;\n  });\n\n  let navigate: NavigateFunction = React.useCallback(\n    (to: To | number, options: NavigateOptions = {}) => {\n      warning(activeRef.current, navigateEffectWarning);\n\n      // Short circuit here since if this happens on first render the navigate\n      // is useless because we haven't wired up our router subscriber yet\n      if (!activeRef.current) return;\n\n      if (typeof to === \"number\") {\n        router.navigate(to);\n      } else {\n        router.navigate(to, { fromRouteId: id, ...options });\n      }\n    },\n    [router, id]\n  );\n\n  return navigate;\n}\n\nconst alreadyWarned: Record<string, boolean> = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n  if (!cond && !alreadyWarned[key]) {\n    alreadyWarned[key] = true;\n    warning(false, message);\n  }\n}\n", "import type { FutureConfig as RouterFutureConfig } from \"@remix-run/router\";\nimport type { FutureConfig as RenderFutureConfig } from \"./components\";\n\nconst alreadyWarned: { [key: string]: boolean } = {};\n\nexport function warnOnce(key: string, message: string): void {\n  if (!alreadyWarned[message]) {\n    alreadyWarned[message] = true;\n    console.warn(message);\n  }\n}\n\nconst logDeprecation = (flag: string, msg: string, link: string) =>\n  warnOnce(\n    flag,\n    `⚠️ React Router Future Flag Warning: ${msg}. ` +\n      `You can use the \\`${flag}\\` future flag to opt-in early. ` +\n      `For more information, see ${link}.`\n  );\n\nexport function logV6DeprecationWarnings(\n  renderFuture: Partial<RenderFutureConfig> | undefined,\n  routerFuture?: Omit<RouterFutureConfig, \"v7_prependBasename\">\n) {\n  if (!renderFuture?.v7_startTransition) {\n    logDeprecation(\n      \"v7_startTransition\",\n      \"React Router will begin wrapping state updates in `React.startTransition` in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\"\n    );\n  }\n\n  if (\n    !renderFuture?.v7_relativeSplatPath &&\n    (!routerFuture || !routerFuture.v7_relativeSplatPath)\n  ) {\n    logDeprecation(\n      \"v7_relativeSplatPath\",\n      \"Relative route resolution within Splat routes is changing in v7\",\n      \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\"\n    );\n  }\n\n  if (routerFuture) {\n    if (!routerFuture.v7_fetcherPersist) {\n      logDeprecation(\n        \"v7_fetcherPersist\",\n        \"The persistence behavior of fetchers is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\"\n      );\n    }\n\n    if (!routerFuture.v7_normalizeFormMethod) {\n      logDeprecation(\n        \"v7_normalizeFormMethod\",\n        \"Casing of `formMethod` fields is being normalized to uppercase in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\"\n      );\n    }\n\n    if (!routerFuture.v7_partialHydration) {\n      logDeprecation(\n        \"v7_partialHydration\",\n        \"`RouterProvider` hydration behavior is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\"\n      );\n    }\n\n    if (!routerFuture.v7_skipActionErrorRevalidation) {\n      logDeprecation(\n        \"v7_skipActionErrorRevalidation\",\n        \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\",\n        \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\"\n      );\n    }\n  }\n}\n", "import type {\n  InitialEntry,\n  LazyRouteFunction,\n  Location,\n  MemoryHistory,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  RouterState,\n  RouterSubscriber,\n  To,\n  TrackedPromise,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  UNSAFE_getResolveToMatches as getResolveToMatches,\n  UNSAFE_invariant as invariant,\n  parsePath,\n  resolveTo,\n  stripBasename,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\nimport * as React from \"react\";\n\nimport type {\n  DataRouteObject,\n  IndexRouteObject,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./context\";\nimport {\n  AwaitContext,\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./context\";\nimport {\n  _renderMatches,\n  useAsyncValue,\n  useInRouterContext,\n  useLocation,\n  useNavigate,\n  useOutlet,\n  useRoutes,\n  useRoutesImpl,\n} from \"./hooks\";\nimport { logV6DeprecationWarnings } from \"./deprecations\";\n\nexport interface FutureConfig {\n  v7_relativeSplatPath: boolean;\n  v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n  fallbackElement?: React.ReactNode;\n  router: RemixRouter;\n  // Only accept future flags relevant to rendering behavior\n  // routing flags should be accessed via router.future\n  future?: Partial<Pick<FutureConfig, \"v7_startTransition\">>;\n}\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let { v7_startTransition } = future || {};\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (newState: RouterState) => {\n      if (v7_startTransition && startTransitionImpl) {\n        startTransitionImpl(() => setStateImpl(newState));\n      } else {\n        setStateImpl(newState);\n      }\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [router, future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <Router\n            basename={basename}\n            location={state.location}\n            navigationType={state.historyAction}\n            navigator={navigator}\n            future={{\n              v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n            }}\n          >\n            {state.initialized || router.future.v7_partialHydration ? (\n              <DataRoutes\n                routes={router.routes}\n                future={router.future}\n                state={state}\n              />\n            ) : (\n              fallbackElement\n            )}\n          </Router>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface MemoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  initialEntries?: InitialEntry[];\n  initialIndex?: number;\n  future?: Partial<FutureConfig>;\n}\n\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nexport function MemoryRouter({\n  basename,\n  children,\n  initialEntries,\n  initialIndex,\n  future,\n}: MemoryRouterProps): React.ReactElement {\n  let historyRef = React.useRef<MemoryHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createMemoryHistory({\n      initialEntries,\n      initialIndex,\n      v5Compat: true,\n    });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface NavigateProps {\n  to: To;\n  replace?: boolean;\n  state?: any;\n  relative?: RelativeRoutingType;\n}\n\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nexport function Navigate({\n  to,\n  replace,\n  state,\n  relative,\n}: NavigateProps): null {\n  invariant(\n    useInRouterContext(),\n    // TODO: This error is probably because they somehow have 2 versions of\n    // the router loaded. We can help them understand how to avoid that.\n    `<Navigate> may be used only in the context of a <Router> component.`\n  );\n\n  let { future, static: isStatic } = React.useContext(NavigationContext);\n\n  warning(\n    !isStatic,\n    `<Navigate> must not be used on the initial render in a <StaticRouter>. ` +\n      `This is a no-op, but you should modify your code so the <Navigate> is ` +\n      `only ever rendered in response to some user interaction or state change.`\n  );\n\n  let { matches } = React.useContext(RouteContext);\n  let { pathname: locationPathname } = useLocation();\n  let navigate = useNavigate();\n\n  // Resolve the path outside of the effect so that when effects run twice in\n  // StrictMode they navigate to the same place\n  let path = resolveTo(\n    to,\n    getResolveToMatches(matches, future.v7_relativeSplatPath),\n    locationPathname,\n    relative === \"path\"\n  );\n  let jsonPath = JSON.stringify(path);\n\n  React.useEffect(\n    () => navigate(JSON.parse(jsonPath), { replace, state, relative }),\n    [navigate, jsonPath, relative, replace, state]\n  );\n\n  return null;\n}\n\nexport interface OutletProps {\n  context?: unknown;\n}\n\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nexport function Outlet(props: OutletProps): React.ReactElement | null {\n  return useOutlet(props.context);\n}\n\nexport interface PathRouteProps {\n  caseSensitive?: NonIndexRouteObject[\"caseSensitive\"];\n  path?: NonIndexRouteObject[\"path\"];\n  id?: NonIndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<NonIndexRouteObject>;\n  loader?: NonIndexRouteObject[\"loader\"];\n  action?: NonIndexRouteObject[\"action\"];\n  hasErrorBoundary?: NonIndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: NonIndexRouteObject[\"shouldRevalidate\"];\n  handle?: NonIndexRouteObject[\"handle\"];\n  index?: false;\n  children?: React.ReactNode;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport interface LayoutRouteProps extends PathRouteProps {}\n\nexport interface IndexRouteProps {\n  caseSensitive?: IndexRouteObject[\"caseSensitive\"];\n  path?: IndexRouteObject[\"path\"];\n  id?: IndexRouteObject[\"id\"];\n  lazy?: LazyRouteFunction<IndexRouteObject>;\n  loader?: IndexRouteObject[\"loader\"];\n  action?: IndexRouteObject[\"action\"];\n  hasErrorBoundary?: IndexRouteObject[\"hasErrorBoundary\"];\n  shouldRevalidate?: IndexRouteObject[\"shouldRevalidate\"];\n  handle?: IndexRouteObject[\"handle\"];\n  index: true;\n  children?: undefined;\n  element?: React.ReactNode | null;\n  hydrateFallbackElement?: React.ReactNode | null;\n  errorElement?: React.ReactNode | null;\n  Component?: React.ComponentType | null;\n  HydrateFallback?: React.ComponentType | null;\n  ErrorBoundary?: React.ComponentType | null;\n}\n\nexport type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;\n\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nexport function Route(_props: RouteProps): React.ReactElement | null {\n  invariant(\n    false,\n    `A <Route> is only ever to be used as the child of <Routes> element, ` +\n      `never rendered directly. Please wrap your <Route> in a <Routes>.`\n  );\n}\n\nexport interface RouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  location: Partial<Location> | string;\n  navigationType?: NavigationType;\n  navigator: Navigator;\n  static?: boolean;\n  future?: Partial<Pick<FutureConfig, \"v7_relativeSplatPath\">>;\n}\n\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nexport function Router({\n  basename: basenameProp = \"/\",\n  children = null,\n  location: locationProp,\n  navigationType = NavigationType.Pop,\n  navigator,\n  static: staticProp = false,\n  future,\n}: RouterProps): React.ReactElement | null {\n  invariant(\n    !useInRouterContext(),\n    `You cannot render a <Router> inside another <Router>.` +\n      ` You should never have more than one in your app.`\n  );\n\n  // Preserve trailing slashes on basename, so we can let the user control\n  // the enforcement of trailing slashes throughout the app\n  let basename = basenameProp.replace(/^\\/*/, \"/\");\n  let navigationContext = React.useMemo(\n    () => ({\n      basename,\n      navigator,\n      static: staticProp,\n      future: {\n        v7_relativeSplatPath: false,\n        ...future,\n      },\n    }),\n    [basename, future, navigator, staticProp]\n  );\n\n  if (typeof locationProp === \"string\") {\n    locationProp = parsePath(locationProp);\n  }\n\n  let {\n    pathname = \"/\",\n    search = \"\",\n    hash = \"\",\n    state = null,\n    key = \"default\",\n  } = locationProp;\n\n  let locationContext = React.useMemo(() => {\n    let trailingPathname = stripBasename(pathname, basename);\n\n    if (trailingPathname == null) {\n      return null;\n    }\n\n    return {\n      location: {\n        pathname: trailingPathname,\n        search,\n        hash,\n        state,\n        key,\n      },\n      navigationType,\n    };\n  }, [basename, pathname, search, hash, state, key, navigationType]);\n\n  warning(\n    locationContext != null,\n    `<Router basename=\"${basename}\"> is not able to match the URL ` +\n      `\"${pathname}${search}${hash}\" because it does not start with the ` +\n      `basename, so the <Router> won't render anything.`\n  );\n\n  if (locationContext == null) {\n    return null;\n  }\n\n  return (\n    <NavigationContext.Provider value={navigationContext}>\n      <LocationContext.Provider children={children} value={locationContext} />\n    </NavigationContext.Provider>\n  );\n}\n\nexport interface RoutesProps {\n  children?: React.ReactNode;\n  location?: Partial<Location> | string;\n}\n\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nexport function Routes({\n  children,\n  location,\n}: RoutesProps): React.ReactElement | null {\n  return useRoutes(createRoutesFromChildren(children), location);\n}\n\nexport interface AwaitResolveRenderFunction {\n  (data: Awaited<any>): React.ReactNode;\n}\n\nexport interface AwaitProps {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}\n\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nexport function Await({ children, errorElement, resolve }: AwaitProps) {\n  return (\n    <AwaitErrorBoundary resolve={resolve} errorElement={errorElement}>\n      <ResolveAwait>{children}</ResolveAwait>\n    </AwaitErrorBoundary>\n  );\n}\n\ntype AwaitErrorBoundaryProps = React.PropsWithChildren<{\n  errorElement?: React.ReactNode;\n  resolve: TrackedPromise | any;\n}>;\n\ntype AwaitErrorBoundaryState = {\n  error: any;\n};\n\nenum AwaitRenderStatus {\n  pending,\n  success,\n  error,\n}\n\nconst neverSettledPromise = new Promise(() => {});\n\nclass AwaitErrorBoundary extends React.Component<\n  AwaitErrorBoundaryProps,\n  AwaitErrorBoundaryState\n> {\n  constructor(props: AwaitErrorBoundaryProps) {\n    super(props);\n    this.state = { error: null };\n  }\n\n  static getDerivedStateFromError(error: any) {\n    return { error };\n  }\n\n  componentDidCatch(error: any, errorInfo: any) {\n    console.error(\n      \"<Await> caught the following error during render\",\n      error,\n      errorInfo\n    );\n  }\n\n  render() {\n    let { children, errorElement, resolve } = this.props;\n\n    let promise: TrackedPromise | null = null;\n    let status: AwaitRenderStatus = AwaitRenderStatus.pending;\n\n    if (!(resolve instanceof Promise)) {\n      // Didn't get a promise - provide as a resolved promise\n      status = AwaitRenderStatus.success;\n      promise = Promise.resolve();\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_data\", { get: () => resolve });\n    } else if (this.state.error) {\n      // Caught a render error, provide it as a rejected promise\n      status = AwaitRenderStatus.error;\n      let renderError = this.state.error;\n      promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n      Object.defineProperty(promise, \"_tracked\", { get: () => true });\n      Object.defineProperty(promise, \"_error\", { get: () => renderError });\n    } else if ((resolve as TrackedPromise)._tracked) {\n      // Already tracked promise - check contents\n      promise = resolve;\n      status =\n        \"_error\" in promise\n          ? AwaitRenderStatus.error\n          : \"_data\" in promise\n          ? AwaitRenderStatus.success\n          : AwaitRenderStatus.pending;\n    } else {\n      // Raw (untracked) promise - track it\n      status = AwaitRenderStatus.pending;\n      Object.defineProperty(resolve, \"_tracked\", { get: () => true });\n      promise = resolve.then(\n        (data: any) =>\n          Object.defineProperty(resolve, \"_data\", { get: () => data }),\n        (error: any) =>\n          Object.defineProperty(resolve, \"_error\", { get: () => error })\n      );\n    }\n\n    if (\n      status === AwaitRenderStatus.error &&\n      promise._error instanceof AbortedDeferredError\n    ) {\n      // Freeze the UI by throwing a never resolved promise\n      throw neverSettledPromise;\n    }\n\n    if (status === AwaitRenderStatus.error && !errorElement) {\n      // No errorElement, throw to the nearest route-level error boundary\n      throw promise._error;\n    }\n\n    if (status === AwaitRenderStatus.error) {\n      // Render via our errorElement\n      return <AwaitContext.Provider value={promise} children={errorElement} />;\n    }\n\n    if (status === AwaitRenderStatus.success) {\n      // Render children with resolved value\n      return <AwaitContext.Provider value={promise} children={children} />;\n    }\n\n    // Throw to the suspense boundary\n    throw promise;\n  }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait({\n  children,\n}: {\n  children: React.ReactNode | AwaitResolveRenderFunction;\n}) {\n  let data = useAsyncValue();\n  let toRender = typeof children === \"function\" ? children(data) : children;\n  return <>{toRender}</>;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nexport function createRoutesFromChildren(\n  children: React.ReactNode,\n  parentPath: number[] = []\n): RouteObject[] {\n  let routes: RouteObject[] = [];\n\n  React.Children.forEach(children, (element, index) => {\n    if (!React.isValidElement(element)) {\n      // Ignore non-elements. This allows people to more easily inline\n      // conditionals in their route config.\n      return;\n    }\n\n    let treePath = [...parentPath, index];\n\n    if (element.type === React.Fragment) {\n      // Transparently support React.Fragment and its children.\n      routes.push.apply(\n        routes,\n        createRoutesFromChildren(element.props.children, treePath)\n      );\n      return;\n    }\n\n    invariant(\n      element.type === Route,\n      `[${\n        typeof element.type === \"string\" ? element.type : element.type.name\n      }] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`\n    );\n\n    invariant(\n      !element.props.index || !element.props.children,\n      \"An index route cannot have child routes.\"\n    );\n\n    let route: RouteObject = {\n      id: element.props.id || treePath.join(\"-\"),\n      caseSensitive: element.props.caseSensitive,\n      element: element.props.element,\n      Component: element.props.Component,\n      index: element.props.index,\n      path: element.props.path,\n      loader: element.props.loader,\n      action: element.props.action,\n      errorElement: element.props.errorElement,\n      ErrorBoundary: element.props.ErrorBoundary,\n      hasErrorBoundary:\n        element.props.ErrorBoundary != null ||\n        element.props.errorElement != null,\n      shouldRevalidate: element.props.shouldRevalidate,\n      handle: element.props.handle,\n      lazy: element.props.lazy,\n    };\n\n    if (element.props.children) {\n      route.children = createRoutesFromChildren(\n        element.props.children,\n        treePath\n      );\n    }\n\n    routes.push(route);\n  });\n\n  return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nexport function renderMatches(\n  matches: RouteMatch[] | null\n): React.ReactElement | null {\n  return _renderMatches(matches);\n}\n", "import * as React from \"react\";\nimport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AgnosticPatchRoutesOnNavigationFunction,\n  AgnosticPatchRoutesOnNavigationFunctionArgs,\n  Blocker,\n  BlockerFunction,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  HydrationState,\n  InitialEntry,\n  JsonFunction,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  Navigation,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  RedirectFunction,\n  RelativeRoutingType,\n  Router as RemixRouter,\n  FutureConfig as RouterFutureConfig,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"@remix-run/router\";\nimport {\n  AbortedDeferredError,\n  Action as NavigationType,\n  createMemoryHistory,\n  createPath,\n  createRouter,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  resolvePath,\n  UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n  AwaitProps,\n  FutureConfig,\n  IndexRouteProps,\n  LayoutRouteProps,\n  MemoryRouterProps,\n  NavigateProps,\n  OutletProps,\n  PathRouteProps,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n} from \"./lib/components\";\nimport {\n  Await,\n  MemoryRouter,\n  Navigate,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createRoutesFromChildren,\n  renderMatches,\n} from \"./lib/components\";\nimport type {\n  DataRouteMatch,\n  DataRouteObject,\n  IndexRouteObject,\n  NavigateOptions,\n  Navigator,\n  NonIndexRouteObject,\n  RouteMatch,\n  RouteObject,\n} from \"./lib/context\";\nimport {\n  DataRouterContext,\n  DataRouterStateContext,\n  LocationContext,\n  NavigationContext,\n  RouteContext,\n} from \"./lib/context\";\nimport type { NavigateFunction } from \"./lib/hooks\";\nimport {\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteId,\n  useRouteLoaderData,\n  useRoutes,\n  useRoutesImpl,\n} from \"./lib/hooks\";\nimport { logV6DeprecationWarnings } from \"./lib/deprecations\";\n\n// Exported for backwards compatibility, but not being used internally anymore\ntype Hash = string;\ntype Pathname = string;\ntype Search = string;\n\n// Expose react-router public API\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LayoutRouteProps,\n  LazyRouteFunction,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  ParamParseKey,\n  Params,\n  Path,\n  PathMatch,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  Pathname,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n  Blocker,\n  BlockerFunction,\n};\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  RouterProvider,\n  Routes,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromChildren as createRoutesFromElements,\n  defer,\n  generatePath,\n  isRouteErrorResponse,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useBlocker,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n};\n\nexport type PatchRoutesOnNavigationFunctionArgs =\n  AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;\n\nexport type PatchRoutesOnNavigationFunction =\n  AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;\n\nfunction mapRouteProperties(route: RouteObject) {\n  let updates: Partial<RouteObject> & { hasErrorBoundary: boolean } = {\n    // Note: this check also occurs in createRoutesFromChildren so update\n    // there if you change this -- please and thank you!\n    hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null,\n  };\n\n  if (route.Component) {\n    if (__DEV__) {\n      if (route.element) {\n        warning(\n          false,\n          \"You should not include both `Component` and `element` on your route - \" +\n            \"`Component` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      element: React.createElement(route.Component),\n      Component: undefined,\n    });\n  }\n\n  if (route.HydrateFallback) {\n    if (__DEV__) {\n      if (route.hydrateFallbackElement) {\n        warning(\n          false,\n          \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" +\n            \"`HydrateFallback` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      hydrateFallbackElement: React.createElement(route.HydrateFallback),\n      HydrateFallback: undefined,\n    });\n  }\n\n  if (route.ErrorBoundary) {\n    if (__DEV__) {\n      if (route.errorElement) {\n        warning(\n          false,\n          \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" +\n            \"`ErrorBoundary` will be used.\"\n        );\n      }\n    }\n    Object.assign(updates, {\n      errorElement: React.createElement(route.ErrorBoundary),\n      ErrorBoundary: undefined,\n    });\n  }\n\n  return updates;\n}\n\nexport function createMemoryRouter(\n  routes: RouteObject[],\n  opts?: {\n    basename?: string;\n    future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n    hydrationData?: HydrationState;\n    initialEntries?: InitialEntry[];\n    initialIndex?: number;\n    dataStrategy?: DataStrategyFunction;\n    patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  }\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createMemoryHistory({\n      initialEntries: opts?.initialEntries,\n      initialIndex: opts?.initialIndex,\n    }),\n    hydrationData: opts?.hydrationData,\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n  }).initialize();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  DataRouterContext as UNSAFE_DataRouterContext,\n  DataRouterStateContext as UNSAFE_DataRouterStateContext,\n  LocationContext as UNSAFE_LocationContext,\n  NavigationContext as UNSAFE_NavigationContext,\n  RouteContext as UNSAFE_RouteContext,\n  mapRouteProperties as UNSAFE_mapRouteProperties,\n  useRouteId as UNSAFE_useRouteId,\n  useRoutesImpl as UNSAFE_useRoutesImpl,\n  logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings,\n};\n", "import type {\n  FormEncType,\n  HTMLFormMethod,\n  RelativeRoutingType,\n} from \"@remix-run/router\";\nimport { stripBasename, UNSAFE_warning as warning } from \"@remix-run/router\";\n\nexport const defaultMethod: HTMLFormMethod = \"get\";\nconst defaultEncType: FormEncType = \"application/x-www-form-urlencoded\";\n\nexport function isHtmlElement(object: any): object is HTMLElement {\n  return object != null && typeof object.tagName === \"string\";\n}\n\nexport function isButtonElement(object: any): object is HTMLButtonElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"button\";\n}\n\nexport function isFormElement(object: any): object is HTMLFormElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"form\";\n}\n\nexport function isInputElement(object: any): object is HTMLInputElement {\n  return isHtmlElement(object) && object.tagName.toLowerCase() === \"input\";\n}\n\ntype LimitedMouseEvent = Pick<\n  MouseEvent,\n  \"button\" | \"metaKey\" | \"altKey\" | \"ctrlKey\" | \"shiftKey\"\n>;\n\nfunction isModifiedEvent(event: LimitedMouseEvent) {\n  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nexport function shouldProcessLinkClick(\n  event: LimitedMouseEvent,\n  target?: string\n) {\n  return (\n    event.button === 0 && // Ignore everything but left clicks\n    (!target || target === \"_self\") && // Let browser handle \"target=_blank\" etc.\n    !isModifiedEvent(event) // Ignore clicks with modifier keys\n  );\n}\n\nexport type ParamKeyValuePair = [string, string];\n\nexport type URLSearchParamsInit =\n  | string\n  | ParamKeyValuePair[]\n  | Record<string, string | string[]>\n  | URLSearchParams;\n\n/**\n * Creates a URLSearchParams object using the given initializer.\n *\n * This is identical to `new URLSearchParams(init)` except it also\n * supports arrays as values in the object form of the initializer\n * instead of just strings. This is convenient when you need multiple\n * values for a given key, but don't want to use an array initializer.\n *\n * For example, instead of:\n *\n *   let searchParams = new URLSearchParams([\n *     ['sort', 'name'],\n *     ['sort', 'price']\n *   ]);\n *\n * you can do:\n *\n *   let searchParams = createSearchParams({\n *     sort: ['name', 'price']\n *   });\n */\nexport function createSearchParams(\n  init: URLSearchParamsInit = \"\"\n): URLSearchParams {\n  return new URLSearchParams(\n    typeof init === \"string\" ||\n    Array.isArray(init) ||\n    init instanceof URLSearchParams\n      ? init\n      : Object.keys(init).reduce((memo, key) => {\n          let value = init[key];\n          return memo.concat(\n            Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]]\n          );\n        }, [] as ParamKeyValuePair[])\n  );\n}\n\nexport function getSearchParamsForLocation(\n  locationSearch: string,\n  defaultSearchParams: URLSearchParams | null\n) {\n  let searchParams = createSearchParams(locationSearch);\n\n  if (defaultSearchParams) {\n    // Use `defaultSearchParams.forEach(...)` here instead of iterating of\n    // `defaultSearchParams.keys()` to work-around a bug in Firefox related to\n    // web extensions. Relevant Bugzilla tickets:\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n    // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984\n    defaultSearchParams.forEach((_, key) => {\n      if (!searchParams.has(key)) {\n        defaultSearchParams.getAll(key).forEach((value) => {\n          searchParams.append(key, value);\n        });\n      }\n    });\n  }\n\n  return searchParams;\n}\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n  [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type SubmitTarget =\n  | HTMLFormElement\n  | HTMLButtonElement\n  | HTMLInputElement\n  | FormData\n  | URLSearchParams\n  | JsonValue\n  | null;\n\n// One-time check for submitter support\nlet _formDataSupportsSubmitter: boolean | null = null;\n\nfunction isFormDataSubmitterSupported() {\n  if (_formDataSupportsSubmitter === null) {\n    try {\n      new FormData(\n        document.createElement(\"form\"),\n        // @ts-expect-error if FormData supports the submitter parameter, this will throw\n        0\n      );\n      _formDataSupportsSubmitter = false;\n    } catch (e) {\n      _formDataSupportsSubmitter = true;\n    }\n  }\n  return _formDataSupportsSubmitter;\n}\n\n/**\n * Submit options shared by both navigations and fetchers\n */\ninterface SharedSubmitOptions {\n  /**\n   * The HTTP method used to submit the form. Overrides `<form method>`.\n   * Defaults to \"GET\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * The action URL path used to submit the form. Overrides `<form action>`.\n   * Defaults to the path of the current route.\n   */\n  action?: string;\n\n  /**\n   * The encoding used to submit the form. Overrides `<form encType>`.\n   * Defaults to \"application/x-www-form-urlencoded\".\n   */\n  encType?: FormEncType;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * In browser-based environments, prevent resetting scroll after this\n   * navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * Enable flushSync for this submission's state updates\n   */\n  flushSync?: boolean;\n}\n\n/**\n * Submit options available to fetchers\n */\nexport interface FetcherSubmitOptions extends SharedSubmitOptions {}\n\n/**\n * Submit options available to navigations\n */\nexport interface SubmitOptions extends FetcherSubmitOptions {\n  /**\n   * Set `true` to replace the current entry in the browser's history stack\n   * instead of creating a new one (i.e. stay on \"the same page\"). Defaults\n   * to `false`.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Enable view transitions on this submission navigation\n   */\n  viewTransition?: boolean;\n}\n\nconst supportedFormEncTypes: Set<FormEncType> = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\nfunction getFormEncType(encType: string | null) {\n  if (encType != null && !supportedFormEncTypes.has(encType as FormEncType)) {\n    warning(\n      false,\n      `\"${encType}\" is not a valid \\`encType\\` for \\`<Form>\\`/\\`<fetcher.Form>\\` ` +\n        `and will default to \"${defaultEncType}\"`\n    );\n\n    return null;\n  }\n  return encType;\n}\n\nexport function getFormSubmissionInfo(\n  target: SubmitTarget,\n  basename: string\n): {\n  action: string | null;\n  method: string;\n  encType: string;\n  formData: FormData | undefined;\n  body: any;\n} {\n  let method: string;\n  let action: string | null;\n  let encType: string;\n  let formData: FormData | undefined;\n  let body: any;\n\n  if (isFormElement(target)) {\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n    method = target.getAttribute(\"method\") || defaultMethod;\n    encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n\n    formData = new FormData(target);\n  } else if (\n    isButtonElement(target) ||\n    (isInputElement(target) &&\n      (target.type === \"submit\" || target.type === \"image\"))\n  ) {\n    let form = target.form;\n\n    if (form == null) {\n      throw new Error(\n        `Cannot submit a <button> or <input type=\"submit\"> without a <form>`\n      );\n    }\n\n    // <button>/<input type=\"submit\"> may override attributes of <form>\n\n    // When grabbing the action from the element, it will have had the basename\n    // prefixed to ensure non-JS scenarios work, so strip it since we'll\n    // re-prefix in the router\n    let attr = target.getAttribute(\"formaction\") || form.getAttribute(\"action\");\n    action = attr ? stripBasename(attr, basename) : null;\n\n    method =\n      target.getAttribute(\"formmethod\") ||\n      form.getAttribute(\"method\") ||\n      defaultMethod;\n    encType =\n      getFormEncType(target.getAttribute(\"formenctype\")) ||\n      getFormEncType(form.getAttribute(\"enctype\")) ||\n      defaultEncType;\n\n    // Build a FormData object populated from a form and submitter\n    formData = new FormData(form, target);\n\n    // If this browser doesn't support the `FormData(el, submitter)` format,\n    // then tack on the submitter value at the end.  This is a lightweight\n    // solution that is not 100% spec compliant.  For complete support in older\n    // browsers, consider using the `formdata-submitter-polyfill` package\n    if (!isFormDataSubmitterSupported()) {\n      let { name, type, value } = target;\n      if (type === \"image\") {\n        let prefix = name ? `${name}.` : \"\";\n        formData.append(`${prefix}x`, \"0\");\n        formData.append(`${prefix}y`, \"0\");\n      } else if (name) {\n        formData.append(name, value);\n      }\n    }\n  } else if (isHtmlElement(target)) {\n    throw new Error(\n      `Cannot submit element that is not <form>, <button>, or ` +\n        `<input type=\"submit|image\">`\n    );\n  } else {\n    method = defaultMethod;\n    action = null;\n    encType = defaultEncType;\n    body = target;\n  }\n\n  // Send body for <Form encType=\"text/plain\" so we encode it into text\n  if (formData && encType === \"text/plain\") {\n    body = formData;\n    formData = undefined;\n  }\n\n  return { action, method: method.toLowerCase(), encType, formData, body };\n}\n", "/**\n * NOTE: If you refactor this to split up the modules into separate files,\n * you'll need to update the rollup config for react-router-dom-v5-compat.\n */\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type {\n  DataRouteObject,\n  FutureConfig,\n  Location,\n  NavigateOptions,\n  NavigationType,\n  Navigator,\n  RelativeRoutingType,\n  RouteObject,\n  RouterProps,\n  RouterProviderProps,\n  To,\n  DataStrategyFunction,\n  PatchRoutesOnNavigationFunction,\n} from \"react-router\";\nimport {\n  Router,\n  createPath,\n  useHref,\n  useLocation,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useResolvedPath,\n  useBlocker,\n  UNSAFE_DataRouterContext as DataRouterContext,\n  UNSAFE_DataRouterStateContext as DataRouterStateContext,\n  UNSAFE_NavigationContext as NavigationContext,\n  UNSAFE_RouteContext as RouteContext,\n  UNSAFE_logV6DeprecationWarnings as logV6DeprecationWarnings,\n  UNSAFE_mapRouteProperties as mapRouteProperties,\n  UNSAFE_useRouteId as useRouteId,\n  UNSAFE_useRoutesImpl as useRoutesImpl,\n} from \"react-router\";\nimport type {\n  BrowserHistory,\n  Fetcher,\n  FormEncType,\n  FormMethod,\n  FutureConfig as RouterFutureConfig,\n  GetScrollRestorationKeyFunction,\n  HashHistory,\n  History,\n  HTMLFormMethod,\n  HydrationState,\n  Router as RemixRouter,\n  V7_FormMethod,\n  RouterState,\n  RouterSubscriber,\n  BlockerFunction,\n} from \"@remix-run/router\";\nimport {\n  createRouter,\n  createBrowserHistory,\n  createHashHistory,\n  joinPaths,\n  stripBasename,\n  UNSAFE_ErrorResponseImpl as ErrorResponseImpl,\n  UNSAFE_invariant as invariant,\n  UNSAFE_warning as warning,\n  matchPath,\n  IDLE_FETCHER,\n} from \"@remix-run/router\";\n\nimport type {\n  SubmitOptions,\n  ParamKeyValuePair,\n  URLSearchParamsInit,\n  SubmitTarget,\n  FetcherSubmitOptions,\n} from \"./dom\";\nimport {\n  createSearchParams,\n  defaultMethod,\n  getFormSubmissionInfo,\n  getSearchParamsForLocation,\n  shouldProcessLinkClick,\n} from \"./dom\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Re-exports\n////////////////////////////////////////////////////////////////////////////////\n\nexport type {\n  FormEncType,\n  FormMethod,\n  GetScrollRestorationKeyFunction,\n  ParamKeyValuePair,\n  SubmitOptions,\n  URLSearchParamsInit,\n  V7_FormMethod,\n};\nexport { createSearchParams, ErrorResponseImpl as UNSAFE_ErrorResponseImpl };\n\n// Note: Keep in sync with react-router exports!\nexport type {\n  ActionFunction,\n  ActionFunctionArgs,\n  AwaitProps,\n  Blocker,\n  BlockerFunction,\n  DataRouteMatch,\n  DataRouteObject,\n  DataStrategyFunction,\n  DataStrategyFunctionArgs,\n  DataStrategyMatch,\n  DataStrategyResult,\n  ErrorResponse,\n  Fetcher,\n  FutureConfig,\n  Hash,\n  IndexRouteObject,\n  IndexRouteProps,\n  JsonFunction,\n  LazyRouteFunction,\n  LayoutRouteProps,\n  LoaderFunction,\n  LoaderFunctionArgs,\n  Location,\n  MemoryRouterProps,\n  NavigateFunction,\n  NavigateOptions,\n  NavigateProps,\n  Navigation,\n  Navigator,\n  NonIndexRouteObject,\n  OutletProps,\n  Params,\n  ParamParseKey,\n  PatchRoutesOnNavigationFunction,\n  PatchRoutesOnNavigationFunctionArgs,\n  Path,\n  PathMatch,\n  Pathname,\n  PathParam,\n  PathPattern,\n  PathRouteProps,\n  RedirectFunction,\n  RelativeRoutingType,\n  RouteMatch,\n  RouteObject,\n  RouteProps,\n  RouterProps,\n  RouterProviderProps,\n  RoutesProps,\n  Search,\n  ShouldRevalidateFunction,\n  ShouldRevalidateFunctionArgs,\n  To,\n  UIMatch,\n} from \"react-router\";\nexport {\n  AbortedDeferredError,\n  Await,\n  MemoryRouter,\n  Navigate,\n  NavigationType,\n  Outlet,\n  Route,\n  Router,\n  Routes,\n  createMemoryRouter,\n  createPath,\n  createRoutesFromChildren,\n  createRoutesFromElements,\n  defer,\n  isRouteErrorResponse,\n  generatePath,\n  json,\n  matchPath,\n  matchRoutes,\n  parsePath,\n  redirect,\n  redirectDocument,\n  replace,\n  renderMatches,\n  resolvePath,\n  useActionData,\n  useAsyncError,\n  useAsyncValue,\n  useBlocker,\n  useHref,\n  useInRouterContext,\n  useLoaderData,\n  useLocation,\n  useMatch,\n  useMatches,\n  useNavigate,\n  useNavigation,\n  useNavigationType,\n  useOutlet,\n  useOutletContext,\n  useParams,\n  useResolvedPath,\n  useRevalidator,\n  useRouteError,\n  useRouteLoaderData,\n  useRoutes,\n} from \"react-router\";\n\n///////////////////////////////////////////////////////////////////////////////\n// DANGER! PLEASE READ ME!\n// We provide these exports as an escape hatch in the event that you need any\n// routing data that we don't provide an explicit API for. With that said, we\n// want to cover your use case if we can, so if you feel the need to use these\n// we want to hear from you. Let us know what you're building and we'll do our\n// best to make sure we can support you!\n//\n// We consider these exports an implementation detail and do not guarantee\n// against any breaking changes, regardless of the semver release. Use with\n// extreme caution and only if you understand the consequences. Godspeed.\n///////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport {\n  UNSAFE_DataRouterContext,\n  UNSAFE_DataRouterStateContext,\n  UNSAFE_NavigationContext,\n  UNSAFE_LocationContext,\n  UNSAFE_RouteContext,\n  UNSAFE_useRouteId,\n} from \"react-router\";\n//#endregion\n\ndeclare global {\n  var __staticRouterHydrationData: HydrationState | undefined;\n  var __reactRouterVersion: string;\n  interface Document {\n    startViewTransition(cb: () => Promise<void> | void): ViewTransition;\n  }\n}\n\n// HEY YOU! DON'T TOUCH THIS VARIABLE!\n//\n// It is replaced with the proper version at build time via a babel plugin in\n// the rollup config.\n//\n// Export a global property onto the window for React Router detection by the\n// Core Web Vitals Technology Report.  This way they can configure the `wappalyzer`\n// to detect and properly classify live websites as being built with React Router:\n// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json\nconst REACT_ROUTER_VERSION = \"0\";\ntry {\n  window.__reactRouterVersion = REACT_ROUTER_VERSION;\n} catch (e) {\n  // no-op\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Routers\n////////////////////////////////////////////////////////////////////////////////\n\ninterface DOMRouterOpts {\n  basename?: string;\n  future?: Partial<Omit<RouterFutureConfig, \"v7_prependBasename\">>;\n  hydrationData?: HydrationState;\n  dataStrategy?: DataStrategyFunction;\n  patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;\n  window?: Window;\n}\n\nexport function createBrowserRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createBrowserHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nexport function createHashRouter(\n  routes: RouteObject[],\n  opts?: DOMRouterOpts\n): RemixRouter {\n  return createRouter({\n    basename: opts?.basename,\n    future: {\n      ...opts?.future,\n      v7_prependBasename: true,\n    },\n    history: createHashHistory({ window: opts?.window }),\n    hydrationData: opts?.hydrationData || parseHydrationData(),\n    routes,\n    mapRouteProperties,\n    dataStrategy: opts?.dataStrategy,\n    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,\n    window: opts?.window,\n  }).initialize();\n}\n\nfunction parseHydrationData(): HydrationState | undefined {\n  let state = window?.__staticRouterHydrationData;\n  if (state && state.errors) {\n    state = {\n      ...state,\n      errors: deserializeErrors(state.errors),\n    };\n  }\n  return state;\n}\n\nfunction deserializeErrors(\n  errors: RemixRouter[\"state\"][\"errors\"]\n): RemixRouter[\"state\"][\"errors\"] {\n  if (!errors) return null;\n  let entries = Object.entries(errors);\n  let serialized: RemixRouter[\"state\"][\"errors\"] = {};\n  for (let [key, val] of entries) {\n    // Hey you!  If you change this, please change the corresponding logic in\n    // serializeErrors in react-router-dom/server.tsx :)\n    if (val && val.__type === \"RouteErrorResponse\") {\n      serialized[key] = new ErrorResponseImpl(\n        val.status,\n        val.statusText,\n        val.data,\n        val.internal === true\n      );\n    } else if (val && val.__type === \"Error\") {\n      // Attempt to reconstruct the right type of Error (i.e., ReferenceError)\n      if (val.__subType) {\n        let ErrorConstructor = window[val.__subType];\n        if (typeof ErrorConstructor === \"function\") {\n          try {\n            // @ts-expect-error\n            let error = new ErrorConstructor(val.message);\n            // Wipe away the client-side stack trace.  Nothing to fill it in with\n            // because we don't serialize SSR stack traces for security reasons\n            error.stack = \"\";\n            serialized[key] = error;\n          } catch (e) {\n            // no-op - fall through and create a normal Error\n          }\n        }\n      }\n\n      if (serialized[key] == null) {\n        let error = new Error(val.message);\n        // Wipe away the client-side stack trace.  Nothing to fill it in with\n        // because we don't serialize SSR stack traces for security reasons\n        error.stack = \"\";\n        serialized[key] = error;\n      }\n    } else {\n      serialized[key] = val;\n    }\n  }\n  return serialized;\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Contexts\n////////////////////////////////////////////////////////////////////////////////\n\ntype ViewTransitionContextObject =\n  | {\n      isTransitioning: false;\n    }\n  | {\n      isTransitioning: true;\n      flushSync: boolean;\n      currentLocation: Location;\n      nextLocation: Location;\n    };\n\nconst ViewTransitionContext = React.createContext<ViewTransitionContextObject>({\n  isTransitioning: false,\n});\nif (__DEV__) {\n  ViewTransitionContext.displayName = \"ViewTransition\";\n}\n\nexport { ViewTransitionContext as UNSAFE_ViewTransitionContext };\n\n// TODO: (v7) Change the useFetcher data from `any` to `unknown`\ntype FetchersContextObject = Map<string, any>;\n\nconst FetchersContext = React.createContext<FetchersContextObject>(new Map());\nif (__DEV__) {\n  FetchersContext.displayName = \"Fetchers\";\n}\n\nexport { FetchersContext as UNSAFE_FetchersContext };\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Components\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n  Webpack + React 17 fails to compile on any of the following because webpack\n  complains that `startTransition` doesn't exist in `React`:\n  * import { startTransition } from \"react\"\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n  * import * as React from from \"react\";\n    \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n  Moving it to a constant such as the following solves the Webpack/React 17 issue:\n  * import * as React from from \"react\";\n    const START_TRANSITION = \"startTransition\";\n    START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n  However, that introduces webpack/terser minification issues in production builds\n  in React 18 where minification/obfuscation ends up removing the call of\n  React.startTransition entirely from the first half of the ternary.  Grabbing\n  this exported reference once up front resolves that issue.\n\n  See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\nconst FLUSH_SYNC = \"flushSync\";\nconst flushSyncImpl = ReactDOM[FLUSH_SYNC];\nconst USE_ID = \"useId\";\nconst useIdImpl = React[USE_ID];\n\nfunction startTransitionSafe(cb: () => void) {\n  if (startTransitionImpl) {\n    startTransitionImpl(cb);\n  } else {\n    cb();\n  }\n}\n\nfunction flushSyncSafe(cb: () => void) {\n  if (flushSyncImpl) {\n    flushSyncImpl(cb);\n  } else {\n    cb();\n  }\n}\n\ninterface ViewTransition {\n  finished: Promise<void>;\n  ready: Promise<void>;\n  updateCallbackDone: Promise<void>;\n  skipTransition(): void;\n}\n\nclass Deferred<T> {\n  status: \"pending\" | \"resolved\" | \"rejected\" = \"pending\";\n  promise: Promise<T>;\n  // @ts-expect-error - no initializer\n  resolve: (value: T) => void;\n  // @ts-expect-error - no initializer\n  reject: (reason?: unknown) => void;\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = (value) => {\n        if (this.status === \"pending\") {\n          this.status = \"resolved\";\n          resolve(value);\n        }\n      };\n      this.reject = (reason) => {\n        if (this.status === \"pending\") {\n          this.status = \"rejected\";\n          reject(reason);\n        }\n      };\n    });\n  }\n}\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n  fallbackElement,\n  router,\n  future,\n}: RouterProviderProps): React.ReactElement {\n  let [state, setStateImpl] = React.useState(router.state);\n  let [pendingState, setPendingState] = React.useState<RouterState>();\n  let [vtContext, setVtContext] = React.useState<ViewTransitionContextObject>({\n    isTransitioning: false,\n  });\n  let [renderDfd, setRenderDfd] = React.useState<Deferred<void>>();\n  let [transition, setTransition] = React.useState<ViewTransition>();\n  let [interruption, setInterruption] = React.useState<{\n    state: RouterState;\n    currentLocation: Location;\n    nextLocation: Location;\n  }>();\n  let fetcherData = React.useRef<Map<string, any>>(new Map());\n  let { v7_startTransition } = future || {};\n\n  let optInStartTransition = React.useCallback(\n    (cb: () => void) => {\n      if (v7_startTransition) {\n        startTransitionSafe(cb);\n      } else {\n        cb();\n      }\n    },\n    [v7_startTransition]\n  );\n\n  let setState = React.useCallback<RouterSubscriber>(\n    (\n      newState: RouterState,\n      {\n        deletedFetchers,\n        flushSync: flushSync,\n        viewTransitionOpts: viewTransitionOpts,\n      }\n    ) => {\n      deletedFetchers.forEach((key) => fetcherData.current.delete(key));\n      newState.fetchers.forEach((fetcher, key) => {\n        if (fetcher.data !== undefined) {\n          fetcherData.current.set(key, fetcher.data);\n        }\n      });\n\n      let isViewTransitionUnavailable =\n        router.window == null ||\n        router.window.document == null ||\n        typeof router.window.document.startViewTransition !== \"function\";\n\n      // If this isn't a view transition or it's not available in this browser,\n      // just update and be done with it\n      if (!viewTransitionOpts || isViewTransitionUnavailable) {\n        if (flushSync) {\n          flushSyncSafe(() => setStateImpl(newState));\n        } else {\n          optInStartTransition(() => setStateImpl(newState));\n        }\n        return;\n      }\n\n      // flushSync + startViewTransition\n      if (flushSync) {\n        // Flush through the context to mark DOM elements as transition=ing\n        flushSyncSafe(() => {\n          // Cancel any pending transitions\n          if (transition) {\n            renderDfd && renderDfd.resolve();\n            transition.skipTransition();\n          }\n          setVtContext({\n            isTransitioning: true,\n            flushSync: true,\n            currentLocation: viewTransitionOpts.currentLocation,\n            nextLocation: viewTransitionOpts.nextLocation,\n          });\n        });\n\n        // Update the DOM\n        let t = router.window!.document.startViewTransition(() => {\n          flushSyncSafe(() => setStateImpl(newState));\n        });\n\n        // Clean up after the animation completes\n        t.finished.finally(() => {\n          flushSyncSafe(() => {\n            setRenderDfd(undefined);\n            setTransition(undefined);\n            setPendingState(undefined);\n            setVtContext({ isTransitioning: false });\n          });\n        });\n\n        flushSyncSafe(() => setTransition(t));\n        return;\n      }\n\n      // startTransition + startViewTransition\n      if (transition) {\n        // Interrupting an in-progress transition, cancel and let everything flush\n        // out, and then kick off a new transition from the interruption state\n        renderDfd && renderDfd.resolve();\n        transition.skipTransition();\n        setInterruption({\n          state: newState,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      } else {\n        // Completed navigation update with opted-in view transitions, let 'er rip\n        setPendingState(newState);\n        setVtContext({\n          isTransitioning: true,\n          flushSync: false,\n          currentLocation: viewTransitionOpts.currentLocation,\n          nextLocation: viewTransitionOpts.nextLocation,\n        });\n      }\n    },\n    [router.window, transition, renderDfd, fetcherData, optInStartTransition]\n  );\n\n  // Need to use a layout effect here so we are subscribed early enough to\n  // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n  React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n  // When we start a view transition, create a Deferred we can use for the\n  // eventual \"completed\" render\n  React.useEffect(() => {\n    if (vtContext.isTransitioning && !vtContext.flushSync) {\n      setRenderDfd(new Deferred<void>());\n    }\n  }, [vtContext]);\n\n  // Once the deferred is created, kick off startViewTransition() to update the\n  // DOM and then wait on the Deferred to resolve (indicating the DOM update has\n  // happened)\n  React.useEffect(() => {\n    if (renderDfd && pendingState && router.window) {\n      let newState = pendingState;\n      let renderPromise = renderDfd.promise;\n      let transition = router.window.document.startViewTransition(async () => {\n        optInStartTransition(() => setStateImpl(newState));\n        await renderPromise;\n      });\n      transition.finished.finally(() => {\n        setRenderDfd(undefined);\n        setTransition(undefined);\n        setPendingState(undefined);\n        setVtContext({ isTransitioning: false });\n      });\n      setTransition(transition);\n    }\n  }, [optInStartTransition, pendingState, renderDfd, router.window]);\n\n  // When the new location finally renders and is committed to the DOM, this\n  // effect will run to resolve the transition\n  React.useEffect(() => {\n    if (\n      renderDfd &&\n      pendingState &&\n      state.location.key === pendingState.location.key\n    ) {\n      renderDfd.resolve();\n    }\n  }, [renderDfd, transition, state.location, pendingState]);\n\n  // If we get interrupted with a new navigation during a transition, we skip\n  // the active transition, let it cleanup, then kick it off again here\n  React.useEffect(() => {\n    if (!vtContext.isTransitioning && interruption) {\n      setPendingState(interruption.state);\n      setVtContext({\n        isTransitioning: true,\n        flushSync: false,\n        currentLocation: interruption.currentLocation,\n        nextLocation: interruption.nextLocation,\n      });\n      setInterruption(undefined);\n    }\n  }, [vtContext.isTransitioning, interruption]);\n\n  React.useEffect(() => {\n    warning(\n      fallbackElement == null || !router.future.v7_partialHydration,\n      \"`<RouterProvider fallbackElement>` is deprecated when using \" +\n        \"`v7_partialHydration`, use a `HydrateFallback` component instead\"\n    );\n    // Only log this once on initial mount\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  let navigator = React.useMemo((): Navigator => {\n    return {\n      createHref: router.createHref,\n      encodeLocation: router.encodeLocation,\n      go: (n) => router.navigate(n),\n      push: (to, state, opts) =>\n        router.navigate(to, {\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n      replace: (to, state, opts) =>\n        router.navigate(to, {\n          replace: true,\n          state,\n          preventScrollReset: opts?.preventScrollReset,\n        }),\n    };\n  }, [router]);\n\n  let basename = router.basename || \"/\";\n\n  let dataRouterContext = React.useMemo(\n    () => ({\n      router,\n      navigator,\n      static: false,\n      basename,\n    }),\n    [router, navigator, basename]\n  );\n\n  let routerFuture = React.useMemo<RouterProps[\"future\"]>(\n    () => ({\n      v7_relativeSplatPath: router.future.v7_relativeSplatPath,\n    }),\n    [router.future.v7_relativeSplatPath]\n  );\n\n  React.useEffect(\n    () => logV6DeprecationWarnings(future, router.future),\n    [future, router.future]\n  );\n\n  // The fragment and {null} here are important!  We need them to keep React 18's\n  // useId happy when we are server-rendering since we may have a <script> here\n  // containing the hydrated server-side staticContext (from StaticRouterProvider).\n  // useId relies on the component tree structure to generate deterministic id's\n  // so we need to ensure it remains the same on the client even though\n  // we don't need the <script> tag\n  return (\n    <>\n      <DataRouterContext.Provider value={dataRouterContext}>\n        <DataRouterStateContext.Provider value={state}>\n          <FetchersContext.Provider value={fetcherData.current}>\n            <ViewTransitionContext.Provider value={vtContext}>\n              <Router\n                basename={basename}\n                location={state.location}\n                navigationType={state.historyAction}\n                navigator={navigator}\n                future={routerFuture}\n              >\n                {state.initialized || router.future.v7_partialHydration ? (\n                  <MemoizedDataRoutes\n                    routes={router.routes}\n                    future={router.future}\n                    state={state}\n                  />\n                ) : (\n                  fallbackElement\n                )}\n              </Router>\n            </ViewTransitionContext.Provider>\n          </FetchersContext.Provider>\n        </DataRouterStateContext.Provider>\n      </DataRouterContext.Provider>\n      {null}\n    </>\n  );\n}\n\n// Memoize to avoid re-renders when updating `ViewTransitionContext`\nconst MemoizedDataRoutes = React.memo(DataRoutes);\n\nfunction DataRoutes({\n  routes,\n  future,\n  state,\n}: {\n  routes: DataRouteObject[];\n  future: RemixRouter[\"future\"];\n  state: RouterState;\n}): React.ReactElement | null {\n  return useRoutesImpl(routes, undefined, state, future);\n}\n\nexport interface BrowserRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Provides the cleanest URLs.\n */\nexport function BrowserRouter({\n  basename,\n  children,\n  future,\n  window,\n}: BrowserRouterProps) {\n  let historyRef = React.useRef<BrowserHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createBrowserHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HashRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: Partial<FutureConfig>;\n  window?: Window;\n}\n\n/**\n * A `<Router>` for use in web browsers. Stores the location in the hash\n * portion of the URL so it is not sent to the server.\n */\nexport function HashRouter({\n  basename,\n  children,\n  future,\n  window,\n}: HashRouterProps) {\n  let historyRef = React.useRef<HashHistory>();\n  if (historyRef.current == null) {\n    historyRef.current = createHashHistory({ window, v5Compat: true });\n  }\n\n  let history = historyRef.current;\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nexport interface HistoryRouterProps {\n  basename?: string;\n  children?: React.ReactNode;\n  future?: FutureConfig;\n  history: History;\n}\n\n/**\n * A `<Router>` that accepts a pre-instantiated history object. It's important\n * to note that using your own history object is highly discouraged and may add\n * two versions of the history library to your bundles unless you use the same\n * version of the history library that React Router uses internally.\n */\nfunction HistoryRouter({\n  basename,\n  children,\n  future,\n  history,\n}: HistoryRouterProps) {\n  let [state, setStateImpl] = React.useState({\n    action: history.action,\n    location: history.location,\n  });\n  let { v7_startTransition } = future || {};\n  let setState = React.useCallback(\n    (newState: { action: NavigationType; location: Location }) => {\n      v7_startTransition && startTransitionImpl\n        ? startTransitionImpl(() => setStateImpl(newState))\n        : setStateImpl(newState);\n    },\n    [setStateImpl, v7_startTransition]\n  );\n\n  React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n\n  React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n\n  return (\n    <Router\n      basename={basename}\n      children={children}\n      location={state.location}\n      navigationType={state.action}\n      navigator={history}\n      future={future}\n    />\n  );\n}\n\nif (__DEV__) {\n  HistoryRouter.displayName = \"unstable_HistoryRouter\";\n}\n\nexport { HistoryRouter as unstable_HistoryRouter };\n\nexport interface LinkProps\n  extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n  reloadDocument?: boolean;\n  replace?: boolean;\n  state?: any;\n  preventScrollReset?: boolean;\n  relative?: RelativeRoutingType;\n  to: To;\n  viewTransition?: boolean;\n}\n\nconst isBrowser =\n  typeof window !== \"undefined\" &&\n  typeof window.document !== \"undefined\" &&\n  typeof window.document.createElement !== \"undefined\";\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/**\n * The public API for rendering a history-aware `<a>`.\n */\nexport const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(\n  function LinkWithRef(\n    {\n      onClick,\n      relative,\n      reloadDocument,\n      replace,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      viewTransition,\n      ...rest\n    },\n    ref\n  ) {\n    let { basename } = React.useContext(NavigationContext);\n\n    // Rendered into <a href> for absolute URLs\n    let absoluteHref;\n    let isExternal = false;\n\n    if (typeof to === \"string\" && ABSOLUTE_URL_REGEX.test(to)) {\n      // Render the absolute href server- and client-side\n      absoluteHref = to;\n\n      // Only check for external origins client-side\n      if (isBrowser) {\n        try {\n          let currentUrl = new URL(window.location.href);\n          let targetUrl = to.startsWith(\"//\")\n            ? new URL(currentUrl.protocol + to)\n            : new URL(to);\n          let path = stripBasename(targetUrl.pathname, basename);\n\n          if (targetUrl.origin === currentUrl.origin && path != null) {\n            // Strip the protocol/origin/basename for same-origin absolute URLs\n            to = path + targetUrl.search + targetUrl.hash;\n          } else {\n            isExternal = true;\n          }\n        } catch (e) {\n          // We can't do external URL detection without a valid URL\n          warning(\n            false,\n            `<Link to=\"${to}\"> contains an invalid URL which will probably break ` +\n              `when clicked - please update to a valid URL path.`\n          );\n        }\n      }\n    }\n\n    // Rendered into <a href> for relative URLs\n    let href = useHref(to, { relative });\n\n    let internalOnClick = useLinkClickHandler(to, {\n      replace,\n      state,\n      target,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    });\n    function handleClick(\n      event: React.MouseEvent<HTMLAnchorElement, MouseEvent>\n    ) {\n      if (onClick) onClick(event);\n      if (!event.defaultPrevented) {\n        internalOnClick(event);\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/anchor-has-content\n      <a\n        {...rest}\n        href={absoluteHref || href}\n        onClick={isExternal || reloadDocument ? onClick : handleClick}\n        ref={ref}\n        target={target}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Link.displayName = \"Link\";\n}\n\nexport type NavLinkRenderProps = {\n  isActive: boolean;\n  isPending: boolean;\n  isTransitioning: boolean;\n};\n\nexport interface NavLinkProps\n  extends Omit<LinkProps, \"className\" | \"style\" | \"children\"> {\n  children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);\n  caseSensitive?: boolean;\n  className?: string | ((props: NavLinkRenderProps) => string | undefined);\n  end?: boolean;\n  style?:\n    | React.CSSProperties\n    | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);\n}\n\n/**\n * A `<Link>` wrapper that knows if it's \"active\" or not.\n */\nexport const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(\n  function NavLinkWithRef(\n    {\n      \"aria-current\": ariaCurrentProp = \"page\",\n      caseSensitive = false,\n      className: classNameProp = \"\",\n      end = false,\n      style: styleProp,\n      to,\n      viewTransition,\n      children,\n      ...rest\n    },\n    ref\n  ) {\n    let path = useResolvedPath(to, { relative: rest.relative });\n    let location = useLocation();\n    let routerState = React.useContext(DataRouterStateContext);\n    let { navigator, basename } = React.useContext(NavigationContext);\n    let isTransitioning =\n      routerState != null &&\n      // Conditional usage is OK here because the usage of a data router is static\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      useViewTransitionState(path) &&\n      viewTransition === true;\n\n    let toPathname = navigator.encodeLocation\n      ? navigator.encodeLocation(path).pathname\n      : path.pathname;\n    let locationPathname = location.pathname;\n    let nextLocationPathname =\n      routerState && routerState.navigation && routerState.navigation.location\n        ? routerState.navigation.location.pathname\n        : null;\n\n    if (!caseSensitive) {\n      locationPathname = locationPathname.toLowerCase();\n      nextLocationPathname = nextLocationPathname\n        ? nextLocationPathname.toLowerCase()\n        : null;\n      toPathname = toPathname.toLowerCase();\n    }\n\n    if (nextLocationPathname && basename) {\n      nextLocationPathname =\n        stripBasename(nextLocationPathname, basename) || nextLocationPathname;\n    }\n\n    // If the `to` has a trailing slash, look at that exact spot.  Otherwise,\n    // we're looking for a slash _after_ what's in `to`.  For example:\n    //\n    // <NavLink to=\"/users\"> and <NavLink to=\"/users/\">\n    // both want to look for a / at index 6 to match URL `/users/matt`\n    const endSlashPosition =\n      toPathname !== \"/\" && toPathname.endsWith(\"/\")\n        ? toPathname.length - 1\n        : toPathname.length;\n    let isActive =\n      locationPathname === toPathname ||\n      (!end &&\n        locationPathname.startsWith(toPathname) &&\n        locationPathname.charAt(endSlashPosition) === \"/\");\n\n    let isPending =\n      nextLocationPathname != null &&\n      (nextLocationPathname === toPathname ||\n        (!end &&\n          nextLocationPathname.startsWith(toPathname) &&\n          nextLocationPathname.charAt(toPathname.length) === \"/\"));\n\n    let renderProps = {\n      isActive,\n      isPending,\n      isTransitioning,\n    };\n\n    let ariaCurrent = isActive ? ariaCurrentProp : undefined;\n\n    let className: string | undefined;\n    if (typeof classNameProp === \"function\") {\n      className = classNameProp(renderProps);\n    } else {\n      // If the className prop is not a function, we use a default `active`\n      // class for <NavLink />s that are active. In v5 `active` was the default\n      // value for `activeClassName`, but we are removing that API and can still\n      // use the old default behavior for a cleaner upgrade path and keep the\n      // simple styling rules working as they currently do.\n      className = [\n        classNameProp,\n        isActive ? \"active\" : null,\n        isPending ? \"pending\" : null,\n        isTransitioning ? \"transitioning\" : null,\n      ]\n        .filter(Boolean)\n        .join(\" \");\n    }\n\n    let style =\n      typeof styleProp === \"function\" ? styleProp(renderProps) : styleProp;\n\n    return (\n      <Link\n        {...rest}\n        aria-current={ariaCurrent}\n        className={className}\n        ref={ref}\n        style={style}\n        to={to}\n        viewTransition={viewTransition}\n      >\n        {typeof children === \"function\" ? children(renderProps) : children}\n      </Link>\n    );\n  }\n);\n\nif (__DEV__) {\n  NavLink.displayName = \"NavLink\";\n}\n\n/**\n * Form props shared by navigations and fetchers\n */\ninterface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {\n  /**\n   * The HTTP verb to use when the form is submit. Supports \"get\", \"post\",\n   * \"put\", \"delete\", \"patch\".\n   */\n  method?: HTMLFormMethod;\n\n  /**\n   * `<form encType>` - enhancing beyond the normal string type and limiting\n   * to the built-in browser supported values\n   */\n  encType?:\n    | \"application/x-www-form-urlencoded\"\n    | \"multipart/form-data\"\n    | \"text/plain\";\n\n  /**\n   * Normal `<form action>` but supports React Router's relative paths.\n   */\n  action?: string;\n\n  /**\n   * Determines whether the form action is relative to the route hierarchy or\n   * the pathname.  Use this if you want to opt out of navigating the route\n   * hierarchy and want to instead route based on /-delimited URL segments\n   */\n  relative?: RelativeRoutingType;\n\n  /**\n   * Prevent the scroll position from resetting to the top of the viewport on\n   * completion of the navigation when using the <ScrollRestoration> component\n   */\n  preventScrollReset?: boolean;\n\n  /**\n   * A function to call when the form is submitted. If you call\n   * `event.preventDefault()` then this form will not do anything.\n   */\n  onSubmit?: React.FormEventHandler<HTMLFormElement>;\n}\n\n/**\n * Form props available to fetchers\n */\nexport interface FetcherFormProps extends SharedFormProps {}\n\n/**\n * Form props available to navigations\n */\nexport interface FormProps extends SharedFormProps {\n  /**\n   * Indicate a specific fetcherKey to use when using navigate=false\n   */\n  fetcherKey?: string;\n\n  /**\n   * navigate=false will use a fetcher instead of a navigation\n   */\n  navigate?: boolean;\n\n  /**\n   * Forces a full document navigation instead of a fetch.\n   */\n  reloadDocument?: boolean;\n\n  /**\n   * Replaces the current entry in the browser history stack when the form\n   * navigates. Use this if you don't want the user to be able to click \"back\"\n   * to the page with the form on it.\n   */\n  replace?: boolean;\n\n  /**\n   * State object to add to the history stack entry for this navigation\n   */\n  state?: any;\n\n  /**\n   * Enable view transitions on this Form navigation\n   */\n  viewTransition?: boolean;\n}\n\ntype HTMLSubmitEvent = React.BaseSyntheticEvent<\n  SubmitEvent,\n  Event,\n  HTMLFormElement\n>;\n\ntype HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;\n\n/**\n * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except\n * that the interaction with the server is with `fetch` instead of new document\n * requests, allowing components to add nicer UX to the page as the form is\n * submitted and returns with data.\n */\nexport const Form = React.forwardRef<HTMLFormElement, FormProps>(\n  (\n    {\n      fetcherKey,\n      navigate,\n      reloadDocument,\n      replace,\n      state,\n      method = defaultMethod,\n      action,\n      onSubmit,\n      relative,\n      preventScrollReset,\n      viewTransition,\n      ...props\n    },\n    forwardedRef\n  ) => {\n    let submit = useSubmit();\n    let formAction = useFormAction(action, { relative });\n    let formMethod: HTMLFormMethod =\n      method.toLowerCase() === \"get\" ? \"get\" : \"post\";\n\n    let submitHandler: React.FormEventHandler<HTMLFormElement> = (event) => {\n      onSubmit && onSubmit(event);\n      if (event.defaultPrevented) return;\n      event.preventDefault();\n\n      let submitter = (event as unknown as HTMLSubmitEvent).nativeEvent\n        .submitter as HTMLFormSubmitter | null;\n\n      let submitMethod =\n        (submitter?.getAttribute(\"formmethod\") as HTMLFormMethod | undefined) ||\n        method;\n\n      submit(submitter || event.currentTarget, {\n        fetcherKey,\n        method: submitMethod,\n        navigate,\n        replace,\n        state,\n        relative,\n        preventScrollReset,\n        viewTransition,\n      });\n    };\n\n    return (\n      <form\n        ref={forwardedRef}\n        method={formMethod}\n        action={formAction}\n        onSubmit={reloadDocument ? onSubmit : submitHandler}\n        {...props}\n      />\n    );\n  }\n);\n\nif (__DEV__) {\n  Form.displayName = \"Form\";\n}\n\nexport interface ScrollRestorationProps {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n}\n\n/**\n * This component will emulate the browser's scroll restoration on location\n * changes.\n */\nexport function ScrollRestoration({\n  getKey,\n  storageKey,\n}: ScrollRestorationProps) {\n  useScrollRestoration({ getKey, storageKey });\n  return null;\n}\n\nif (__DEV__) {\n  ScrollRestoration.displayName = \"ScrollRestoration\";\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hooks\n////////////////////////////////////////////////////////////////////////////////\n\nenum DataRouterHook {\n  UseScrollRestoration = \"useScrollRestoration\",\n  UseSubmit = \"useSubmit\",\n  UseSubmitFetcher = \"useSubmitFetcher\",\n  UseFetcher = \"useFetcher\",\n  useViewTransitionState = \"useViewTransitionState\",\n}\n\nenum DataRouterStateHook {\n  UseFetcher = \"useFetcher\",\n  UseFetchers = \"useFetchers\",\n  UseScrollRestoration = \"useScrollRestoration\",\n}\n\n// Internal hooks\n\nfunction getDataRouterConsoleError(\n  hookName: DataRouterHook | DataRouterStateHook\n) {\n  return `${hookName} must be used within a data router.  See https://reactrouter.com/v6/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n  let ctx = React.useContext(DataRouterContext);\n  invariant(ctx, getDataRouterConsoleError(hookName));\n  return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n  let state = React.useContext(DataRouterStateContext);\n  invariant(state, getDataRouterConsoleError(hookName));\n  return state;\n}\n\n// External hooks\n\n/**\n * Handles the click behavior for router `<Link>` components. This is useful if\n * you need to create custom `<Link>` components with the same click behavior we\n * use in our exported `<Link>`.\n */\nexport function useLinkClickHandler<E extends Element = HTMLAnchorElement>(\n  to: To,\n  {\n    target,\n    replace: replaceProp,\n    state,\n    preventScrollReset,\n    relative,\n    viewTransition,\n  }: {\n    target?: React.HTMLAttributeAnchorTarget;\n    replace?: boolean;\n    state?: any;\n    preventScrollReset?: boolean;\n    relative?: RelativeRoutingType;\n    viewTransition?: boolean;\n  } = {}\n): (event: React.MouseEvent<E, MouseEvent>) => void {\n  let navigate = useNavigate();\n  let location = useLocation();\n  let path = useResolvedPath(to, { relative });\n\n  return React.useCallback(\n    (event: React.MouseEvent<E, MouseEvent>) => {\n      if (shouldProcessLinkClick(event, target)) {\n        event.preventDefault();\n\n        // If the URL hasn't changed, a regular <a> will do a replace instead of\n        // a push, so do the same here unless the replace prop is explicitly set\n        let replace =\n          replaceProp !== undefined\n            ? replaceProp\n            : createPath(location) === createPath(path);\n\n        navigate(to, {\n          replace,\n          state,\n          preventScrollReset,\n          relative,\n          viewTransition,\n        });\n      }\n    },\n    [\n      location,\n      navigate,\n      path,\n      replaceProp,\n      state,\n      target,\n      to,\n      preventScrollReset,\n      relative,\n      viewTransition,\n    ]\n  );\n}\n\n/**\n * A convenient wrapper for reading and writing search parameters via the\n * URLSearchParams interface.\n */\nexport function useSearchParams(\n  defaultInit?: URLSearchParamsInit\n): [URLSearchParams, SetURLSearchParams] {\n  warning(\n    typeof URLSearchParams !== \"undefined\",\n    `You cannot use the \\`useSearchParams\\` hook in a browser that does not ` +\n      `support the URLSearchParams API. If you need to support Internet ` +\n      `Explorer 11, we recommend you load a polyfill such as ` +\n      `https://github.com/ungap/url-search-params.`\n  );\n\n  let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));\n  let hasSetSearchParamsRef = React.useRef(false);\n\n  let location = useLocation();\n  let searchParams = React.useMemo(\n    () =>\n      // Only merge in the defaults if we haven't yet called setSearchParams.\n      // Once we call that we want those to take precedence, otherwise you can't\n      // remove a param with setSearchParams({}) if it has an initial value\n      getSearchParamsForLocation(\n        location.search,\n        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current\n      ),\n    [location.search]\n  );\n\n  let navigate = useNavigate();\n  let setSearchParams = React.useCallback<SetURLSearchParams>(\n    (nextInit, navigateOptions) => {\n      const newSearchParams = createSearchParams(\n        typeof nextInit === \"function\" ? nextInit(searchParams) : nextInit\n      );\n      hasSetSearchParamsRef.current = true;\n      navigate(\"?\" + newSearchParams, navigateOptions);\n    },\n    [navigate, searchParams]\n  );\n\n  return [searchParams, setSearchParams];\n}\n\nexport type SetURLSearchParams = (\n  nextInit?:\n    | URLSearchParamsInit\n    | ((prev: URLSearchParams) => URLSearchParamsInit),\n  navigateOpts?: NavigateOptions\n) => void;\n\n/**\n * Submits a HTML `<form>` to the server without reloading the page.\n */\nexport interface SubmitFunction {\n  (\n    /**\n     * Specifies the `<form>` to be submitted to the server, a specific\n     * `<button>` or `<input type=\"submit\">` to use to submit the form, or some\n     * arbitrary data to submit.\n     *\n     * Note: When using a `<button>` its `name` and `value` will also be\n     * included in the form data that is submitted.\n     */\n    target: SubmitTarget,\n\n    /**\n     * Options that override the `<form>`'s own attributes. Required when\n     * submitting arbitrary data without a backing `<form>`.\n     */\n    options?: SubmitOptions\n  ): void;\n}\n\n/**\n * Submits a fetcher `<form>` to the server without reloading the page.\n */\nexport interface FetcherSubmitFunction {\n  (\n    target: SubmitTarget,\n    // Fetchers cannot replace or set state because they are not navigation events\n    options?: FetcherSubmitOptions\n  ): void;\n}\n\nfunction validateClientSideSubmission() {\n  if (typeof document === \"undefined\") {\n    throw new Error(\n      \"You are calling submit during the server render. \" +\n        \"Try calling submit within a `useEffect` or callback instead.\"\n    );\n  }\n}\n\nlet fetcherId = 0;\nlet getUniqueFetcherId = () => `__${String(++fetcherId)}__`;\n\n/**\n * Returns a function that may be used to programmatically submit a form (or\n * some arbitrary data) to the server.\n */\nexport function useSubmit(): SubmitFunction {\n  let { router } = useDataRouterContext(DataRouterHook.UseSubmit);\n  let { basename } = React.useContext(NavigationContext);\n  let currentRouteId = useRouteId();\n\n  return React.useCallback<SubmitFunction>(\n    (target, options = {}) => {\n      validateClientSideSubmission();\n\n      let { action, method, encType, formData, body } = getFormSubmissionInfo(\n        target,\n        basename\n      );\n\n      if (options.navigate === false) {\n        let key = options.fetcherKey || getUniqueFetcherId();\n        router.fetch(key, currentRouteId, options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          flushSync: options.flushSync,\n        });\n      } else {\n        router.navigate(options.action || action, {\n          preventScrollReset: options.preventScrollReset,\n          formData,\n          body,\n          formMethod: options.method || (method as HTMLFormMethod),\n          formEncType: options.encType || (encType as FormEncType),\n          replace: options.replace,\n          state: options.state,\n          fromRouteId: currentRouteId,\n          flushSync: options.flushSync,\n          viewTransition: options.viewTransition,\n        });\n      }\n    },\n    [router, basename, currentRouteId]\n  );\n}\n\n// v7: Eventually we should deprecate this entirely in favor of using the\n// router method directly?\nexport function useFormAction(\n  action?: string,\n  { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n  let { basename } = React.useContext(NavigationContext);\n  let routeContext = React.useContext(RouteContext);\n  invariant(routeContext, \"useFormAction must be used inside a RouteContext\");\n\n  let [match] = routeContext.matches.slice(-1);\n  // Shallow clone path so we can modify it below, otherwise we modify the\n  // object referenced by useMemo inside useResolvedPath\n  let path = { ...useResolvedPath(action ? action : \".\", { relative }) };\n\n  // If no action was specified, browsers will persist current search params\n  // when determining the path, so match that behavior\n  // https://github.com/remix-run/remix/issues/927\n  let location = useLocation();\n  if (action == null) {\n    // Safe to write to this directly here since if action was undefined, we\n    // would have called useResolvedPath(\".\") which will never include a search\n    path.search = location.search;\n\n    // When grabbing search params from the URL, remove any included ?index param\n    // since it might not apply to our contextual route.  We add it back based\n    // on match.route.index below\n    let params = new URLSearchParams(path.search);\n    let indexValues = params.getAll(\"index\");\n    let hasNakedIndexParam = indexValues.some((v) => v === \"\");\n    if (hasNakedIndexParam) {\n      params.delete(\"index\");\n      indexValues.filter((v) => v).forEach((v) => params.append(\"index\", v));\n      let qs = params.toString();\n      path.search = qs ? `?${qs}` : \"\";\n    }\n  }\n\n  if ((!action || action === \".\") && match.route.index) {\n    path.search = path.search\n      ? path.search.replace(/^\\?/, \"?index&\")\n      : \"?index\";\n  }\n\n  // If we're operating within a basename, prepend it to the pathname prior\n  // to creating the form action.  If this is a root navigation, then just use\n  // the raw basename which allows the basename to have full control over the\n  // presence of a trailing slash on root actions\n  if (basename !== \"/\") {\n    path.pathname =\n      path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n  }\n\n  return createPath(path);\n}\n\nexport type FetcherWithComponents<TData> = Fetcher<TData> & {\n  Form: React.ForwardRefExoticComponent<\n    FetcherFormProps & React.RefAttributes<HTMLFormElement>\n  >;\n  submit: FetcherSubmitFunction;\n  load: (href: string, opts?: { flushSync?: boolean }) => void;\n};\n\n// TODO: (v7) Change the useFetcher generic default from `any` to `unknown`\n\n/**\n * Interacts with route loaders and actions without causing a navigation. Great\n * for any interaction that stays on the same page.\n */\nexport function useFetcher<TData = any>({\n  key,\n}: { key?: string } = {}): FetcherWithComponents<TData> {\n  let { router } = useDataRouterContext(DataRouterHook.UseFetcher);\n  let state = useDataRouterState(DataRouterStateHook.UseFetcher);\n  let fetcherData = React.useContext(FetchersContext);\n  let route = React.useContext(RouteContext);\n  let routeId = route.matches[route.matches.length - 1]?.route.id;\n\n  invariant(fetcherData, `useFetcher must be used inside a FetchersContext`);\n  invariant(route, `useFetcher must be used inside a RouteContext`);\n  invariant(\n    routeId != null,\n    `useFetcher can only be used on routes that contain a unique \"id\"`\n  );\n\n  // Fetcher key handling\n  // OK to call conditionally to feature detect `useId`\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  let defaultKey = useIdImpl ? useIdImpl() : \"\";\n  let [fetcherKey, setFetcherKey] = React.useState<string>(key || defaultKey);\n  if (key && key !== fetcherKey) {\n    setFetcherKey(key);\n  } else if (!fetcherKey) {\n    // We will only fall through here when `useId` is not available\n    setFetcherKey(getUniqueFetcherId());\n  }\n\n  // Registration/cleanup\n  React.useEffect(() => {\n    router.getFetcher(fetcherKey);\n    return () => {\n      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this\n      // will not delete immediately but instead queue up a delete after the\n      // fetcher returns to an `idle` state\n      router.deleteFetcher(fetcherKey);\n    };\n  }, [router, fetcherKey]);\n\n  // Fetcher additions\n  let load = React.useCallback(\n    (href: string, opts?: { flushSync?: boolean }) => {\n      invariant(routeId, \"No routeId available for fetcher.load()\");\n      router.fetch(fetcherKey, routeId, href, opts);\n    },\n    [fetcherKey, routeId, router]\n  );\n\n  let submitImpl = useSubmit();\n  let submit = React.useCallback<FetcherSubmitFunction>(\n    (target, opts) => {\n      submitImpl(target, {\n        ...opts,\n        navigate: false,\n        fetcherKey,\n      });\n    },\n    [fetcherKey, submitImpl]\n  );\n\n  let FetcherForm = React.useMemo(() => {\n    let FetcherForm = React.forwardRef<HTMLFormElement, FetcherFormProps>(\n      (props, ref) => {\n        return (\n          <Form {...props} navigate={false} fetcherKey={fetcherKey} ref={ref} />\n        );\n      }\n    );\n    if (__DEV__) {\n      FetcherForm.displayName = \"fetcher.Form\";\n    }\n    return FetcherForm;\n  }, [fetcherKey]);\n\n  // Exposed FetcherWithComponents\n  let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;\n  let data = fetcherData.get(fetcherKey);\n  let fetcherWithComponents = React.useMemo(\n    () => ({\n      Form: FetcherForm,\n      submit,\n      load,\n      ...fetcher,\n      data,\n    }),\n    [FetcherForm, submit, load, fetcher, data]\n  );\n\n  return fetcherWithComponents;\n}\n\n/**\n * Provides all fetchers currently on the page. Useful for layouts and parent\n * routes that need to provide pending/optimistic UI regarding the fetch.\n */\nexport function useFetchers(): (Fetcher & { key: string })[] {\n  let state = useDataRouterState(DataRouterStateHook.UseFetchers);\n  return Array.from(state.fetchers.entries()).map(([key, fetcher]) => ({\n    ...fetcher,\n    key,\n  }));\n}\n\nconst SCROLL_RESTORATION_STORAGE_KEY = \"react-router-scroll-positions\";\nlet savedScrollPositions: Record<string, number> = {};\n\n/**\n * When rendered inside a RouterProvider, will restore scroll positions on navigations\n */\nfunction useScrollRestoration({\n  getKey,\n  storageKey,\n}: {\n  getKey?: GetScrollRestorationKeyFunction;\n  storageKey?: string;\n} = {}) {\n  let { router } = useDataRouterContext(DataRouterHook.UseScrollRestoration);\n  let { restoreScrollPosition, preventScrollReset } = useDataRouterState(\n    DataRouterStateHook.UseScrollRestoration\n  );\n  let { basename } = React.useContext(NavigationContext);\n  let location = useLocation();\n  let matches = useMatches();\n  let navigation = useNavigation();\n\n  // Trigger manual scroll restoration while we're active\n  React.useEffect(() => {\n    window.history.scrollRestoration = \"manual\";\n    return () => {\n      window.history.scrollRestoration = \"auto\";\n    };\n  }, []);\n\n  // Save positions on pagehide\n  usePageHide(\n    React.useCallback(() => {\n      if (navigation.state === \"idle\") {\n        let key = (getKey ? getKey(location, matches) : null) || location.key;\n        savedScrollPositions[key] = window.scrollY;\n      }\n      try {\n        sessionStorage.setItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY,\n          JSON.stringify(savedScrollPositions)\n        );\n      } catch (error) {\n        warning(\n          false,\n          `Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (${error}).`\n        );\n      }\n      window.history.scrollRestoration = \"auto\";\n    }, [storageKey, getKey, navigation.state, location, matches])\n  );\n\n  // Read in any saved scroll locations\n  if (typeof document !== \"undefined\") {\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      try {\n        let sessionPositions = sessionStorage.getItem(\n          storageKey || SCROLL_RESTORATION_STORAGE_KEY\n        );\n        if (sessionPositions) {\n          savedScrollPositions = JSON.parse(sessionPositions);\n        }\n      } catch (e) {\n        // no-op, use default empty object\n      }\n    }, [storageKey]);\n\n    // Enable scroll restoration in the router\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      let getKeyWithoutBasename: GetScrollRestorationKeyFunction | undefined =\n        getKey && basename !== \"/\"\n          ? (location, matches) =>\n              getKey(\n                // Strip the basename to match useLocation()\n                {\n                  ...location,\n                  pathname:\n                    stripBasename(location.pathname, basename) ||\n                    location.pathname,\n                },\n                matches\n              )\n          : getKey;\n      let disableScrollRestoration = router?.enableScrollRestoration(\n        savedScrollPositions,\n        () => window.scrollY,\n        getKeyWithoutBasename\n      );\n      return () => disableScrollRestoration && disableScrollRestoration();\n    }, [router, basename, getKey]);\n\n    // Restore scrolling when state.restoreScrollPosition changes\n    // eslint-disable-next-line react-hooks/rules-of-hooks\n    React.useLayoutEffect(() => {\n      // Explicit false means don't do anything (used for submissions)\n      if (restoreScrollPosition === false) {\n        return;\n      }\n\n      // been here before, scroll to it\n      if (typeof restoreScrollPosition === \"number\") {\n        window.scrollTo(0, restoreScrollPosition);\n        return;\n      }\n\n      // try to scroll to the hash\n      if (location.hash) {\n        let el = document.getElementById(\n          decodeURIComponent(location.hash.slice(1))\n        );\n        if (el) {\n          el.scrollIntoView();\n          return;\n        }\n      }\n\n      // Don't reset if this navigation opted out\n      if (preventScrollReset === true) {\n        return;\n      }\n\n      // otherwise go to the top on new locations\n      window.scrollTo(0, 0);\n    }, [location, restoreScrollPosition, preventScrollReset]);\n  }\n}\n\nexport { useScrollRestoration as UNSAFE_useScrollRestoration };\n\n/**\n * Setup a callback to be fired on the window's `beforeunload` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nexport function useBeforeUnload(\n  callback: (event: BeforeUnloadEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"beforeunload\", callback, opts);\n    return () => {\n      window.removeEventListener(\"beforeunload\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Setup a callback to be fired on the window's `pagehide` event. This is\n * useful for saving some data to `window.localStorage` just before the page\n * refreshes.  This event is better supported than beforeunload across browsers.\n *\n * Note: The `callback` argument should be a function created with\n * `React.useCallback()`.\n */\nfunction usePageHide(\n  callback: (event: PageTransitionEvent) => any,\n  options?: { capture?: boolean }\n): void {\n  let { capture } = options || {};\n  React.useEffect(() => {\n    let opts = capture != null ? { capture } : undefined;\n    window.addEventListener(\"pagehide\", callback, opts);\n    return () => {\n      window.removeEventListener(\"pagehide\", callback, opts);\n    };\n  }, [callback, capture]);\n}\n\n/**\n * Wrapper around useBlocker to show a window.confirm prompt to users instead\n * of building a custom UI with useBlocker.\n *\n * Warning: This has *a lot of rough edges* and behaves very differently (and\n * very incorrectly in some cases) across browsers if user click addition\n * back/forward navigations while the confirm is open.  Use at your own risk.\n */\nfunction usePrompt({\n  when,\n  message,\n}: {\n  when: boolean | BlockerFunction;\n  message: string;\n}) {\n  let blocker = useBlocker(when);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\") {\n      let proceed = window.confirm(message);\n      if (proceed) {\n        // This timeout is needed to avoid a weird \"race\" on POP navigations\n        // between the `window.history` revert navigation and the result of\n        // `window.confirm`\n        setTimeout(blocker.proceed, 0);\n      } else {\n        blocker.reset();\n      }\n    }\n  }, [blocker, message]);\n\n  React.useEffect(() => {\n    if (blocker.state === \"blocked\" && !when) {\n      blocker.reset();\n    }\n  }, [blocker, when]);\n}\n\nexport { usePrompt as unstable_usePrompt };\n\n/**\n * Return a boolean indicating if there is an active view transition to the\n * given href.  You can use this value to render CSS classes or viewTransitionName\n * styles onto your elements\n *\n * @param href The destination href\n * @param [opts.relative] Relative routing type (\"route\" | \"path\")\n */\nfunction useViewTransitionState(\n  to: To,\n  opts: { relative?: RelativeRoutingType } = {}\n) {\n  let vtContext = React.useContext(ViewTransitionContext);\n\n  invariant(\n    vtContext != null,\n    \"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  \" +\n      \"Did you accidentally import `RouterProvider` from `react-router`?\"\n  );\n\n  let { basename } = useDataRouterContext(\n    DataRouterHook.useViewTransitionState\n  );\n  let path = useResolvedPath(to, { relative: opts.relative });\n  if (!vtContext.isTransitioning) {\n    return false;\n  }\n\n  let currentPath =\n    stripBasename(vtContext.currentLocation.pathname, basename) ||\n    vtContext.currentLocation.pathname;\n  let nextPath =\n    stripBasename(vtContext.nextLocation.pathname, basename) ||\n    vtContext.nextLocation.pathname;\n\n  // Transition is active if we're going to or coming from the indicated\n  // destination.  This ensures that other PUSH navigations that reverse\n  // an indicated transition apply.  I.e., on the list view you have:\n  //\n  //   <NavLink to=\"/details/1\" viewTransition>\n  //\n  // If you click the breadcrumb back to the list view:\n  //\n  //   <NavLink to=\"/list\" viewTransition>\n  //\n  // We should apply the transition because it's indicated as active going\n  // from /list -> /details/1 and therefore should be active on the reverse\n  // (even though this isn't strictly a POP reverse)\n  return (\n    matchPath(path.pathname, nextPath) != null ||\n    matchPath(path.pathname, currentPath) != null\n  );\n}\n\nexport { useViewTransitionState as useViewTransitionState };\n\n//#endregion\n"],
+  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOYA;CAAZ,SAAYA,SAAM;AAQhBA,EAAAA,QAAA,KAAA,IAAA;AAOAA,EAAAA,QAAA,MAAA,IAAA;AAMAA,EAAAA,QAAA,SAAA,IAAA;AACF,GAtBYA,WAAAA,SAsBX,CAAA,EAAA;AAqKD,IAAMC,oBAAoB;AAmCV,SAAAC,oBACdC,SAAkC;AAAA,MAAlCA,YAAA,QAAA;AAAAA,cAAgC,CAAA;EAAE;AAElC,MAAI;IAAEC,iBAAiB,CAAC,GAAG;IAAGC;IAAcC,WAAW;EAAO,IAAGH;AACjE,MAAII;AACJA,YAAUH,eAAeI,IAAI,CAACC,OAAOC,WACnCC,qBACEF,OACA,OAAOA,UAAU,WAAW,OAAOA,MAAMG,OACzCF,WAAU,IAAI,YAAYG,MAAS,CACpC;AAEH,MAAIH,QAAQI,WACVT,gBAAgB,OAAOE,QAAQQ,SAAS,IAAIV,YAAY;AAE1D,MAAIW,SAAShB,OAAOiB;AACpB,MAAIC,WAA4B;AAEhC,WAASJ,WAAWK,GAAS;AAC3B,WAAOC,KAAKC,IAAID,KAAKE,IAAIH,GAAG,CAAC,GAAGZ,QAAQQ,SAAS,CAAC;EACpD;AACA,WAASQ,qBAAkB;AACzB,WAAOhB,QAAQG,KAAK;EACtB;AACA,WAASC,qBACPa,IACAZ,OACAa,KAAY;AAAA,QADZb,UAAa,QAAA;AAAbA,cAAa;IAAI;AAGjB,QAAIc,WAAWC,eACbpB,UAAUgB,mBAAkB,EAAGK,WAAW,KAC1CJ,IACAZ,OACAa,GAAG;AAELI,YACEH,SAASE,SAASE,OAAO,CAAC,MAAM,KAAG,6DACwBC,KAAKC,UAC9DR,EAAE,CACD;AAEL,WAAOE;EACT;AAEA,WAASO,WAAWT,IAAM;AACxB,W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,KAAKqJ;EAAQ,CAAE;AAC1D,MAAI,CAACpF,UAAU9B,iBAAiB;AAC9B,WAAO;EACR;AAED,MAAI2S,cACF1V,cAAc6E,UAAU2B,gBAAgB2E,UAAU1L,QAAQ,KAC1DoF,UAAU2B,gBAAgB2E;AAC5B,MAAIwK,WACF3V,cAAc6E,UAAU4B,aAAa0E,UAAU1L,QAAQ,KACvDoF,UAAU4B,aAAa0E;AAezB,SACEyK,UAAU1K,KAAKC,UAAUwK,QAAQ,KAAK,QACtCC,UAAU1K,KAAKC,UAAUuK,WAAW,KAAK;AAE7C;",
+  "names": ["Action", "PopStateEventType", "createMemoryHistory", "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", "createHref", "createPath", "history", "createURL", "URL", "encodeLocation", "path", "parsePath", "search", "hash", "push", "Push", "nextLocation", "splice", "delta", "replace", "Replace", "go", "nextIndex", "listen", "fn", "createBrowserHistory", "createBrowserLocation", "window", "globalHistory", "usr", "createBrowserHref", "getUrlBasedHistory", "createHashHistory", "createHashLocation", "substr", "startsWith", "createHashHref", "base", "document", "querySelector", "href", "getAttribute", "url", "hashIndex", "indexOf", "slice", "validateHashLocation", "invariant", "value", "message", "Error", "cond", "console", "warn", "e", "createKey", "random", "toString", "getHistoryState", "idx", "current", "_extends", "_ref", "parsedPath", "searchIndex", "getLocation", "validateLocation", "defaultView", "getIndex", "replaceState", "handlePop", "historyState", "pushState", "error", "DOMException", "name", "assign", "origin", "addEventListener", "removeEventListener", "ResultType", "immutableRouteKeys", "Set", "isIndexRoute", "route", "convertRoutesToDataRoutes", "routes", "mapRouteProperties", "parentPath", "manifest", "treePath", "String", "id", "join", "children", "indexRoute", "pathOrLayoutRoute", "matchRoutes", "locationArg", "basename", "matchRoutesImpl", "allowPartial", "stripBasename", "branches", "flattenRoutes", "rankRouteBranches", "matches", "i", "decoded", "decodePath", "matchRouteBranch", "convertRouteMatchToUiMatch", "match", "loaderData", "params", "data", "handle", "parentsMeta", "flattenRoute", "relativePath", "meta", "caseSensitive", "childrenIndex", "joinPaths", "routesMeta", "concat", "score", "computeScore", "forEach", "_route$path", "includes", "exploded", "explodeOptionalSegments", "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", "matchPath", "Object", "pathnameBase", "normalizePathname", "generatePath", "originalPath", "prefix", "p", "array", "isLastSegment", "star", "keyMatch", "optional", "param", "pattern", "matcher", "compiledParams", "compilePath", "captureGroups", "memo", "paramName", "splatValue", "regexpSource", "_", "RegExp", "v", "decodeURIComponent", "toLowerCase", "startIndex", "nextChar", "resolvePath", "fromPathname", "toPathname", "resolvePathname", "normalizeSearch", "normalizeHash", "relativeSegments", "pop", "getInvalidPathError", "char", "field", "dest", "getPathContributingMatches", "getResolveToMatches", "v7_relativeSplatPath", "pathMatches", "resolveTo", "toArg", "routePathnames", "locationPathname", "isPathRelative", "isEmptyPath", "from", "routePathnameIndex", "toSegments", "shift", "hasExplicitTrailingSlash", "hasCurrentTrailingSlash", "joinPaths", "paths", "join", "replace", "normalizePathname", "pathname", "normalizeSearch", "search", "startsWith", "normalizeHash", "hash", "json", "data", "init", "responseInit", "status", "headers", "Headers", "has", "set", "Response", "JSON", "stringify", "_extends", "AbortedDeferredError", "Error", "DeferredData", "constructor", "data", "responseInit", "pendingKeysSet", "Set", "subscribers", "deferredKeys", "invariant", "Array", "isArray", "reject", "abortPromise", "Promise", "_", "r", "controller", "AbortController", "onAbort", "unlistenAbortSignal", "signal", "removeEventListener", "addEventListener", "Object", "entries", "reduce", "acc", "_ref2", "key", "value", "assign", "trackPromise", "done", "init", "push", "add", "promise", "race", "then", "onSettle", "undefined", "error", "catch", "defineProperty", "get", "aborted", "delete", "undefinedError", "emit", "settledKey", "forEach", "subscriber", "subscribe", "fn", "cancel", "abort", "v", "k", "resolveData", "resolve", "size", "unwrappedData", "_ref3", "unwrapTrackedPromise", "pendingKeys", "from", "isTrackedPromise", "_tracked", "_error", "_data", "defer", "status", "redirect", "url", "headers", "Headers", "set", "Response", "_extends", "redirectDocument", "response", "replace", "ErrorResponseImpl", "statusText", "internal", "toString", "isRouteErrorResponse", "validMutationMethodsArr", "validMutationMethods", "validRequestMethodsArr", "validRequestMethods", "redirectStatusCodes", "redirectPreserveMethodStatusCodes", "IDLE_NAVIGATION", "state", "location", "formMethod", "formAction", "formEncType", "formData", "json", "text", "IDLE_FETCHER", "IDLE_BLOCKER", "proceed", "reset", "ABSOLUTE_URL_REGEX", "defaultMapRouteProperties", "route", "hasErrorBoundary", "Boolean", "TRANSITIONS_STORAGE_KEY", "createRouter", "routerWindow", "window", "isBrowser", "document", "createElement", "isServer", "routes", "length", "mapRouteProperties", "detectErrorBoundary", "manifest", "dataRoutes", "convertRoutesToDataRoutes", "inFlightDataRoutes", "basename", "dataStrategyImpl", "dataStrategy", "defaultDataStrategy", "patchRoutesOnNavigationImpl", "patchRoutesOnNavigation", "future", "v7_fetcherPersist", "v7_normalizeFormMethod", "v7_partialHydration", "v7_prependBasename", "v7_relativeSplatPath", "v7_skipActionErrorRevalidation", "unlistenHistory", "savedScrollPositions", "getScrollRestorationKey", "getScrollPosition", "initialScrollRestored", "hydrationData", "initialMatches", "matchRoutes", "history", "initialErrors", "getInternalRouterError", "pathname", "matches", "getShortCircuitMatches", "id", "fogOfWar", "checkFogOfWar", "active", "initialized", "some", "m", "lazy", "loader", "loaderData", "errors", "idx", "findIndex", "slice", "every", "shouldLoadRouteOnHydration", "router", "historyAction", "action", "navigation", "restoreScrollPosition", "preventScrollReset", "revalidation", "actionData", "fetchers", "Map", "blockers", "pendingAction", "HistoryAction", "Pop", "pendingPreventScrollReset", "pendingNavigationController", "pendingViewTransitionEnabled", "appliedViewTransitions", "removePageHideEventListener", "isUninterruptedRevalidation", "isRevalidationRequired", "cancelledDeferredRoutes", "cancelledFetcherLoads", "fetchControllers", "incrementingLoadId", "pendingNavigationLoadId", "fetchReloadIds", "fetchRedirectIds", "fetchLoadMatches", "activeFetchers", "deletedFetchers", "activeDeferreds", "blockerFunctions", "unblockBlockerHistoryUpdate", "initialize", "listen", "_ref", "delta", "warning", "blockerKey", "shouldBlockNavigation", "currentLocation", "nextLocation", "nextHistoryUpdatePromise", "go", "updateBlocker", "updateState", "startNavigation", "restoreAppliedTransitions", "_saveAppliedTransitions", "persistAppliedTransitions", "initialHydration", "dispose", "clear", "deleteFetcher", "deleteBlocker", "newState", "opts", "completedFetchers", "deletedFetchersKeys", "fetcher", "has", "viewTransitionOpts", "flushSync", "completeNavigation", "_temp", "_location$state", "_location$state2", "isActionReload", "isMutationMethod", "_isRedirect", "keys", "mergeLoaderData", "Push", "Replace", "priorPaths", "toPaths", "getSavedScrollPosition", "navigate", "to", "normalizedPath", "normalizeTo", "fromRouteId", "relative", "path", "submission", "normalizeNavigateOptions", "createLocation", "encodeLocation", "userReplace", "search", "pendingError", "enableViewTransition", "viewTransition", "revalidate", "interruptActiveLoads", "startUninterruptedRevalidation", "overrideNavigation", "saveScrollPosition", "routesToUse", "loadingNavigation", "notFoundMatches", "handleNavigational404", "isHashChangeOnly", "request", "createClientSideRequest", "pendingActionResult", "findNearestBoundary", "type", "ResultType", "actionResult", "handleAction", "shortCircuited", "routeId", "result", "isErrorResult", "getLoadingNavigation", "updatedMatches", "handleLoaders", "fetcherSubmission", "getActionDataForCommit", "isFogOfWar", "getSubmittingNavigation", "discoverResult", "discoverRoutes", "boundaryId", "partialMatches", "actionMatch", "getTargetMatch", "method", "results", "callDataStrategy", "isRedirectResult", "normalizeRedirectLocation", "URL", "startRedirectNavigation", "isDeferredResult", "boundaryMatch", "activeSubmission", "getSubmissionFromNavigation", "shouldUpdateNavigationState", "getUpdatedActionData", "matchesToLoad", "revalidatingFetchers", "getMatchesToLoad", "cancelActiveDeferreds", "updatedFetchers", "markFetchRedirectsDone", "updates", "getUpdatedRevalidatingFetchers", "rf", "abortFetcher", "abortPendingFetchRevalidations", "f", "loaderResults", "fetcherResults", "callLoadersAndMaybeResolveData", "findRedirect", "processLoaderData", "deferredData", "didAbortFetchLoads", "abortStaleFetchLoads", "shouldUpdateFetchers", "revalidatingFetcher", "getLoadingFetcher", "fetch", "href", "setFetcherError", "match", "handleFetcherAction", "handleFetcherLoader", "requestMatches", "detectAndHandle405Error", "existingFetcher", "updateFetcherState", "getSubmittingFetcher", "abortController", "fetchRequest", "originatingLoadId", "actionResults", "getDoneFetcher", "revalidationRequest", "loadId", "loadFetcher", "filter", "staleKey", "doneFetcher", "resolveDeferredData", "isNavigation", "_temp2", "redirectLocation", "isDocumentReload", "test", "createURL", "origin", "stripBasename", "redirectHistoryAction", "fetcherKey", "dataResults", "callDataStrategyImpl", "e", "isRedirectDataStrategyResultResult", "normalizeRelativeRoutingRedirectResponse", "convertDataStrategyResultToDataResult", "fetchersToLoad", "currentMatches", "loaderResultsPromise", "fetcherResultsPromise", "all", "map", "resolveNavigationDeferredResults", "resolveFetcherDeferredResults", "getFetcher", "deleteFetcherAndUpdateState", "count", "markFetchersDone", "doneKeys", "landedId", "yeetedKeys", "getBlocker", "blocker", "newBlocker", "blockerFunction", "predicate", "cancelledRouteIds", "dfd", "enableScrollRestoration", "positions", "getPosition", "getKey", "y", "getScrollKey", "convertRouteMatchToUiMatch", "fogMatches", "matchRoutesImpl", "params", "isNonHMR", "localManifest", "patch", "children", "patchRoutesImpl", "newMatches", "newPartialMatches", "i", "_internalSetRoutes", "newRoutes", "patchRoutes", "createHref", "_internalFetchControllers", "_internalActiveDeferreds", "UNSAFE_DEFERRED_SYMBOL", "Symbol", "isSubmissionNavigation", "opts", "formData", "body", "undefined", "normalizeTo", "location", "matches", "basename", "prependBasename", "to", "v7_relativeSplatPath", "fromRouteId", "relative", "contextualMatches", "activeRouteMatch", "match", "push", "route", "id", "length", "path", "resolveTo", "getResolveToMatches", "stripBasename", "pathname", "search", "hash", "nakedIndex", "hasNakedIndexQuery", "index", "replace", "params", "URLSearchParams", "indexValues", "getAll", "delete", "filter", "v", "forEach", "append", "qs", "toString", "joinPaths", "createPath", "normalizeNavigateOptions", "normalizeFormMethod", "isFetcher", "formMethod", "isValidMethod", "error", "getInternalRouterError", "method", "getInvalidBodyError", "type", "rawFormMethod", "toUpperCase", "toLowerCase", "formAction", "stripHashFromPath", "formEncType", "isMutationMethod", "text", "FormData", "Array", "from", "entries", "reduce", "acc", "_ref3", "name", "value", "String", "submission", "json", "JSON", "parse", "e", "invariant", "searchParams", "convertFormDataToSearchParams", "convertSearchParamsToFormData", "parsedPath", "parsePath", "getLoaderMatchesUntilBoundary", "boundaryId", "includeBoundary", "findIndex", "m", "slice", "getMatchesToLoad", "history", "state", "initialHydration", "skipActionErrorRevalidation", "isRevalidationRequired", "cancelledDeferredRoutes", "cancelledFetcherLoads", "deletedFetchers", "fetchLoadMatches", "fetchRedirectIds", "routesToUse", "pendingActionResult", "actionResult", "isErrorResult", "data", "currentUrl", "createURL", "nextUrl", "boundaryMatches", "errors", "Object", "keys", "actionStatus", "statusCode", "shouldSkipRevalidation", "navigationMatches", "lazy", "loader", "shouldLoadRouteOnHydration", "loaderData", "isNewLoader", "some", "currentRouteMatch", "nextRouteMatch", "shouldRevalidateLoader", "_extends", "currentParams", "nextParams", "defaultShouldRevalidate", "isNewRouteInstance", "revalidatingFetchers", "f", "key", "routeId", "has", "fetcherMatches", "matchRoutes", "controller", "fetcher", "fetchers", "get", "fetcherMatch", "getTargetMatch", "shouldRevalidate", "AbortController", "hasData", "hasError", "hydrate", "currentLoaderData", "currentMatch", "isNew", "isMissingData", "currentPath", "endsWith", "loaderMatch", "arg", "routeChoice", "patchRoutesImpl", "children", "manifest", "mapRouteProperties", "_childrenToPatch", "childrenToPatch", "uniqueChildren", "newRoute", "existingRoute", "isSameRoute", "newRoutes", "convertRoutesToDataRoutes", "caseSensitive", "every", "aChild", "i", "_existingRoute$childr", "bChild", "loadLazyRouteModule", "lazyRoute", "routeToUpdate", "routeUpdates", "lazyRouteProperty", "staticRouteValue", "isPropertyStaticallyDefined", "warning", "immutableRouteKeys", "assign", "defaultDataStrategy", "_ref4", "matchesToLoad", "shouldLoad", "results", "Promise", "all", "map", "resolve", "result", "callDataStrategyImpl", "dataStrategyImpl", "request", "fetcherKey", "requestContext", "loadRouteDefinitionsPromises", "dsMatches", "loadRoutePromise", "handlerOverride", "callLoaderOrAction", "ResultType", "context", "staticContext", "onReject", "runHandler", "handler", "reject", "abortPromise", "_", "r", "signal", "addEventListener", "actualHandler", "ctx", "Error", "handlerPromise", "val", "race", "handlerError", "catch", "url", "URL", "removeEventListener", "convertDataStrategyResultToDataResult", "dataStrategyResult", "isResponse", "contentType", "headers", "test", "ErrorResponseImpl", "status", "statusText", "isDataWithResponseInit", "_result$init2", "_result$init", "init", "isRouteErrorResponse", "isDeferredData", "_result$init3", "_result$init4", "deferred", "deferredData", "Headers", "_result$init5", "_result$init6", "normalizeRelativeRoutingRedirectResponse", "response", "ABSOLUTE_URL_REGEX", "trimmedMatches", "set", "normalizeRedirectLocation", "normalizedLocation", "startsWith", "protocol", "isSameBasename", "origin", "createClientSideRequest", "stringify", "Request", "processRouteLoaderData", "activeDeferreds", "skipLoaderErrorBubbling", "foundError", "loaderHeaders", "pendingError", "isRedirectResult", "boundaryMatch", "findNearestBoundary", "isDeferredResult", "processLoaderData", "fetcherResults", "rf", "aborted", "doneFetcher", "getDoneFetcher", "mergeLoaderData", "newLoaderData", "mergedLoaderData", "hasOwnProperty", "getActionDataForCommit", "actionData", "eligibleMatches", "reverse", "find", "hasErrorBoundary", "getShortCircuitMatches", "routes", "pathnameBase", "_temp5", "message", "errorMessage", "findRedirect", "isHashChangeOnly", "a", "b", "isRedirectDataStrategyResultResult", "result", "isResponse", "redirectStatusCodes", "has", "status", "isDeferredResult", "type", "ResultType", "deferred", "isErrorResult", "error", "isRedirectResult", "redirect", "isDataWithResponseInit", "value", "isDeferredData", "data", "subscribe", "cancel", "resolveData", "statusText", "headers", "body", "isValidMethod", "method", "validRequestMethods", "has", "toLowerCase", "isMutationMethod", "validMutationMethods", "resolveNavigationDeferredResults", "matches", "results", "signal", "currentMatches", "currentLoaderData", "entries", "Object", "index", "length", "routeId", "result", "match", "find", "m", "route", "id", "currentMatch", "isRevalidatingLoader", "isNewRouteInstance", "undefined", "isDeferredResult", "resolveDeferredData", "then", "resolveFetcherDeferredResults", "revalidatingFetchers", "key", "controller", "invariant", "unwrap", "aborted", "deferredData", "resolveData", "type", "ResultType", "data", "unwrappedData", "e", "error", "hasNakedIndexQuery", "search", "URLSearchParams", "getAll", "some", "v", "getTargetMatch", "location", "parsePath", "pathMatches", "getPathContributingMatches", "getSubmissionFromNavigation", "navigation", "formMethod", "formAction", "formEncType", "text", "formData", "json", "getLoadingNavigation", "submission", "state", "getSubmittingNavigation", "getLoadingFetcher", "fetcher", "getSubmittingFetcher", "existingFetcher", "getDoneFetcher", "restoreAppliedTransitions", "_window", "transitions", "sessionPositions", "sessionStorage", "getItem", "TRANSITIONS_STORAGE_KEY", "JSON", "parse", "k", "Array", "isArray", "set", "Set", "persistAppliedTransitions", "size", "setItem", "stringify", "warning", "DataRouterContext", "createContext", "process", "displayName", "DataRouterStateContext", "AwaitContext", "NavigationContext", "LocationContext", "RouteContext", "outlet", "matches", "isDataRoute", "RouteErrorContext", "useHref", "to", "_temp", "relative", "useInRouterContext", "invariant", "basename", "navigator", "useContext", "hash", "pathname", "search", "useResolvedPath", "joinedPathname", "joinPaths", "createHref", "useLocation", "location", "useNavigationType", "navigationType", "useMatch", "pattern", "useMemo", "matchPath", "decodePath", "navigateEffectWarning", "useIsomorphicLayoutEffect", "cb", "isStatic", "static", "React", "useLayoutEffect", "useNavigate", "useNavigateStable", "useNavigateUnstable", "dataRouterContext", "future", "locationPathname", "routePathnamesJson", "JSON", "stringify", "getResolveToMatches", "v7_relativeSplatPath", "activeRef", "useRef", "current", "navigate", "useCallback", "options", "warning", "go", "path", "resolveTo", "parse", "replace", "push", "state", "OutletContext", "useOutletContext", "useOutlet", "context", "createElement", "Provider", "value", "useParams", "routeMatch", "length", "params", "_temp2", "useRoutes", "routes", "locationArg", "useRoutesImpl", "dataRouterState", "parentMatches", "parentParams", "parentPathname", "parentPathnameBase", "pathnameBase", "parentRoute", "route", "parentPath", "warningOnce", "endsWith", "locationFromContext", "_parsedLocationArg$pa", "parsedLocationArg", "parsePath", "startsWith", "remainingPathname", "parentSegments", "split", "segments", "slice", "join", "matchRoutes", "element", "undefined", "Component", "lazy", "renderedMatches", "_renderMatches", "map", "match", "Object", "assign", "encodeLocation", "_extends", "key", "NavigationType", "Pop", "DefaultErrorComponent", "error", "useRouteError", "message", "isRouteErrorResponse", "status", "statusText", "Error", "stack", "lightgrey", "preStyles", "padding", "backgroundColor", "codeStyles", "devInfo", "console", "Fragment", "style", "fontStyle", "defaultErrorElement", "RenderErrorBoundary", "constructor", "props", "revalidation", "getDerivedStateFromError", "getDerivedStateFromProps", "componentDidCatch", "errorInfo", "render", "routeContext", "children", "component", "RenderedRoute", "_ref", "staticContext", "errorElement", "ErrorBoundary", "_deepestRenderedBoundaryId", "id", "_dataRouterState", "_future", "errors", "v7_partialHydration", "initialized", "errorIndex", "findIndex", "m", "keys", "Math", "min", "renderFallback", "fallbackIndex", "i", "HydrateFallback", "hydrateFallbackElement", "loaderData", "needsToRunLoader", "loader", "reduceRight", "index", "shouldRenderHydrateFallback", "concat", "getChildren", "DataRouterHook", "DataRouterStateHook", "getDataRouterConsoleError", "hookName", "useDataRouterContext", "ctx", "useDataRouterState", "useRouteContext", "useCurrentRouteId", "thisRoute", "useRouteId", "UseRouteId", "useNavigation", "UseNavigation", "navigation", "useRevalidator", "UseRevalidator", "revalidate", "router", "useMatches", "UseMatches", "convertRouteMatchToUiMatch", "useLoaderData", "UseLoaderData", "routeId", "useRouteLoaderData", "UseRouteLoaderData", "useActionData", "UseActionData", "actionData", "_state$errors", "UseRouteError", "useAsyncValue", "_data", "useAsyncError", "_error", "blockerId", "useBlocker", "shouldBlock", "UseBlocker", "blockerKey", "setBlockerKey", "useState", "blockerFunction", "arg", "currentLocation", "nextLocation", "historyAction", "stripBasename", "useEffect", "String", "deleteBlocker", "getBlocker", "blockers", "has", "get", "IDLE_BLOCKER", "UseNavigateStable", "fromRouteId", "alreadyWarned", "cond", "warnOnce", "warn", "logDeprecation", "flag", "msg", "link", "logV6DeprecationWarnings", "renderFuture", "routerFuture", "v7_startTransition", "v7_fetcherPersist", "v7_normalizeFormMethod", "v7_skipActionErrorRevalidation", "START_TRANSITION", "startTransitionImpl", "MemoryRouter", "_ref3", "basename", "children", "initialEntries", "initialIndex", "future", "historyRef", "useRef", "current", "createMemoryHistory", "v5Compat", "history", "state", "setStateImpl", "useState", "action", "location", "v7_startTransition", "setState", "useCallback", "newState", "startTransitionImpl", "React", "useLayoutEffect", "listen", "useEffect", "logV6DeprecationWarnings", "createElement", "Router", "navigationType", "navigator", "Navigate", "_ref4", "to", "replace", "relative", "useInRouterContext", "process", "invariant", "static", "isStatic", "useContext", "NavigationContext", "warning", "matches", "RouteContext", "pathname", "locationPathname", "useLocation", "navigate", "useNavigate", "path", "resolveTo", "getResolveToMatches", "v7_relativeSplatPath", "jsonPath", "JSON", "stringify", "parse", "Outlet", "props", "useOutlet", "context", "Route", "_props", "_ref5", "basenameProp", "locationProp", "NavigationType", "Pop", "staticProp", "navigationContext", "useMemo", "_extends", "parsePath", "search", "hash", "key", "locationContext", "trailingPathname", "stripBasename", "Provider", "value", "LocationContext", "Routes", "_ref6", "useRoutes", "createRoutesFromChildren", "Await", "_ref7", "errorElement", "resolve", "AwaitErrorBoundary", "ResolveAwait", "AwaitRenderStatus", "neverSettledPromise", "Promise", "Component", "constructor", "error", "getDerivedStateFromError", "componentDidCatch", "errorInfo", "console", "render", "promise", "status", "pending", "success", "Object", "defineProperty", "get", "renderError", "reject", "catch", "_tracked", "then", "data", "_error", "AbortedDeferredError", "AwaitContext", "_ref8", "useAsyncValue", "toRender", "Fragment", "parentPath", "routes", "Children", "forEach", "element", "index", "isValidElement", "treePath", "type", "push", "apply", "name", "route", "id", "join", "caseSensitive", "loader", "ErrorBoundary", "hasErrorBoundary", "shouldRevalidate", "handle", "lazy", "renderMatches", "_renderMatches", "mapRouteProperties", "updates", "assign", "undefined", "HydrateFallback", "hydrateFallbackElement", "createMemoryRouter", "opts", "createRouter", "v7_prependBasename", "hydrationData", "dataStrategy", "patchRoutesOnNavigation", "initialize", "defaultMethod", "defaultEncType", "isHtmlElement", "object", "tagName", "isButtonElement", "toLowerCase", "isFormElement", "isInputElement", "isModifiedEvent", "event", "metaKey", "altKey", "ctrlKey", "shiftKey", "shouldProcessLinkClick", "target", "button", "createSearchParams", "init", "URLSearchParams", "Array", "isArray", "Object", "keys", "reduce", "memo", "key", "value", "concat", "map", "v", "getSearchParamsForLocation", "locationSearch", "defaultSearchParams", "searchParams", "forEach", "_", "has", "getAll", "append", "_formDataSupportsSubmitter", "isFormDataSubmitterSupported", "FormData", "document", "createElement", "e", "supportedFormEncTypes", "Set", "getFormEncType", "encType", "process", "warning", "getFormSubmissionInfo", "basename", "method", "action", "formData", "body", "attr", "getAttribute", "stripBasename", "type", "form", "Error", "name", "prefix", "undefined", "REACT_ROUTER_VERSION", "window", "__reactRouterVersion", "createBrowserRouter", "routes", "opts", "createRouter", "future", "_extends", "v7_prependBasename", "history", "createBrowserHistory", "hydrationData", "parseHydrationData", "dataStrategy", "patchRoutesOnNavigation", "initialize", "createHashRouter", "createHashHistory", "_window", "state", "__staticRouterHydrationData", "errors", "deserializeErrors", "entries", "serialized", "val", "__type", "ErrorResponseImpl", "status", "statusText", "data", "internal", "__subType", "ErrorConstructor", "error", "message", "stack", "ViewTransitionContext", "createContext", "isTransitioning", "displayName", "FetchersContext", "Map", "START_TRANSITION", "startTransitionImpl", "React", "FLUSH_SYNC", "flushSyncImpl", "ReactDOM", "USE_ID", "useIdImpl", "startTransitionSafe", "cb", "flushSyncSafe", "Deferred", "constructor", "promise", "Promise", "resolve", "reject", "reason", "RouterProvider", "_ref", "fallbackElement", "router", "setStateImpl", "useState", "pendingState", "setPendingState", "vtContext", "setVtContext", "renderDfd", "setRenderDfd", "transition", "setTransition", "interruption", "setInterruption", "fetcherData", "useRef", "v7_startTransition", "optInStartTransition", "useCallback", "setState", "newState", "_ref2", "deletedFetchers", "flushSync", "viewTransitionOpts", "current", "delete", "fetchers", "fetcher", "set", "isViewTransitionUnavailable", "startViewTransition", "skipTransition", "currentLocation", "nextLocation", "t", "finished", "finally", "useLayoutEffect", "subscribe", "useEffect", "renderPromise", "location", "v7_partialHydration", "navigator", "useMemo", "createHref", "encodeLocation", "go", "n", "navigate", "push", "to", "preventScrollReset", "replace", "dataRouterContext", "static", "routerFuture", "v7_relativeSplatPath", "logV6DeprecationWarnings", "Fragment", "DataRouterContext", "Provider", "DataRouterStateContext", "Router", "navigationType", "historyAction", "initialized", "MemoizedDataRoutes", "DataRoutes", "_ref3", "useRoutesImpl", "BrowserRouter", "_ref4", "children", "historyRef", "v5Compat", "listen", "HashRouter", "_ref5", "HistoryRouter", "_ref6", "isBrowser", "ABSOLUTE_URL_REGEX", "Link", "forwardRef", "LinkWithRef", "_ref7", "ref", "onClick", "relative", "reloadDocument", "viewTransition", "rest", "_objectWithoutPropertiesLoose", "_excluded", "useContext", "NavigationContext", "absoluteHref", "isExternal", "test", "currentUrl", "URL", "href", "targetUrl", "startsWith", "protocol", "path", "pathname", "origin", "search", "hash", "useHref", "internalOnClick", "useLinkClickHandler", "handleClick", "defaultPrevented", "NavLink", "NavLinkWithRef", "_ref8", "ariaCurrentProp", "caseSensitive", "className", "classNameProp", "end", "style", "styleProp", "_excluded2", "useResolvedPath", "useLocation", "routerState", "useViewTransitionState", "toPathname", "locationPathname", "nextLocationPathname", "navigation", "endSlashPosition", "endsWith", "length", "isActive", "charAt", "isPending", "renderProps", "ariaCurrent", "filter", "Boolean", "join", "Form", "_ref9", "forwardedRef", "fetcherKey", "onSubmit", "props", "_excluded3", "submit", "useSubmit", "formAction", "useFormAction", "formMethod", "submitHandler", "preventDefault", "submitter", "nativeEvent", "submitMethod", "currentTarget", "ScrollRestoration", "_ref10", "getKey", "storageKey", "useScrollRestoration", "DataRouterHook", "DataRouterStateHook", "getDataRouterConsoleError", "hookName", "useDataRouterContext", "ctx", "invariant", "useDataRouterState", "_temp", "replaceProp", "useNavigate", "createPath", "useSearchParams", "defaultInit", "defaultSearchParamsRef", "hasSetSearchParamsRef", "setSearchParams", "nextInit", "navigateOptions", "newSearchParams", "validateClientSideSubmission", "fetcherId", "getUniqueFetcherId", "String", "UseSubmit", "currentRouteId", "useRouteId", "options", "fetch", "formEncType", "fromRouteId", "_temp2", "routeContext", "RouteContext", "match", "matches", "slice", "params", "indexValues", "hasNakedIndexParam", "some", "qs", "toString", "route", "index", "joinPaths", "useFetcher", "_temp3", "_route$matches", "UseFetcher", "routeId", "id", "defaultKey", "setFetcherKey", "getFetcher", "deleteFetcher", "load", "submitImpl", "FetcherForm", "get", "IDLE_FETCHER", "fetcherWithComponents", "useFetchers", "UseFetchers", "from", "_ref11", "SCROLL_RESTORATION_STORAGE_KEY", "savedScrollPositions", "_temp4", "UseScrollRestoration", "restoreScrollPosition", "useMatches", "useNavigation", "scrollRestoration", "usePageHide", "scrollY", "sessionStorage", "setItem", "JSON", "stringify", "sessionPositions", "getItem", "parse", "getKeyWithoutBasename", "disableScrollRestoration", "enableScrollRestoration", "scrollTo", "el", "getElementById", "decodeURIComponent", "scrollIntoView", "useBeforeUnload", "callback", "capture", "addEventListener", "removeEventListener", "usePrompt", "_ref12", "when", "blocker", "useBlocker", "proceed", "confirm", "setTimeout", "reset", "currentPath", "nextPath", "matchPath"]
 }
