{"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n  CacheNodeSeedData,\n  FlightRouterState,\n  FlightSegmentPath,\n  ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData } from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n  startPPRNavigation,\n  spawnDynamicRequests,\n  FreshnessPolicy,\n  type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n  EntryStatus,\n  readRouteCacheEntry,\n  deprecated_requestOptimisticRouteCacheEntry,\n  convertRootFlightRouterStateToRouteTree,\n  getStaleAt,\n  writeStaticStageResponseIntoCache,\n  processRuntimePrefetchStream,\n  writeDynamicRenderResponseIntoCache,\n  type RouteTree,\n  type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { PageVaryPath } from './vary-path'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n  state: AppRouterState,\n  url: URL,\n  currentUrl: URL,\n  currentRenderedSearch: string,\n  currentCacheNode: CacheNode | null,\n  currentFlightRouterState: FlightRouterState,\n  nextUrl: string | null,\n  freshnessPolicy: FreshnessPolicy,\n  scrollBehavior: ScrollBehavior,\n  navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n  // Instant Navigation Testing API: when the lock is active, ensure a\n  // prefetch task has been initiated before proceeding with the navigation.\n  // This guarantees that segment data requests are at least pending, even\n  // for routes that already have a cached route tree. Without this, the\n  // static shell might be incomplete because some segments were never\n  // requested.\n  if (process.env.__NEXT_EXPOSE_TESTING_API) {\n    const { isNavigationLocked } =\n      require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n    if (isNavigationLocked()) {\n      return ensurePrefetchThenNavigate(\n        state,\n        url,\n        currentUrl,\n        currentRenderedSearch,\n        currentCacheNode,\n        currentFlightRouterState,\n        nextUrl,\n        freshnessPolicy,\n        scrollBehavior,\n        navigateType\n      )\n    }\n  }\n\n  return navigateImpl(\n    state,\n    url,\n    currentUrl,\n    currentRenderedSearch,\n    currentCacheNode,\n    currentFlightRouterState,\n    nextUrl,\n    freshnessPolicy,\n    scrollBehavior,\n    navigateType\n  )\n}\n\nfunction navigateImpl(\n  state: AppRouterState,\n  url: URL,\n  currentUrl: URL,\n  currentRenderedSearch: string,\n  currentCacheNode: CacheNode | null,\n  currentFlightRouterState: FlightRouterState,\n  nextUrl: string | null,\n  freshnessPolicy: FreshnessPolicy,\n  scrollBehavior: ScrollBehavior,\n  navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n  const now = Date.now()\n  const href = url.href\n\n  const cacheKey = createCacheKey(href, nextUrl)\n  const route = readRouteCacheEntry(now, cacheKey)\n  if (route !== null && route.status === EntryStatus.Fulfilled) {\n    // We have a matching prefetch.\n    return navigateUsingPrefetchedRouteTree(\n      now,\n      state,\n      url,\n      currentUrl,\n      currentRenderedSearch,\n      nextUrl,\n      currentCacheNode,\n      currentFlightRouterState,\n      freshnessPolicy,\n      scrollBehavior,\n      navigateType,\n      route\n    )\n  }\n\n  // There was no matching route tree in the cache. Let's see if we can\n  // construct an \"optimistic\" route tree using the deprecated search-params\n  // based matching. This is only used when the new optimisticRouting flag is\n  // disabled.\n  //\n  // Do not construct an optimistic route tree if there was a cache hit, but\n  // the entry has a rejected status, since it may have been rejected due to a\n  // rewrite or redirect based on the search params.\n  //\n  // TODO: There are multiple reasons a prefetch might be rejected; we should\n  // track them explicitly and choose what to do here based on that.\n  if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n    if (route === null || route.status !== EntryStatus.Rejected) {\n      const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n        now,\n        url,\n        nextUrl\n      )\n      if (optimisticRoute !== null) {\n        // We have an optimistic route tree. Proceed with the normal flow.\n        return navigateUsingPrefetchedRouteTree(\n          now,\n          state,\n          url,\n          currentUrl,\n          currentRenderedSearch,\n          nextUrl,\n          currentCacheNode,\n          currentFlightRouterState,\n          freshnessPolicy,\n          scrollBehavior,\n          navigateType,\n          optimisticRoute\n        )\n      }\n    }\n  }\n\n  // There's no matching prefetch for this route in the cache. We must lazily\n  // fetch it from the server before we can perform the navigation.\n  //\n  // TODO: If this is a gesture navigation, instead of performing a\n  // dynamic request, we should do a runtime prefetch.\n  return navigateToUnknownRoute(\n    now,\n    state,\n    url,\n    currentUrl,\n    currentRenderedSearch,\n    nextUrl,\n    currentCacheNode,\n    currentFlightRouterState,\n    freshnessPolicy,\n    scrollBehavior,\n    navigateType\n  ).catch(() => {\n    // If the navigation fails, return the current state\n    return state\n  })\n}\n\nexport function navigateToKnownRoute(\n  now: number,\n  state: AppRouterState,\n  url: URL,\n  canonicalUrl: string,\n  navigationSeed: NavigationSeed,\n  currentUrl: URL,\n  currentRenderedSearch: string,\n  currentCacheNode: CacheNode | null,\n  currentFlightRouterState: FlightRouterState,\n  freshnessPolicy: FreshnessPolicy,\n  nextUrl: string | null,\n  scrollBehavior: ScrollBehavior,\n  navigateType: 'push' | 'replace',\n  debugInfo: Array<unknown> | null,\n  // The route cache entry used for this navigation, if it came from route\n  // prediction. Passed through so it can be marked as having a dynamic rewrite\n  // if the server returns a different pathname (indicating dynamic rewrite\n  // behavior).\n  //\n  // When null, the navigation did not use route prediction - either because\n  // the route was already fully cached, or it's a navigation that doesn't\n  // involve prediction (refresh, history traversal, server action, etc.).\n  // In these cases, if a mismatch occurs, we still mark the route as having a\n  // dynamic rewrite by traversing the known route tree (see\n  // dispatchRetryDueToTreeMismatch).\n  routeCacheEntry: FulfilledRouteCacheEntry | null\n): AppRouterState {\n  // A version of navigate() that accepts the target route tree as an argument\n  // rather than reading it from the prefetch cache.\n  const accumulation: NavigationRequestAccumulation = {\n    separateRefreshUrls: null,\n    scrollRef: null,\n  }\n  // We special case navigations to the exact same URL as the current location.\n  // It's a common UI pattern for apps to refresh when you click a link to the\n  // current page. So when this happens, we refresh the dynamic data in the page\n  // segments.\n  //\n  // Note that this does not apply if the any part of the hash or search query\n  // has changed. This might feel a bit weird but it makes more sense when you\n  // consider that the way to trigger this behavior is to click the same link\n  // multiple times.\n  //\n  // TODO: We should probably refresh the *entire* route when this case occurs,\n  // not just the page segments. Essentially treating it the same as a refresh()\n  // triggered by an action, which is the more explicit way of modeling the UI\n  // pattern described above.\n  //\n  // Also note that this only refreshes the dynamic data, not static/ cached\n  // data. If the page segment is fully static and prefetched, the request is\n  // skipped. (This is also how refresh() works.)\n  const isSamePageNavigation = url.href === currentUrl.href\n  const task = startPPRNavigation(\n    now,\n    currentUrl,\n    currentRenderedSearch,\n    currentCacheNode,\n    currentFlightRouterState,\n    navigationSeed.routeTree,\n    navigationSeed.metadataVaryPath,\n    freshnessPolicy,\n    navigationSeed.data,\n    navigationSeed.head,\n    navigationSeed.dynamicStaleAt,\n    isSamePageNavigation,\n    accumulation\n  )\n  if (task !== null) {\n    if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n      spawnDynamicRequests(\n        task,\n        url,\n        nextUrl,\n        freshnessPolicy,\n        accumulation,\n        routeCacheEntry,\n        navigateType\n      )\n    }\n    return completeSoftNavigation(\n      state,\n      url,\n      nextUrl,\n      task.route,\n      task.node,\n      navigationSeed.renderedSearch,\n      canonicalUrl,\n      navigateType,\n      scrollBehavior,\n      accumulation.scrollRef,\n      debugInfo\n    )\n  }\n  // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n  return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n  now: number,\n  state: AppRouterState,\n  url: URL,\n  currentUrl: URL,\n  currentRenderedSearch: string,\n  nextUrl: string | null,\n  currentCacheNode: CacheNode | null,\n  currentFlightRouterState: FlightRouterState,\n  freshnessPolicy: FreshnessPolicy,\n  scrollBehavior: ScrollBehavior,\n  navigateType: 'push' | 'replace',\n  route: FulfilledRouteCacheEntry\n): AppRouterState {\n  const routeTree = route.tree\n  const canonicalUrl = route.canonicalUrl + url.hash\n  const renderedSearch = route.renderedSearch\n  const prefetchSeed: NavigationSeed = {\n    renderedSearch,\n    routeTree,\n    metadataVaryPath: route.metadata.varyPath as any,\n    data: null,\n    head: null,\n    dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n  }\n  return navigateToKnownRoute(\n    now,\n    state,\n    url,\n    canonicalUrl,\n    prefetchSeed,\n    currentUrl,\n    currentRenderedSearch,\n    currentCacheNode,\n    currentFlightRouterState,\n    freshnessPolicy,\n    nextUrl,\n    scrollBehavior,\n    navigateType,\n    null,\n    route\n  )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n  '',\n  {},\n  null,\n  'refetch',\n]\n\nasync function navigateToUnknownRoute(\n  now: number,\n  state: AppRouterState,\n  url: URL,\n  currentUrl: URL,\n  currentRenderedSearch: string,\n  nextUrl: string | null,\n  currentCacheNode: CacheNode | null,\n  currentFlightRouterState: FlightRouterState,\n  freshnessPolicy: FreshnessPolicy,\n  scrollBehavior: ScrollBehavior,\n  navigateType: 'push' | 'replace'\n): Promise<AppRouterState> {\n  // Runs when a navigation happens but there's no cached prefetch we can use.\n  // Don't bother to wait for a prefetch response; go straight to a full\n  // navigation that contains both static and dynamic data in a single stream.\n  // (This is unlike the old navigation implementation, which instead blocks\n  // the dynamic request until a prefetch request is received.)\n  //\n  // To avoid duplication of logic, we're going to pretend that the tree\n  // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n  // use the same server response to write the actual data into the CacheNode\n  // tree. So it's the same flow as the \"happy path\" (prefetch, then\n  // navigation), except we use a single server response for both stages.\n\n  let dynamicRequestTree: FlightRouterState\n  switch (freshnessPolicy) {\n    case FreshnessPolicy.Default:\n    case FreshnessPolicy.HistoryTraversal:\n    case FreshnessPolicy.Gesture:\n      dynamicRequestTree = currentFlightRouterState\n      break\n    case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n    case FreshnessPolicy.RefreshAll:\n    case FreshnessPolicy.HMRRefresh:\n      dynamicRequestTree = DynamicRequestTreeForEntireRoute\n      break\n    default:\n      freshnessPolicy satisfies never\n      dynamicRequestTree = currentFlightRouterState\n      break\n  }\n\n  const promiseForDynamicServerResponse = fetchServerResponse(url, {\n    flightRouterState: dynamicRequestTree,\n    nextUrl,\n  })\n  const result = await promiseForDynamicServerResponse\n  if (typeof result === 'string') {\n    // This is an MPA navigation.\n    const redirectUrl = new URL(result, location.origin)\n    return completeHardNavigation(state, redirectUrl, navigateType)\n  }\n\n  const {\n    flightData,\n    canonicalUrl,\n    renderedSearch,\n    couldBeIntercepted,\n    supportsPerSegmentPrefetching,\n    dynamicStaleTime,\n    staticStageData,\n    runtimePrefetchStream,\n    responseHeaders,\n    debugInfo,\n  } = result\n\n  // Since the response format of dynamic requests and prefetches is slightly\n  // different, we'll need to massage the data a bit. Create FlightRouterState\n  // tree that simulates what we'd receive as the result of a prefetch.\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    currentFlightRouterState,\n    flightData,\n    renderedSearch,\n    dynamicStaleTime\n  )\n\n  // Learn the route pattern so we can predict it for future navigations.\n  // hasDynamicRewrite is false because this is a fresh navigation to an\n  // unknown route - any rewrite detection happens during the traversal inside\n  // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n  // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n  const metadataVaryPath = navigationSeed.metadataVaryPath\n  if (metadataVaryPath !== null) {\n    discoverKnownRoute(\n      now,\n      url.pathname,\n      nextUrl,\n      null, // No pending entry\n      navigationSeed.routeTree,\n      metadataVaryPath,\n      couldBeIntercepted,\n      createHrefFromUrl(canonicalUrl),\n      supportsPerSegmentPrefetching,\n      false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n    )\n\n    if (staticStageData !== null) {\n      const { response: staticStageResponse, isResponsePartial } =\n        staticStageData\n\n      // Write the static stage of the response into the segment cache so that\n      // subsequent navigations can serve cached static segments instantly.\n      getStaleAt(now, staticStageResponse.s)\n        .then((staleAt) => {\n          const buildId =\n            responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n            staticStageResponse.b\n\n          writeStaticStageResponseIntoCache(\n            now,\n            staticStageResponse.f,\n            buildId,\n            staticStageResponse.h,\n            staleAt,\n            currentFlightRouterState,\n            renderedSearch,\n            isResponsePartial\n          )\n        })\n        .catch(() => {\n          // The static stage processing failed. Not fatal — the navigation\n          // completed normally, we just won't write into the cache.\n        })\n    }\n\n    if (runtimePrefetchStream !== null) {\n      processRuntimePrefetchStream(\n        now,\n        runtimePrefetchStream,\n        currentFlightRouterState,\n        renderedSearch\n      )\n        .then((processed) => {\n          if (processed !== null) {\n            writeDynamicRenderResponseIntoCache(\n              now,\n              FetchStrategy.PPRRuntime,\n              processed.flightDatas,\n              processed.buildId,\n              processed.isResponsePartial,\n              processed.headVaryParams,\n              processed.staleAt,\n              processed.navigationSeed,\n              null\n            )\n          }\n        })\n        .catch(() => {\n          // The runtime prefetch cache write failed. Not fatal — the\n          // navigation completed normally, we just won't cache runtime data.\n        })\n    }\n  }\n\n  return navigateToKnownRoute(\n    now,\n    state,\n    url,\n    createHrefFromUrl(canonicalUrl),\n    navigationSeed,\n    currentUrl,\n    currentRenderedSearch,\n    currentCacheNode,\n    currentFlightRouterState,\n    freshnessPolicy,\n    nextUrl,\n    scrollBehavior,\n    navigateType,\n    debugInfo,\n    // Unknown route navigations don't use route prediction - the route tree\n    // came directly from the server. If a mismatch occurs during dynamic data\n    // fetch, the retry handler will traverse the known route tree to mark the\n    // entry as having a dynamic rewrite.\n    null\n  )\n}\n\nexport function completeHardNavigation(\n  state: AppRouterState,\n  url: URL,\n  navigateType: 'push' | 'replace'\n): AppRouterState {\n  if (isJavaScriptURLString(url.href)) {\n    console.error(\n      'Next.js has blocked a javascript: URL as a security precaution.'\n    )\n    return state\n  }\n  const newState: AppRouterState = {\n    canonicalUrl:\n      url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n    pushRef: {\n      pendingPush: navigateType === 'push',\n      mpaNavigation: true,\n      preserveCustomHistoryState: false,\n    },\n    // TODO: None of the rest of these values are consistent with the incoming\n    // navigation. We rely on the fact that AppRouter will suspend and trigger\n    // a hard navigation before it accesses any of these values. But instead\n    // we should trigger the hard navigation and blocking any subsequent\n    // router updates without updating React.\n    renderedSearch: state.renderedSearch,\n    focusAndScrollRef: state.focusAndScrollRef,\n    cache: state.cache,\n    tree: state.tree,\n    nextUrl: state.nextUrl,\n    previousNextUrl: state.previousNextUrl,\n    debugInfo: null,\n  }\n  return newState\n}\n\nexport function completeSoftNavigation(\n  oldState: AppRouterState,\n  url: URL,\n  referringNextUrl: string | null,\n  tree: FlightRouterState,\n  cache: CacheNode,\n  renderedSearch: string,\n  canonicalUrl: string,\n  navigateType: 'push' | 'replace',\n  scrollBehavior: ScrollBehavior,\n  scrollRef: ScrollRef | null,\n  collectedDebugInfo: Array<unknown> | null\n) {\n  // The \"Next-Url\" is a special representation of the URL that Next.js\n  // uses to implement interception routes.\n  // TODO: Get rid of this extra traversal by computing this during the\n  // same traversal that computes the tree itself. We should also figure out\n  // what is the minimum information needed for the server to correctly\n  // intercept the route.\n  const changedPath = computeChangedPath(oldState.tree, tree)\n  const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n  // This value is stored on the state as `previousNextUrl`; the naming is\n  // confusing. What it represents is the \"Next-Url\" header that was used to\n  // fetch the incoming route. It's essentially the refererer URL, but in a\n  // Next.js specific format. During refreshes, this is sent back to the server\n  // instead of the current route's \"Next-Url\" so that the same interception\n  // logic is applied as during the original navigation.\n  const previousNextUrl = referringNextUrl\n\n  // Check if the only thing that changed was the hash fragment.\n  const oldUrl = new URL(oldState.canonicalUrl, url)\n  const onlyHashChange =\n    // We don't need to compare the origins, because client-driven\n    // navigations are always same-origin.\n    url.pathname === oldUrl.pathname &&\n    url.search === oldUrl.search &&\n    url.hash !== oldUrl.hash\n\n  // Determine whether and how the page should scroll after this\n  // navigation.\n  //\n  // By default, we scroll to the segments that were navigated to — i.e.\n  // segments in the new part of the route, as opposed to shared segments\n  // that were already part of the previous route. All newly navigated\n  // segments share a single ScrollRef. When they mount, the first one\n  // to mount initiates the scroll. They share a ref so that only one\n  // scroll happens per navigation.\n  //\n  // If a subsequent navigation produces new segments, those supersede\n  // any pending scroll from the previous navigation by invalidating its\n  // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n  // a refresh where the route structure didn't change), any pending\n  // scrolls from previous navigations are unaffected.\n  //\n  // The branches below handle special cases layered on top of this\n  // default model.\n  let activeScrollRef: ScrollRef | null\n  let forceScroll: boolean\n  if (scrollBehavior === ScrollBehavior.NoScroll) {\n    // The user explicitly opted out of scrolling (e.g. scroll={false}\n    // on a Link or router.push).\n    //\n    // If this navigation created new scroll targets (scrollRef !== null),\n    // neutralize them. If it didn't, any prior scroll targets carried\n    // forward on the cache nodes via reuseSharedCacheNode remain active.\n    if (scrollRef !== null) {\n      scrollRef.current = false\n    }\n    activeScrollRef = oldState.focusAndScrollRef.scrollRef\n    forceScroll = false\n  } else if (onlyHashChange) {\n    // Hash-only navigations should scroll regardless of per-node state.\n    // Create a fresh ref so the first segment to scroll consumes it.\n    //\n    // Invalidate any scroll ref from a prior navigation that hasn't\n    // been consumed yet.\n    const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n    if (oldScrollRef !== null) {\n      oldScrollRef.current = false\n    }\n    // Also invalidate any per-node refs that were accumulated during\n    // this navigation's tree construction — the hash-only ref\n    // supersedes them.\n    if (scrollRef !== null) {\n      scrollRef.current = false\n    }\n    activeScrollRef = { current: true }\n    forceScroll = true\n  } else {\n    // Default case. Use the accumulated scrollRef (may be null if no\n    // new segments were created). The handler checks per-node refs, so\n    // unchanged parallel route slots won't scroll.\n    activeScrollRef = scrollRef\n\n    // If this navigation created new scroll targets, invalidate any\n    // pending scroll from a previous navigation.\n    if (scrollRef !== null) {\n      const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n      if (oldScrollRef !== null) {\n        oldScrollRef.current = false\n      }\n    }\n    forceScroll = false\n  }\n\n  const newState: AppRouterState = {\n    canonicalUrl,\n    renderedSearch,\n    pushRef: {\n      pendingPush: navigateType === 'push',\n      mpaNavigation: false,\n      preserveCustomHistoryState: false,\n    },\n    focusAndScrollRef: {\n      scrollRef: activeScrollRef,\n      forceScroll,\n      onlyHashChange,\n      hashFragment:\n        // Remove leading # and decode hash to make non-latin hashes work.\n        //\n        // Empty hash should trigger default behavior of scrolling layout into\n        // view. #top is handled in layout-router.\n        //\n        // Refer to `ScrollAndFocusHandler` for details on how this is used.\n        scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n          ? decodeURIComponent(url.hash.slice(1))\n          : oldState.focusAndScrollRef.hashFragment,\n    },\n    cache,\n    tree,\n    nextUrl: nextUrlForNewRoute,\n    previousNextUrl,\n    debugInfo: collectedDebugInfo,\n  }\n  return newState\n}\n\nexport function completeTraverseNavigation(\n  state: AppRouterState,\n  url: URL,\n  renderedSearch: string,\n  cache: CacheNode,\n  tree: FlightRouterState,\n  nextUrl: string | null\n) {\n  return {\n    // Set canonical url\n    canonicalUrl: createHrefFromUrl(url),\n    renderedSearch,\n    pushRef: {\n      pendingPush: false,\n      mpaNavigation: false,\n      // Ensures that the custom history state that was set is preserved when applying this update.\n      preserveCustomHistoryState: true,\n    },\n    focusAndScrollRef: state.focusAndScrollRef,\n    cache,\n    // Restore provided tree\n    tree,\n    nextUrl,\n    // TODO: We need to restore previousNextUrl, too, which represents the\n    // Next-Url that was used to fetch the data. Anywhere we fetch using the\n    // canonical URL, there should be a corresponding Next-Url.\n    previousNextUrl: null,\n    debugInfo: null,\n  }\n}\n\n// TODO: The rest of this file is related to converting the server response into\n// the data structures used by the client. Probably should move to a\n// separate module.\n\nexport type NavigationSeed = {\n  renderedSearch: string\n  routeTree: RouteTree\n  metadataVaryPath: PageVaryPath | null\n  data: CacheNodeSeedData | null\n  head: HeadData | null\n  dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n  now: number,\n  currentTree: FlightRouterState,\n  flightData: Array<NormalizedFlightData> | null,\n  renderedSearch: string,\n  dynamicStaleTimeSeconds: number\n): NavigationSeed {\n  // During a client navigation or prefetch, the server sends back only a patch\n  // for the parts of the tree that have changed.\n  //\n  // This applies the patch to the base tree to create a full representation of\n  // the resulting tree.\n  //\n  // The return type includes a full FlightRouterState tree and a full\n  // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n  // eventually be unified, but there's still lots of existing code that\n  // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n  //\n  // TODO: This similar to what apply-router-state-patch-to-tree does. It\n  // will eventually fully replace it. We should get rid of all the remaining\n  // places where we iterate over the server patch format. This should also\n  // eventually replace normalizeFlightData.\n\n  let baseTree: FlightRouterState = currentTree\n  let baseData: CacheNodeSeedData | null = null\n  let head: HeadData | null = null\n  if (flightData !== null) {\n    for (const {\n      segmentPath,\n      tree: treePatch,\n      seedData: dataPatch,\n      head: headPatch,\n    } of flightData) {\n      const result = convertServerPatchToFullTreeImpl(\n        baseTree,\n        baseData,\n        treePatch,\n        dataPatch,\n        segmentPath,\n        renderedSearch,\n        0\n      )\n      baseTree = result.tree\n      baseData = result.data\n      // This is the same for all patches per response, so just pick an\n      // arbitrary one\n      head = headPatch\n    }\n  }\n\n  const finalFlightRouterState = baseTree\n\n  // Convert the final FlightRouterState into a RouteTree type.\n  //\n  // TODO: Eventually, FlightRouterState will evolve to being a transport format\n  // only. The RouteTree type will become the main type used for dealing with\n  // routes on the client, and we'll store it in the state directly.\n  const acc = { metadataVaryPath: null }\n  const routeTree = convertRootFlightRouterStateToRouteTree(\n    finalFlightRouterState,\n    renderedSearch as NormalizedSearch,\n    acc\n  )\n\n  return {\n    routeTree,\n    metadataVaryPath: acc.metadataVaryPath,\n    data: baseData,\n    renderedSearch,\n    head,\n    dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n  }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n  baseRouterState: FlightRouterState,\n  baseData: CacheNodeSeedData | null,\n  treePatch: FlightRouterState,\n  dataPatch: CacheNodeSeedData | null,\n  segmentPath: FlightSegmentPath,\n  renderedSearch: string,\n  index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n  if (index === segmentPath.length) {\n    // We reached the part of the tree that we need to patch.\n    return {\n      tree: treePatch,\n      data: dataPatch,\n    }\n  }\n\n  // segmentPath represents the parent path of subtree. It's a repeating\n  // pattern of parallel route key and segment:\n  //\n  //   [string, Segment, string, Segment, string, Segment, ...]\n  //\n  // This path tells us which part of the base tree to apply the tree patch.\n  //\n  // NOTE: We receive the FlightRouterState patch in the same request as the\n  // seed data patch. Therefore we don't need to worry about diffing the segment\n  // values; we can assume the server sent us a correct result.\n  const updatedParallelRouteKey: string = segmentPath[index]\n  // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n  const baseTreeChildren = baseRouterState[1]\n  const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n  const newTreeChildren: Record<string, FlightRouterState> = {}\n  const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n  for (const parallelRouteKey in baseTreeChildren) {\n    const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n    const childBaseSeedData =\n      baseSeedDataChildren !== null\n        ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n        : null\n    if (parallelRouteKey === updatedParallelRouteKey) {\n      const result = convertServerPatchToFullTreeImpl(\n        childBaseRouterState,\n        childBaseSeedData,\n        treePatch,\n        dataPatch,\n        segmentPath,\n        renderedSearch,\n        // Advance the index by two and keep cloning until we reach\n        // the end of the segment path.\n        index + 2\n      )\n\n      newTreeChildren[parallelRouteKey] = result.tree\n      newSeedDataChildren[parallelRouteKey] = result.data\n    } else {\n      // This child is not being patched. Copy it over as-is.\n      newTreeChildren[parallelRouteKey] = childBaseRouterState\n      newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n    }\n  }\n\n  let clonedTree: FlightRouterState\n  let clonedSeedData: CacheNodeSeedData\n  // Clone all the fields except the children.\n\n  // Clone the FlightRouterState tree. Based on equivalent logic in\n  // apply-router-state-patch-to-tree, but should confirm whether we need to\n  // copy all of these fields. Not sure the server ever sends, e.g. the\n  // refetch marker.\n  clonedTree = [baseRouterState[0], newTreeChildren]\n  if (2 in baseRouterState) {\n    const compressedRefreshState = baseRouterState[2]\n    if (\n      compressedRefreshState !== undefined &&\n      compressedRefreshState !== null\n    ) {\n      // Since this part of the tree was patched with new data, any parent\n      // refresh states should be updated to reflect the new rendered search\n      // value. (The refresh state acts like a \"context provider\".) All pages\n      // within the same server response share the same renderedSearch value,\n      // but the same RouteTree could be composed from multiple different\n      // routes, and multiple responses.\n      clonedTree[2] = [compressedRefreshState[0], renderedSearch]\n    }\n  }\n  if (3 in baseRouterState) {\n    clonedTree[3] = baseRouterState[3]\n  }\n  if (4 in baseRouterState) {\n    clonedTree[4] = baseRouterState[4]\n  }\n\n  // Clone the CacheNodeSeedData tree.\n  const isEmptySeedDataPartial = true\n  clonedSeedData = [\n    null,\n    newSeedDataChildren,\n    null,\n    isEmptySeedDataPartial,\n    null,\n  ]\n\n  return {\n    tree: clonedTree,\n    data: clonedSeedData,\n  }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n  state: AppRouterState,\n  url: URL,\n  currentUrl: URL,\n  currentRenderedSearch: string,\n  currentCacheNode: CacheNode | null,\n  currentFlightRouterState: FlightRouterState,\n  nextUrl: string | null,\n  freshnessPolicy: FreshnessPolicy,\n  scrollBehavior: ScrollBehavior,\n  navigateType: 'push' | 'replace'\n): Promise<AppRouterState> {\n  const link = getLinkForCurrentNavigation()\n  const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n  // Transition the cookie to captured-SPA immediately, before waiting\n  // for the prefetch. This ensures the devtools panel can update its UI\n  // right away, even if the prefetch takes time (e.g. dev compilation).\n  // The \"to\" tree starts as null and is filled in after the prefetch\n  // resolves and the navigation produces a new router state.\n  const { transitionToCapturedSPA, updateCapturedSPAToTree } =\n    require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n  transitionToCapturedSPA(currentFlightRouterState, null)\n\n  const cacheKey = createCacheKey(url.href, nextUrl)\n\n  await new Promise<void>((resolve) => {\n    schedulePrefetchTask(\n      cacheKey,\n      currentFlightRouterState,\n      fetchStrategy,\n      PrefetchPriority.Default,\n      null, // onInvalidate\n      resolve // _onComplete callback\n    )\n  })\n\n  // Prefetch is complete. Proceed with the normal navigation flow, which\n  // will now find the route in the cache.\n  const result = await navigateImpl(\n    state,\n    url,\n    currentUrl,\n    currentRenderedSearch,\n    currentCacheNode,\n    currentFlightRouterState,\n    nextUrl,\n    freshnessPolicy,\n    scrollBehavior,\n    navigateType\n  )\n\n  // Update the cookie with the resolved \"to\" tree so the devtools\n  // panel can display both routes immediately.\n  updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n\n  return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","convertServerPatchToFullTree","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","routeTree","metadataVaryPath","data","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","computeDynamicStaleAt","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","flightData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","discoverKnownRoute","pathname","createHrefFromUrl","response","staticStageResponse","isResponsePartial","getStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writeStaticStageResponseIntoCache","f","h","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","FetchStrategy","PPRRuntime","flightDatas","headVaryParams","isJavaScriptURLString","console","error","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","search","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","currentTree","dynamicStaleTimeSeconds","baseTree","baseData","segmentPath","treePatch","seedData","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","acc","convertRootFlightRouterStateToRouteTree","baseRouterState","index","length","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","parallelRouteKey","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","undefined","isEmptySeedDataPartial","link","getLinkForCurrentNavigation","fetchStrategy","PPR","transitionToCapturedSPA","updateCapturedSPAToTree","Promise","resolve","schedulePrefetchTask","PrefetchPriority"],"mappings":";;;;;;;;;;;;;;;;;;;IAkhBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA4CAC,4BAA4B;eAA5BA;;IAzrBAC,QAAQ;eAARA;;IAmJAC,oBAAoB;eAApBA;;;qCA5LoB;gCAM7B;mCAC2B;2BACY;uBAYvC;kCAC4B;0BACmB;2BACjB;uBACW;uBACJ;oCAGb;oCACI;+BACG;yBACyB;AAUxD,SAASD,SACdE,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC;IAEhC,oEAAoE;IACpE,0EAA0E;IAC1E,wEAAwE;IACxE,sEAAsE;IACtE,oEAAoE;IACpE,aAAa;IACb,IAAIC,QAAQC,GAAG,CAACC,yBAAyB,EAAE;QACzC,MAAM,EAAEC,kBAAkB,EAAE,GAC1BC,QAAQ;QACV,IAAID,sBAAsB;YACxB,OAAOE,2BACLf,OACAC,KACAC,YACAC,uBACAC,kBAC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