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ACF,CACH","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","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","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","history","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","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","array","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","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","DataWithResponseInit","constructor","type","AbortedDeferredError","DeferredData","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","dataStrategyImpl","dataStrategy","defaultDataStrategy","patchRoutesOnNavigationImpl","patchRoutesOnNavigation","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","v7_skipActionErrorRevalidation","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","checkFogOfWar","active","initialized","m","lazy","loader","errors","findIndex","shouldLoadRouteOnHydration","fogOfWar","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","unblockBlockerHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","nextHistoryUpdatePromise","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","viewTransitionOpts","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","handleNavigational404","isHashChangeOnly","request","createClientSideRequest","pendingActionResult","findNearestBoundary","actionResult","handleAction","shortCircuited","routeId","isErrorResult","getLoadingNavigation","updatedMatches","handleLoaders","fetcherSubmission","getActionDataForCommit","isFogOfWar","getSubmittingNavigation","discoverResult","discoverRoutes","boundaryId","partialMatches","actionMatch","getTargetMatch","method","callDataStrategy","isRedirectResult","normalizeRedirectLocation","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","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","detectAndHandle405Error","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","isNavigation","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetcherKey","results","dataResults","callDataStrategyImpl","e","isRedirectDataStrategyResultResult","normalizeRelativeRoutingRedirectResponse","convertDataStrategyResultToDataResult","fetchersToLoad","currentMatches","loaderResultsPromise","fetcherResultsPromise","all","resolveNavigationDeferredResults","resolveFetcherDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","isNonHMR","localManifest","patch","patchRoutesImpl","newMatches","newPartialMatches","_internalSetRoutes","newRoutes","patchRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","v7_throwAbortReason","query","_temp3","requestContext","skipLoaderErrorBubbling","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isDataStrategyResult","isRedirectResponse","isRouteRequest","throwStaticHandlerAbortedError","Location","loaderRequest","Request","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","_deepestRenderedBoundaryId","reason","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","nakedIndex","hasNakedIndexQuery","URLSearchParams","indexValues","getAll","append","qs","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","includeBoundary","skipActionErrorRevalidation","currentUrl","nextUrl","boundaryMatches","actionStatus","shouldSkipRevalidation","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","hasData","hasError","hydrate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","_childrenToPatch","childrenToPatch","uniqueChildren","newRoute","existingRoute","isSameRoute","aChild","_existingRoute$childr","bChild","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","isPropertyStaticallyDefined","_ref4","shouldLoad","loadRouteDefinitionsPromises","dsMatches","loadRoutePromise","handlerOverride","callLoaderOrAction","staticContext","onReject","runHandler","handler","actualHandler","ctx","handlerPromise","handlerError","dataStrategyResult","contentType","isDataWithResponseInit","_result$init2","_result$init","isDeferredData","_result$init3","_result$init4","deferred","_result$init5","_result$init6","trimmedMatches","normalizedLocation","protocol","isSameBasename","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","reverse","_temp5","errorMessage","isRevalidatingLoader","unwrap","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"sources":["../esm/npm/@remix-run/router@1.21.0/node_modules/@remix-run/router/history.ts","../esm/npm/@remix-run/router@1.21.0/node_modules/@remix-run/router/utils.ts","../esm/npm/@remix-run/router@1.21.0/node_modules/@remix-run/router/router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n  /**\n   * A POP indicates a change to an arbitrary index in the history stack, such\n   * as a back or forward navigation. It does not describe the direction of the\n   * navigation, only that the current index changed.\n   *\n   * Note: This is the default action for newly created history objects.\n   */\n  Pop = \"POP\",\n\n  /**\n   * A PUSH indicates a new entry being added to the history stack, such as when\n   * a link is clicked and a new page loads. When this happens, all subsequent\n   * entries in the stack are lost.\n   */\n  Push = \"PUSH\",\n\n  /**\n   * A REPLACE indicates the entry at the current index in the history stack\n   * being replaced by a new one.\n   */\n  Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n  /**\n   * A URL pathname, beginning with a /.\n   */\n  pathname: string;\n\n  /**\n   * A URL search string, beginning with a ?.\n   */\n  search: string;\n\n  /**\n   * A URL fragment identifier, beginning with a #.\n   */\n  hash: string;\n}\n\n// 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\u003cState = any\u003e 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\u003cPath\u003e;\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 \u003ca href\u003e 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): () =\u003e 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\u003cLocation\u003e;\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) =\u003e\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 \u0026\u0026 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 \u0026\u0026 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 () =\u003e {\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 \u0026\u0026 globalHistory.state.usr) || null,\n      (globalHistory.state \u0026\u0026 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 (\u003cRoute path=\"*\"\u003e) since that matches internally against\n    // \"/*\" and we'd expect /#something to 404 in a hash router app.\n    if (!pathname.startsWith(\"/\") \u0026\u0026 !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 \u0026\u0026 globalHistory.state.usr) || null,\n      (globalHistory.state \u0026\u0026 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 \u0026\u0026 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\u003cT\u003e(\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\u003cLocation\u003e {\n  let location: Readonly\u003cLocation\u003e = {\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 \u0026\u0026 (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\u003cPath\u003e) {\n  if (search \u0026\u0026 search !== \"?\")\n    pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n  if (hash \u0026\u0026 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\u003cPath\u003e {\n  let parsedPath: Partial\u003cPath\u003e = {};\n\n  if (path) {\n    let hashIndex = path.indexOf(\"#\");\n    if (hashIndex \u003e= 0) {\n      parsedPath.hash = path.substr(hashIndex);\n      path = path.substr(0, hashIndex);\n    }\n\n    let searchIndex = path.indexOf(\"?\");\n    if (searchIndex \u003e= 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\"]) =\u003e Location,\n  createHref: (window: Window, to: To) =\u003e string,\n  validateLocation: ((location: Location, to: To) =\u003e 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 \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026 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 () =\u003e {\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 -\u003e 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\u003cLowerCaseFormMethod\u003e;\n\n/**\n * Users can specify either lowercase or uppercase form methods on `\u003cForm\u003e`,\n * useSubmit(), `\u003cfetcher.Form\u003e`, 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\u003cFormMethod, \"get\"\u003e;\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\u003cV7_FormMethod, \"GET\"\u003e;\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 } \u0026 {\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\u003cContext\u003e {\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\u003cContext = any\u003e\n  extends DataFunctionArgs\u003cContext\u003e {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\u003cContext = any\u003e\n  extends DataFunctionArgs\u003cContext\u003e {}\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\u003cunknown\u003e | null;\n\ntype DataFunctionReturnValue = Promise\u003cDataFunctionValue\u003e | DataFunctionValue;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction\u003cContext = any\u003e = {\n  (\n    args: LoaderFunctionArgs\u003cContext\u003e,\n    handlerCtx?: unknown\n  ): DataFunctionReturnValue;\n} \u0026 { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction\u003cContext = any\u003e {\n  (\n    args: ActionFunctionArgs\u003cContext\u003e,\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\u003cstring, AgnosticDataRouteObject\u003e {\n  shouldLoad: boolean;\n  resolve: (\n    handlerOverride?: (\n      handler: (ctx?: unknown) =\u003e DataFunctionReturnValue\n    ) =\u003e DataFunctionReturnValue\n  ) =\u003e Promise\u003cDataStrategyResult\u003e;\n}\n\nexport interface DataStrategyFunctionArgs\u003cContext = any\u003e\n  extends DataFunctionArgs\u003cContext\u003e {\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\u003cRecord\u003cstring, DataStrategyResult\u003e\u003e;\n}\n\nexport type AgnosticPatchRoutesOnNavigationFunctionArgs\u003c\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n\u003e = {\n  path: string;\n  matches: M[];\n  patch: (routeId: string | null, children: O[]) =\u003e void;\n};\n\nexport type AgnosticPatchRoutesOnNavigationFunction\u003c\n  O extends AgnosticRouteObject = AgnosticRouteObject,\n  M extends AgnosticRouteMatch = AgnosticRouteMatch\n\u003e = (\n  opts: AgnosticPatchRoutesOnNavigationFunctionArgs\u003cO, M\u003e\n) =\u003e void | Promise\u003cvoid\u003e;\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  } \u0026 Record\u003cstring, any\u003e;\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\u003cImmutableRouteKey\u003e([\n  \"lazy\",\n  \"caseSensitive\",\n  \"path\",\n  \"id\",\n  \"index\",\n  \"children\",\n]);\n\ntype RequireOne\u003cT, Key = keyof T\u003e = Exclude\u003c\n  {\n    [K in keyof T]: K extends Key ? Omit\u003cT, K\u003e \u0026 Required\u003cPick\u003cT, K\u003e\u003e : never;\n  }[keyof T],\n  undefined\n\u003e;\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\u003cR extends AgnosticRouteObject\u003e {\n  (): Promise\u003cRequireOne\u003cOmit\u003cR, ImmutableRouteKey\u003e\u003e\u003e;\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\u003cAgnosticBaseRouteObject\u003e;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject \u0026 {\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 \u0026 {\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 \u0026 {\n  id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject \u0026 {\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\u003cstring, AgnosticDataRouteObject | undefined\u003e;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam\u003cPath extends string\u003e =\n  // split path into individual path segments\n  Path extends `${infer L}/${infer R}`\n    ? _PathParam\u003cL\u003e | _PathParam\u003cR\u003e\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/*\" -\u003e \"*\"\n * \":a\" -\u003e \"a\"\n * \"/a/:b\" -\u003e \"b\"\n * \"/a/blahblahblah:b\" -\u003e \"b\"\n * \"/:a/:b\" -\u003e \"a\" | \"b\"\n * \"/:a/b/:c/*\" -\u003e \"a\" | \"c\" | \"*\"\n */\nexport type PathParam\u003cPath extends string\u003e =\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\u003cRest\u003e\n    : // look for params in the absence of wildcards\n      _PathParam\u003cPath\u003e;\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\u003cSegment extends string\u003e =\n  // if you could not find path params, fallback to `string`\n  [PathParam\u003cSegment\u003e] extends [never] ? string : PathParam\u003cSegment\u003e;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params\u003cKey extends string = string\u003e = {\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\u003c\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params\u003cParamKey\u003e;\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\u003cstring, AgnosticDataRouteObject\u003e {}\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) =\u003e {\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\u003c\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e(\n  routes: RouteObjectType[],\n  locationArg: Partial\u003cLocation\u003e | string,\n  basename = \"/\"\n): AgnosticRouteMatch\u003cstring, RouteObjectType\u003e[] | null {\n  return matchRoutesImpl(routes, locationArg, basename, false);\n}\n\nexport function matchRoutesImpl\u003c\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e(\n  routes: RouteObjectType[],\n  locationArg: Partial\u003cLocation\u003e | string,\n  basename: string,\n  allowPartial: boolean\n): AgnosticRouteMatch\u003cstring, RouteObjectType\u003e[] | 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 \u0026\u0026 i \u003c 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\u003cstring, RouteObjectType\u003e(\n      branches[i],\n      decoded,\n      allowPartial\n    );\n  }\n\n  return matches;\n}\n\nexport interface UIMatch\u003cData = unknown, Handle = unknown\u003e {\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\u003c\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e {\n  relativePath: string;\n  caseSensitive: boolean;\n  childrenIndex: number;\n  route: RouteObjectType;\n}\n\ninterface RouteBranch\u003c\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e {\n  path: string;\n  score: number;\n  routesMeta: RouteMeta\u003cRouteObjectType\u003e[];\n}\n\nfunction flattenRoutes\u003c\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e(\n  routes: RouteObjectType[],\n  branches: RouteBranch\u003cRouteObjectType\u003e[] = [],\n  parentsMeta: RouteMeta\u003cRouteObjectType\u003e[] = [],\n  parentPath = \"\"\n): RouteBranch\u003cRouteObjectType\u003e[] {\n  let flattenRoute = (\n    route: RouteObjectType,\n    index: number,\n    relativePath?: string\n  ) =\u003e {\n    let meta: RouteMeta\u003cRouteObjectType\u003e = {\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 \u0026\u0026 route.children.length \u003e 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 \u0026\u0026 !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) =\u003e {\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?` -\u003e `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` -\u003e `/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) =\u003e\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) =\u003e\n    path.startsWith(\"/\") \u0026\u0026 exploded === \"\" ? \"/\" : exploded\n  );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n  branches.sort((a, b) =\u003e\n    a.score !== b.score\n      ? b.score - a.score // Higher score first\n      : compareIndexes(\n          a.routesMeta.map((meta) =\u003e meta.childrenIndex),\n          b.routesMeta.map((meta) =\u003e 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) =\u003e 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) =\u003e !isSplat(s))\n    .reduce(\n      (score, segment) =\u003e\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 \u0026\u0026 a.slice(0, -1).every((n, i) =\u003e 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\u003c\n  ParamKey extends string = string,\n  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n\u003e(\n  branch: RouteBranch\u003cRouteObjectType\u003e,\n  pathname: string,\n  allowPartial = false\n): AgnosticRouteMatch\u003cParamKey, RouteObjectType\u003e[] | null {\n  let { routesMeta } = branch;\n\n  let matchedParams = {};\n  let matchedPathname = \"/\";\n  let matches: AgnosticRouteMatch\u003cParamKey, RouteObjectType\u003e[] = [];\n  for (let i = 0; i \u003c 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 \u0026\u0026\n      end \u0026\u0026\n      allowPartial \u0026\u0026\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\u003cParamKey\u003e,\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\u003cPath extends string\u003e(\n  originalPath: Path,\n  params: {\n    [key in PathParam\u003cPath\u003e]: string | null;\n  } = {} as any\n): string {\n  let path: string = originalPath;\n  if (path.endsWith(\"*\") \u0026\u0026 path !== \"*\" \u0026\u0026 !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) =\u003e\n    p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n  const segments = path\n    .split(/\\/+/)\n    .map((segment, index, array) =\u003e {\n      const isLastSegment = index === array.length - 1;\n\n      // only apply the splat if it's the last segment\n      if (isLastSegment \u0026\u0026 segment === \"*\") {\n        const star = \"*\" as PathParam\u003cPath\u003e;\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\u003cPath\u003e];\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) =\u003e !!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\u003cPath extends string = string\u003e {\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\u003cParamKey extends string = string\u003e {\n  /**\n   * The names and values of dynamic parameters in the URL.\n   */\n  params: Params\u003cParamKey\u003e;\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\u003cT\u003e = {\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\u003c\n  ParamKey extends ParamParseKey\u003cPath\u003e,\n  Path extends string\n\u003e(\n  pattern: PathPattern\u003cPath\u003e | Path,\n  pathname: string\n): PathMatch\u003cParamKey\u003e | 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\u003cMutable\u003cParams\u003e\u003e(\n    (memo, { paramName, isOptional }, index) =\u003e {\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 \u0026\u0026 !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, \"\\\\$\u0026\") // Escape special regex chars\n      .replace(\n        /\\/:([\\w-]+)(\\?)?/g,\n        (_: string, paramName: string, isOptional) =\u003e {\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 !== \"\" \u0026\u0026 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) =\u003e 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 \u0026\u0026 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) =\u003e {\n    if (segment === \"..\") {\n      // Keep the root \"\" segment so the pathname starts at /\n      if (segments.length \u003e 1) segments.pop();\n    } else if (segment !== \".\") {\n      segments.push(segment);\n    }\n  });\n\n  return segments.length \u003e 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n  char: string,\n  field: string,\n  dest: string,\n  path: Partial\u003cPath\u003e\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 \u003cLink to=\"...\"\u003e 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 *   \u003cRoute path=\"/\"\u003e\n *     \u003cRoute path=\"accounts\" element={\u003cLink to=\"..\"}\u003e\n *   \u003c/Route\u003e\n *\n *   \u003cRoute path=\"/\"\u003e\n *     \u003cRoute path=\"accounts\"\u003e\n *       \u003cRoute element={\u003cAccountsLayout /\u003e}\u003e       // \u003c-- Does not contribute\n *         \u003cRoute index element={\u003cLink to=\"..\"} /\u003e  // \u003c-- Does not contribute\n *       \u003c/Route\n *     \u003c/Route\u003e\n *   \u003c/Route\u003e\n */\nexport function getPathContributingMatches\u003c\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n\u003e(matches: T[]) {\n  return matches.filter(\n    (match, index) =\u003e\n      index === 0 || (match.route.path \u0026\u0026 match.route.path.length \u003e 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\u003c\n  T extends AgnosticRouteMatch = AgnosticRouteMatch\n\u003e(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) =\u003e\n      idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase\n    );\n  }\n\n  return pathMatches.map((match) =\u003e 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\u003cPath\u003e;\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 `\u003cLink to\u003e` 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 \u003ca href\u003e works and a major reason we call this a\n    // \"to\" value instead of a \"href\".\n    if (!isPathRelative \u0026\u0026 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 \u003e= 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 \u0026\u0026 toPathname !== \"/\" \u0026\u0026 toPathname.endsWith(\"/\");\n  // Or if this was a link to the current path which has a trailing slash\n  let hasCurrentTrailingSlash =\n    (isEmptyPath || toPathname === \".\") \u0026\u0026 locationPathname.endsWith(\"/\");\n  if (\n    !path.pathname.endsWith(\"/\") \u0026\u0026\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 =\u003e\n  paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =\u003e\n  pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =\u003e\n  !search || search === \"?\"\n    ? \"\"\n    : search.startsWith(\"?\")\n    ? search\n    : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =\u003e\n  !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = \u003cData\u003e(\n  data: Data,\n  init?: number | ResponseInit\n) =\u003e 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 = {}) =\u003e {\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\u003cD\u003e {\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\u003cD\u003e(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\u003cany\u003e {\n  _tracked?: boolean;\n  _data?: any;\n  _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n  private pendingKeysSet: Set\u003cstring\u003e = new Set\u003cstring\u003e();\n  private controller: AbortController;\n  private abortPromise: Promise\u003cvoid\u003e;\n  private unlistenAbortSignal: () =\u003e void;\n  private subscribers: Set\u003c(aborted: boolean, settledKey?: string) =\u003e void\u003e =\n    new Set();\n  data: Record\u003cstring, unknown\u003e;\n  init?: ResponseInit;\n  deferredKeys: string[] = [];\n\n  constructor(data: Record\u003cstring, unknown\u003e, responseInit?: ResponseInit) {\n    invariant(\n      data \u0026\u0026 typeof data === \"object\" \u0026\u0026 !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) =\u003e void;\n    this.abortPromise = new Promise((_, r) =\u003e (reject = r));\n    this.controller = new AbortController();\n    let onAbort = () =\u003e\n      reject(new AbortedDeferredError(\"Deferred data aborted\"));\n    this.unlistenAbortSignal = () =\u003e\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]) =\u003e\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\u003cunknown\u003e | 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) =\u003e this.onSettle(promise, key, undefined, data as unknown),\n      (error) =\u003e 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(() =\u003e {});\n\n    Object.defineProperty(promise, \"_tracked\", { get: () =\u003e 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 \u0026\u0026\n      error instanceof AbortedDeferredError\n    ) {\n      this.unlistenAbortSignal();\n      Object.defineProperty(promise, \"_error\", { get: () =\u003e 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 \u0026\u0026 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: () =\u003e undefinedError });\n      this.emit(false, key);\n      return Promise.reject(undefinedError);\n    }\n\n    if (data === undefined) {\n      Object.defineProperty(promise, \"_error\", { get: () =\u003e error });\n      this.emit(false, key);\n      return Promise.reject(error);\n    }\n\n    Object.defineProperty(promise, \"_data\", { get: () =\u003e data });\n    this.emit(false, key);\n    return data;\n  }\n\n  private emit(aborted: boolean, settledKey?: string) {\n    this.subscribers.forEach((subscriber) =\u003e subscriber(aborted, settledKey));\n  }\n\n  subscribe(fn: (aborted: boolean, settledKey?: string) =\u003e void) {\n    this.subscribers.add(fn);\n    return () =\u003e this.subscribers.delete(fn);\n  }\n\n  cancel() {\n    this.controller.abort();\n    this.pendingKeysSet.forEach((v, k) =\u003e 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 = () =\u003e this.cancel();\n      signal.addEventListener(\"abort\", onAbort);\n      aborted = await new Promise((resolve) =\u003e {\n        this.subscribe((aborted) =\u003e {\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 \u0026\u0026 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]) =\u003e\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 \u0026\u0026 (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\u003cstring, unknown\u003e,\n  init?: number | ResponseInit\n) =\u003e 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 = {}) =\u003e {\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) =\u003e 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) =\u003e {\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) =\u003e {\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) =\u003e {\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 \u0026\u0026\n    typeof error.status === \"number\" \u0026\u0026\n    typeof error.statusText === \"string\" \u0026\u0026\n    typeof error.internal === \"boolean\" \u0026\u0026\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): () =\u003e 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\u003cstring, number\u003e,\n    getScrollPosition: GetScrollPositionFunction,\n    getKey?: GetScrollRestorationKeyFunction\n  ): () =\u003e 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\u003cvoid\u003e;\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\u003cvoid\u003e;\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\u003cTData = any\u003e(key: string): Fetcher\u003cTData\u003e;\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\u003cstring, AbortController\u003e;\n\n  /**\n   * @internal\n   * PRIVATE - DO NOT USE\n   *\n   * Internal pending DeferredData instances accessed by unit tests\n   */\n  _internalActiveDeferreds: Map\u003cstring, DeferredData\u003e;\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 -\u003e scroll position to restore to\n   *  - false -\u003e do not restore scroll at all (used during submissions)\n   *  - null -\u003e 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\u003cstring, Fetcher\u003e;\n\n  /**\n   * Map of current blockers\n   */\n  blockers: Map\u003cstring, Blocker\u003e;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial\u003c\n  Pick\u003cRouterState, \"loaderData\" | \"actionData\" | \"errors\"\u003e\n\u003e;\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\u003cFutureConfig\u003e;\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\u003cstring, Headers\u003e;\n  actionHeaders: Record\u003cstring, Headers\u003e;\n  activeDeferreds: Record\u003cstring, DeferredData\u003e | 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\u003cStaticHandlerContext | Response\u003e;\n  queryRoute(\n    request: Request,\n    opts?: {\n      routeId?: string;\n      requestContext?: unknown;\n      dataStrategy?: DataStrategyFunction;\n    }\n  ): Promise\u003cany\u003e;\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 \u0026 {\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} \u0026 (\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 \u0026 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 \u0026 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\u003cTData = any\u003e = {\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\u003cTData = any\u003e =\n  FetcherStates\u003cTData\u003e[keyof FetcherStates\u003cTData\u003e];\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}) =\u003e 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\u003cMutationFormMethod\u003e(\n  validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n  \"get\",\n  ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set\u003cFormMethod\u003e(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) =\u003e ({\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\" \u0026\u0026\n    typeof routerWindow.document !== \"undefined\" \u0026\u0026\n    typeof routerWindow.document.createElement !== \"undefined\";\n  const isServer = !isBrowser;\n\n  invariant(\n    init.routes.length \u003e 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) =\u003e ({\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: (() =\u003e void) | null = null;\n  // Externally-provided functions to call on all state changes\n  let subscribers = new Set\u003cRouterSubscriber\u003e();\n  // Externally-provided object to hold scroll restoration locations during routing\n  let savedScrollPositions: Record\u003cstring, number\u003e | 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 \u003cScrollRestoration /\u003e 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 \u0026\u0026 !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 \u0026\u0026 !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 \u0026\u0026 fogOfWar.matches) {\n        initialMatches = fogOfWar.matches;\n      }\n    }\n  } else if (initialMatches.some((m) =\u003e 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) =\u003e 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) =\u003e errors![m.route.id] !== undefined\n      );\n      initialized = initialMatches\n        .slice(0, idx + 1)\n        .every((m) =\u003e !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n    } else {\n      initialized = initialMatches.every(\n        (m) =\u003e !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 \u0026\u0026 init.hydrationData.loaderData) || {},\n    actionData: (init.hydrationData \u0026\u0026 init.hydrationData.actionData) || null,\n    errors: (init.hydrationData \u0026\u0026 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\u003cstring, Set\u003cstring\u003e\u003e = new Map\u003c\n    string,\n    Set\u003cstring\u003e\n  \u003e();\n\n  // Cleanup function for persisting applied transitions to sessionStorage\n  let removePageHideEventListener: (() =\u003e 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\u003cstring\u003e = new Set();\n\n  // AbortControllers for any in-flight fetchers\n  let fetchControllers = new Map\u003cstring, AbortController\u003e();\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\u003cstring, number\u003e();\n\n  // Fetchers that triggered redirect navigations\n  let fetchRedirectIds = new Set\u003cstring\u003e();\n\n  // Most recent href/match for fetcher.load calls for fetchers\n  let fetchLoadMatches = new Map\u003cstring, FetchLoadMatch\u003e();\n\n  // Ref-count mounted fetchers so we know when it's ok to clean them up\n  let activeFetchers = new Map\u003cstring, number\u003e();\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\u003cstring\u003e();\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\u003cstring, DeferredData\u003e();\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\u003cstring, BlockerFunction\u003e();\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\u003c\n    string,\n    ReturnType\u003cAgnosticPatchRoutesOnNavigationFunction\u003e\n  \u003e();\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: (() =\u003e 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 }) =\u003e {\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 \u0026\u0026 delta != null) {\n          // Restore the URL to match the current UI, but don't update router state\n          let nextHistoryUpdatePromise = new Promise\u003cvoid\u003e((resolve) =\u003e {\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(() =\u003e 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 = () =\u003e\n        persistAppliedTransitions(routerWindow, appliedViewTransitions);\n      routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n      removePageHideEventListener = () =\u003e\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 \u0026\u0026 pendingNavigationController.abort();\n    state.fetchers.forEach((_, key) =\u003e deleteFetcher(key));\n    state.blockers.forEach((_, key) =\u003e deleteBlocker(key));\n  }\n\n  // Subscribe to state updates for the router\n  function subscribe(fn: RouterSubscriber) {\n    subscribers.add(fn);\n    return () =\u003e subscribers.delete(fn);\n  }\n\n  // Update our state and notify the calling context of the change\n  function updateState(\n    newState: Partial\u003cRouterState\u003e,\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) =\u003e {\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) =\u003e\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) =\u003e state.fetchers.delete(key));\n      deletedFetchersKeys.forEach((key) =\u003e 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\u003cOmit\u003cRouterState, \"action\" | \"location\" | \"navigation\"\u003e\u003e,\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 \u0026\u0026\n      state.navigation.formMethod != null \u0026\u0026\n      isMutationMethod(state.navigation.formMethod) \u0026\u0026\n      state.navigation.state === \"loading\" \u0026\u0026\n      location.state?._isRedirect !== true;\n\n    let actionData: RouteData | null;\n    if (newState.actionData) {\n      if (Object.keys(newState.actionData).length \u003e 0) {\n        actionData = newState.actionData;\n      } else {\n        // Empty actionData -\u003e 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 \u003e 0) {\n      blockers = new Map(blockers);\n      blockers.forEach((_, k) =\u003e 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 \u0026\u0026\n        isMutationMethod(state.navigation.formMethod) \u0026\u0026\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 \u0026\u0026 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\u003cstring\u003e([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\u003cvoid\u003e {\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 \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026\n      isMutationMethod(submission.formMethod) \u0026\u0026\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 \u0026\u0026 \"preventScrollReset\" in opts\n        ? opts.preventScrollReset === true\n        : undefined;\n\n    let flushSync = (opts \u0026\u0026 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 \u0026\u0026 opts.replace,\n      enableViewTransition: opts \u0026\u0026 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\u003cvoid\u003e {\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 \u0026\u0026 pendingNavigationController.abort();\n    pendingNavigationController = null;\n    pendingAction = historyAction;\n    isUninterruptedRevalidation =\n      (opts \u0026\u0026 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 \u0026\u0026 opts.preventScrollReset) === true;\n\n    pendingViewTransitionEnabled = (opts \u0026\u0026 opts.enableViewTransition) === true;\n\n    let routesToUse = inFlightDataRoutes || dataRoutes;\n    let loadingNavigation = opts \u0026\u0026 opts.overrideNavigation;\n    let matches = matchRoutes(routesToUse, location, basename);\n    let flushSync = (opts \u0026\u0026 opts.flushSync) === true;\n\n    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n    if (fogOfWar.active \u0026\u0026 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 \u003cForm method=\"post\"\u003e\n    // which will default to a navigation to /page\n    if (\n      state.initialized \u0026\u0026\n      !isRevalidationRequired \u0026\u0026\n      isHashChangeOnly(state.location, location) \u0026\u0026\n      !(opts \u0026\u0026 opts.submission \u0026\u0026 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 \u0026\u0026 opts.submission\n    );\n    let pendingActionResult: PendingActionResult | undefined;\n\n    if (opts \u0026\u0026 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 \u0026\u0026\n      opts.submission \u0026\u0026\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) \u0026\u0026\n          isRouteErrorResponse(result.error) \u0026\u0026\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 \u0026\u0026 opts.submission,\n      opts \u0026\u0026 opts.fetcherSubmission,\n      opts \u0026\u0026 opts.replace,\n      opts \u0026\u0026 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\u003cHandleActionResult\u003e {\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 \u0026\u0026 !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 \u0026\u0026 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 \u0026\u0026 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\u003cHandleLoadersResult\u003e {\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 \u0026\u0026\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 \u0026\u0026 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) =\u003e\n        !(matches \u0026\u0026 matches.some((m) =\u003e m.route.id === routeId)) ||\n        (matchesToLoad \u0026\u0026 matchesToLoad.some((m) =\u003e 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 \u0026\u0026 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 \u0026\u0026 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\u003cRouterState\u003e = {};\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 \u003e 0) {\n        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n      }\n      updateState(updates, { flushSync });\n    }\n\n    revalidatingFetchers.forEach((rf) =\u003e {\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 = () =\u003e\n      revalidatingFetchers.forEach((f) =\u003e 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) =\u003e 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) =\u003e {\n      deferredData.subscribe((aborted) =\u003e {\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 \u0026\u0026 initialHydration \u0026\u0026 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 \u003e 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\u003cstring, RouteData\u003e | null | undefined {\n    if (pendingActionResult \u0026\u0026 !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) =\u003e {\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 \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026 opts.preventScrollReset) === true;\n\n    if (submission \u0026\u0026 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 \u0026\u0026 !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 \u0026\u0026 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 \u0026\u0026 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 \u003e 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) =\u003e rf.key !== key)\n      .forEach((rf) =\u003e {\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 = () =\u003e\n      revalidatingFetchers.forEach((rf) =\u003e 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) =\u003e 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\" \u0026\u0026\n      loadId \u003e pendingNavigationLoadId\n    ) {\n      invariant(pendingAction, \"Expected pending action\");\n      pendingNavigationController \u0026\u0026 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 \u003e 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 \u0026\u0026\n      !fetcherSubmission \u0026\u0026\n      formMethod \u0026\u0026\n      formAction \u0026\u0026\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) \u0026\u0026\n      activeSubmission \u0026\u0026\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\u003cRecord\u003cstring, DataResult\u003e\u003e {\n    let results: Record\u003cstring, DataStrategyResult\u003e;\n    let dataResults: Record\u003cstring, DataResult\u003e = {};\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) =\u003e {\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) =\u003e {\n        if (f.matches \u0026\u0026 f.match \u0026\u0026 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) =\u003e 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) =\u003e {\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 \u0026\u0026 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 \u0026\u0026 opts.flushSync) === true }\n    );\n  }\n\n  function getFetcher\u003cTData = any\u003e(key: string): Fetcher\u003cTData\u003e {\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) \u0026\u0026\n      !(fetcher \u0026\u0026 fetcher.state === \"loading\" \u0026\u0026 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 \u003c= 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 \u003c 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 \u003e 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\" \u0026\u0026 newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" \u0026\u0026 newBlocker.state === \"blocked\") ||\n        (blocker.state === \"blocked\" \u0026\u0026 newBlocker.state === \"proceeding\") ||\n        (blocker.state === \"blocked\" \u0026\u0026 newBlocker.state === \"unblocked\") ||\n        (blocker.state === \"proceeding\" \u0026\u0026 newBlocker.state === \"unblocked\"),\n      `Invalid blocker state transition: ${blocker.state} -\u003e ${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 \u003e 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 \u0026\u0026 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) =\u003e boolean\n  ): string[] {\n    let cancelledRouteIds: string[] = [];\n    activeDeferreds.forEach((dfd, routeId) =\u003e {\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 \u003cScrollRestoration\u003e component\n  function enableScrollRestoration(\n    positions: Record\u003cstring, number\u003e,\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 \u003cScrollRestoration/\u003e\n    // and therefore have no savedScrollPositions available\n    if (!initialScrollRestored \u0026\u0026 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 () =\u003e {\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) =\u003e 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 \u0026\u0026 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\u003cAgnosticDataRouteObject\u003e(\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 \u003e 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\u003cAgnosticDataRouteObject\u003e(\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\u003cDiscoverRoutesResult\u003e {\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) =\u003e {\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 \u0026\u0026 !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\u003cAgnosticDataRouteObject\u003e(\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 \u0026\u0026\n          partialMatches.every(\n            (m, i) =\u003e 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) =\u003e init.history.createHref(to),\n    encodeLocation: (to: To) =\u003e 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\u003cStaticHandlerFutureConfig\u003e;\n}\n\nexport function createStaticHandler(\n  routes: AgnosticRouteObject[],\n  opts?: CreateStaticHandlerOptions\n): StaticHandler {\n  invariant(\n    routes.length \u003e 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) =\u003e ({\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\u003cStaticHandlerContext | Response\u003e {\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) \u0026\u0026 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\u003cany\u003e {\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) \u0026\u0026 method !== \"HEAD\" \u0026\u0026 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) =\u003e m.route.id === routeId)\n      : getTargetMatch(matches, location);\n\n    if (routeId \u0026\u0026 !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\u003cOmit\u003cStaticHandlerContext, \"location\" | \"basename\"\u003e | Response\u003e {\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) \u0026\u0026 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\u003cOmit\u003cStaticHandlerContext, \"location\" | \"basename\"\u003e | Response\u003e {\n    let result: DataResult;\n\n    if (!actionMatch.route.action \u0026\u0026 !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\u003c\n    | Omit\u003c\n        StaticHandlerContext,\n        \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n      \u003e\n    | Response\n  \u003e {\n    let isRouteRequest = routeMatch != null;\n\n    // Short circuit if we have no loaders to run (queryRoute())\n    if (\n      isRouteRequest \u0026\u0026\n      !routeMatch?.route.loader \u0026\u0026\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 \u0026\u0026 isErrorResult(pendingActionResult[1])\n      ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0])\n      : matches;\n    let matchesToLoad = requestMatches.filter(\n      (m) =\u003e 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) =\u003e Object.assign(acc, { [m.route.id]: null }),\n          {}\n        ),\n        errors:\n          pendingActionResult \u0026\u0026 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\u003cstring, DeferredData\u003e();\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\u003cstring\u003e(\n      matchesToLoad.map((match) =\u003e match.route.id)\n    );\n    matches.forEach((match) =\u003e {\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 \u003e 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\u003cRecord\u003cstring, DataResult\u003e\u003e {\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\u003cstring, DataResult\u003e = {};\n    await Promise.all(\n      matches.map(async (match) =\u003e {\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) \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026\n    ((\"formData\" in opts \u0026\u0026 opts.formData != null) ||\n      (\"body\" in opts \u0026\u0026 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 === \".\") \u0026\u0026 activeRouteMatch) {\n    let nakedIndex = hasNakedIndexQuery(path.search);\n    if (activeRouteMatch.route.index \u0026\u0026 !nakedIndex) {\n      // Add one when we're targeting an index route\n      path.search = path.search\n        ? path.search.replace(/^\\?/, \"?index\u0026\")\n        : \"?index\";\n    } else if (!activeRouteMatch.route.index \u0026\u0026 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) =\u003e v).forEach((v) =\u003e 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 \u0026\u0026 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 \u0026\u0026 !isValidMethod(opts.formMethod)) {\n    return {\n      path,\n      error: getInternalRouterError(405, { method: opts.formMethod }),\n    };\n  }\n\n  let getInvalidBodyError = () =\u003e ({\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]) =\u003e `${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 \u0026\u0026 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 \u0026\u0026 parsedPath.search \u0026\u0026 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) =\u003e m.route.id === boundaryId);\n  if (index \u003e= 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\u003cstring\u003e,\n  deletedFetchers: Set\u003cstring\u003e,\n  fetchLoadMatches: Map\u003cstring, FetchLoadMatch\u003e,\n  fetchRedirectIds: Set\u003cstring\u003e,\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 \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026 actionStatus \u0026\u0026 actionStatus \u003e= 400;\n\n  let navigationMatches = boundaryMatches.filter((match, index) =\u003e {\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) =\u003e 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) =\u003e {\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) =\u003e 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 \u0026\u0026\n      fetcher.state !== \"idle\" \u0026\u0026\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 \u0026\u0026 loaderData[route.id] !== undefined;\n  let hasError = errors != null \u0026\u0026 errors[route.id] !== undefined;\n\n  // Don't run if we error'd during SSR\n  if (!hasData \u0026\u0026 hasError) {\n    return false;\n  }\n\n  // Explicitly opting-in to running on hydration\n  if (typeof route.loader === \"function\" \u0026\u0026 route.loader.hydrate === true) {\n    return true;\n  }\n\n  // Otherwise, run if we're not yet initialized with anything\n  return !hasData \u0026\u0026 !hasError;\n}\n\nfunction isNewLoader(\n  currentLoaderData: RouteData,\n  currentMatch: AgnosticDataRouteMatch,\n  match: AgnosticDataRouteMatch\n) {\n  let isNew =\n    // [a] -\u003e [a, b]\n    !currentMatch ||\n    // [a, b] -\u003e [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 -\u003e /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 -\u003e files/finances.xls\n    (currentPath != null \u0026\u0026\n      currentPath.endsWith(\"*\") \u0026\u0026\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) =\u003e\n      !childrenToPatch.some((existingRoute) =\u003e\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 \u0026\u0026\n    \"id\" in existingRoute \u0026\u0026\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 \u0026\u0026\n      newRoute.path === existingRoute.path \u0026\u0026\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) \u0026\u0026\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) =\u003e\n    existingRoute.children?.some((bChild) =\u003e 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\u003cstring, any\u003e = {};\n  for (let lazyRouteProperty in lazyRoute) {\n    let staticRouteValue =\n      routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n    let isPropertyStaticallyDefined =\n      staticRouteValue !== undefined \u0026\u0026\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 \u0026\u0026\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\u003cDataStrategyFunction\u003e {\n  let matchesToLoad = matches.filter((m) =\u003e m.shouldLoad);\n  let results = await Promise.all(matchesToLoad.map((m) =\u003e m.resolve()));\n  return results.reduce(\n    (acc, result, i) =\u003e\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\u003cRecord\u003cstring, DataStrategyResult\u003e\u003e {\n  let loadRouteDefinitionsPromises = matches.map((m) =\u003e\n    m.route.lazy\n      ? loadLazyRouteModule(m.route, mapRouteProperties, manifest)\n      : undefined\n  );\n\n  let dsMatches = matches.map((match, i) =\u003e {\n    let loadRoutePromise = loadRouteDefinitionsPromises[i];\n    let shouldLoad = matchesToLoad.some((m) =\u003e 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) =\u003e {\n      if (\n        handlerOverride \u0026\u0026\n        request.method === \"GET\" \u0026\u0026\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\u003cvoid\u003e | undefined,\n  handlerOverride: Parameters\u003cDataStrategyMatch[\"resolve\"]\u003e[0],\n  staticContext?: unknown\n): Promise\u003cDataStrategyResult\u003e {\n  let result: DataStrategyResult;\n  let onReject: (() =\u003e void) | undefined;\n\n  let runHandler = (\n    handler: AgnosticRouteObject[\"loader\"] | AgnosticRouteObject[\"action\"]\n  ): Promise\u003cDataStrategyResult\u003e =\u003e {\n    // Setup a promise we can race against so that abort signals short circuit\n    let reject: () =\u003e void;\n    // This will never resolve so safe to type it as Promise\u003cDataStrategyResult\u003e to\n    // satisfy the function return value\n    let abortPromise = new Promise\u003cDataStrategyResult\u003e((_, r) =\u003e (reject = r));\n    onReject = () =\u003e reject();\n    request.signal.addEventListener(\"abort\", onReject);\n\n    let actualHandler = (ctx?: unknown) =\u003e {\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\u003cDataStrategyResult\u003e = (async () =\u003e {\n      try {\n        let val = await (handlerOverride\n          ? handlerOverride((ctx: unknown) =\u003e 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) =\u003e {\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\u003cDataResult\u003e {\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 \u0026\u0026 /\\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 \u0026\u0026 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) =\u003e 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 \u0026\u0026 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 \u0026\u0026 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\" \u0026\u0026\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\u003cstring, DataResult\u003e,\n  pendingActionResult: PendingActionResult | undefined,\n  activeDeferreds: Map\u003cstring, DeferredData\u003e,\n  skipLoaderErrorBubbling: boolean\n): {\n  loaderData: RouterState[\"loaderData\"];\n  errors: RouterState[\"errors\"] | null;\n  statusCode: number;\n  loaderHeaders: Record\u003cstring, Headers\u003e;\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\u003cstring, Headers\u003e = {};\n  let pendingError =\n    pendingActionResult \u0026\u0026 isErrorResult(pendingActionResult[1])\n      ? pendingActionResult[1].error\n      : undefined;\n\n  // Process loader results into state.loaderData/state.errors\n  matches.forEach((match) =\u003e {\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 \u0026\u0026\n          result.statusCode !== 200 \u0026\u0026\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 \u0026\u0026 result.statusCode !== 200 \u0026\u0026 !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 \u0026\u0026 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\u003cstring, DataResult\u003e,\n  pendingActionResult: PendingActionResult | undefined,\n  revalidatingFetchers: RevalidatingFetcher[],\n  fetcherResults: Record\u003cstring, DataResult\u003e,\n  activeDeferreds: Map\u003cstring, DeferredData\u003e\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) =\u003e {\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 \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026 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 \u0026\u0026 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) =\u003e m.route.id === routeId) + 1)\n    : [...matches];\n  return (\n    eligibleMatches.reverse().find((m) =\u003e 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) =\u003e 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 \u0026\u0026 pathname \u0026\u0026 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 \u0026\u0026 pathname \u0026\u0026 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\u003cstring, DataResult\u003e\n): { key: string; result: RedirectResult } | undefined {\n  let entries = Object.entries(results);\n  for (let i = entries.length - 1; i \u003e= 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 -\u003e /page#hash\n    return b.hash !== \"\";\n  } else if (a.hash === b.hash) {\n    // /page#hash -\u003e /page#hash\n    return true;\n  } else if (b.hash !== \"\") {\n    // /page#hash -\u003e /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 -\u003e /page\n  return false;\n}\n\nfunction isPromise\u003cT = unknown\u003e(val: unknown): val is Promise\u003cT\u003e {\n  return typeof val === \"object\" \u0026\u0026 val != null \u0026\u0026 \"then\" in val;\n}\n\nfunction isDataStrategyResult(result: unknown): result is DataStrategyResult {\n  return (\n    result != null \u0026\u0026\n    typeof result === \"object\" \u0026\u0026\n    \"type\" in result \u0026\u0026\n    \"result\" in result \u0026\u0026\n    (result.type === ResultType.data || result.type === ResultType.error)\n  );\n}\n\nfunction isRedirectDataStrategyResultResult(result: DataStrategyResult) {\n  return (\n    isResponse(result.result) \u0026\u0026 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 \u0026\u0026 result.type) === ResultType.redirect;\n}\n\nexport function isDataWithResponseInit(\n  value: any\n): value is DataWithResponseInit\u003cunknown\u003e {\n  return (\n    typeof value === \"object\" \u0026\u0026\n    value != null \u0026\u0026\n    \"type\" in value \u0026\u0026\n    \"data\" in value \u0026\u0026\n    \"init\" in value \u0026\u0026\n    value.type === \"DataWithResponseInit\"\n  );\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n  let deferred: DeferredData = value;\n  return (\n    deferred \u0026\u0026\n    typeof deferred === \"object\" \u0026\u0026\n    typeof deferred.data === \"object\" \u0026\u0026\n    typeof deferred.subscribe === \"function\" \u0026\u0026\n    typeof deferred.cancel === \"function\" \u0026\u0026\n    typeof deferred.resolveData === \"function\"\n  );\n}\n\nfunction isResponse(value: any): value is Response {\n  return (\n    value != null \u0026\u0026\n    typeof value.status === \"number\" \u0026\u0026\n    typeof value.statusText === \"string\" \u0026\u0026\n    typeof value.headers === \"object\" \u0026\u0026\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 \u003e= 300 \u0026\u0026 status \u003c= 399 \u0026\u0026 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\u003cstring, DataResult\u003e,\n  signal: AbortSignal,\n  currentMatches: AgnosticDataRouteMatch[],\n  currentLoaderData: RouteData\n) {\n  let entries = Object.entries(results);\n  for (let index = 0; index \u003c entries.length; index++) {\n    let [routeId, result] = entries[index];\n    let match = matches.find((m) =\u003e 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) =\u003e m.route.id === match!.route.id\n    );\n    let isRevalidatingLoader =\n      currentMatch != null \u0026\u0026\n      !isNewRouteInstance(currentMatch, match) \u0026\u0026\n      (currentLoaderData \u0026\u0026 currentLoaderData[match.route.id]) !== undefined;\n\n    if (isDeferredResult(result) \u0026\u0026 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) =\u003e {\n        if (result) {\n          results[routeId] = result;\n        }\n      });\n    }\n  }\n}\n\nasync function resolveFetcherDeferredResults(\n  matches: (AgnosticDataRouteMatch | null)[],\n  results: Record\u003cstring, DataResult\u003e,\n  revalidatingFetchers: RevalidatingFetcher[]\n) {\n  for (let index = 0; index \u003c revalidatingFetchers.length; index++) {\n    let { key, routeId, controller } = revalidatingFetchers[index];\n    let result = results[key];\n    let match = matches.find((m) =\u003e 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) =\u003e {\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\u003cSuccessResult | ErrorResult | undefined\u003e {\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) =\u003e 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 \u0026\u0026\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\u003cstring, Set\u003cstring\u003e\u003e\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 \u0026\u0026 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\u003cstring, Set\u003cstring\u003e\u003e\n) {\n  if (transitions.size \u003e 0) {\n    let json: Record\u003cstring, string[]\u003e = {};\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"],"version":3}
