{"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":["fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","convertRootFlightRouterStateToRouteTree","getStaleAt","writeStaticStageResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","routeTree","metadataVaryPath","data","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","flightData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","pathname","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","f","h","processed","PPRRuntime","flightDatas","headVaryParams","console","error","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","search","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","currentTree","dynamicStaleTimeSeconds","baseTree","baseData","segmentPath","treePatch","seedData","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","acc","baseRouterState","index","length","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","parallelRouteKey","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","undefined","isEmptySeedDataPartial","link","fetchStrategy","PPR","transitionToCapturedSPA","updateCapturedSPAToTree","Promise","resolve"],"mappings":"AASA,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,eAAe,QAEV,oCAAmC;AAC1C,SAASC,iBAAiB,QAAQ,yCAAwC;AAC1E,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,WAAW,EACXC,mBAAmB,EACnBC,2CAA2C,EAC3CC,uCAAuC,EACvCC,UAAU,EACVC,iCAAiC,EACjCC,4BAA4B,EAC5BC,mCAAmC,QAG9B,UAAS;AAChB,SAASC,kBAAkB,QAAQ,sBAAqB;AACxD,SAASC,cAAc,QAA+B,cAAa;AACnE,SAASC,oBAAoB,QAAQ,cAAa;AAClD,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,UAAS;AACzD,SAASC,2BAA2B,QAAQ,WAAU;AAGtD,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,qBAAqB,QAAQ,2BAA0B;AAChE,SAASC,uBAAuB,EAAEC,qBAAqB,QAAQ,YAAW;AAE1E;;;;;;;CAOC,GACD,OAAO,SAASC,SACd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